long-context-attention

feifeibearApache-2.0活跃维护

统一序列并行注意力实现,把 Ulysses 和 Ring Attention 混合成 2D 并行,让长上下文 Transformer 训练和推理能扩展到超长序列。

USP: Unified (a.k.a. Hybrid, 2D) Sequence Parallel Attention for Long Context Transformers Model Training and Inference

0.6.4发布于 2026-01-13 08:13 UTC696star86fork同步于 2026-11-07 07:28 UTC

怎么上手

由 README 提炼,执行前请确认
pip install flash-attn
pip install yunchang
硬件要求按 README 说明

README 未给出显存要求;H100/B100 用 FA v3,A100/L40 用 FA v2,NPU 可用 Torch 实现(不支持反向),Intel XPU 需 sgl-kernel-xpu(仅前向)。

昇腾 / Ascend多卡 / 张量并行
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

融合 Ulysses 与 Ring Attention 的混合序列并行注意力,用于长上下文 LLM 训练与推理

统一序列并行注意力实现,把 Ulysses 和 Ring Attention 混合成 2D 并行,让长上下文 Transformer 训练和推理能扩展到超长序列。

核心能力

  • 混合 Ulysses 与 Ring Attention 实现统一序列并行
  • 用 zigzag/stripe 负载均衡策略处理 causal 掩码
  • 支持 FA、FA3、Torch、Sage、FlashInfer 等多种注意力后端
  • 可作为 Attention 的 drop-in 替换接入现有模型
  • 已在 Megatron-LM 中验证 DP 与 USP 损失曲线对齐

容易踩的坑

FlashAttention 是最易出错的依赖,需匹配 2.6.x/2.7.x 或从源码装 FA v3;NPU 的 TORCH_EFFICIENT 与 XPU 后端均不支持反向传播;Sage/SpargeAttention 与 FlashInfer 需自行从源码安装且仅支持前向。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本0.6.4
  1. 0.6.40.6.4 is release on Jan 13 2026最新正式版2026-01-13 · 2026-01-13 08:13 UTC

    What's Changed

    New Contributors

    Full Changelog: https://github.com/feifeibear/long-context-attention/compare/0.6.3...0.6.4

  2. 0.6.3.post10.6.3.post1 is released on 21th April 20252025-04-21 · 2025-04-21 01:52 UTC
    查看更新说明
  3. 0.6.30.6.3 is released on 18th April2025-04-18 · 2025-04-18 05:39 UTC
    查看更新说明

    What's Changed

    New Contributors

    Full Changelog: https://github.com/feifeibear/long-context-attention/compare/0.6.2...0.6.3

  4. 0.6.20.6.2 is released 8th April 20252025-04-08 · 2025-04-08 09:14 UTC
    查看更新说明

    What's Changed

    New Contributors

    Full Changelog: https://github.com/feifeibear/long-context-attention/compare/0.6.1...0.6.2

  5. 0.6.10.6.1 is released on 20th March 2025!2025-03-20 · 2025-03-20 01:32 UTC
    查看更新说明

    What's Changed

    New Contributors

    Full Changelog: https://github.com/feifeibear/long-context-attention/compare/0.6.0...0.6.1

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    YunChang: A Unified Sequence Parallel (USP) Attention for Long Context LLM Model Training and Inference.

    [Tech Report] USP: A Unified Sequence Parallelism Approach for Long Context Generative AI

    This repo provides a sequence parallel approach that synergizes the strengths of two popular distributed attentions, i.e. DeepSpeed-Ulysses-Attention and Ring-Attention, delivering a more general and stronger versatility and better performance. The project is built on zhuzilin/ring-flash-attention and refers to the DeepSpeed-Ulysses.

    USP has been applied in NVIDIA/TransformerEngine AttnFuncWithCPAndKVP2P. You can use it in API attn_forward_func_with_cp.

    Why not apply Ulysses and Ring Attention Individually?

    • Ulysses is sensitive to the number of attention heads. The parallelism degree in Ulysses cannot exceed the number of heads. Consequently, it is not suitable for GQA (Grouped Query Attention) and MQA (Multi-Query Attention) scenarios. For instance, Ulysses does not operate effectively with a single head. In addition, since Tensor Parallelism also requires division across the head number dimension, achieving compatibility between Ulysses and TP can be challenging.

    • Ring-Attention is ineffient than Ulysses in computation and communication. Ring-Attention segments the Query, Key, and Value (QKV) into smaller blocks, which can lead to a decrease in efficiency when using FlashAttention. Even with the communication and computation processes fully overlapped, the total execution time lags behind that of Ulysses. Furthermore, Ring-Attention utilizes asynchronous peer-to-peer communication, which not only has a lower bandwidth utilization compared to collective communication methods but also poses the risk of potential communication deadlocks in large-scale deployments.

    LongContextAttention, also known as Unified Sequence Parallelism and Hybrid Sequence Parallelism

    LongContextAttention is a unified sequence parallel , also known as hybrid sequence parallel ,that hybrid DeepSpeed-Ulysses-Attention and Ring-Attention therefore addressing the limitations of both methods.

    1. Installation

    FlashAttention is the most important external dependency and is often the cause of errors when installing and using yunchang. Yunchang supports flash_attn 2.6.x and 2.7.x, both v3 and v2 versions. Additionally, yunchang supports runs without flash_attn, which is suitable for NPUs.

    As shown in the figure below, there are three usage methods based on the flash_attn situation:

    1. For H100, B100, hardware that supports FA v3, ring_flash_attn uses FA v3.

    2. For A100, L40, hardware that supports FA v2, ring_flash_attn uses FA v2.

    3. For hardware such as NPUs that does not support FA, use torch to implement attention computation. In this case, there is no need to install flash_attn, and you should apply LongContextAttention(ring_impl_type="basic", attn_type=AttnType.TORCH_EFFICIENT). Note: the backward pass is not supported for AttnType.TORCH_EFFICIENT.

    4. For Intel XPU (Xe GPU / BMG), use sgl-kernel-xpu which provides flash_attn_varlen_func for XPU. Apply LongContextAttention(ring_impl_type="basic_xpu", attn_type=AttnType.XPU). Note: the backward pass is not supported for AttnType.XPU.

    Option 1: pip install

    pip install flash-attn

    pip install yunchang

    Apply FlashAttention V3: Since FA V3 is beta-released, you need to install FlashAttention V3 from source code.

    Follow the FlashAttention beta-release to install V3 for NVIDIA Hopper GPUs.

    We applied the Nov 10 2024 commit b443207c1fc4c98e4532aad4e88cfee1d590d996.

    Option 2: build from local.

    pip install .

    Install for AMD GPU: install_amd.md

    Install for Intel XPU: install_xpu.md

    2. Usage

    Please refer to test/test_hybrid_qkvpacked_attn.py and test/test_hybrid_attn.py for usage.

    In short, we take the zigzag ring attention implementation as an example:

    1. apply set_seq_parallel_pg to set the process group
    2. extract local tensors with zigzag_extract_local. We need reorder the input tokens or input tensors for load balance ring attention.
    3. then apply LongContextAttention(ring_impl_type="zigzag") as a drop-in replacement for Attention implementation.
    from yunchang import (
        AsyncLongContextAttention,
        LongContextAttention,
        set_seq_parallel_pg,
        EXTRACT_FUNC_DICT
    )
    from yunchang.kernels import AttnType
    
    sp_ulysses_degree = 2
    sp_ring_degree = 4
    
    # support world_size = 8
    set_seq_parallel_pg(sp_ulysses_degree, sp_ring_degree, rank, world_size)
    
    # attn_type could be FA, FA3, TORCH_EFFICIENT.
    longctx_attn = LongContextAttention(ring_impl_type="zigzag", attn_type=AttnType.FA)
    
    # if you use NPUs, where no flash_attn is supported, you can use the following code.
    # LongContextAttention(ring_impl_type="zigzag", attn_type=AttnType.TORCH_EFFICIENT)
    
    # if you use Intel XPU (BMG/Xe), use sgl-kernel-xpu flash attention (forward-only).
    # LongContextAttention(ring_impl_type="basic_xpu", attn_type=AttnType.XPU)
    
    # extract a local shard for the global Q, K, V.
    local_q = EXTRACT_FUNC_DICT["zigzag"](
            Q, rank, world_size=world_size, rd=sp_ring_degree, ud=sp_ulysses_degree
        ).detach().clone()
    ...
    
    local_out = usp_attn(
            local_q,
            local_k,
            local_v,
            dropout_p=dropout_p,
            causal=True, # zigzag and stripe is load balance strategy for causal=True
            window_size=window_size,
            softcap=0.0,
            alibi_slopes=alibi_slopes,
            deterministic=deterministic,
            return_attn_probs=True,
        )
    
    

    3.Test

    if you do not install yuanchang, add the project root directory to the PYTHONPATH:

    export PYTHONPATH=$PWD:$PYTHONPATH
    
    • FlashAttn/Torch Test
    torchrun --nproc_per_node=4 ./test/test_hybrid_attn.py --sp_ulysses_degree 2 --ring_impl_type "zigzag" --causal --attn_impl fa --use_bwd
    torchrun --nproc_per_node=4 ./test/test_hybrid_attn.py --sp_ulysses_degree 2 --ring_impl_type "zigzag" --causal --attn_impl torch
    torchrun --nproc_per_node 8 test/test_hybrid_qkvpacked_attn.py
    
    • Sage/SpargeAttention Test (fwd only, Non causal)

    you need install SpargeAttn and SageAttention from source.

    torchrun --nproc_per_node=4 ./test/test_hybrid_attn.py --sp_ulysses_degree 2 --attn_impl sage_fp8
    
    torchrun --nproc_per_node=4 ./test/test_hybrid_attn.py --sp_ulysses_degree 4 --attn_impl sparse_sage --sparse_sage_tune_mode
    
    • FlashInfer Test (fwd only)

    Install FlashInfer from here.

    torchrun --nproc_per_node=4 --master_port=1234 ./test/test_hybrid_attn.py --sp_ulysses_degree 2 --ring_impl_type 'basic_flashinfer' --attn_impl flashinfer
    
    • Intel XPU Test (fwd only, requires sgl-kernel-xpu)
    torchrun --nproc_per_node=4 ./test/test_hybrid_attn_xpu.py --seqlen 2048 --causal
    

    4. Verified in Megatron-LM

    The loss curves for Data Parallel (DP) and Unified Sequence Parallel (ulysses=2+ring=2) are closely aligned, as illustrated in the figure. This alignment confirms the accuracy of the unified sequence parallel.

    When utilizing load-balance Ring Attention with a causal mask, it is essential to reorder the Query tensors using the EXTRACT_FUNC_DICT function.

    In Megatron-LM, you can reorder the input tokens before feeding them into the model and apply the same reordering to the RoPE parameters. For detailed instructions, please refer to our paper.

    For an example implementation, you can check out this PR, which integrates USP into a BAAI's Megatron-LM framework.

    6. Benchmark

    bash ./scripts/run_qkvpack_compare.sh
    

    On an 8xA100 NVLink machine, the benchmark results are as follows:

    On an 8xL20 PCIe machine and a 4xA100 PCIe machine, the benchmark results are as follows:

    Some Conclusions:

    1. If the head number is enough, Ulysses outperforms Ring-Attention. The All-to-All communication of Ulysses is highly efficient within a single machine, with a very low overhead ratio. In contrast, Ring splits computation and communication, which increases the overall of computation time, and even with complete overlap, it is slower than Ulysses.

    2. QKV packed (LongContextAttentionQKVPacked) is better than the QKV no packed (LongContextAttention) version, with the difference becoming more pronounced as the sequence length decreases. MAQ and GQA can only use the no packed version.

    3. Among the variants of the Ring-Attention implementation, zigzag and stripe perform better than basic. Typically, zigzag is slightly better than stripe, but as the sequence length increases, the difference between zigzag and stripe becomes less noticeable. It is worth noting that both zigzag and stripe have specific layout requirements for the sequence dimension.

    4. Hybrid parallelism works well to heterogeneous network devices. For example, on an 8-GPU L20 setup, the optimal performance is achieved when ulysess_degree is set to 2 and ring_degree is set to 4.

    7. Best Practice for 4D Parallelism

    We analyze the impact of introducing Sequnce Parallelism to Data/ZeRO/Tensor/Pipeline Parallelism in a technique report, which can be found at here.

    Some best practices are listed here:

    1. We suggest using Unified-SP in place of SP-Ring and SP-Ulysses, as it encompasses the capabilities of both while offering additional benefits.

    2. DP (data parallelism) vs SP: We suggest prioritizing the use of DP over SP if possible. Only when the batch size (bs) is insufficient for partitioning should one consider whether to employ SP

    3. Utilizing SP, it should always be used in conjunction wit ZeRO-1/2.

    4. Unified-SP has lower communication cost than Tensor Parallel with megatron-lm sequence parallelism (TP-sp)! You can use Unified-SP to replace TP for better speed. However, now switching TP (tensor parallelism) to SP+ZeRO2 cannot increase the sequence length in training. SP+ZeRO3 can train a similar sequence length as TP-sp. We suggest that SP may have an advantage over TP when employing GQA in terms of communication cost, as GQA can reduce the communication cost of SP without affecting TP.

    5. Setting a higher parallel degree of SP parallelism is possible, which may need to set a large ring degree when the head number is limited, to train a long sequence across a greater number of computational devices. But TP could not be set a high parallel.

    8. Projects apply USP

    I am honored that this repository has contributed to the following projects:

    1. xdit-project/xDiT
    2. NVlabs/VILA
    3. feifeibear/Odysseus-Transformer
    4. Ascend/AscendSpeed
    5. jzhang38/EasyContext
    6. FlagOpen/FlagScale
    7. zhiyuanhubj/LongRecipe
    8. NVIDIA/TransformerEngine
    9. xdit-project/mochi-xdit

    9. Cite Us

    USP: A Unified Sequence Parallelism Approach for Long Context Generative AI

    @article{fang2024unified,
      title={A Unified Sequence Parallelism Approach for Long Context Generative AI},
      author={Fang, Jiarui and Zhao, Shangchun},
      journal={arXiv preprint arXiv:2405.07719},
      year={2024}
    }