xformers README

The project's README from github.com/facebookresearch/xformers. As one markdown file: README.md.

Open in Colab
CircleCI Codecov black
PRs welcome


xFormers - Toolbox to Accelerate Research on Transformers

xFormers is:

Installing xFormers

# [linux & win] cuda 12.6 version
pip3 install -U xformers --index-url https://download.pytorch.org/whl/cu126
# [linux & win] cuda 12.8 version
pip3 install -U xformers --index-url https://download.pytorch.org/whl/cu128
# [linux & win] cuda 13.0 version
pip3 install -U xformers --index-url https://download.pytorch.org/whl/cu130
# [linux only] (EXPERIMENTAL) rocm 7.1 version
pip3 install -U xformers --index-url https://download.pytorch.org/whl/rocm7.1
# Same requirements as for the stable version above
pip install --pre -U xformers
# (Optional) Makes the build much faster
pip install ninja
# Set TORCH_CUDA_ARCH_LIST if running and building on different GPU types
# NOTE: pytorch must already be installed!
pip install -v --no-build-isolation -U git+https://github.com/facebookresearch/xformers.git@main#egg=xformers
# (this can take dozens of minutes)

Benchmarks

Memory-efficient MHA Benchmarks for ViTS Setup: A100 on f16, measured total time for a forward+backward pass

Note that this is exact attention, not an approximation, just by calling xformers.ops.memory_efficient_attention

More benchmarks

xFormers provides many components, and more benchmarks are available in BENCHMARKS.md.

(Optional) Testing the installation

This command will provide information on an xFormers installation, and what kernels are built/available:

python -m xformers.info

Using xFormers

Key Features

  1. Optimized building blocks, beyond PyTorch primitives
    1. Memory-efficient exact attention - up to 10x faster
    2. sparse attention
    3. block-sparse attention
    4. fused softmax
    5. fused linear layer
    6. fused layer norm
    7. fused dropout(activation(x+bias))
    8. fused SwiGLU

Install troubleshooting

License

xFormers has a BSD-style license, as found in the LICENSE file. It includes code from the triton-lang/kernels repo.

Citing xFormers

If you use xFormers in your publication, please cite it by using the following BibTeX entry.

@Misc{xFormers2022,
  author =       {Benjamin Lefaudeux and Francisco Massa and Diana Liskovich and Wenhan Xiong and Vittorio Caggiano and Sean Naren and Min Xu and Jieru Hu and Marta Tintore and Susan Zhang and Patrick Labatut and Daniel Haziza and Luca Wehrstedt and Jeremy Reizenstein and Grigory Sizov},
  title =        {xFormers: A modular and hackable Transformer modelling library},
  howpublished = {\url{https://github.com/facebookresearch/xformers}},
  year =         {2022}
}

Credits

The following repositories are used in xFormers, either in close to original form or as an inspiration:

xformers (facebookresearch/xformers)

Searching Database…

10.6K ·GitHub
Что это такое?xFormers — это набор инструментов от Meta (Facebook Research) с гибкими, оптимизированными строительными блоками для Transformer, которые можно комбинировать между собой — переиспользуемые куски для своих моделей, а не монолитный фреймворк.
Это отдельное приложение или библиотека, которую я импортирую в свой код?Это Python-библиотека: независимые, настраиваемые строительные блоки, которые можно использовать без шаблонного кода. Они не привязаны к конкретной области — исследователи применяют их в компьютерном зрении, NLP и не только.
Что должно быть установлено заранее?PyTorch 2.10.0 — стабильный pip-пакет собран под неё; другие версии PyTorch (включая ночные сборки) требуют dev-бинарники или сборку из исходников.
Что чаще всего идёт не так при установке?Самое хрупкое — сборка из исходников: NVCC должен совпадать с вашей CUDA runtime и версией GCC, задайте TORCHCUDAARCHLIST под целевые GPU, а если при сборке кончается память, используйте MAXJOBS=2. На Windows включите длинные пути плюс git config --global core.longpaths true.
Какая у него лицензия?Лицензия в стиле BSD, как указано в файле LICENSE; в кодовой базе также есть код из репозитория triton-lang/kernels.
Чтобы реально этим пользоваться, нужна ли видеокарта NVIDIA?На практике да — xFormers содержит собственные CUDA-ядра (при необходимости переключается на другие библиотеки), а CI репозитория также собирается под AMD ROCm.
Какая главная фишка?Экономящее память точное attention — до 10 раз быстрее, причём это именно точный attention, а не приближение, доступный через xformers.ops. В опубликованном бенчмарке замерен forward+backward проход на A100 в f16.
Что ещё есть в наборе кроме attention?Разреженный (sparse) и блочно-разреженный attention, а также набор fused-операций: fused softmax, fused линейные слои, fused layer norm, fused dropout(activation(x+bias)) и fused SwiGLU — всё подаётся как оптимизированные блоки поверх обычных примитивов PyTorch.
Почему брать его, а не обычный PyTorch?Проект ориентирован на исследования: вы получаете самые свежие компоненты, которых ещё нет в массовых библиотеках вроде PyTorch, причём скорость и экономия памяти заявлены как цели дизайна.
Как проверить, какие ядра реально есть в моей установке?Запустите команду проверки установки из раздела 'Testing the installation' в README — она выдаст информацию о вашей установке xFormers и о том, какие ядра были собраны и доступны.
Size
42.9 MB
Stars
10.6K
Age
5y
Commits · 90 Days