Skip to content

Test Whisper on Ascend NPU using ACL Python API - #2986

Merged
csukuangfj merged 1 commit into
k2-fsa:masterfrom
csukuangfj:whisper-ascend
Jan 5, 2026
Merged

csukuangfj merged 1 commit into
k2-fsa:masterfrom
csukuangfj:whisper-ascend

Conversation

@csukuangfj

@csukuangfj csukuangfj commented Jan 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Tests

    • Added end-to-end inference testing for Ascend NPU models, enabling model validation with audio input.
  • Chores

    • Removed debug logging output from model inference scripts for cleaner operation.

✏️ Tip: You can customize this high-level summary in your review settings.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jan 5, 2026
@coderabbitai

coderabbitai Bot commented Jan 5, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

This PR adds Ascend-NPU support for Whisper model testing by introducing a new comprehensive test module with ONNX/InferSession-based inference, audio processing, and feature computation. A shared ONNX export delegation is added, and debug print statements are removed from existing RKNN tests.

Changes

Cohort / File(s) Summary
Ascend-NPU ONNX Support
scripts/whisper/ascend-npu/export_onnx.py, scripts/whisper/ascend-npu/test_om.py
New export module delegating to RKNN implementation. New comprehensive test harness introducing OmModel class for encoder/decoder inference, KV cache management, feature computation via kaldi_native_fbank, audio loading with librosa, and full decoding loop with causal masking and token-to-text conversion.
RKNN Debug Cleanup
scripts/whisper/rknn/test_on_rk3588_board.py
Removed debug print statements from encoder output processing, encoder path selection, and decoder loop iterations.

Sequence Diagram(s)

sequenceDiagram
    participant Audio as Audio File
    participant FeatComp as Feature Computation
    participant Encoder as Encoder InferSession
    participant Decoder as Decoder InferSession
    participant KVCache as KV Cache Manager
    participant TokenMap as Token Mapper

    Audio->>FeatComp: load_audio(filename)<br/>16kHz WAV → float32
    FeatComp->>FeatComp: compute_features()<br/>kaldi_native_fbank → 80-dim
    FeatComp->>FeatComp: pad/trim to 3000 frames<br/>transpose to (1,80,3000)
    FeatComp->>Encoder: run_encoder(features)
    rect rgb(200, 240, 255)
    Note over Encoder: Initialize OmModel<br/>load encoder/decoder sessions
    Encoder->>KVCache: get_self_cache()<br/>allocate initial KV tensors
    end
    Encoder-->>Decoder: return cross_kv
    KVCache-->>Decoder: initialized self_kv
    rect rgb(240, 220, 255)
    Note over Decoder: Decoding Loop (≤100 steps or EOT)
    loop Until EOT or max steps
        Decoder->>Decoder: causal_mask_1d(offset, 3000)<br/>compute position mask
        Decoder->>Decoder: run_decoder(tokens, self_kv,<br/>cross_kv, offset, mask)
        Decoder->>KVCache: update self_kv from decoder output
        Decoder->>Decoder: append new token to sequence
    end
    end
    Decoder->>TokenMap: decode token IDs<br/>lookup → base64-decode
    TokenMap-->>Audio: output text transcription
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Export Whisper to RK NPU #2983: Reuses rknn/export_onnx.py via new ascend-npu delegation and introduces Ascend-NPU ONNX/InferSession test harness analogous to RKNN implementation.

Suggested labels

size:XL

Poem

🐰 A whisper flows through NPU streams,
Features dance in Fbank dreams,
KV caches bloom like carrot rows,
Encoders hop, decoders glow,
From audio seeds to text that grows! 🥕

✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b1db3ea and eb486a6.

📒 Files selected for processing (3)
  • scripts/whisper/ascend-npu/export_onnx.py
  • scripts/whisper/ascend-npu/test_om.py
  • scripts/whisper/rknn/test_on_rk3588_board.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello @csukuangfj, 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 significantly expands the project's hardware compatibility by integrating Whisper model testing capabilities for Ascend NPUs. It provides a dedicated Python script that orchestrates the entire inference pipeline, from audio input and feature computation to the final transcription using optimized encoder and decoder models. This enables efficient evaluation and deployment of Whisper models on Ascend platforms.

Highlights

  • Ascend NPU Integration: Introduces new scripts to enable testing of Whisper models on Ascend NPU hardware using the ACL Python API.
  • Whisper Model Inference Script: Adds test_om.py, a comprehensive script for performing Whisper inference on Ascend NPU, covering audio loading, feature extraction, and encoder-decoder model execution.
  • Model Configuration Handling: The OmModel class in test_om.py dynamically configures Whisper model parameters (e.g., sot_sequence, eot, layer counts) based on the model name, supporting different Whisper variants.
  • Code Cleanup: Removes debug print statements from the existing test_on_rk3588_board.py script, improving code cleanliness.
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. ↩

@csukuangfj
csukuangfj merged commit c305335 into k2-fsa:master Jan 5, 2026
1 check was pending
@csukuangfj
csukuangfj deleted the whisper-ascend branch January 5, 2026 23:52

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

Copy link
Copy Markdown

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 a test script for Whisper on Ascend NPU using the ACL Python API. The changes include a new test script, a file that seems to be a misplaced symlink, and cleanup of print statements in an existing script.

My review focuses on the new script and the file structure. I've found a critical issue with a file that should likely be a symbolic link. I've also suggested improvements for code quality and maintainability in the new test script, including adding type hints, specifying file encoding, and refactoring duplicated code.

@@ -0,0 +1 @@
../rknn/export_onnx.py No newline at end of file

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

critical

This file appears to be intended as a symbolic link to ../rknn/export_onnx.py, but it's a regular file containing the path as its content. This will not work as a Python script. If you execute it with python, it will raise a SyntaxError. It should be a symbolic link. You can create it with ln -s ../rknn/export_onnx.py scripts/whisper/ascend-npu/export_onnx.py and commit the symlink.

Comment on lines +103 to +109
def load_tokens(filename):
tokens = dict()
with open(filename, "r") as f:
for line in f:
t, i = line.split()
tokens[int(i)] = t
return tokens

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The load_tokens function can be improved by adding type hints for better readability and maintainability. Also, it's a good practice to explicitly specify the encoding when opening text files to avoid platform-dependent behavior. I'd suggest using utf-8.

Suggested change
def load_tokens(filename):
tokens = dict()
with open(filename, "r") as f:
for line in f:
t, i = line.split()
tokens[int(i)] = t
return tokens
def load_tokens(filename: str) -> "dict[int, str]":
tokens = dict()
with open(filename, "r", encoding="utf-8") as f:
for line in f:
t, i = line.split()
tokens[int(i)] = t
return tokens

Comment on lines +216 to +250
offset = np.array([0], dtype=np.int32)
for t in model.sot_sequence:
token = np.array([[t]], dtype=np.int32) # sot
mask = causal_mask_1d(offset.item(), model.n_text_ctx)

out = model.run_decoder(
tokens=token, self_kv=self_kv, cross_kv=cross_kv, offset=offset, mask=mask
)

for i in range(1, len(out)):
self_kv[i - 1][:, offset.item() : offset.item() + 1, :] = out[i]

offset += 1

idx = out[0][0, 0].argmax()

eot = model.eot

ans = []

while idx != eot and offset.item() < 100:
ans.append(idx)
token = np.array([[idx]], dtype=np.int32)

mask = causal_mask_1d(offset.item(), model.n_text_ctx)

out = model.run_decoder(
tokens=token, self_kv=self_kv, cross_kv=cross_kv, offset=offset, mask=mask
)

for i in range(1, len(out)):
self_kv[i - 1][:, offset.item() : offset.item() + 1, :] = out[i]

offset += 1
idx = out[0][0, 0].argmax()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The decoding logic is duplicated in the loop for the SOT sequence and the main decoding while loop. This can be refactored into a helper function to improve code readability and maintainability.

    offset = np.array([0], dtype=np.int32)

    def _decode_one_step(model, token_id, self_kv, cross_kv, current_offset):
        token = np.array([[token_id]], dtype=np.int32)
        mask = causal_mask_1d(current_offset.item(), model.n_text_ctx)

        out = model.run_decoder(
            tokens=token, self_kv=self_kv, cross_kv=cross_kv, offset=current_offset, mask=mask
        )

        for i in range(1, len(out)):
            self_kv[i - 1][:, current_offset.item() : current_offset.item() + 1, :] = out[i]

        current_offset += 1
        return out, current_offset

    for t in model.sot_sequence:
        out, offset = _decode_one_step(model, t, self_kv, cross_kv, offset)

    idx = out[0][0, 0].argmax()

    eot = model.eot

    ans = []

    while idx != eot and offset.item() < 100:
        ans.append(idx)
        out, offset = _decode_one_step(model, idx, self_kv, cross_kv, offset)
        idx = out[0][0, 0].argmax()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant