Flash Attention Setup¶
Flash Attention is a memory-efficient attention algorithm for transformer models that reduces memory usage for long sequences. Installing it requires PyTorch with CUDA support and careful dependency management. This guide covers two installation paths using uv: from a pre-built wheel (faster, no compilation), or built from source when no compatible wheel is available.
Prerequisites¶
Make sure to read the following sections of the documentation before using this example:
Other resources:
Installation¶
Flash Attention provides pre-built wheels for common combinations of CUDA, PyTorch, and Python on the Flash Attention releases page.
Some dashboards are available online to help find the right wheel for your configuration, like this one, where you can copy an URL or download the wheel to your local machine.
If a compatible wheel is listed, use the From a pre-built wheel section. Otherwise, use Building from source to compile Flash Attention on a compute node.
From a pre-built wheel¶
Pre-built wheels are available for common CUDA, PyTorch, and Python combinations. Wheel filenames encode the target configuration, like :
This wheel targets:
flash_attn-2.8.3.post1— flash attention2.8.3.post1cu126— CUDA 12.6torch2.7— PyTorch 2.7cp312— Python 3.12linux_x86_64— Linux x86_64
Tip
Pre-built wheels require no compilation and can be installed on login nodes.
Add the wheel URL as a dependency source in pyproject.toml,
replacing the URL with the one matching the target configuration:
Install the dependencies:
Reusing a locally built wheel
A wheel built from source (see theBuilding from source)
can also be used. In the sources section of the pyproject.toml,
replace url by path, like:
Building from source¶
Build Flash Attention from source when no pre-built wheel matches the target CUDA, PyTorch, and Python combination.
Warning
Building from source requires significant memory and time. Do not run the build on login nodes, submit a dedicated job to a compute node instead.
Use the following configuration and job script:
Warning
MAX_JOBS = "4" limits parallel compilation to prevent
out-of-memory errors during the build. Increase this value only
when the compute node has sufficient memory for more parallel jobs.
FLASH_ATTENTION_SKIP_CUDA_BUILD = "0" ensures that Flash Attention
is compiled with CUDA support.
Tip
Adapt TORCH_CUDA_ARCH_LIST to the compute capability of the
target GPU. Find compute capabilities on the
NVIDIA website. "9.0"
targets the H100. To support multiple architectures, separate
values with semicolons: TORCH_CUDA_ARCH_LIST="9.0;8.0;...".
Submit the build using the job script:
Once the build completes, uv caches the compiled wheel, which can be reused in other projects without recompiling. To reuse the wheel directly, (for example, on an other cluster), locate the cached wheel with:
Example¶
The full source code for this example is available on the mila-docs GitHub repository.
Running this example¶
Submit the job with sbatch: