Skip to content

Epoxrt more zipformer ctc models to qnn - #2921

Merged
csukuangfj merged 2 commits into
k2-fsa:masterfrom
csukuangfj:zipformer-qnn-model
Dec 22, 2025
Merged

csukuangfj merged 2 commits into
k2-fsa:masterfrom
csukuangfj:zipformer-qnn-model

Conversation

@csukuangfj

@csukuangfj csukuangfj commented Dec 22, 2025 •

Copy link
Copy Markdown
Collaborator

Please see
https://k2-fsa.github.io/sherpa/onnx/qnn/models.html

Screenshot 2025-12-22 at 18 22 44

Summary by CodeRabbit

  • New Features

    • Added support for ZIPformer CTC models with context binary assets, enabling more flexible model deployment options.
    • Introduced dynamic build matrix generation for automated model compilation across multiple configurations and hardware targets.
  • Chores

    • Enhanced CI/CD infrastructure and build workflows to support expanded ZIPformer model export capabilities.

✏️ 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 Dec 22, 2025
@coderabbitai

coderabbitai Bot commented Dec 22, 2025 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Introduces QNN context binary support for ZIPformer CTC models by adding a matrix-generation Python script, updating the CI/CD workflow to use generated build matrices, and extending model-selection logic across Android and C++ components to recognize context binaries as valid alternatives to model files.

Changes

Cohort / File(s) Summary
Build Matrix Generation
.github/scripts/export-qnn/generate_zipformer.py
New Python script that generates a configuration matrix for ZIPformer models by iterating over SOC and input-duration combinations, conditionally filtering for 5-second models with specific model versions, and outputting configurations as JSON.
Workflow Configuration
.github/workflows/export-zipformer-ctc-to-qnn-20250703.yaml
Converts workflow from static to matrix-driven: adds generate_build_matrix job to produce dynamic configuration matrix, updates branch trigger, expands setup/bootstrap steps (Python venv, toolkit, dependencies), replaces fixed matrix entries with fromJson() sourcing, introduces conditional build steps per model target (20250703, 20251222), and updates artifact naming and release logic.
Model Selection & Validation
sherpa-onnx/csrc/offline-recognizer-impl.cc, sherpa-onnx/csrc/offline-zipformer-ctc-model-config.cc
Extends QNN Zipformer CTC selection to trigger when either the model file is non-empty OR a context binary is provided; adds pre-checks validating context binary existence when model is empty; conditionally routes to QNN validation based on model file extension or context binary presence.
Android Asset Handling
android/SherpaOnnxSimulateStreamingAsr/app/src/main/java/com/k2fsa/sherpa/onnx/simulate/streaming/asr/SimulateStreamingAsr.kt
Shifts Zipformer CTC asset preparation trigger from strict model-file presence to combined check for model OR context binary, ensuring context binary is always copied within this conditional block.

Sequence Diagram

sequenceDiagram
    participant PythonScript as Python Script<br/>(generate_zipformer.py)
    participant Matrix as Build Matrix<br/>(GitHub Output)
    participant Workflow as Workflow Job<br/>(export-zipformer-ctc-to-qnn)
    participant BuildEnv as Build Environment<br/>(Setup & Bootstrap)
    participant QNNTools as QNN Tools &<br/>Config Generation
    participant Artifacts as Artifact<br/>Storage

    PythonScript->>PythonScript: Iterate over SOC × input-duration<br/>combinations
    PythonScript->>PythonScript: Conditionally filter<br/>per model_name
    PythonScript->>Matrix: Generate & export<br/>config matrix
    
    Matrix->>Workflow: Dispatch parallel jobs<br/>with matrix values
    
    par Matrix-Driven Execution
        Workflow->>BuildEnv: Setup Python venv,<br/>toolkit, dependencies
        BuildEnv->>QNNTools: Initialize QNN<br/>environment
        QNNTools->>QNNTools: Generate context binary<br/>& model configs
    and Parallel Artifact Creation
        QNNTools->>Artifacts: Create per-target<br/>artifacts (binary, models)
        Artifacts->>Artifacts: Package into<br/>tarballs & directories
    end
    
    Artifacts->>Matrix: Store artifacts<br/>for release
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • Workflow complexity: Large YAML file with matrix-driven job coordination, multiple conditional build steps, and updated artifact organization requiring careful validation of matrix expansion and dependency chains
  • Conditional logic heterogeneity: Model-selection and validation changes span C++ factory pattern, Android asset handling, and validation logic—each requiring separate reasoning about context-binary fallback behavior
  • Python script correctness: Matrix generation logic including Cartesian product filtering needs validation against expected output format and SOC/model combinations
  • Integration testing: Cross-component changes (Python → workflow → C++ → Android) require verification that matrix output correctly drives subsequent build steps and asset handling

Possibly related PRs

  • #2815: Both PRs modify the export-zipformer-ctc-to-qnn workflow and introduce matrix-driven CI/CD infrastructure for Zipformer CTC model exports.
  • #2809: Both PRs extend QNN support across the same code paths (offline-recognizer, model-config, Android asset handling) and share the context-binary validation patterns.
  • #2768: Introduces the QnnConfig type and its context_binary field that is now conditionally validated and checked in this PR's model-selection logic.

Poem

🐰 A matrix blooms in Python's hand,
Each ZIPformer by config planned,
Context binaries dance with glee,
Through workflows wild, async and free!
QNN paths now have a choice—
Two routes to victory, raise your voice! 🎉

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94a040e and 1a004f9.

📒 Files selected for processing (5)
  • .github/scripts/export-qnn/generate_zipformer.py
  • .github/workflows/export-zipformer-ctc-to-qnn-20250703.yaml
  • android/SherpaOnnxSimulateStreamingAsr/app/src/main/java/com/k2fsa/sherpa/onnx/simulate/streaming/asr/SimulateStreamingAsr.kt
  • sherpa-onnx/csrc/offline-recognizer-impl.cc
  • sherpa-onnx/csrc/offline-zipformer-ctc-model-config.cc

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 enhances the integration and management of Zipformer CTC models within the Qualcomm Neural Processing SDK (QNN) framework. It introduces automation for generating QNN export configurations across diverse hardware and model variations, while simultaneously upgrading the C++ runtime to natively support and validate models provided as QNN context binaries. These changes collectively improve the flexibility, robustness, and ease of deploying QNN-optimized speech recognition models.

Highlights

  • New QNN Export Configuration Script: A new Python script, generate_zipformer.py, has been added to automate the creation of JSON configurations for exporting various Zipformer CTC models to QNN. This script considers different Qualcomm SOCs, architectures, input durations, and model versions, streamlining the QNN export process.
  • Enhanced QNN Model Loading Logic: The C++ backend (offline-recognizer-impl.cc) has been updated to allow the OfflineRecognizerZipformerCtcQnnImpl to be instantiated if either a traditional model file path or a QNN context binary path is provided. This change offers greater flexibility in how QNN-optimized Zipformer CTC models can be loaded and utilized.
  • Improved Model Validation for QNN Context Binaries: The validation logic for OfflineZipformerCtcModelConfig (offline-zipformer-ctc-model-config.cc) has been refined. It now correctly handles scenarios where a Zipformer CTC model is provided solely as a QNN context binary, ensuring proper file existence checks and robust model configuration validation.
Ignored Files
  • Ignored by pattern: .github/workflows/** (1)
    • .github/workflows/export-zipformer-ctc-to-qnn-20250703.yaml
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. ↩

@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 introduces a new Python script (generate_zipformer.py) responsible for generating Zipformer model configurations, including filtering specific model versions and input durations, which are then outputted as JSON. The primary C++ changes modify sherpa-onnx/csrc/offline-recognizer-impl.cc and sherpa-onnx/csrc/offline-zipformer-ctc-model-config.cc to enhance QNN model loading by allowing the OfflineRecognizerZipformerCtcQnnImpl to be initialized and validated based on the presence of a QNN context binary, even if the main model path is not provided. Review feedback suggests improving the readability of the new Python script by combining nested if statements and renaming a variable, and also recommends reformatting multi-line conditions in the C++ implementation for better code consistency.

Comment on lines +31 to +34
if model_name == "20251222":
if num_seconds not in ["5"]:
# TODO(fangjun): We only upload model-5-seconds.onnx right now
continue

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

For better readability, the nested if statements can be combined into a single if with a compound condition. This makes the logic more direct and easier to understand at a glance.

Suggested change
if model_name == "20251222":
if num_seconds not in ["5"]:
# TODO(fangjun): We only upload model-5-seconds.onnx right now
continue
if model_name == "20251222" and num_seconds != "5":
# TODO(fangjun): We only upload model-5-seconds.onnx right now
continue

Comment on lines +46 to +48
ans = [asdict(c) for c in configs]

print(json.dumps({"include": ans}))

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 variable name ans is not very descriptive. Renaming it to something like config_dicts would improve code clarity and make it easier for future maintainers to understand its purpose. Remember to update its usage in the print statement as well.

Suggested change
ans = [asdict(c) for c in configs]
print(json.dumps({"include": ans}))
config_dicts = [asdict(c) for c in configs]
print(json.dumps({"include": config_dicts}))

Comment on lines +179 to +181
} else if (!config.model_config.zipformer_ctc.model.empty() ||
!config.model_config.zipformer_ctc.qnn_config.context_binary
.empty()) {

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 formatting of this multi-line condition is inconsistent with the surrounding code (e.g., lines 174-175). To improve code consistency and readability, please format it to match the existing style.

    } else if (!config.model_config.zipformer_ctc.model.empty() ||
               !config.model_config.zipformer_ctc.qnn_config.context_binary.empty()) {

Comment on lines +502 to +504
} else if (!config.model_config.zipformer_ctc.model.empty() ||
!config.model_config.zipformer_ctc.qnn_config.context_binary
.empty()) {

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 formatting of this multi-line condition is inconsistent with the surrounding code (e.g., lines 497-498). To improve code consistency and readability, please format it to match the existing style.

    } else if (!config.model_config.zipformer_ctc.model.empty() ||
               !config.model_config.zipformer_ctc.qnn_config.context_binary.empty()) {

@csukuangfj
csukuangfj merged commit 16e399f into k2-fsa:master Dec 22, 2025
25 of 26 checks passed
@csukuangfj
csukuangfj deleted the zipformer-qnn-model branch December 22, 2025 10:42
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