Skip to content

[Feature] add DFlash Support#7162

Closed
chenaoxuan wants to merge 1 commit intovllm-project:releases/v0.13.0from
chenaoxuan:dflash
Closed

[Feature] add DFlash Support#7162
chenaoxuan wants to merge 1 commit intovllm-project:releases/v0.13.0from
chenaoxuan:dflash

Conversation

@chenaoxuan
Copy link
Copy Markdown
Contributor

@chenaoxuan chenaoxuan commented Mar 11, 2026

The current PR has been closed and moved to PR-8118 to support the latest vllm-ascend main.

Purpose

We first supported DFlash on Ascend-NPU and then maintained it.

DFlash ("DFlash: Block Diffusion for Flash Speculative Decoding") is a parallel speculative decoding algorithm that generates multiple candidate tokens at once through a diffusion process.

Main changes:

  • Add dflash propose implementation on the basis of eagle_proposer.
  • Reuse the original kv-cache to store target_hidden_states to provide full context.
  • Modify the attention backend and add bidirectional attention branch.
  • Modify model_runner_v1 to support calling the dflash module.
  • Supports batch_size>1.

Quick Start

  • Based on vLLM PR.
  • Use official DFlash weights.
  • --speculative-config '{"num_speculative_tokens": 8, "method":"dflash","model":"weight_path","enforce_eager": true, "disable_padded_drafter_batch": true}'

Test Results

Verified with Sglang(GPU) and Vllm(GPU) version of Qwen3-8B-DFlash-b16 in GSM8K dataset.

T=0 Draft Tokens = 16, Max Tokens = 2048

Batch size Framework Mean acceptance length
4 SGlang 6.07
4 vLLM 6.08
4 vLLM-Ascend 6.05
8 SGlang 6.07
8 vLLM 6.08
8 vLLM-Ascend 6.06
16 SGlang 6.08
16 vLLM 6.08
16 vLLM-Ascend 6.08
32 SGlang 6.08
32 vLLM 6.09
32 vLLM-Ascend 6.08

Next Plan

  • Support graph: PIECEWISE or FULLGRAPH.
  • More elegant code: loop optimization.
  • Support Data-Parallel.
  • Operator optimization: now the maximum number of TND layout's for the FIA operator is 16. Therefore, the maximum sepc_num is 15. Although this issue can be bypassed, the performance will be affected.

@github-actions
Copy link
Copy Markdown
Contributor

This pull request has conflicts, please resolve those before we can evaluate the pull request.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces comprehensive support for DFlash, a parallel speculative decoding algorithm, enabling its use within the Ascend-NPU environment. The changes involve adapting core components like the attention mechanism and rotary embeddings, alongside implementing dedicated logic for DFlash's token proposal and dummy run procedures. This integration aims to enhance the efficiency of speculative decoding by leveraging DFlash's diffusion-based approach for generating multiple candidate tokens simultaneously.

Highlights

  • DFlash Integration: Introduced support for DFlash, a parallel speculative decoding algorithm, within the Ascend-NPU environment.
  • Attention Mechanism Adaptation: Modified the attention score calculation to handle DFlash's non-causal nature by adjusting sparse mode and mask application.
  • Rotary Embedding Adjustment: Updated rotary embedding tensor dimensions to accommodate DFlash's requirements, specifically doubling the batch token dimension.
  • Dedicated DFlash Proposer Logic: Implemented specific _dummy_run_dflash and _dflash_propose methods within the EagleProposer to manage DFlash's unique token generation and metadata handling.
  • Framework Integration: Seamlessly integrated DFlash into the existing speculative decoding framework by updating method dispatch and model runner configurations.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • vllm_ascend/attention/attention_v1.py
    • Modified attention score calculation to support DFlash by conditionally applying causal mask and sparse mode.
  • vllm_ascend/ops/rotary_embedding.py
    • Adjusted rotary embedding tensor dimensions for DFlash speculative decoding.
  • vllm_ascend/spec_decode/init.py
    • Included 'dflash' as a supported speculative decoding method using EagleProposer.
  • vllm_ascend/spec_decode/eagle_proposer.py
    • Removed a restrictive assertion in attention layer name processing.
    • Added DFlash-specific sharing of the language model head.
    • Introduced a dedicated dummy run path for DFlash.
    • Implemented the core DFlash token proposal logic and dummy run functionality.
  • vllm_ascend/worker/model_runner_v1.py
    • Updated drafter setup to recognize DFlash as an EagleProposer method.
    • Conditionally invoked DFlash-specific token proposal logic.
    • Passed the drafter method to the auxiliary hidden state layer retrieval function.
Activity
  • No specific activity was recorded for this pull request.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for DFlash speculative decoding. The changes span across attention layers, rotary embeddings, and the model runner to accommodate the new decoding logic. My review focuses on improving code maintainability by reducing duplication and addressing potential issues like magic numbers and removed assertions. Overall, the changes seem to be in the right direction to support DFlash.

Comment on lines +595 to +627
if not attn_metadata.causal:
# for dflash
attn_output, _ = torch_npu.npu_fused_infer_attention_score(
query=query,
key=key,
value=value,
block_table=block_table,
input_layout="TND",
block_size=block_size,
actual_seq_lengths=attn_metadata.actual_seq_lengths_q,
actual_seq_lengths_kv=actual_seq_lengths_kv,
num_key_value_heads=self.num_kv_heads,
num_heads=self.num_heads,
scale=self.scale,
sparse_mode=0,
)
else:
# Get workspace from cache or calculate it if not present.
attn_output, _ = torch_npu.npu_fused_infer_attention_score(
query=query,
key=key,
value=value,
atten_mask=attn_metadata.attn_mask,
block_table=block_table,
input_layout="TND",
block_size=block_size,
actual_seq_lengths=attn_metadata.actual_seq_lengths_q,
actual_seq_lengths_kv=actual_seq_lengths_kv,
num_key_value_heads=self.num_kv_heads,
num_heads=self.num_heads,
scale=self.scale,
sparse_mode=3,
)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There's significant code duplication between the if and else branches. Most arguments to torch_npu.npu_fused_infer_attention_score are the same. This can be refactored to improve readability and maintainability by creating a common dictionary of arguments.

        common_kwargs = {
            "query": query,
            "key": key,
            "value": value,
            "block_table": block_table,
            "input_layout": "TND",
            "block_size": block_size,
            "actual_seq_lengths": attn_metadata.actual_seq_lengths_q,
            "actual_seq_lengths_kv": actual_seq_lengths_kv,
            "num_key_value_heads": self.num_kv_heads,
            "num_heads": self.num_heads,
            "scale": self.scale,
        }
        if not attn_metadata.causal:
            # for dflash
            attn_output, _ = torch_npu.npu_fused_infer_attention_score(
                **common_kwargs,
                sparse_mode=0,
            )
        else:
            # Get workspace from cache or calculate it if not present.
            attn_output, _ = torch_npu.npu_fused_infer_attention_score(
                **common_kwargs,
                atten_mask=attn_metadata.attn_mask,
                sparse_mode=3,
            )

Comment on lines +93 to +108
if vllm_config.speculative_config.method == "dflash":
_cos = torch.ones(1, max_num_batched_tokens * 2, 1, rope_dim, dtype=dtype, device=device)
_sin = torch.zeros(1, max_num_batched_tokens * 2, 1, rope_dim, dtype=dtype, device=device)
else:
_cos = torch.ones(1,
max_num_batched_tokens,
1,
rope_dim,
dtype=dtype,
device=device)
_sin = torch.zeros(1,
max_num_batched_tokens,
1,
rope_dim,
dtype=dtype,
device=device)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The if/else block for creating _cos and _sin tensors contains duplicated code. This can be simplified by using a multiplier to determine the size, making the code more concise and easier to maintain.

        size_multiplier = 2 if vllm_config.speculative_config and vllm_config.speculative_config.method == "dflash" else 1
        shape = (1, max_num_batched_tokens * size_multiplier, 1, rope_dim)
        _cos = torch.ones(*shape, dtype=dtype, device=device)
        _sin = torch.zeros(*shape, dtype=dtype, device=device)

draft_indexer_layer_names = indexer_layers - target_indexer_layer_names
draft_attn_layer_names = draft_attn_layer_names - draft_indexer_layer_names
assert len(draft_attn_layer_names) == 1
self.attn_layer_names = list(sorted(draft_attn_layer_names))
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The assertion assert len(draft_attn_layer_names) == 1 was removed. While this might be necessary for DFlash, it removes a safety check for other methods like 'eagle' and 'eagle3'. This could lead to unexpected behavior if the draft model for those methods changes. It would be safer to make this check conditional to avoid potential regressions.

        if self.method != "dflash":
            assert len(draft_attn_layer_names) == 1, (
                f"Expected 1 draft attention layer for method '{self.method}', "
                f"but found {len(draft_attn_layer_names)}."
            )
        self.attn_layer_names = list(sorted(draft_attn_layer_names))

total_num_query_tokens = batch_size * num_query_tokens
num_kv_tokens = num_context_tokens + total_num_query_tokens

MASK_TOKEN_ID = 151669
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The magic number 151669 is used for MASK_TOKEN_ID. This should be defined as a named constant at the top of the file or in a configuration file to improve readability and maintainability.

        MASK_TOKEN_ID = 151669  # TODO: Refactor to a named constant

Comment on lines +1453 to +1477
if self.speculative_config.method == "dflash":
draft_token_ids = self.drafter._dflash_propose(
target_token_ids=target_token_ids,
target_positions=target_positions,
target_hidden_states=target_hidden_states,
next_token_ids=next_token_ids,
last_token_indices=token_indices_to_sample,
common_attn_metadata=common_attn_metadata
)
else:
draft_token_ids = self.drafter._propose(
target_token_ids=target_token_ids,
target_positions=target_positions,
target_hidden_states=target_hidden_states,
next_token_ids=next_token_ids,
last_token_indices=token_indices_to_sample,
common_attn_metadata=common_attn_metadata,
sampling_metadata=sampling_metadata,
req_scheduled_tokens=req_scheduled_tokens,
long_seq_metadata=long_seq_metadata,
num_prefill_reqs=num_prefill_reqs,
num_decode_reqs=num_decode_reqs,
scheduler_output=scheduler_output,
num_scheduled_tokens=num_scheduled_tokens,
)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There is significant code duplication in the if/else block for calling _dflash_propose and _propose. Many arguments are shared. This can be refactored to improve readability and maintainability by using a dictionary for common arguments.

                propose_kwargs = {
                    "target_token_ids": target_token_ids,
                    "target_positions": target_positions,
                    "target_hidden_states": target_hidden_states,
                    "next_token_ids": next_token_ids,
                    "last_token_indices": token_indices_to_sample,
                    "common_attn_metadata": common_attn_metadata,
                }
                if self.speculative_config.method == "dflash":
                    draft_token_ids = self.drafter._dflash_propose(**propose_kwargs)
                else:
                    propose_kwargs.update({
                        "sampling_metadata": sampling_metadata,
                        "req_scheduled_tokens": req_scheduled_tokens,
                        "long_seq_metadata": long_seq_metadata,
                        "num_prefill_reqs": num_prefill_reqs,
                        "num_decode_reqs": num_decode_reqs,
                        "scheduler_output": scheduler_output,
                        "num_scheduled_tokens": num_scheduled_tokens,
                    })
                    draft_token_ids = self.drafter._propose(**propose_kwargs)

@wangxiyuan
Copy link
Copy Markdown
Collaborator

wangxiyuan commented Mar 13, 2026

Thanks for the PR. It's great. While we hope to support dflash base on vLLM change. Once vllm-project/vllm#36847 is merged, you can implement Ascend one basing on it to reduce code re-write

@chenaoxuan
Copy link
Copy Markdown
Contributor Author

Thanks for the PR. It's great. While we hope to support dflash base on vLLM change. Once vllm-project/vllm#36847 is merged, you can implement Ascend one basing on it to reduce code re-write

Yes, I noticed that this PR has been merged into vllm-main, but vllm-ascend does not yet support the current commit. The cherry-pick version based on this PR has already started development.

@HossamAmer12
Copy link
Copy Markdown

@chenaoxuan I am working on enabling dflash on vllm-ascend -- I downloaded the vllm on main, I also downloaded the vllm-ascend from this code

Can you provide your thoughts if this is going to work? What will be the blockers?

@chenaoxuan
Copy link
Copy Markdown
Contributor Author

@chenaoxuan I am working on enabling dflash on vllm-ascend -- I downloaded the vllm on main, I also downloaded the vllm-ascend from this code

Can you provide your thoughts if this is going to work? What will be the blockers?

You can temporarily use this vllm version: Link
Of course, it can run normally.
However, we are currently refactoring the code based on the latest vllm main and vllm-ascend main, and it will be launched soon (perhaps next week).

@HossamAmer12
Copy link
Copy Markdown

@chenaoxuan I did progress with the latest versions too. Let's collaborate on this so that we can merge efforts.

@chenaoxuan
Copy link
Copy Markdown
Contributor Author

@chenaoxuan I did progress with the latest versions too. Let's collaborate on this so that we can merge efforts.

I am delighted to collaborate. How can we further communicate? Or through what form?

@HossamAmer12
Copy link
Copy Markdown

@chenaoxuan Great, happy to collaborate! We can coordinate here on the RFC for visibility, and if needed we can also chat for quicker discussion. I’m currently working on adapting vLLM with vllm-ascend using the latest versions, and I also ran simulations for vLLM on GPU. What part are you focusing on? If it’s easier to chat, feel free to reach me on Slack/WeLink (or let me know what platform you prefer).

@chenaoxuan
Copy link
Copy Markdown
Contributor Author

@chenaoxuan Great, happy to collaborate! We can coordinate here on the RFC for visibility, and if needed we can also chat for quicker discussion. I’m currently working on adapting vLLM with vllm-ascend using the latest versions, and I also ran simulations for vLLM on GPU. What part are you focusing on? If it’s easier to chat, feel free to reach me on Slack/WeLink (or let me know what platform you prefer).

I tried to contact you via WeLink, but it seems I don't have the necessary permissions, so I couldn't send the message...

@chenaoxuan chenaoxuan closed this Apr 10, 2026
wangxiyuan pushed a commit that referenced this pull request Apr 16, 2026
**This PR is inherited from PR-[7162
](#7162) and supports
the latest vllm-ascend main. The old version is closed.**


### Purpose
**We first supported DFlash on Ascend-NPU and then maintained it.**

> DFlash ("[DFlash: Block Diffusion for Flash Speculative
Decoding](https://arxiv.org/abs/2602.06036)") is a parallel speculative
decoding algorithm that generates multiple candidate tokens at once
through a diffusion process.

Main changes:
- Corresponds to the official support of vllm merged
PR-[36847](vllm-project/vllm#36847).
- Add dflash proposer implementation on the basis of
SpecDecodeBaseProposer.
- Modify the attention backend and add bidirectional attention branch.
- Modify model_runner_v1 to support calling the dflash module.

### Quick Start
[!Attention!] 
As of April 10, vllm-ascend is not compatible with vllm that supports
DFlash.
Therefore, cherry-pick is required:
`cd vllm`
`git checkout -b new-branch v0.19.0`
`git cherry-pick dc14cbf0c06e8a124bdf0c03e8e267feef60887e`

[Weights]
Use official DFlash
[weights](https://huggingface.co/collections/z-lab/dflash).

[Config]
--speculative-config '{"num_speculative_tokens": 8,
"method":"dflash","model":"weight_path","enforce_eager": true}'

### Test Results
#### Acceptance rate
Verified with Sglang(GPU) and Vllm(GPU) version of Qwen3-8B-DFlash-b16
in GSM8K dataset.

T=0 Draft Tokens = 16, Max Tokens = 2048

| Batch Size | Framework | Mean Acceptance Length |
|-----|-----|-----|
| 4 | SGlang | 6.07 |
| 4 | vLLM | 6.08 |
| 4 | vLLM-Ascend | 6.05 |
| 8 | SGlang | 6.07 |
| 8 | vLLM | 6.08 |
| 8 | vLLM-Ascend | 6.06 |
| 16 | SGlang | 6.08 |
| 16 | vLLM | 6.08 |
| 16 | vLLM-Ascend | 6.08 |
| 32 | SGlang | 6.08 |
| 32 | vLLM | 6.09 |
| 32 | vLLM-Ascend | 6.08 |

#### Performance
Qwen3-8B, DP1/TP1, constructing gsm8k dataset to repeat the input length
to 3.5K/output length 1.5K, data num 400, batch_size 16, temperature 0
| Method | Graph Mode | Spec Num | Mean Acceptance Length | TOPT(ms) |
Output Token Throughput(token/s)|
|-----|-----|-----|-----|-----|-----|
| Eagle3 | FULL_DECODE_ONLY | 3 | 2.81 | 16.4 | 943.60(baseline) |
| Eagle3 | FULL_DECODE_ONLY | 8 | 3.60 | 19.5 | 795.34(↓15.7%) |
| Dflash | PIECEWISE  | 8 | 5.25 | 12.4 | 1248.93(↑32.4%) |

#### Accuracy
Qwen3-8B, DP1/TP1, output length 3.5K, data num 300, batch_size 16,
temperature 0
| Method | Graph Mode | Spec Num | Dataset |  Accuracy(%) |
|-----|-----|-----|-----|-----|
| Eagle3 | FULL_DECODE_ONLY | 3 | gsm8k | 84.67 |
| Dflash | PIECEWISE  | 8 | gsm8k | 85.00 |

### Next Plan
- Support FULL_DECODE_ONLY
- Support Qwen3.5
- The NPU Triton multi-core is faulty. Currently, only use a single core
to process all reqs, which needs to be improved.
- Operator optimization: now the maximum number of TND layout's for the
FIA operator is 16. Therefore, the maximum sepc_num is 15. Although this
issue can be bypassed, the performance will be affected.
- vLLM main: https://github.com/vllm-project/vllm/commit/v0.19.0

Signed-off-by: chenaoxuan <cax1165@163.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants