diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000000000000000000000000000000000000..1972a0c95ea1dbdaa8d52c81bdbc78608f1aaf60 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,36 @@ +[run] +concurrency = thread,multiprocessing +omit = + /tmp/* + /home/TestData/* + /workspace/Megatron-LM/* + nemo/collections/multimodal/* + nemo/collections/multimodal_autoregressive/* + nemo/collections/vision/* + nemo/collections/diffusion/* + nemo/collections/nlp/* + + nemo/collections/asr/* + nemo/collections/speechlm/* + nemo/collections/tts/* + + # omit from audio + nemo/collections/audio/data/data_simulation.py + nemo/collections/audio/metrics/squim.py + nemo/collections/audio/losses/maxine/* + nemo/collections/audio/models/maxine/* + nemo/collections/audio/parts/utils/maxine.py + + nemo/core/* + nemo/collections/common/* + + /workspace/config-3.12.py + /workspace/config-3.py + /workspace/config.py + +[paths] +source = + nemo/ + /home/runner/work/NeMo/NeMo/nemo + /workspace/nemo + diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..14f5114d01be349d8328bcbbfab08ca0c0a9ba98 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,19 @@ +__pycache__ +*.pyc +*.pyo +*.pyd +.Python +env +pip-log.txt +pip-delete-this-directory.txt +.tox +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +*.log +.git +**/*.nemo +**/*.ckpt diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000000000000000000000000000000000000..5b6ce4b5d164c641d8a7bfdd946b7208346d96ee --- /dev/null +++ b/.flake8 @@ -0,0 +1,9 @@ +[flake8] +max-line-length = 119 +select = + F541, # f-string without any placeholders + F841, # local variable 'x' is assigned to but never used + F401, # 'x' imported but unused + E741, # ambiguous variable name 'l' + F821, # undefined name 'x' + E266, # too many leading '#' for block comment \ No newline at end of file diff --git a/.flake8.other b/.flake8.other new file mode 100644 index 0000000000000000000000000000000000000000..5b6ce4b5d164c641d8a7bfdd946b7208346d96ee --- /dev/null +++ b/.flake8.other @@ -0,0 +1,9 @@ +[flake8] +max-line-length = 119 +select = + F541, # f-string without any placeholders + F841, # local variable 'x' is assigned to but never used + F401, # 'x' imported but unused + E741, # ambiguous variable name 'l' + F821, # undefined name 'x' + E266, # too many leading '#' for block comment \ No newline at end of file diff --git a/.flake8.speech b/.flake8.speech new file mode 100644 index 0000000000000000000000000000000000000000..c12fa1100c35a01f349da1e616ab67c7c0bc80e9 --- /dev/null +++ b/.flake8.speech @@ -0,0 +1,9 @@ +[flake8] +max-line-length = 119 +select = + F541, # f-string without any placeholders + F841, # local variable 'x' is assigned to but never used + F401, # 'x' imported but unused + E741, # ambiguous variable name 'l' + F821, # undefined name 'x' + E266, # too many leading '#' for block comment diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..0c8a6462917849aa4753affa6a506e2c3c5e5eb6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ *.7z filter=lfs diff=lfs merge=lfs -text +*.ipynb filter=lfs diff=lfs merge=lfs -text *.arrow filter=lfs diff=lfs merge=lfs -text *.avro filter=lfs diff=lfs merge=lfs -text *.bin filter=lfs diff=lfs merge=lfs -text diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000000000000000000000000000000000..5aedacf07f1b8b3877a51ef392a87c04dffb97a2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,42 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** + +A clear and concise description of what the bug is. + +**Steps/Code to reproduce bug** + +Please list *minimal* steps or code snippet for us to be able to reproduce the bug. + +A helpful guide on on how to craft a minimal bug report http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports. + + +**Expected behavior** + +A clear and concise description of what you expected to happen. + +**Environment overview (please complete the following information)** + + - Environment location: [Bare-metal, Docker, Cloud(specify cloud provider - AWS, Azure, GCP, Collab)] + - Method of NeMo install: [pip install or from source]. Please specify exact commands you used to install. + - If method of install is [Docker], provide `docker pull` & `docker run` commands used + +**Environment details** + +If NVIDIA docker image is used you don't need to specify these. +Otherwise, please provide: +- OS version +- PyTorch version +- Python version + +**Additional context** + +Add any other context about the problem here. +Example: GPU model diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..99d680b0ab430eee5b7c7b49241df938840b8777 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,2 @@ +blank_issues_enabled: false + diff --git a/.github/ISSUE_TEMPLATE/dev_container_bug_report.md b/.github/ISSUE_TEMPLATE/dev_container_bug_report.md new file mode 100644 index 0000000000000000000000000000000000000000..fe81ec6252d87561407d46821d6189f0cf808e0c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/dev_container_bug_report.md @@ -0,0 +1,35 @@ +--- +container pulled on date: mm/dd/yyyy +name: Dev container - Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** + +A clear and concise description of what the bug is. + +**Steps/Code to reproduce bug** + +Please list *minimal* steps or code snippet for us to be able to reproduce the bug. + +A helpful guide on on how to craft a minimal bug report http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports. + + +**Expected behavior** + +A clear and concise description of what you expected to happen. + +**Environment overview (please complete the following information)** + + - Environment location: Docker + - Method of install: Please specify exact commands you used to install. + - If method of install is [Docker], provide `docker pull` & `docker run` commands used + +**Additional context** + +Add any other context about the problem here. +Example: GPU model diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000000000000000000000000000000..355e5539394af46c032a423a4753f3efcca68316 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,25 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: feature request +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** + +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** + +A clear and concise description of what you want to happen. +Provide a code snippet on how new APIs/changes would be used by others. + +**Describe alternatives you've considered** + +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** + +Add any other context or screenshots about the feature request here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..ca927bd24183437d129a7f8ae34c2af418e62cab --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,57 @@ +> [!IMPORTANT] +> The `Update branch` button must only be pressed in very rare occassions. +> An outdated branch is never blocking the merge of a PR. +> Please reach out to the automation team before pressing that button. + +# What does this PR do ? + +Add a one line overview of what this PR aims to accomplish. + +**Collection**: [Note which collection this PR will affect] + +# Changelog + +- Add specific line by line info of high level changes in this PR. + +# Usage + +- You can potentially add a usage example below + +```python +# Add a code snippet demonstrating how to use this +``` + +# GitHub Actions CI + +The Jenkins CI system has been replaced by GitHub Actions self-hosted runners. + +The GitHub Actions CI will run automatically when the "Run CICD" label is added to the PR. +To re-run CI remove and add the label again. +To run CI on an untrusted fork, a NeMo user with write access must first click "Approve and run". + +# Before your PR is "Ready for review" + +**Pre checks**: + +- [ ] Make sure you read and followed [Contributor guidelines](https://github.com/NVIDIA/NeMo/blob/main/CONTRIBUTING.md) +- [ ] Did you write any new necessary tests? +- [ ] Did you add or update any necessary documentation? +- [ ] Does the PR affect components that are optional to install? (Ex: Numba, Pynini, Apex etc) + - [ ] Reviewer: Does the PR have correct import guards for all optional libraries? + +**PR Type**: + +- [ ] New Feature +- [ ] Bugfix +- [ ] Documentation + +If you haven't finished some of the above items you can still open "Draft" PR. + +## Who can review? + +Anyone in the community is free to review the PR once the checks have passed. +[Contributor guidelines](https://github.com/NVIDIA/NeMo/blob/main/CONTRIBUTING.md) contains specific people who can review PRs to various areas. + +# Additional Information + +- Related to # (issue) diff --git a/.github/actions/cancel-workflow/action.yml b/.github/actions/cancel-workflow/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..6c1f85aea8d6f4fc5ee670737074376b203fba84 --- /dev/null +++ b/.github/actions/cancel-workflow/action.yml @@ -0,0 +1,25 @@ +name: Cancel Workflow +description: > + Cancels the current workflow run, i.e. all jobs. Useful if you want to cancel the rest of the workflow when one job + fails. Note that this will cause the workflow to appear cancelled, not failed. + +# Cancelling the workflow in a post-script (like this: +# https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#runspost; can also be done with +# this action: https://github.com/webiny/action-post-run, see Git history of this file) wouldn't help the status, it +# would still be cancelled. It actually indeed is, but it would be nicer to set it to failed, but there seems to be no +# way to do this. + +runs: + using: "composite" + steps: + - name: Cancel Workflow + # # Fork PRs won't have a token with write access to Actions, thus won't be able to cancel the workflow. + # if: github.event.pull_request == '' || github.event.pull_request.head.repo.fork == false + shell: bash + run: | + curl --verbose \ + -X POST \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer ${{ github.token }}" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + https://api.github.com/repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/cancel \ No newline at end of file diff --git a/.github/actions/test-template/action.yml b/.github/actions/test-template/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..9ec8ce51d1dbc3df34eef42466429a410b3eadde --- /dev/null +++ b/.github/actions/test-template/action.yml @@ -0,0 +1,231 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: "Test Template" +description: "Template for running NeMo tests in a containerized environment" + +inputs: + runner: + description: "Runner to use for test" + required: true + timeout: + description: "Max runtime of test in minutes" + required: false + default: "10" + script: + description: "Test script to execute" + required: true + after_script: + description: "Script to run after main test" + required: false + default: ":" + is_optional: + description: "Failure will cancel all other tests if set to true" + required: false + default: "false" + is_unit_test: + description: "Upload coverage as unit test" + required: false + default: "false" + tests_to_run: + description: "Tests to run" + required: false + default: '["all"]' + image: + description: "Image to use for test" + required: false + default: "nemo_container" + cpu-only: + description: "Run tests on CPU only" + required: false + default: "false" + test_dir: + description: "Directory under tests/ containing the test scripts" + required: false + default: "functional_tests" +runs: + using: "composite" + steps: + - name: Noop + shell: bash + run: | + chmod -R u+rwX ${{ github.run_id }} + echo "noop" + + - name: Docker system cleanup + shell: bash + run: | + docker system prune -af --filter "until=24h" --filter "label!=nemo.pr_number=${{ github.event.pull_request.number || 0 }}" --force || true + + - name: Docker pull image + shell: bash + run: | + docker pull nemoci.azurecr.io/${{ inputs.image }}:${{ github.run_id }} + + - name: Clean repos + shell: bash + run: | + + - name: Create UUID + id: uuid + shell: bash + run: | + echo "id=$(uuidgen)" >> "$GITHUB_OUTPUT" + + - name: Checkout NeMo + uses: actions/checkout@v6 + env: + DIR: ${{ github.run_id }} + with: + path: ${{ github.run_id }}/${{steps.uuid.outputs.id }}/NeMo + + - name: Start container + shell: bash + env: + DIR: ${{ github.run_id }} + run: | + mkdir -p $DIR + + # Map of runner names to GPU device configurations + declare -A GPU_CONFIGS=( + ["myVm-01"]="0,1" + ["myVm-02"]="2,3" + ["myVm-03"]="4,5" + ["myVm-04"]="6,7" + ) + + ARG=("") + if [[ "${{ inputs.cpu-only }}" == "false" ]]; then + ARG=("--runtime=nvidia --gpus all") + fi + + cmd=$(cat <&1 | tee $DIR/err.log + + RUN_TEST_EOF + ) + + echo "timeout_in_seconds=$(( ${{ inputs.timeout }} * 60 ))" | tee -a "$GITHUB_OUTPUT" + echo "$cmd" | tee "$DIR/job.sh" + + - name: Run main script + uses: nick-fields/retry@v3 + with: + timeout_seconds: ${{ steps.create.outputs.timeout_in_seconds }} + max_attempts: 3 + shell: bash + retry_on: timeout + command: /bin/bash ${{ github.run_id }}/job.sh + on_retry_command: /bin/bash ${{ github.run_id }}/retry_job.sh + + - name: Check result + id: check + shell: bash + env: + DIR: ${{ github.run_id }} + run: | + cat $DIR/err.log + + log=$(tail -c 2000 $DIR/err.log | base64 -w 0) + echo "log=$log" >> "$GITHUB_OUTPUT" + + potential_infra_failure=$(cat $DIR/err.log | grep -Eqiw "device" && echo true || echo false) + echo "potential_infra_failure=$potential_infra_failure" >> "$GITHUB_OUTPUT" + + docker exec nemo_container_${{ github.run_id }}_${{ inputs.runner }} coverage combine + docker exec nemo_container_${{ github.run_id }}_${{ inputs.runner }} coverage xml + docker cp nemo_container_${{ github.run_id }}_${{ inputs.runner }}:/workspace/.coverage $DIR/.coverage + docker cp nemo_container_${{ github.run_id }}_${{ inputs.runner }}:/workspace/coverage.xml $DIR/coverage.xml + + coverage_report=coverage-${{ steps.create.outputs.coverage-prefix }}-${{ github.run_id }}-$(uuidgen) + echo "coverage_report=$coverage_report" >> "$GITHUB_OUTPUT" + + IS_SUCCESS=$(tail -n 1 $DIR/err.log | grep -q "Finished successfully." && echo "true" || echo "false") + + if [[ "$IS_SUCCESS" == "false" && "${{ inputs.is_optional }}" == "true" ]]; then + echo "::warning:: Test failed, but displayed as successful because it is marked as optional." + IS_SUCCESS=true + fi + + if [[ "$IS_SUCCESS" == "false" ]]; then + echo Test did not finish successfully. + exit 1 + fi + + exit $EXIT_CODE + + - name: Test coverage + shell: bash -x -e -u -o pipefail {0} + run: | + docker exec -t nemo_container_${{ github.run_id }}_${{ inputs.runner }} coverage report -i + + - name: Upload artifacts + uses: actions/upload-artifact@v6 + if: ${{ steps.check.outputs.coverage_report != 'none' }} + with: + name: ${{ steps.check.outputs.coverage_report }} + path: | + ${{ github.run_id }}/coverage.xml + ${{ github.run_id }}/.coverage + include-hidden-files: true + + - name: Container shutdown + if: always() + shell: bash + run: | + docker exec nemo_container_${{ github.run_id }}_${{ inputs.runner }} bash -c "chown -R $(id -u):$(id -g) /workspace" + rm -rf $(pwd)/${{ github.run_id }}/${{steps.uuid.outputs.id }} || true + docker container rm -f nemo_container_${{ github.run_id }}_${{ inputs.runner }} || true diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 0000000000000000000000000000000000000000..853589525d049b9c40a18dcb56fe220ac5539d39 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,41 @@ +ASR: +- nemo/collections/asr/**/* +- examples/asr/**/* +- tutorials/asr/**/* +- docs/source/asr/**/* +- tests/collections/asr/** + +Speaker Tasks: +- examples/speaker_tasks/**/* +- tutorials/speaker_tasks/**/* + +TTS: +- nemo/collections/tts/**/* +- nemo/collections/common/tokenizers/text_to_speech/** +- examples/tts/**/* +- tutorials/tts/**/* +- docs/source/tts/**/* +- scripts/dataset_processing/tts/** +- scripts/tts_dataset_files/** +- tests/collections/tts/** +- tests/collections/common/tokenizers/text_to_speech/** + +Audio: +- nemo/collections/audio/**/* +- examples/audio/**/* +- tutorials/audio/**/* +- docs/source/audio/**/* +- tests/collections/audio/** + +core: +- nemo/core/**/* +- tests/core/** + +common: +- nemo/collections/common/**/* + +CI: +- .github/**/* +- Jenkinsfile +- Dockerfile +- ci.groovy diff --git a/.github/scripts/__init__.py b/.github/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.github/scripts/notify.py b/.github/scripts/notify.py new file mode 100644 index 0000000000000000000000000000000000000000..233313a735b90430ee5d4823bf849801470bbc1f --- /dev/null +++ b/.github/scripts/notify.py @@ -0,0 +1,79 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os + +import requests +from github import Github + + +def send_slack_notification(): + # Get environment variables + gh_token = os.environ.get('GH_TOKEN') + webhook_url = os.environ.get('SLACK_WEBHOOK') + repository = os.environ.get('REPOSITORY') + run_id = os.environ.get('RUN_ID') + server_url = os.environ.get('SERVER_URL', 'https://github.com') + pr_number = int(os.environ.get('PR_NUMBER', 0)) + branch_name = os.environ.get('BRANCH_NAME') + + # Get failure info from GitHub API + gh = Github(gh_token) + repo = gh.get_repo(repository) + + # Get failed jobs + failed_jobs = [job.name for job in repo.get_workflow_run(int(run_id)).jobs() if job.conclusion == 'failure'] + + if pr_number != 0: + pr = repo.get_pull(pr_number) + + title = f"*<{server_url}/{repository}/pull/{pr_number}|PR#{pr_number}>: {pr.title.replace('`', '')}*" + author = f"<{server_url}/{pr.user.login}|{pr.user.login}>" + branch = f"<{server_url}/{pr.head.repo.full_name}/tree/{pr.head.ref}|{pr.head.ref}>" + else: + title = f"*Run on <{server_url}/{repository}/tree/{branch_name}|{branch_name}>*" + author = "No author" + branch = f"<{server_url}/{repository}/tree/{branch_name}|{branch_name}>" + + blocks = [ + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": ( + f"{title}\n" + f"• Author: {author}\n" + f"• Branch: {branch}\n" + f"• Pipeline: <{server_url}/{repository}/actions/runs/{run_id}|View Run>\n" + f"• Failed Jobs:\n" + + "\n".join( + [ + f" • <{server_url}/{repository}/actions/runs/{run_id}|{job.split('/')[-1]}>" + for job in failed_jobs + if job.split('/')[-1] != 'Nemo_CICD_Test' + ] + ) + ), + }, + } + ] + + print({"blocks": blocks}) + + # Send to Slack + response = requests.post(webhook_url, json={"blocks": blocks}) + response.raise_for_status() + + +if __name__ == "__main__": + send_slack_notification() diff --git a/.github/workflows/_build_container.yml b/.github/workflows/_build_container.yml new file mode 100644 index 0000000000000000000000000000000000000000..5d877fe59028612030e5e0b8788a87f05ce6297b --- /dev/null +++ b/.github/workflows/_build_container.yml @@ -0,0 +1,89 @@ +name: ~Build container template +on: + workflow_call: + inputs: + image-name: + required: true + type: string + description: "The name of the image to build" + dockerfile: + required: true + type: string + runner: + required: false + default: self-hosted-azure-builder + type: string + description: "The runner to use for the build" + +jobs: + pre-flight: + runs-on: ubuntu-latest + outputs: + build_args: ${{ steps.manifest.outputs.BUILD_ARGS }} + cache-from: ${{ steps.cache_from.outputs.LAST_PRS }} + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Parse manifest.json + id: manifest + run: | + BUILD_ARGS=$(cat << EOF + BASE_IMAGE=$(cat requirements/manifest.json | jq -r '."ngc-pytorch"') + TRTLLM_REPO=$(cat requirements/manifest.json | jq -r '."vcs-dependencies"."trt-llm".repo') + TRTLLM_TAG=$(cat requirements/manifest.json | jq -r '."vcs-dependencies"."trt-llm".ref') + MLM_REPO=$(cat requirements/manifest.json | jq -r '."vcs-dependencies"."megatron-lm".repo') + MLM_TAG=$(cat requirements/manifest.json | jq -r '."vcs-dependencies"."megatron-lm".ref') + TE_REPO=$(cat requirements/manifest.json | jq -r '."vcs-dependencies".transformer_engine.repo') + TE_TAG=$(cat requirements/manifest.json | jq -r '."vcs-dependencies".transformer_engine.ref') + APEX_REPO=$(cat requirements/manifest.json | jq -r '."vcs-dependencies".apex.repo') + APEX_TAG=$(cat requirements/manifest.json | jq -r '."vcs-dependencies".apex.ref') + EOF + ) + + echo "BUILD_ARGS<> $GITHUB_OUTPUT + echo "$BUILD_ARGS" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + - name: Get last merged PR + id: cache_from + env: + GH_TOKEN: ${{ github.token }} + run: | + LAST_PRS=$(gh api graphql -f query=' + query { + repository(owner: "NVIDIA", name: "NeMo") { + pullRequests(states: MERGED, first: 100, orderBy: {field: UPDATED_AT, direction: DESC}) { + nodes { + number + } + } + } + }' | jq -r '.data.repository.pullRequests.nodes[].number' | while read -r number; do + echo "nemoci.azurecr.io/${{ inputs.image-name }}-buildcache:$number" + done) + + echo "LAST_PRS<> $GITHUB_OUTPUT + echo "$LAST_PRS" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + build: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_build_container.yml@v0.27.0 + needs: [pre-flight] + with: + image-name: ${{ inputs.image-name }} + dockerfile: ${{ inputs.dockerfile }} + image-label: nemo-core + build-args: | + IMAGE_LABEL=nemo-core + NEMO_TAG=${{ github.sha }} + NEMO_REPO=https://github.com/NVIDIA/NeMo + PR_NUMBER=${{ github.event.pull_request.number || 0 }} + ${{ needs.pre-flight.outputs.build_args }} + prune-filter-timerange: 24h + use-inline-cache: false + cache-from: | + nemoci.azurecr.io/${{ inputs.image-name }}-buildcache:main + nemoci.azurecr.io/${{ inputs.image-name }}-buildcache:${{ github.event.pull_request.number || 0 }} + ${{ needs.pre-flight.outputs.cache-from }} + runner: ${{ inputs.runner }} diff --git a/.github/workflows/_bump_mcore_tag.yml b/.github/workflows/_bump_mcore_tag.yml new file mode 100644 index 0000000000000000000000000000000000000000..56e316f933b9324368b1092fd3c6d04ad0ae8fbb --- /dev/null +++ b/.github/workflows/_bump_mcore_tag.yml @@ -0,0 +1,56 @@ +name: ~Bump Megatron Tag template +on: + workflow_call: + inputs: + nemo-target-branch: + required: true + type: string + description: "The target branch to bump" + mcore-target-branch: + required: true + type: string + description: "The target branch to bump" + secrets: + PAT: + required: true + +jobs: + update-branch: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ inputs.nemo-target-branch }} + + - name: Set Git config + run: | + git config --local user.email "actions@github.com" + git config --local user.name "Github Actions" + - name: Merge weekly-bump-${{ inputs.nemo-target-branch }} back to base branch + env: + SOURCE_BRANCH: weekly-bump-${{ inputs.nemo-target-branch }} + TARGET_BRANCH: ${{ inputs.nemo-target-branch }} + run: | + if git ls-remote --exit-code origin $SOURCE_BRANCH; then + git fetch --unshallow + git checkout $SOURCE_BRANCH + git pull + git merge --no-ff $TARGET_BRANCH -m "chore: Auto-merge $TARGET_BRANCH into $SOURCE_BRANCH" + else + git checkout -b $SOURCE_BRANCH $TARGET_BRANCH + fi + git push -u origin $SOURCE_BRANCH + + mcore: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_bump_yamlfile.yml@v0.27.1 + needs: [update-branch] + with: + source-repository: NVIDIA/Megatron-LM + source-ref: ${{ inputs.mcore-target-branch }} + yaml-path: '."vcs-dependencies"."megatron-lm".ref' + file: requirements/manifest.json + base-branch: weekly-bump-${{ inputs.nemo-target-branch }} + cicd-labels: Run CICD,no-fail-fast + pr-reviewers: ${{ inputs.pr-reviewers }} + secrets: + PAT: ${{ secrets.PAT }} diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml new file mode 100644 index 0000000000000000000000000000000000000000..af7419d6945dfffff0dc0a5f3329c3c4513bc65d --- /dev/null +++ b/.github/workflows/build-docs.yml @@ -0,0 +1,76 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Build docs + +on: + pull_request: + branches: + - main + - r** + paths: + - "docs/**" + push: + branches: + - main + - r** + paths: + - "docs/**" + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ github.event.label.name || 'main' }}-${{ github.event_name }} + cancel-in-progress: true + +jobs: + pre-flight: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_cicd_preflight.yml@v0.74.0 + + build-docs: + needs: [pre-flight] + if: needs.pre-flight.outputs.is_deployment_workflow != 'true' + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_build_docs.yml@v0.83.0 + with: + docs-directory: docs/source + sync-all: true + no-extras: "--no-extra cu12" + + build-docs-summary: + needs: [pre-flight, build-docs] + if: | + ( + needs.pre-flight.outputs.is_deployment_workflow == 'true' + || always() + ) + && !cancelled() + runs-on: ubuntu-latest + steps: + - name: Get workflow result + id: result + shell: bash -x -e -u -o pipefail {0} + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ github.run_id }} + SKIPPING_IS_ALLOWED: ${{ needs.pre-flight.outputs.docs_only == 'true' || needs.pre-flight.outputs.is_deployment_workflow == 'true' }} + run: | + FAILED_JOBS=$(gh run view $GITHUB_RUN_ID --json jobs --jq '[.jobs[] | select(.status == "completed" and .conclusion != "success")] | length') || echo 0 + + if [ "${FAILED_JOBS:-0}" -eq 0 ] || [ "$SKIPPING_IS_ALLOWED" == "true" ]; then + echo "✅ All previous jobs completed successfully" + exit 0 + else + echo "❌ Found $FAILED_JOBS failed job(s)" + # Show which jobs failed + gh run view $GITHUB_RUN_ID --json jobs --jq '.jobs[] | select(.status == "completed" and .conclusion != "success") | .name' + exit 1 + fi diff --git a/.github/workflows/build-test-publish-wheel.yml b/.github/workflows/build-test-publish-wheel.yml new file mode 100644 index 0000000000000000000000000000000000000000..29f8be8c1e10fa2e211b0511aaa09dbe3468a35f --- /dev/null +++ b/.github/workflows/build-test-publish-wheel.yml @@ -0,0 +1,38 @@ +# Copyright (c) 2020-2021, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Build, test, and publish a PyPi wheel (to testpypi). + +on: + push: + branches: + - main + - "r**" + +defaults: + run: + shell: bash -x -e -u -o pipefail {0} + +jobs: + build-test-publish-wheel: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_build_test_publish_wheel.yml@v0.22.3 + with: + dry-run: true + python-package: nemo + python-version: "3.10" + secrets: + TWINE_USERNAME: ${{ secrets.TWINE_USERNAME }} + TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD }} + SLACK_WEBHOOK: ${{ secrets.SLACK_RELEASE_ENDPOINT }} + SLACK_WEBHOOK_ADMIN: ${{ secrets.SLACK_WEBHOOK_ADMIN }} diff --git a/.github/workflows/cherry-pick-release-commit.yml b/.github/workflows/cherry-pick-release-commit.yml new file mode 100644 index 0000000000000000000000000000000000000000..32f06df504ea2059f5c313a9310de05b6b35e87f --- /dev/null +++ b/.github/workflows/cherry-pick-release-commit.yml @@ -0,0 +1,14 @@ +name: Create PR to main with cherry-pick from release + +on: + push: + branches: + - main + +jobs: + cherry-pick: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_cherry_pick.yml@v0.63.0 + secrets: + PAT: ${{ secrets.PAT }} + SLACK_WEBHOOK_ADMIN: ${{ secrets.SLACK_WEBHOOK_ADMIN }} + SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }} diff --git a/.github/workflows/cicd-approve-test-queue.yml b/.github/workflows/cicd-approve-test-queue.yml new file mode 100644 index 0000000000000000000000000000000000000000..608005072b5d7a04d0e2963884fcc28e162cd9fe --- /dev/null +++ b/.github/workflows/cicd-approve-test-queue.yml @@ -0,0 +1,175 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Approve Test Queue + +on: + schedule: + - cron: '*/5 * * * *' # Runs every 5 minutes + workflow_dispatch: # Allows manual triggering + +jobs: + approve-queue: + runs-on: ubuntu-latest + environment: main + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install requests + + - name: Approve waiting deployments + env: + GITHUB_TOKEN: ${{ secrets.PAT }} + MAX_CONCURRENCY: ${{ vars.MAX_CONCURRENCY || 1 }} + run: | + python - <= MAX_CONCURRENCY: + print("Maximum concurrency reached, no new approvals will be made") + exit(0) + + # Get waiting CI workflows for test environment + print("Fetching deployments...") + pending_workflows = get_workflow_runs("waiting") + pending_workflows = [run for run in pending_workflows if run["name"] == "CICD NeMo"] + + # Sort deployments by creation date (oldest first) + print("Sorting workflows...") + pending_workflows = sorted(pending_workflows, key=lambda x: x["created_at"]) + + # Process each deployment + print("Processing ...") + for workflow in pending_workflows: + if total_workflows >= MAX_CONCURRENCY: + print("Maximum concurrency reached, stopping approvals") + break + + workflow_id = workflow["id"] + workflow_name = workflow["display_title"] + print(f"Approving workflow {workflow_name} with Run Id: {workflow_id}") + + deployment_url = f"actions/runs/{workflow_id}/pending_deployments" + deployment = make_request(deployment_url)[0] + environment_id = deployment["environment"]["id"] + + # Approve the deployment + status_data = { + "environment_ids": [environment_id], + "state": "approved", + "comment": "Automatically approved by queue manager" + } + result = make_request(deployment_url, method="POST", data=status_data) + + if result: + total_workflows += 1 + else: + print(f"Failed to approve deployment {deployment['id']}") + exit(1) + + EOF + notify: + if: failure() + runs-on: ubuntu-latest + needs: [approve-queue] + steps: + - name: Notify + env: + SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }} + SLACK_WEBHOOK_ADMIN: + GITHUB_RUN_ID: ${{ github.run_id }} + GITHUB_REPOSITORY: ${{ github.repository }} + run: | + curl -X POST \ + -H 'Content-type: application/json' \ + --data "{\"text\":\":robot_joy: failed. Please review manually.\n\ncc ${SLACK_WEBHOOK_ADMIN}\"}" \ + $SLACK_WEBHOOK diff --git a/.github/workflows/cicd-main-speech.yml b/.github/workflows/cicd-main-speech.yml new file mode 100644 index 0000000000000000000000000000000000000000..14892065d126c475fd912025cde52ffbdccdddfa --- /dev/null +++ b/.github/workflows/cicd-main-speech.yml @@ -0,0 +1,483 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: NeMo E2E Speech Tests +on: + workflow_call: + inputs: + test_to_run: + required: true + type: string + image-name: + required: false + default: nemo_container_speech + type: string + +jobs: + build: + uses: ./.github/workflows/_build_container.yml + with: + image-name: ${{ inputs.image-name }} + dockerfile: docker/Dockerfile.ci + + unit-tests: + strategy: + fail-fast: false + matrix: + include: + - script: L0_Unit_Tests_GPU_ASR + runner: self-hosted-azure-gpus-1 + timeout: 30 + - script: L0_Unit_Tests_CPU_ASR + runner: azure-gpu-vm-runner1-cpu + cpu-only: true + timeout: 30 + - script: L0_Unit_Tests_GPU_TTS + runner: self-hosted-azure-gpus-1 + - script: L0_Unit_Tests_CPU_TTS + runner: self-hosted-azure-cpu + cpu-only: true + - script: L0_Unit_Tests_GPU_Audio + runner: self-hosted-azure-gpus-1 + - script: L0_Unit_Tests_CPU_Audio + runner: self-hosted-azure-cpu + cpu-only: true + - script: L0_Unit_Tests_GPU_SpeechLM2 + runner: self-hosted-azure-gpus-1 + timeout: 20 + - script: L0_Unit_Tests_CPU_SpeechLM2 + runner: self-hosted-azure-cpu + cpu-only: true + timeout: 20 + needs: [build] + runs-on: ${{ matrix.runner }} + name: ${{ matrix.script }} + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + path: ${{ github.run_id }} + - name: main + uses: NVIDIA/NeMo/.github/actions/test-template@main + with: + runner: ${{ runner.name }} + script: ${{ matrix.script }} + is_unit_test: true + tests_to_run: ${{ inputs.test_to_run }} + image: ${{ inputs.image-name }} + timeout: ${{ matrix.timeout || 10 }} + cpu-only: ${{ matrix.cpu-only || false }} + is_optional: ${{ matrix.is-optional || false }} + + e2e-tests: + strategy: + fail-fast: false + matrix: + include: + - runner: self-hosted-azure-gpus-1 + script: ASR_dev_run_Speech_to_Text + - runner: self-hosted-azure-gpus-1 + script: Optional_ASR_dev_run_Speech_To_Text_Finetuning + is-optional: true + - runner: self-hosted-azure-gpus-1 + script: Optional_ASR_dev_run_Speech_To_Text_HF_Finetuning + is-optional: true + - runner: self-hosted-azure-gpus-1 + script: ASR_dev_run_Speech_to_Text_WPE_-_Conformer + - runner: self-hosted-azure-gpus-1 + script: ASR_dev_run_Speech_to_Text_Hybrid_RNNT_CTC_Prompt + - runner: self-hosted-azure-gpus-1 + script: L2_ASR_Multi-dataloader_dev_run_Speech_to_Text_multi-dataloader + - runner: self-hosted-azure-gpus-1 + script: L2_ASR_Multi-dataloader_dev_run_Speech_to_Label_multi-dataloader + - runner: self-hosted-azure-gpus-1 + script: L2_ASR_Adapters_Linear_Adapters + - runner: self-hosted-azure-gpus-1 + script: L2_ASR_Adapters_RelPos_MHA_Adapters + - runner: self-hosted-azure + script: L2_Speech_to_Text_EMA + - runner: self-hosted-azure-gpus-1 + script: L2_Speech_to_Text_AED + - runner: self-hosted-azure-gpus-1 + script: L2_Speaker_dev_run_Speech_to_Label + - runner: self-hosted-azure + script: L2_Speech_Estimate_Duration_Bins + - runner: self-hosted-azure + script: L2_Speech_Batch_Size_OOMptimizer + - runner: self-hosted-azure + script: Optional_L2_Speech_Batch_Size_OOMptimizer_Canary + is-optional: true + - runner: self-hosted-azure + script: L2_Speech_Transcription_Speech_to_Text_Transcribe + - runner: self-hosted-azure + script: L2_Speech_Transcription_Speech_to_Text_Streaming_Infer + - runner: self-hosted-azure + script: L2_Speech_Transcription_Speech_to_Text_Cache_Aware_Infer + - runner: self-hosted-azure + script: L2_Speech_Transcription_Streaming_Inference + - runner: self-hosted-azure + script: L2_Speech_Transcription_Speech_to_Text_Inference_Boost_GT + - runner: self-hosted-azure + script: L2_Speech_Transcription_Speech_to_Text_Transcribe_Boost_GT + - runner: self-hosted-azure + script: L2_Speech_Transcription_Canary_Transcribe_Full_Manifest + - runner: self-hosted-azure + script: L2_Speech_Transcription_Canary_Transcribe_With_Prompt + - runner: self-hosted-azure + script: L2_Speech_Transcription_Canary_Transcribe_Audio_Dir + - runner: self-hosted-azure + script: L2_Speech_Transcription_Canary_Streaming_Full_Manifest + - runner: self-hosted-azure + script: L2_Longform_Speech_Transcription_Canary_Chunked_Infer_from_Audio_Dir + - runner: self-hosted-azure + script: L2_Longform_Speech_Transcription_with_TimeStamps_Canary_Chunked_Infer_from_Audio_Dir + - runner: self-hosted-azure + script: L2_Longform_Speech_Transcription_with_TimeStamps_Canary_Chunked_Infer_from_Manifest + - runner: self-hosted-azure-gpus-1 + script: Speech_Checkpoints_tests + timeout: 20 + - runner: self-hosted-azure-gpus-1 + script: L2_Speaker_dev_run_Speaker_Recognition + - runner: self-hosted-azure-gpus-1 + script: L2_Speaker_dev_run_EndtoEnd_Speaker_Diarization_Sortformer + - runner: self-hosted-azure + script: L2_Speaker_dev_run_EndtoEnd_Diarizer_Inference + - runner: self-hosted-azure + script: L2_Speaker_dev_run_Speaker_Diarization_with_ASR_Inference + - runner: self-hosted-azure + script: L2_Speaker_dev_run_Clustering_Diarizer_Inference + - runner: self-hosted-azure + script: L2_Speaker_dev_run_Multispeaker_ASR_Data_Simulation + - runner: self-hosted-azure + script: L2_TTS_Fast_dev_runs_1_FastPitch + - runner: self-hosted-azure + script: L2_TTS_Fast_dev_runs_1_Hifigan + - runner: self-hosted-azure + script: L2_G2P_Models_G2P_Conformer_training_evaluation_and_inference + - runner: self-hosted-azure + script: SPEECHLM_HF_Training_DuplexS2S + - runner: self-hosted-azure + script: SPEECHLM_HF_Training_DuplexS2SSpeechDecoder + - runner: self-hosted-azure + script: SPEECHLM_HF_Training_SALM + timeout: 20 + - runner: self-hosted-azure + script: L2_TTS_Fast_dev_runs_Magpietts_DecoderContext + - runner: self-hosted-azure + script: L2_TTS_Fast_dev_runs_Magpietts_MultiEncoder + - runner: self-hosted-azure + script: L2_TTS_Fast_dev_runs_Magpietts_MoE + - runner: self-hosted-azure + script: L2_TTS_Fast_dev_runs_Magpietts_OnlinePO + - runner: self-hosted-azure + script: L2_TTS_InferEvaluate_Magpietts_ZeroShot + - runner: self-hosted-azure + script: L2_TTS_InferEvaluate_Magpietts_SeenSpeakers + - runner: self-hosted-azure + script: L2_TTS_InferEvaluatelongform_Magpietts_ZeroShot + - runner: self-hosted-azure + script: L2_TTS_InferEvaluate_Magpietts_MoE_ZeroShot + - runner: self-hosted-azure + script: L2_TTS_InferEvaluatelongform_Magpietts_MoE_ZeroShot + - runner: self-hosted-azure + script: L2_TTS_InferEvaluate_Magpietts_FrameStacking + - runner: self-hosted-azure + script: L2_TTS_Fast_dev_runs_EasyMagpietts_Qwen + - runner: self-hosted-azure + script: L2_TTS_Fast_dev_runs_EasyMagpietts_Nemotron + - runner: self-hosted-azure + script: L2_TTS_Fast_dev_runs_EasyMagpietts_OnlinePO + timeout: 20 + - runner: self-hosted-azure + script: L2_TTS_InferEvaluate_EasyMagpietts + needs: [unit-tests] + runs-on: ${{ matrix.runner }} + name: ${{ matrix.is-optional && 'PLEASEFIXME_' || '' }}${{ matrix.script }} + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + path: ${{ github.run_id }} + - name: main + uses: NVIDIA/NeMo/.github/actions/test-template@main + with: + runner: ${{ runner.name }} + script: ${{ matrix.script }} + tests_to_run: ${{ inputs.test_to_run }} + image: ${{ inputs.image-name }} + timeout: ${{ matrix.timeout || 10 }} + is_optional: ${{ matrix.is-optional || false }} + + e2e-nightly: + if: ${{ github.event_name == 'schedule' || contains(github.event.pull_request.labels.*.name, 'Run e2e nightly') }} + strategy: + fail-fast: false + matrix: + include: + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_de_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_es_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_it_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_ua_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_pl_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_hr_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_be_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_fr_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_ru_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_nl_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_fa_fastconformer_hybrid_large + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_ka_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_kk_ru_fastconformer_hybrid_large + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_ka_fastconformer_hybrid_transducer_ctc_large_streaming_80ms_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_uz_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_ar_fastconformer_hybrid_large_pc_v1_0 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_hy_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_hybrid_medium_streaming_80ms_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_hybrid_medium_streaming_80ms + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_pt_fastconformer_hybrid_large_pc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_es_fastconformer_hybrid_large_pc_nc + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_ar_fastconformer_hybrid_large_pcd_v1_0 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_hybrid_large_streaming_multi + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_ctc_large + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_transducer_large + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_ctc_xlarge + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_transducer_xlarge + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_transducer_xxlarge + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_ctc_xxlarge + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__stt_en_fastconformer_tdt_large + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_stt_en_fastconformer_hybrid_large_streaming_1040ms + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_stt_multilingual_fastconformer_hybrid_large_pc_blend_eu + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_rnnt_1_1b + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_ctc_1_1b + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_rnnt_0_6b + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_ctc_0_6b + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_tdt_1_1b + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_tdt_ctc_1_1b + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_tdt_ctc_0_6b_ja + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_tdt_ctc_110m + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_tdt_0_6b_v2 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_rnnt_110m_da_dk + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_tdt_0_6b_v3 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_ctc_0_6b_Vietnamese + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__canary_1b + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__canary_1b_flash + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__canary_180m_flash + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__canary_1b_v2 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__parakeet_realtime_eou_120m_v1 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__multitalker_parakeet_streaming_0_6b_v1 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__nemotron_speech_streaming_en_0_6b + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__canary_qwen_2_5b + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__diar_sortformer_4spk_v1 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__diar_streaming_sortformer_4spk_v2 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__diar_streaming_sortformer_4spk_v2_1 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_titanet_large + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__speakerverification_en_titanet_large + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__ssl_en_nest_large_v1_0 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__ssl_en_nest_xlarge_v1_0 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_vad_multilingual_marblenet + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_vad_multilingual_frame_marblenet + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__Frame_VAD_Multilingual_MarbleNet_v2_0 + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__se_den_sb_16k_small + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__se_der_sb_16k_small + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__sr_ssl_flowmatching_16k_430m + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_mel_codec_44khz_medium + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_mel_codec_22khz_fullband_medium + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__low_frame_rate_speech_codec_22khz + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__audio_codec_22khz + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__audio_codec_44khz + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__mel_codec_22khz + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__mel_codec_44khz + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__nemo_nano_codec_22khz_1_78kbps_12_5fps + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__nemo_nano_codec_22khz_1_89kbps_21_5fps + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__nemo_nano_codec_22khz_0_6kbps_12_5fps + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__tts_en_fastpitch + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__tts_hifigan + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_nvidia__magpie_tts_multilingual_357m + timeout: 15 + - runner: self-hosted-azure + script: L2_Model_Support_tts_en_e2e_fastspeech2hifigan + timeout: 15 + needs: [unit-tests] + runs-on: ${{ matrix.runner }} + name: ${{ matrix.script }} + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + path: ${{ github.run_id }} + - name: main + uses: NVIDIA/NeMo/.github/actions/test-template@main + with: + runner: ${{ runner.name }} + script: ${{ matrix.script }} + tests_to_run: ${{ inputs.test_to_run }} + image: ${{ inputs.image-name }} + timeout: ${{ matrix.timeout || 10 }} + test_dir: e2e_nightly diff --git a/.github/workflows/cicd-main-unit-tests.yml b/.github/workflows/cicd-main-unit-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..e15ec06e17b3348d6cbe14a51b26492132ea00d0 --- /dev/null +++ b/.github/workflows/cicd-main-unit-tests.yml @@ -0,0 +1,105 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: NeMo Unit Tests +on: + workflow_call: + inputs: + test_to_run: + required: true + type: string + +jobs: + collections-common-tests: + strategy: + fail-fast: false + matrix: + include: + - script: L0_Unit_Tests_GPU_Common + runner: self-hosted-azure-gpus-1 + - script: L0_Unit_Tests_CPU_Common + runner: self-hosted-azure-cpu + cpu-only: true + runs-on: ${{ matrix.runner }} + name: ${{ matrix.script }} + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + path: ${{ github.run_id }} + - name: main + uses: NVIDIA/NeMo/.github/actions/test-template@main + with: + runner: ${{ runner.name }} + script: ${{ matrix.script }} + is_unit_test: true + tests_to_run: ${{ inputs.test_to_run }} + cpu-only: ${{ matrix.cpu-only || false }} + + core-tests: + strategy: + fail-fast: false + matrix: + include: + - script: L0_Unit_Tests_GPU_Core + runner: self-hosted-azure-gpus-1 + - script: L0_Unit_Tests_CPU_Core + runner: self-hosted-azure-cpu + cpu-only: true + - script: L0_Unit_Tests_GPU_Hydra + runner: self-hosted-azure-gpus-1 + - script: L0_Unit_Tests_CPU_Hydra + runner: self-hosted-azure-cpu + cpu-only: true + runs-on: ${{ matrix.runner }} + name: ${{ matrix.script }} + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + path: ${{ github.run_id }} + - name: main + uses: NVIDIA/NeMo/.github/actions/test-template@main + with: + runner: ${{ runner.name }} + script: ${{ matrix.script }} + is_unit_test: true + tests_to_run: ${{ inputs.test_to_run }} + cpu-only: ${{ matrix.cpu-only || false }} + + other-tests: + strategy: + fail-fast: false + matrix: + include: + - script: L0_Unit_Tests_GPU_Others + runner: self-hosted-azure-gpus-1 + - script: L0_Unit_Tests_CPU_Others + runner: self-hosted-azure-cpu + cpu-only: true + runs-on: ${{ matrix.runner }} + name: ${{ matrix.script }} + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + path: ${{ github.run_id }} + - name: main + uses: NVIDIA/NeMo/.github/actions/test-template@main + with: + runner: ${{ runner.name }} + script: ${{ matrix.script }} + is_unit_test: true + tests_to_run: ${{ inputs.test_to_run }} + cpu-only: ${{ matrix.cpu-only || false }} + is_optional: ${{ matrix.is-optional || false }} diff --git a/.github/workflows/cicd-main.yml b/.github/workflows/cicd-main.yml new file mode 100644 index 0000000000000000000000000000000000000000..2e860621e523b93f66164b73e22710b6342a3929 --- /dev/null +++ b/.github/workflows/cicd-main.yml @@ -0,0 +1,395 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: CICD NeMo +on: + schedule: + - cron: 0 0 * * * + pull_request: + branches: + - main + - r** + - weekly-bump* + types: [labeled] + workflow_dispatch: + inputs: + test_to_run: + required: false + default: all + type: string + description: Comma-separated list of tests to run. Use "all" to run the full test suite. + +concurrency: + # group: ${{ github.workflow }}-${{ github.ref == 'refs/heads/main' && github.run_id || github.event.pull_request.number || github.ref }}-${{ github.event_name }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ github.event.label.name || 'main' }}-${{ github.event_name }} + cancel-in-progress: true + +jobs: + pre-flight: + runs-on: ubuntu-latest + outputs: + test_to_run: ${{ steps.test_to_run.outputs.main }} + is_ci_workload: ${{ steps.is_ci_workload.outputs.main }} + no_fail_fast: ${{ steps.no_fail_fast.outputs.main }} + components_to_run: ${{ steps.components_to_run.outputs.main }} + env: + TESTS_TO_RUN: ${{ inputs.test_to_run }} + EVENT_NAME: ${{ github.event_name }} + HAS_LABEL: ${{ github.event.label.name == 'Run CICD' }} + steps: + - name: Checkout branch + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Select components to run + id: components_to_run + run: | + echo "main=[\"speech\"]" | tee -a "$GITHUB_OUTPUT" + + - name: Select tests to run + id: test_to_run + run: | + # For manual dispatch, we replace `all` with the actual job names + if [[ "$EVENT_NAME" == "workflow_dispatch" ]]; then + TESTS_TO_RUN=$TESTS_TO_RUN + + # For correctly labeled PR, we replace `all` with the actual job names + elif [[ "$EVENT_NAME" == "pull_request" && "$HAS_LABEL" == "true" ]]; then + TESTS_TO_RUN=all + + # For incorrectly labeled PR, run no tests + elif [[ "$EVENT_NAME" == "pull_request" && "$HAS_LABEL" != "true" ]]; then + TESTS_TO_RUN="" + + # For push events, run all tests. This is so that we can generate coverage + # on branch `main`. + elif [[ "$EVENT_NAME" == "push" || "$EVENT_NAME" == "schedule" ]]; then + TESTS_TO_RUN=all + + else + echo "Unsupported event_name $EVENT_NAME provided". + exit 1 + fi + + parsed_string=$(echo "$TESTS_TO_RUN" | jq -c --raw-input 'split(",")') + echo "main=${parsed_string}" | tee -a "$GITHUB_OUTPUT" + + - name: Check if this is a CI workload + shell: bash + id: is_ci_workload + run: | + branch_name=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}} + + if [[ "$branch_name" =~ ^bump-ci-container || "$EVENT_NAME" == "schedule" ]]; then + is_ci_workload=true + echo "main=true" | tee -a "$GITHUB_OUTPUT" + else + is_ci_workload=false + fi + + echo "main=$is_ci_workload" | tee -a "$GITHUB_OUTPUT" + + - name: Check if no-fail-fast is set + shell: bash + id: no_fail_fast + env: + HAS_FAIL_FAST_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'no-fail-fast') }} + run: | + if [[ "$HAS_FAIL_FAST_LABEL" == "true" || "$EVENT_NAME" == "schedule" ]]; then + no_fail_fast=true + else + no_fail_fast=false + fi + + echo "main=$no_fail_fast" | tee -a "$GITHUB_OUTPUT" + + code-linting: + if: needs.pre-flight.outputs.test_to_run != '[]' + needs: [pre-flight] + uses: ./.github/workflows/code-linting.yml + + cicd-wait-in-queue: + needs: [pre-flight, code-linting] + runs-on: ubuntu-latest + environment: test + if: | + needs.pre-flight.outputs.test_to_run != '[]' + && needs.pre-flight.outputs.components_to_run != '[]' + && needs.pre-flight.outputs.is_ci_workload == 'false' + steps: + - name: Running CI tests + run: | + echo "Running CI tests" + + cicd-test-container-build: + uses: ./.github/workflows/_build_container.yml + needs: [pre-flight, code-linting, cicd-wait-in-queue] + if: | + needs.pre-flight.outputs.test_to_run != '[]' + && needs.pre-flight.outputs.components_to_run != '[]' + && ( + success() + || ( + needs.cicd-wait-in-queue.result == 'skipped' + && needs.pre-flight.outputs.is_ci_workload == 'true' + ) + ) + && !cancelled() + with: + image-name: nemo_container + dockerfile: docker/Dockerfile.ci + + cicd-import-tests: + if: | + needs.pre-flight.outputs.test_to_run != '[]' + && needs.pre-flight.outputs.components_to_run != '[]' + && ( + success() + || ( + needs.cicd-wait-in-queue.result == 'skipped' + && needs.pre-flight.outputs.is_ci_workload == 'true' + ) + ) + && !cancelled() + needs: [cicd-test-container-build, pre-flight] + runs-on: self-hosted-azure-gpus-1 + steps: + - name: Create UUID + id: uuid + run: | + echo "id=$(uuidgen)" >> "$GITHUB_OUTPUT" + + - name: Checkout NeMo + uses: actions/checkout@v6 + with: + path: ${{ github.run_id }}/${{steps.uuid.outputs.id }}/NeMo + + - name: Run some checks + run: | + docker run \ + --rm \ + --device=/dev/nvidia0 \ + --gpus all \ + --shm-size=8g \ + --volume $(pwd)/${{ github.run_id }}/${{steps.uuid.outputs.id }}/NeMo:/workspace \ + --env TRANSFORMERS_OFFLINE=0 \ + --env HYDRA_FULL_ERROR=1 --env PYTHONUNBUFFERED=1 nemoci.azurecr.io/nemo_container:${{ github.run_id }} bash -c '\ + # PyTorch Lightning version + python -c "import lightning.pytorch; print(lightning.pytorch.__version__)" + + # PyTorch Lightning DDP Checks + CUDA_VISIBLE_DEVICES="0,1" python "tests/core_ptl/check_for_ranks.py" + + # Basic Import Checks + python tests/core_ptl/check_imports.py --domain asr + python tests/core_ptl/check_imports.py --domain tts + ' + + L0_Setup_Test_Data_And_Models: + needs: [pre-flight, cicd-test-container-build, cicd-wait-in-queue] + runs-on: self-hosted-azure + if: | + needs.pre-flight.outputs.test_to_run != '[]' + && needs.pre-flight.outputs.components_to_run != '[]' + && ( + success() + || ( + needs.cicd-wait-in-queue.result == 'skipped' + && needs.pre-flight.outputs.is_ci_workload == 'true' + ) + ) + && !cancelled() + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + path: ${{ github.run_id }} + + - name: main + uses: NVIDIA/NeMo/.github/actions/test-template@main + with: + runner: ${{ runner.name }} + script: L0_Setup_Test_Data_And_Models + tests_to_run: '["L0_Setup_Test_Data_And_Models"]' + + cicd-main-unit-tests: + needs: [pre-flight, cicd-test-container-build] + uses: ./.github/workflows/cicd-main-unit-tests.yml + if: | + needs.pre-flight.outputs.test_to_run != '[]' + && needs.pre-flight.outputs.components_to_run != '[]' + && ( + success() + || ( + needs.cicd-wait-in-queue.result == 'skipped' + && needs.pre-flight.outputs.is_ci_workload == 'true' + ) + ) + && !cancelled() + with: + test_to_run: ${{ needs.pre-flight.outputs.test_to_run }} + + cicd-main-speech: + needs: [pre-flight, cicd-test-container-build, cicd-main-unit-tests] + uses: ./.github/workflows/cicd-main-speech.yml + if: | + ( + needs.pre-flight.outputs.test_to_run != '[]' + && ( + contains(fromJson(needs.pre-flight.outputs.components_to_run), 'speech') + ) + ) + && ( + success() + || ( + needs.cicd-wait-in-queue.result == 'skipped' + && needs.pre-flight.outputs.is_ci_workload == 'true' + ) + ) + && !cancelled() + with: + test_to_run: ${{ needs.pre-flight.outputs.test_to_run }} + + Nemo_CICD_Test: + needs: + - pre-flight + - cicd-test-container-build + - cicd-import-tests + - L0_Setup_Test_Data_And_Models + - cicd-main-unit-tests + - cicd-main-speech + if: always() + runs-on: ubuntu-latest + permissions: write-all + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Get workflow result + id: result + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ github.run_id }} + HAS_LABEL: ${{ github.event.label.name == 'Run CICD' }} + IS_SCHEDULED: ${{ github.event_name == 'schedule' }} + run: | + # Get workflow run details and check job conclusions + LATEST_ATTEMPT=$(gh run view $RUN_ID --json jobs -q '[.jobs[] | select(.conclusion != null) | .conclusion] | last') + NUM_FAILED=$(gh run view $RUN_ID --json jobs -q '[.jobs[] | select(.conclusion == "failure") | .name] | length') + NUM_CANCELLED=$(gh run view $RUN_ID --json jobs -q '[.jobs[] | select(.conclusion == "cancelled") | .name] | length') + + if [[ $NUM_FAILED -eq 0 && $NUM_CANCELLED -eq 0 && ("$HAS_LABEL" == "true" || "$IS_SCHEDULED" == "true") ]]; then + RESULT="success" + elif [[ $NUM_CANCELLED -gt 0 ]]; then + RESULT="cancelled" + else + RESULT="failure" + fi + + # Output the final status + echo "code=$RESULT" | tee -a $GITHUB_OUTPUT + + - name: Checkout for GH CLI + uses: actions/checkout@v6 + + - name: Remove label if not cancelled + if: | + steps.result.outputs.code != 'cancelled' + && github.event.label.name == 'Run CICD' + && github.event.pull_request.head.repo.full_name == github.repository + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.number }} + run: gh pr edit "$PR_NUMBER" --remove-label "Run CICD" + + - name: Pipeline successful, add PR comment + if: | + steps.result.outputs.code == 'success' + && github.event_name == 'pull_request' + && env.SLACK_WEBHOOK != '' + uses: peter-evans/create-or-update-comment@v4 + env: + SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }} + REPOSITORY: ${{ github.repository }} + RUN_ID: ${{ github.run_id }} + with: + issue-number: ${{ github.event.number }} + body: | + [🤖]: Hi @${{ github.event.pull_request.user.login }} 👋, + + We wanted to let you know that a [CICD pipeline](https://github.com/${{ env.REPOSITORY }}/actions/runs/${{ env.RUN_ID }}) for this PR just finished successfully. + + So it might be time to merge this PR or get some approvals. + + - name: Exit + if: ${{ always() }} + env: + RESULT: ${{ steps.result.outputs.code }} + run: | + if [ $RESULT == "success" ]; then + exit 0 + else + exit 1 + fi + + Coverage: + runs-on: ubuntu-latest + needs: [pre-flight, Nemo_CICD_Test] + if: | + needs.pre-flight.outputs.test_to_run != '[]' + && needs.pre-flight.outputs.components_to_run != '[]' + && ( + success() + || needs.Nemo_CICD_Test.result == 'success' + ) + && !cancelled() + strategy: + matrix: + flag: [unit-test, e2e] + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Download coverage reports of current branch + uses: actions/download-artifact@v7 + with: + pattern: coverage-${{ matrix.flag }}-* + + - name: Get total coverage of current branch + shell: bash -x -e -u -o pipefail {0} + if: always() + run: | + pip install coverage + + ls -al . + ls -al coverage-*/ + coverage combine --keep $(ls coverage-*/.coverage) + coverage report -i + rm -rf coverage-* + ls -al + + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} + verbose: true + flags: ${{ matrix.flag }} + + - name: Upload artifacts + uses: actions/upload-artifact@v6 + with: + name: coverage-${{ matrix.flag }}-aggregated + path: | + .coverage + include-hidden-files: true diff --git a/.github/workflows/cicd-relabel-bot.yml b/.github/workflows/cicd-relabel-bot.yml new file mode 100644 index 0000000000000000000000000000000000000000..c7546df322a28ad4d18dec7579466e571b3046fd --- /dev/null +++ b/.github/workflows/cicd-relabel-bot.yml @@ -0,0 +1,36 @@ +# If the PR get's updated by a new commit, it prevents auto-merges +# since there's no CI event attached to the commit anymore. +# This workflow re-attaches the label after a push, if the PR +# was already labeled prior to the push. +name: CICD Relabel bot + +on: + pull_request_target: + +jobs: + relabel: + runs-on: ubuntu-latest + env: + PR_NUMBER: ${{ github.event.number }} + GH_TOKEN: ${{ secrets.NEMO_RELABEL_TOKEN }} + HOSTNAME: ${{ github.server_url }} + permissions: write-all + steps: + - name: Checkout repo + uses: actions/checkout@v6 + + - name: Check if PR was already labeled with `Run CICD` + id: pre-flight + run: | + LABELS=$(gh pr view "$PR_NUMBER" --json labels) + HAS_LABEL=$(echo $LABELS \ + | jq '[.labels[].name] | any(. == "Run CICD")' + ) + + echo "has-label=$HAS_LABEL" | tee -a "$GITHUB_OUTPUT" + + - name: Relabel PR + if: ${{ steps.pre-flight.outputs.has-label == 'true' }} + run: | + gh pr edit "$PR_NUMBER" --remove-label "Run CICD" + gh pr edit "$PR_NUMBER" --add-label "Run CICD" diff --git a/.github/workflows/claude-answer.yml b/.github/workflows/claude-answer.yml new file mode 100644 index 0000000000000000000000000000000000000000..c6a2ed7d2e7aa01e02a1e755156b0f3b3cf44c40 --- /dev/null +++ b/.github/workflows/claude-answer.yml @@ -0,0 +1,65 @@ +name: Claude Answer Issue + +on: + issue_comment: + types: [created] + +permissions: + contents: read + issues: write + id-token: write + +jobs: + authorize: + if: >- + !github.event.issue.pull_request && + contains(github.event.comment.body, '/claude answer') + runs-on: ubuntu-latest + steps: + - name: Check team membership + uses: actions/github-script@v8 + with: + github-token: ${{ secrets.ORG_TEAM_READ_TOKEN }} + script: | + const username = context.payload.comment.user.login; + try { + const res = await github.rest.teams.getMembershipForUserInOrg({ + org: 'NVIDIA-NeMo', + team_slug: 'speech_team', + username, + }); + if (res.data.state !== 'active') { + core.setFailed(`${username} is not an active member of NVIDIA Speech Team`); + } + } catch (e) { + core.setFailed(`${username} is not a member of NVIDIA Speech Team`); + } + + acknowledge: + needs: authorize + runs-on: ubuntu-latest + steps: + - name: Add eyes reaction to comment + uses: actions/github-script@v8 + with: + script: | + await github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + content: 'eyes' + }); + + claude-answer: + needs: acknowledge + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: anthropics/claude-code-action@v1 + with: + prompt: | + You are a helpful assistant for the NeMo repository. + Answer the user's question based on the issue description, comments, and the codebase. + Be concise and provide code references where relevant. + Do NOT make any code changes or create PRs — only answer the question. + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} diff --git a/.github/workflows/claude-fix.yml b/.github/workflows/claude-fix.yml new file mode 100644 index 0000000000000000000000000000000000000000..1f7f208ea5bb4d7f9c8847863a2bb97821f4e9d8 --- /dev/null +++ b/.github/workflows/claude-fix.yml @@ -0,0 +1,114 @@ +name: Claude Fix Issue + +on: + issue_comment: + types: [created] + +permissions: + contents: write + pull-requests: write + issues: write + id-token: write + +jobs: + authorize: + if: >- + !github.event.issue.pull_request && + contains(github.event.comment.body, '/claude fix') + runs-on: ubuntu-latest + steps: + - name: Check team membership + uses: actions/github-script@v8 + with: + github-token: ${{ secrets.ORG_TEAM_READ_TOKEN }} + script: | + const username = context.payload.comment.user.login; + try { + const res = await github.rest.teams.getMembershipForUserInOrg({ + org: 'NVIDIA-NeMo', + team_slug: 'speech_team', + username, + }); + if (res.data.state !== 'active') { + core.setFailed(`${username} is not an active member of NVIDIA Speech Team`); + } + } catch (e) { + core.setFailed(`${username} is not a member of NVIDIA Speech Team`); + } + + acknowledge: + needs: authorize + runs-on: ubuntu-latest + steps: + - name: Add eyes reaction to comment + uses: actions/github-script@v8 + with: + script: | + await github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + content: 'eyes' + }); + + claude-fix: + needs: acknowledge + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: anthropics/claude-code-action@v1 + id: claude + with: + prompt: | + You are a developer working on the NeMo repository. + Implement a focused fix for the issue based on the issue description and comments. + + Requirements: + - Always use `git commit -s` to sign off all commits (DCO requirement). + - Prioritize correctness and minimal scope; avoid unrelated refactors. + - Reproduce or reason about the failure first, then implement the smallest robust fix. + - If required, add or update tests for the changed behavior. If tests are not feasible, explain why. + - If required, update related docs or comments when behavior or usage changes. + + PR expectations: + - Create a new branch and open a pull request with your changes. + - Include a concise summary of root cause and fix based on the following PR template: + ``` + # What does this PR do ? + Add a one line overview of what this PR aims to accomplish. + + # Changelog + Add specific line by line info of high level changes in this PR. + + # Usage + Add a usage example of the changed functionality. + + Related to #${{ github.event.issue.number }} + + This PR is created by Claude. + ``` + + + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + + - name: Label PR with agent-contribution + if: steps.claude.outputs.branch_name + uses: actions/github-script@v8 + with: + script: | + const prs = await github.rest.pulls.list({ + owner: context.repo.owner, + repo: context.repo.repo, + head: `${context.repo.owner}:${process.env.BRANCH_NAME}`, + state: 'open' + }); + if (prs.data.length > 0) { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: prs.data[0].number, + labels: ['agent-contribution'] + }); + } + env: + BRANCH_NAME: ${{ steps.claude.outputs.branch_name }} diff --git a/.github/workflows/claude-review.yml b/.github/workflows/claude-review.yml new file mode 100644 index 0000000000000000000000000000000000000000..e4f3eb4533998a734fc0cdc17b7bbaacbe4de36a --- /dev/null +++ b/.github/workflows/claude-review.yml @@ -0,0 +1,58 @@ +name: Claude Code Review + +on: + issue_comment: + types: [created] + +permissions: + contents: read + pull-requests: write + issues: write + id-token: write + +jobs: + acknowledge: + if: >- + github.event.issue.pull_request && + contains(github.event.comment.body, '/claude review') + runs-on: ubuntu-latest + steps: + - name: Add eyes reaction to comment + uses: actions/github-script@v8 + with: + script: | + await github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + content: 'eyes' + }); + + claude-review: + needs: acknowledge + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_claude_review.yml@v0.79.0 + with: + prompt: | + You are doing a light code review. Keep it concise and actionable. + + Focus ONLY on: + - Critical bugs or logic errors + - Typos in code, comments, or strings + - Missing or insufficient test coverage for changed code + - Outdated or inaccurate documentation affected by the changes + + Do NOT comment on: + - Style preferences or formatting + - Minor naming suggestions + - Architectural opinions or refactoring ideas + - Performance unless there is a clear, measurable issue + + Provide feedback using inline comments for specific code suggestions. + Use top-level comments for general observations. + + IMPORTANT: Do NOT approve the pull request. Only leave comments. + + It's perfectly acceptable to not have anything to comment on. + If you do not have anything to comment on, post "LGTM". + secrets: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} \ No newline at end of file diff --git a/.github/workflows/close-inactive-issue-pr.yml b/.github/workflows/close-inactive-issue-pr.yml new file mode 100644 index 0000000000000000000000000000000000000000..c71997e4b9bf8ec40ff3cbe4220216650acaf726 --- /dev/null +++ b/.github/workflows/close-inactive-issue-pr.yml @@ -0,0 +1,25 @@ +name: Stale-Close-Inactive-Issues-PRs +on: + schedule: + - cron: "30 1 * * *" + +jobs: + close-issues: + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - uses: actions/stale@v6 + with: + operations-per-run: 100 + days-before-issue-stale: 30 + days-before-issue-close: 7 + stale-issue-label: "stale" + stale-issue-message: "This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 7 days." + close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale." + days-before-pr-stale: 14 + days-before-pr-close: 7 + stale-pr-message: "This PR is stale because it has been open for 14 days with no activity. Remove stale label or comment or update or this will be closed in 7 days." + close-pr-message: "This PR was closed because it has been inactive for 7 days since being marked as stale." + repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/code-formatting.yml b/.github/workflows/code-formatting.yml new file mode 100644 index 0000000000000000000000000000000000000000..2fc272bbab654106bad785afc2884b83a1925a02 --- /dev/null +++ b/.github/workflows/code-formatting.yml @@ -0,0 +1,73 @@ +name: Isort and Black Formatting +# Incrementally reformat only changed files with black, all files with isort +# +# Replaces pre-commit.ci, since it reformats all the files. +# See issue https://github.com/pre-commit-ci/issues/issues/90 +# +# The action requires a custom token to trigger workflow after pushing reformatted files back to the branch. +# `secrets.GITHUB_TOKEN` can be used instead, but this will result +# in not running necessary checks after reformatting, which is undesirable. +# For details see https://github.com/orgs/community/discussions/25702 + +on: + pull_request_target: + paths: + - "**.py" + types: [opened, synchronize, reopened, labeled, unlabeled] + +defaults: + run: + shell: bash -x -e -u -o pipefail {0} + +jobs: + reformat_with_isort_and_black: + runs-on: ubuntu-latest + permissions: + # write permissions required to commit changes + contents: write + steps: + - name: Checkout branch + uses: actions/checkout@v6 + with: + # setup repository and ref for PRs, see + # https://github.com/EndBug/add-and-commit?tab=readme-ov-file#working-with-prs + repository: ${{ github.event.pull_request.head.repo.full_name }} + ref: ${{ github.event.pull_request.head.ref }} + # custom token is required to trigger actions after reformatting + pushing + token: ${{ secrets.NEMO_REFORMAT_TOKEN }} + fetch-depth: 0 + + - name: Get changed files + id: changed-files + uses: step-security/changed-files@v45.0.1 + with: + files: | + **.py + + - name: Setup Python env + uses: actions/setup-python@v6 + with: + python-version: "3.10" + + - name: black + uses: psf/black@stable + if: ${{ steps.changed-files.outputs.any_changed == 'true' }} + with: + options: "--verbose" + # apply only to changed files (pass explicitly the files) + src: "${{ steps.changed-files.outputs.all_changed_files }}" + version: "~= 24.3" + + - name: isort + uses: isort/isort-action@v1 + if: ${{ steps.changed-files.outputs.any_changed == 'true' }} + with: + isort-version: "5.13.2" + # reformat all files with isort – safe since the whole repo is already reformatted + configuration: "" + + - uses: EndBug/add-and-commit@v9 + # Commit changes. Nothing is committed if no changes. + with: + message: Apply isort and black reformatting + commit: --signoff diff --git a/.github/workflows/code-init-file-checker.yml b/.github/workflows/code-init-file-checker.yml new file mode 100644 index 0000000000000000000000000000000000000000..7d0444b136afddb29a66eb36176515ef906bcad1 --- /dev/null +++ b/.github/workflows/code-init-file-checker.yml @@ -0,0 +1,23 @@ +name: Check __init__ files + +on: + pull_request: + types: [opened, synchronize, reopened] + +jobs: + check-init-files: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Install init-file-checker + run: pip install init-file-checker + + - name: Run init-file-checker + run: init-file-checker nemo/ diff --git a/.github/workflows/code-linting.yml b/.github/workflows/code-linting.yml new file mode 100644 index 0000000000000000000000000000000000000000..eff0a71756ac7df545c118125c22055c150204fc --- /dev/null +++ b/.github/workflows/code-linting.yml @@ -0,0 +1,160 @@ +name: PyLint and flake8 linting + +on: + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + workflow_call: + +jobs: + linting: + name: "Domain: ${{ matrix.domain }}" + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + domain: [speech, other] + env: + DOMAIN: ${{ matrix.domain }} + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Select filter + id: filter + run: | + if [[ "$DOMAIN" == "speech" ]]; then + FILTER=$(jq -crn '[ + "nemo/collections/common/data/lhotse/*.py", + "nemo/collections/asr/**/*.py", + "nemo/collections/tts/**/*.py", + "nemo/collections/audio/**/*.py", + "nemo/collections/multimodal/speech_llm/**/*.py", + "nemo/collections/speechlm/**/*.py", + "nemo/collections/speechlm2/**/*.py" + ] | join(",")') + + else + FILTER=$(jq -crn '[ + "nemo/**/*.py", + "!nemo/collections/common/data/lhotse/*.py", + "!nemo/collections/asr/**/*.py", + "!nemo/collections/tts/**/*.py", + "!nemo/collections/audio/**/*.py", + "!nemo/collections/multimodal/speech_llm/**/*.py", + "!nemo/collections/speechlm/**/*.py", + "!nemo/collections/speechlm2/**/*.py", + "!nemo/export/**/*.py" + ] | join(",")') + fi + + echo "main=$FILTER" | tee -a "$GITHUB_OUTPUT" + + - name: Get changed files + id: changed-files + uses: step-security/changed-files@v45.0.1 + with: + files: ${{ steps.filter.outputs.main }} + files_separator: "," + separator: " " + + - name: Run PyLint + id: pylint + env: + CHANGED_FILES: ${{ steps.changed-files.outputs.all_changed_files }} + SKIP_DOCS: ${{ contains(github.event.pull_request.labels.*.name, 'skip-docs') }} + SKIP_LINTING: ${{ contains(github.event.pull_request.labels.*.name, 'skip-linting') }} + run: | + if [[ -z "$CHANGED_FILES" ]]; then + echo Nothing to lint. + echo "exit-code=0" | tee -a "$GITHUB_OUTPUT" + exit 0 + fi + + if [[ $SKIP_DOCS == true ]]; then + ADDITIONAL_PYLINT_ARGS="--disable=C0115,C0116" + else + ADDITIONAL_PYLINT_ARGS="" + fi + + if [[ $SKIP_LINTING == true ]]; then + ADDITIONAL_PYLINT_ARGS="--exit-zero" + fi + + pip install pylint + set +e + pylint $ADDITIONAL_PYLINT_ARGS --output "pylintrc.$DOMAIN.txt" --rcfile ".pylintrc.$DOMAIN" ${CHANGED_FILES[@]} + echo "exit-code=$?" | tee -a "$GITHUB_OUTPUT" + + - name: Run flake8 + id: flake8 + env: + CHANGED_FILES: ${{ steps.changed-files.outputs.all_changed_files }} + SKIP_LINTING: ${{ contains(github.event.pull_request.labels.*.name, 'skip-linting') }} + run: | + if [[ -z "$CHANGED_FILES" ]]; then + echo Nothing to lint. + echo "exit-code=0" | tee -a "$GITHUB_OUTPUT" + exit 0 + fi + + if [[ $SKIP_LINTING == true ]]; then + ADDITIONAL_FLAKE8_ARGS="--exit-zero" + else + ADDITIONAL_FLAKE8_ARGS="" + fi + + pip install flake8 + set +e + flake8 $ADDITIONAL_FLAKE8_ARGS --output "flake8.$DOMAIN.txt" --config ".flake8.$DOMAIN" ${CHANGED_FILES[@]} + echo "exit-code=$?" | tee -a "$GITHUB_OUTPUT" + + - name: Summary + env: + PYLINT: ${{ steps.pylint.outputs.exit-code == 0 }} + FLAKE8: ${{ steps.flake8.outputs.exit-code == 0 }} + run: | + + if [[ "$PYLINT" != "true" ]]; then + echo "Pylint output:" | tee -a $GITHUB_STEP_SUMMARY + + echo '```' | tee -a $GITHUB_STEP_SUMMARY + cat pylintrc.$DOMAIN.txt | tee -a $GITHUB_STEP_SUMMARY + echo '```' | tee -a $GITHUB_STEP_SUMMARY + fi + + if [[ "$FLAKE8" != "true" ]]; then + echo "Flake8 output:" | tee -a $GITHUB_STEP_SUMMARY + + echo '```' | tee -a $GITHUB_STEP_SUMMARY + cat flake8.$DOMAIN.txt | tee -a $GITHUB_STEP_SUMMARY + echo '```' | tee -a $GITHUB_STEP_SUMMARY + fi + + if [[ "$PYLINT" != "true" || "$FLAKE8" != "true" ]]; then + echo "The following directories got scanned:" | tee -a $GITHUB_STEP_SUMMARY + + echo '```' | tee -a $GITHUB_STEP_SUMMARY + echo ${{ steps.filter.outputs.main }} | tee -a $GITHUB_STEP_SUMMARY + echo '```' | tee -a $GITHUB_STEP_SUMMARY + + exit 1 + fi + + Nemo_Linting_Test: + needs: linting + runs-on: ubuntu-latest + if: always() + steps: + - name: Main + env: + RESULTS: ${{ toJson(needs.linting) }} + run: | + RESULT=$(echo "$RESULTS" | jq -r '.result') + + if [[ "$RESULT" == "success" ]]; then + echo "All passed." + exit 0 + else + echo "Some linting domains failed." + exit 1 + fi diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000000000000000000000000000000000000..28c060be0990c5221b950d6146b02f5f2332290f --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,75 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "main", "[rv][0-9]*", "gh-pages-src" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "main" ] + schedule: + - cron: '19 1 * * 4' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'python' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + queries: security-and-quality # security-extended, + config-file: ./.github/workflows/config/codeql.yml + + + # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/community-bot.yml b/.github/workflows/community-bot.yml new file mode 100644 index 0000000000000000000000000000000000000000..7e92e011706eb3c6f4c353ab538a17c1e51dce52 --- /dev/null +++ b/.github/workflows/community-bot.yml @@ -0,0 +1,15 @@ +name: Community Bot + +on: + issues: + types: [opened, edited, reopened, closed, deleted] + issue_comment: + types: [created, edited, deleted] + +jobs: + community-bot: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_community_bot.yml@v0.62.0 + with: + community_project_id: ${{ vars.COMMUNITY_PROJECT_ID }} + secrets: + GH_TOKEN: ${{ secrets.PAT }} diff --git a/.github/workflows/config/changelog-config.json b/.github/workflows/config/changelog-config.json new file mode 100644 index 0000000000000000000000000000000000000000..40c98c0a571b6408920d770f9d57809125e89247 --- /dev/null +++ b/.github/workflows/config/changelog-config.json @@ -0,0 +1,134 @@ +{ + "categories": [ + { + "title": "## ASR\n\n
Changelog", + "labels": ["asr"], + "exclude_labels": ["cherry-pick"] + }, + { + "title": "
\n\n## TTS\n\n
Changelog", + "labels": ["tts"], + "exclude_labels": ["cherry-pick"] + }, + { + "title": "
\n\n## NLP / NMT\n\n
Changelog", + "labels": ["nlp", "nmt", "megatron"], + "exclude_labels": ["cherry-pick"] + }, + { + "title": "
\n\n## Text Normalization / Inverse Text Normalization\n\n
Changelog", + "labels": ["tn", "itn"], + "exclude_labels": ["cherry-pick"] + }, + { + "title": "
\n\n## NeMo Tools\n\n
Changelog", + "labels": ["tools"], + "exclude_labels": ["cherry-pick"] + }, + { + "title": "
\n\n## Export\n\n
Changelog", + "labels": ["export"], + "exclude_labels": ["cherry-pick"] + }, + { + "title": "
\n\n## Documentation\n\n
Changelog", + "labels": ["docs"], + "exclude_labels": ["cherry-pick"] + }, + { + "title": "
\n\n## Bugfixes\n\n
Changelog", + "labels": ["bug"], + "exclude_labels": ["cherry-pick"] + }, + { + "title": "
\n\n## Cherrypick\n\n
Changelog", + "labels": ["cherry-pick"], + "exclude_labels": ["cherry-pick"] + } + ], + "ignore_labels": [ + "ignore" + ], + "sort": "ASC", + "template": "\n${{CHANGELOG}}
\n\n## Uncategorized:\n\n
Changelog\n\n${{UNCATEGORIZED}}\n
\n", + "pr_template": "- ${{TITLE}} by @${{AUTHOR}} :: PR: #${{NUMBER}}", + "empty_template": "${{OWNER}}\n${{REPO}}\n${{FROM_TAG}}\n${{TO_TAG}}", + "label_extractor": [ + { + "pattern": "(.*tts.*)|(.*g2p.*)", + "target": "tts", + "flags": "gimu", + "on_property": ["title", "body"] + }, + { + "pattern": "(.*asr.*)|(.*ctc.*)|(.*rnnt.*)|(.*transducer.*)|(.*dali.*)|(.*k2.*)", + "target": "asr", + "flags": "gimu", + "on_property": ["title", "body"] + }, + { + "pattern": "(.*nlp.*)|(.*punctuation.*)|(.*capitalization.*)|(.*entity.*)|(.*glue.*)|(.*entity.*)|(.*retrieval.*)|(.*entity.*)|(.*intent.*)|(.*slot.*)|(.*entity.*)|(.*language.*)|(.*qa.*)|(.*token class.*)|(.*text class.*)", + "target": "nlp", + "flags": "gimu", + "on_property": ["title", "body"] + }, + { + "pattern": "(.*nmt.*)|(.*bignlp.*)|(.*megatron.*)|(.*machine.*)|(.*translation.*)|(.*gpt.*)", + "target": "nmt", + "flags": "gimu", + "on_property": ["title", "body"] + }, + { + "pattern": "(.*tn.*)|(.*itn.*)|(.*text norm.*)", + "target": "tn", + "flags": "gimu", + "on_property": ["title", "body"] + }, + { + "pattern": "(.*sde.*)|(.*ctc segment.*)", + "target": "tools", + "flags": "gimu", + "on_property": ["title", "body"] + }, + { + "pattern": "(.*trt.*)|(.*onnx.*)|(.*export.*)", + "target": "export", + "flags": "gimu", + "on_property": ["title", "body"] + }, + { + "pattern": "(.*\\[x\\] Documentation.*)", + "target": "docs", + "flags": "gmu", + "on_property": ["title", "body"] + }, + { + "pattern": "(.*\\[x\\] Bugfix.*)|(.*patch.*)", + "target": "bug", + "flags": "gmu", + "on_property": ["title", "body"] + }, + { + "pattern": "(.*cherry-pick.*)|(.*cherrypick.*)", + "target": "cherrypick", + "flags": "gimu", + "on_property": ["title", "body"] + } + ], + "duplicate_filter": { + "pattern": ".+", + "on_property": "title", + "method": "match" + }, + "transformers": [ + ], + "max_tags_to_fetch": 100, + "max_pull_requests": 500, + "max_back_track_time_days": 365, + "exclude_merge_branches": [ + ], + "tag_resolver": { + "method": "semver" + } +} + diff --git a/.github/workflows/config/codeql.yml b/.github/workflows/config/codeql.yml new file mode 100644 index 0000000000000000000000000000000000000000..5482696a2c9fae228b24655ac1687112824930a7 --- /dev/null +++ b/.github/workflows/config/codeql.yml @@ -0,0 +1,9 @@ +name: "CodeQL config" + +paths: + - nemo/ + - tests/ + - tools/ + - scripts/ + - examples/ + - .github/ diff --git a/.github/workflows/copyright-check.yml b/.github/workflows/copyright-check.yml new file mode 100644 index 0000000000000000000000000000000000000000..36b7e6c597bf1fa0d3581c691bea54fdeead7962 --- /dev/null +++ b/.github/workflows/copyright-check.yml @@ -0,0 +1,22 @@ +# Copyright (c) 2020-2021, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Copyright check + +on: + pull_request: + +jobs: + copyright-check: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_copyright_check.yml@v0.2.0 diff --git a/.github/workflows/install-test.yml b/.github/workflows/install-test.yml new file mode 100644 index 0000000000000000000000000000000000000000..1822f4fbf6b1f254a710bb672df6446af23f5222 --- /dev/null +++ b/.github/workflows/install-test.yml @@ -0,0 +1,283 @@ +name: CI-Install-Check + +on: + pull_request: + paths: + - "**" + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + test-installs-macos: + name: ${{ matrix.os }}-py${{ matrix.python }}-${{ matrix.installer }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-latest] + python: ["3.10", "3.11", "3.12"] + installer: ["pip-install", "nemo-install"] + steps: + - name: Checkout repo + uses: actions/checkout@v6 + + - name: Check disk space before cleanup + run: df -h + + - name: Free up disk space + run: | + # Remove unnecessary files on macOS + sudo rm -rf /usr/local/lib/android || true + sudo rm -rf /usr/local/.ghcup || true + sudo rm -rf /usr/local/lib/node_modules || true + brew cleanup || true + # Clear pip cache + pip cache purge || true + + - name: Check disk space after cleanup + run: df -h + + - uses: actions/setup-python@v6 + with: + python-version: "${{ matrix.python }}" + + - name: Install NeMo + env: + INSTALLER: ${{ matrix.installer }} + NEMO_TAG: ${{ github.sha }} + NEMO_REPO: ${{ github.server_url }}/${{ github.repository }} + run: | + if [[ "$INSTALLER" == "pip-install" ]]; then + pip install --no-cache-dir -U pip + pip install --no-cache-dir ".[all]" + else + export NEMO_TAG + export NEMO_REPO + export INSTALL_DIR=$(pwd) + + pip install --no-cache-dir ".[all]" + fi + + - name: Check disk space after installation + run: df -h + + - name: Run import checks + run: | + # Run import checks + for collection in "asr" "tts" "lightning" "core"; do + python tests/core_ptl/check_imports.py --domain "$collection" + done + + test-installs-linux-amd: + name: ubuntu-22.04-amd-py${{ matrix.python }}-${{ matrix.installer }} + runs-on: ubuntu-22.04 + strategy: + fail-fast: false + matrix: + python: ["3.10", "3.11", "3.12"] + installer: ["pip-install", "nemo-install"] + steps: + - name: Checkout repo + uses: actions/checkout@v6 + + - name: Check disk space before cleanup + run: df -h + + - name: Free up disk space + run: | + # Remove unnecessary packages and files on Ubuntu + sudo apt-get clean + sudo rm -rf /usr/local/lib/android || true + sudo rm -rf /opt/ghc || true + sudo rm -rf /usr/local/.ghcup || true + sudo rm -rf /usr/share/dotnet || true + sudo rm -rf /opt/az || true + # Clear pip and npm caches + pip cache purge || true + sudo npm cache clean --force || true + + - name: Check disk space after cleanup + run: df -h + + - name: Install Python + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + - name: Install NeMo + env: + INSTALLER: ${{ matrix.installer }} + run: | + if [ "$INSTALLER" = "pip-install" ]; then + pip install --no-cache-dir --upgrade pip + pip install --no-cache-dir ".[all]" + else + export INSTALL_DIR=$(pwd) + pip install --no-cache-dir ".[all]" + fi + + - name: Check disk space after installation + run: df -h + + - name: Run import checks + run: | + # Run import checks + for collection in "asr" "tts" "lightning" "core"; do + python tests/core_ptl/check_imports.py --domain "$collection" + done + + test-asr-install-linux-amd: + name: ubuntu-22.04-amd-py${{ matrix.python }}-asr + runs-on: ubuntu-22.04 + strategy: + fail-fast: false + matrix: + python: ["3.10", "3.11", "3.12"] + steps: + - name: Checkout repo + uses: actions/checkout@v6 + + - name: Check disk space before cleanup + run: df -h + + - name: Free up disk space + run: | + # Remove unnecessary packages and files on Ubuntu + sudo apt-get clean + sudo rm -rf /usr/local/lib/android || true + sudo rm -rf /opt/ghc || true + sudo rm -rf /usr/local/.ghcup || true + sudo rm -rf /usr/share/dotnet || true + sudo rm -rf /opt/az || true + # Clear pip and npm caches + pip cache purge || true + sudo npm cache clean --force || true + + - name: Check disk space after cleanup + run: df -h + + - name: Install Python + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + - name: Install NeMo + run: | + pip install --no-cache-dir --upgrade pip + pip install --no-cache-dir ".[asr]" + + - name: Check disk space after installation + run: df -h + + - name: Run import checks + run: | + # Run import checks + python tests/core_ptl/check_imports.py --domain asr + + test-installs-linux-arm: + name: ubuntu-22.04-arm-py${{ matrix.python }}-${{ matrix.installer }} + runs-on: ubuntu-22.04-arm + strategy: + fail-fast: false + matrix: + python: ["3.10", "3.11", "3.12"] + installer: ["pip-install", "nemo-install"] + steps: + - name: Checkout repo + uses: actions/checkout@v6 + + - name: Check disk space before cleanup + run: df -h + + - name: Free up disk space + run: | + # Remove unnecessary packages and files on Ubuntu ARM + sudo apt-get clean + sudo rm -rf /usr/local/lib/android || true + sudo rm -rf /opt/ghc || true + sudo rm -rf /usr/local/.ghcup || true + sudo rm -rf /usr/share/dotnet || true + sudo rm -rf /opt/az || true + # Clear pip and npm caches + pip cache purge || true + sudo npm cache clean --force || true + + - name: Check disk space after cleanup + run: df -h + + - name: Install Python + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + - name: Install NeMo + env: + INSTALLER: ${{ matrix.installer }} + run: | + if [ "$INSTALLER" = "pip-install" ]; then + pip install --no-cache-dir --upgrade pip + pip install --no-cache-dir ".[all]" + else + export INSTALL_DIR=$(pwd) + pip install --no-cache-dir ".[all]" + fi + + - name: Check disk space after installation + run: df -h + + - name: Run import checks + run: | + # Run import checks + for collection in "asr" "tts" "lightning" "core"; do + python tests/core_ptl/check_imports.py --domain "$collection" + done + + test-asr-installs-linux-arm: + name: ubuntu-22.04-arm-py${{ matrix.python }}-asr + runs-on: ubuntu-22.04-arm + strategy: + fail-fast: false + matrix: + python: ["3.10", "3.11", "3.12"] + steps: + - name: Checkout repo + uses: actions/checkout@v6 + + - name: Check disk space before cleanup + run: df -h + + - name: Free up disk space + run: | + # Remove unnecessary packages and files on Ubuntu ARM + sudo apt-get clean + sudo rm -rf /usr/local/lib/android || true + sudo rm -rf /opt/ghc || true + sudo rm -rf /usr/local/.ghcup || true + sudo rm -rf /usr/share/dotnet || true + sudo rm -rf /opt/az || true + # Clear pip and npm caches + pip cache purge || true + sudo npm cache clean --force || true + + - name: Check disk space after cleanup + run: df -h + + - name: Install Python + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + - name: Install NeMo + run: | + pip install --no-cache-dir --upgrade pip + pip install --no-cache-dir ".[asr]" + + - name: Check disk space after installation + run: df -h + + - name: Run import checks + run: | + # Run import checks + python tests/core_ptl/check_imports.py --domain asr diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 0000000000000000000000000000000000000000..680f9d187a3b77819a0e87e5d3c0fca965d74831 --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,14 @@ +name: "Pull Request Labeler" +on: +- pull_request_target + +jobs: + triage: + permissions: + contents: read + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v4 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" \ No newline at end of file diff --git a/.github/workflows/mcore-tag-bump-bot.yml b/.github/workflows/mcore-tag-bump-bot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b4fdf56ac59fb2738ff9c86f5bfc109ed216f5f1 --- /dev/null +++ b/.github/workflows/mcore-tag-bump-bot.yml @@ -0,0 +1,62 @@ +# Regularly updates the CI container +name: Megatron Tag Bump Bot +on: + workflow_dispatch: + schedule: + - cron: 0 0 * * * + +jobs: + get-release-branch-names: + runs-on: ubuntu-latest + outputs: + mcore: ${{ steps.get-branch.outputs.mcore_release_branch }} + nemo: ${{ steps.get-branch.outputs.nemo_release_branch }} + steps: + - name: Get release branch names + id: get-branch + run: | + latest_branch=$(git ls-remote --heads https://github.com/NVIDIA/Megatron-LM.git 'refs/heads/core_r*' | + grep -o 'core_r[0-9]\+\.[0-9]\+\.[0-9]\+' | + sort -V | + tail -n1) + echo "mcore_release_branch=$latest_branch" >> $GITHUB_OUTPUT + + latest_branch=$(git ls-remote --heads https://github.com/NVIDIA/NeMo.git 'refs/heads/r*' | + grep -o 'r[0-9]\+\.[0-9]\+\.[0-9]\+' | + sort -V | + tail -n1) + echo "nemo_release_branch=$latest_branch" >> $GITHUB_OUTPUT + + bump-tags: + needs: [get-release-branch-names] + strategy: + fail-fast: false + matrix: + include: + - nemo-target-branch: ${{ needs.get-release-branch-names.outputs.nemo }} + mcore-target-branch: ${{ needs.get-release-branch-names.outputs.mcore }} + - nemo-target-branch: main + mcore-target-branch: main + uses: ./.github/workflows/_bump_mcore_tag.yml + with: + nemo-target-branch: ${{ matrix.nemo-target-branch }} + mcore-target-branch: ${{ matrix.mcore-target-branch }} + secrets: + PAT: ${{ secrets.PAT }} + + notify: + if: failure() + runs-on: ubuntu-latest + needs: [bump-tags] + steps: + - name: Notify + env: + SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }} + SLACK_WEBHOOK_ADMIN: + GITHUB_RUN_ID: ${{ github.run_id }} + GITHUB_REPOSITORY: ${{ github.repository }} + run: | + curl -X POST \ + -H 'Content-type: application/json' \ + --data "{\"text\":\":robot_joy: failed. Please fix manually.\n\ncc ${SLACK_WEBHOOK_ADMIN}\"}" \ + $SLACK_WEBHOOK diff --git a/.github/workflows/monitor-single-vm.yml b/.github/workflows/monitor-single-vm.yml new file mode 100644 index 0000000000000000000000000000000000000000..627f34d2a3260ce3fc5f43e0bcb64f1efdadd6e4 --- /dev/null +++ b/.github/workflows/monitor-single-vm.yml @@ -0,0 +1,54 @@ +name: ~shut down a single VM + +on: + workflow_call: + inputs: + vm: + type: string + description: Name of VM + required: true + n_gpus: + type: string + description: Number of GPUs this VM has + required: true + +jobs: + check-status-and-maybe-shutdown: + environment: main + runs-on: ${{ inputs.vm }} + outputs: + status: ${{ steps.status.outputs.main }} + steps: + - name: Check status + id: status + run: | + docker run --rm --runtime=nvidia --gpus ${{ inputs.n_gpus }} ubuntu nvidia-smi + + NUM_GPUS=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l) + + if [[ $NUM_GPUS -ne ${{ inputs.n_gpus }} ]]; then + echo "Issues with GPU detected, will take this runner offline." + echo "main=degraded" >> "$GITHUB_OUTPUT" + else + echo "main=healthy" >> "$GITHUB_OUTPUT" + fi + + - name: Send Slack message & Disconnect runner from GitHub + if: ${{ steps.status.outputs.main == 'degraded' || failure() }} + run: | + MESSAGE='{ + "blocks": [ + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": ":alert: VM bot 🤖: Hey : VM `${{ inputs.vm }}` is having not the best day of their life, maybe bring them an apple or so." + } + } + ] + }' + + curl -X POST -H "Content-type: application/json" --data "$MESSAGE" ${{ secrets.SLACK_WEBHOOK }} + + cd /home/azureuser/actions-runner + echo ${{ secrets.VM_KEY }} | sudo -S ./svc.sh stop diff --git a/.github/workflows/monitor-vms.yml b/.github/workflows/monitor-vms.yml new file mode 100644 index 0000000000000000000000000000000000000000..722a4720b0e923d63367c9d230872c8d300a5bb6 --- /dev/null +++ b/.github/workflows/monitor-vms.yml @@ -0,0 +1,54 @@ +# Regularly updates the CI container +name: Reboots VMs in a controlled way +on: + schedule: + - cron: 0/15 * * * * + workflow_dispatch: + +jobs: + pre-flight: + runs-on: ubuntu-latest + if: github.repository_owner == 'NVIDIA' + outputs: + list-of-vms: ${{ steps.main.outputs.main }} + environment: main + steps: + - name: Get list of VMs + id: main + env: + GITHUB_TOKEN: ${{ secrets.PAT }} + run: | + RUNNERS=$(curl -L \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer $GITHUB_TOKEN" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + https://api.github.com/repos/NVIDIA/NeMo/actions/runners) + + MATRIX=$(echo $RUNNERS \ + | jq -c '[ + .runners[] + | select(.status == "online") + | select(.name | contains("cpu") | not) + | { + "vm": .name, + "n_gpus": [ + .labels[] + | select(.name | endswith("gpu")) | .name + ][0][:1] + } + ] + ' + ) + echo main=$MATRIX | tee -a "$GITHUB_OUTPUT" + + maintenance: + needs: pre-flight + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.pre-flight.outputs.list-of-vms )}} + uses: ./.github/workflows/monitor-single-vm.yml + with: + vm: ${{ matrix.vm }} + n_gpus: ${{ matrix.n_gpus }} + secrets: inherit # pragma: allowlist secret diff --git a/.github/workflows/release-docs.yml b/.github/workflows/release-docs.yml new file mode 100644 index 0000000000000000000000000000000000000000..c0eb33ede8838d0ac760b210eea680155cf457f3 --- /dev/null +++ b/.github/workflows/release-docs.yml @@ -0,0 +1,123 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: Release docs +on: + workflow_dispatch: + inputs: + dry-run: + description: Whether to run the workflow in dry-run mode + required: true + type: boolean + default: true + publish-as-latest: + description: Publish as Latest stable version. + required: false + type: boolean + default: true + docs-version-override: + description: Docs version if commit is not tagged + required: false + type: string + default: "" + update-version-picker: + description: Update version picker. + required: false + type: boolean + default: true + notify-emails: + description: Email addresses to send the notification to. Format as "me@me.com,you@you.com". + required: false + type: string + github-ref: + description: Github ref to checkout + required: false + type: string + default: "" + workflow_call: + inputs: + dry-run: + description: Whether to run the workflow in dry-run mode + required: false + type: boolean + default: true + publish-as-latest: + description: Publish as Latest stable version. + required: false + type: boolean + default: true + docs-version-override: + description: Docs version if commit is not tagged + required: false + type: string + default: "" + update-version-picker: + description: Update version picker. + required: false + type: boolean + default: true + notify-emails: + description: Email addresses to send the notification to. Format as "me@me.com,you@you.com". + required: false + type: string + github-ref: + description: Github ref to checkout + required: false + type: string + default: "" + +jobs: + build-docs: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_build_docs.yml@v0.83.0 + with: + ref: ${{ inputs.github-ref }} + docs-directory: docs/source + sync-all: true + no-extras: "--no-extra cu12" + + publish-docs: + runs-on: ubuntu-latest + needs: [build-docs] + steps: + - uses: actions/checkout@v6 + with: + repository: NVIDIA-NeMo/FW-CI-templates + ref: v0.74.0 + path: FW-CI-templates + + - uses: ./FW-CI-templates/.github/actions/publish-docs + # This workflow runs either on main, or on a version tag. Any other git ref will lead + # to an error. + # If its on main, it will publish to "latest" directory in Akamai. + # If its on a versioned tag, it will extract the version number from the tag (strip `v` prefix) + # and publish to the versioned directory in Akamai. + with: + dry-run: ${{ inputs.dry-run }} + artifacts-name: docs-html + artifacts-path: _build/html + emails-csv: ${{ inputs.notify-emails && format('{0},{1}', vars.docs_release_emails, inputs.notify-emails) || vars.docs_release_emails }} + overwrite-latest-on-tag: ${{ inputs.publish-as-latest }} + docs-version-override: ${{ inputs.docs-version-override }} + update-version-picker: ${{ inputs.update-version-picker }} + run-on-version-tag-only: ${{ github.ref_name != 'main' }} + request-name: nemo-speech-publish-docs-${{ github.run_id }} + aws-region: ${{ vars.DOCS_AWS_REGION }} + aws-role-to-assume: ${{ secrets.AWS_ASSUME_ROLE_ARN }} + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + akamai-host: ${{ secrets.AKAMAI_HOST }} + akamai-client-token: ${{ secrets.AKAMAI_CLIENT_TOKEN }} + akamai-client-secret: ${{ secrets.AKAMAI_CLIENT_SECRET }} + akamai-access-token: ${{ secrets.AKAMAI_ACCESS_TOKEN }} + s3-target-root: ${{ secrets.S3_BUCKET_NAME }} + s3-target-path: nemo/speech diff --git a/.github/workflows/release-freeze.yml b/.github/workflows/release-freeze.yml new file mode 100644 index 0000000000000000000000000000000000000000..61d15baf906fb86158b8ae0d9f4bd441ef5ab581 --- /dev/null +++ b/.github/workflows/release-freeze.yml @@ -0,0 +1,85 @@ +name: "Code freeze" + +on: + workflow_dispatch: + inputs: + type_of_release: + type: choice + description: Type of release + options: + - major + - minor + freeze-commit: + type: string + description: Commit SHA to use for cut-off + required: false + default: main + mcore_version: + description: "Version of MCore to use (must be a valid git ref)" + required: true + type: string + dry-run: + type: boolean + description: Dry-run of code-freeze + required: false + default: true + +jobs: + code-freeze: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_code_freeze.yml@v0.86.0 + with: + library-name: NeMo-Toolkit + python-package: nemo + release-type: ${{ inputs.type_of_release }} + freeze-commit: ${{ inputs.freeze-commit }} + dry-run: ${{ inputs.dry-run }} + use-pat: true + secrets: + SLACK_WEBHOOK: ${{ secrets.SLACK_RELEASE_ENDPOINT }} + SLACK_WEBHOOK_ADMIN: ${{ secrets.SLACK_WEBHOOK_ADMIN }} + PAT: ${{ secrets.PAT }} + + freeze-tags: + runs-on: ubuntu-latest + needs: [code-freeze] + environment: main + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + path: ${{ github.run_id }} + token: ${{ secrets.PAT }} + fetch-depth: 0 + fetch-tags: true + ref: ${{ inputs.dry-run == true && inputs.freeze-commit || needs.code-freeze.outputs.release-branch }} + + - name: Pin branch name in Notebooks + run: | + cd ${{ github.run_id }} + find tutorials -type f -name "*.ipynb" -exec sed -i "s/BRANCH = 'main'/BRANCH = '${{ needs.code-freeze.outputs.release-branch }}'/g" {} + + + - name: Pin MCore in Dockerfile + run: | + cd ${{ github.run_id }} + sed -i 's/^ARG MCORE_TAG=.*$/ARG MCORE_TAG=${{ inputs.mcore_version }}/' docker/Dockerfile.ci + + - name: Show status + run: | + cd ${{ github.run_id }} + git status + + - name: Create PR + uses: peter-evans/create-pull-request@v6 + id: create-pull-request + if: ${{ inputs.dry-run != true }} + with: + path: ${{ github.run_id }} + base: ${{ needs.code-freeze.outputs.release-branch }} + branch: ci/freeze-tags-${{ needs.code-freeze.outputs.release-branch }} + title: "Freeze tags in in `${{ needs.code-freeze.outputs.release-branch }}`" + body: | + 🚀 PR to freeze tags in `${{ needs.code-freeze.outputs.release-branch }}`. + + commit-message: "[🤠]: Howdy folks, let's release NeMo `${{ needs.code-freeze.outputs.release-branch }}` !" + signoff: true + assignees: okoenig diff --git a/.github/workflows/release-nightly-docs.yml b/.github/workflows/release-nightly-docs.yml new file mode 100644 index 0000000000000000000000000000000000000000..89ceb1fbcd8367cab07f70f6d90179cf7865c6bc --- /dev/null +++ b/.github/workflows/release-nightly-docs.yml @@ -0,0 +1,29 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Release Nightly Docs + +on: + schedule: + - cron: "0 10 * * *" + +jobs: + call-release-docs: + uses: ./.github/workflows/release-docs.yml + with: + dry-run: false + publish-as-latest: false + docs-version-override: "nightly" + update-version-picker: false + secrets: inherit diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000000000000000000000000000000000000..fc2e20fd23c0187998f123117262df528bc297f3 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,83 @@ +# Copyright (c) 2020-2021, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: "Release Neural Modules" + +on: + workflow_dispatch: + inputs: + release-ref: + description: Ref (SHA or branch name) to release + required: true + type: string + version-bump-branch: + description: Branch for version bump + required: true + type: string + dry-run: + description: Do not publish a wheel and GitHub release. + required: true + default: true + type: boolean + create-gh-release: + description: Create a GitHub release + required: true + default: true + type: boolean + generate-changelog: + description: Generate changelog + required: false + default: true + type: boolean + publish-docs: + description: Publish docs + required: false + default: false + type: boolean + gh-release-from-tag: + description: Tag of previous release for changelog builder + required: false + type: string + default: "" +jobs: + release: + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_release_library.yml@v0.80.3 + with: + release-ref: ${{ inputs.release-ref }} + python-package: nemo + python-version: "3.10" + library-name: Neural Modules + dry-run: ${{ inputs.dry-run }} + version-bump-branch: ${{ inputs.version-bump-branch }} + create-gh-release: ${{ inputs.create-gh-release }} + app-id: ${{ vars.BOT_ID }} + gh-release-use-changelog-builder: ${{ inputs.generate-changelog }} + publish-docs: ${{ inputs.publish-docs }} + gh-release-from-tag: ${{ inputs.gh-release-from-tag }} + secrets: + TWINE_USERNAME: ${{ secrets.TWINE_USERNAME }} + TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD }} + SLACK_WEBHOOK_ADMIN: ${{ secrets.SLACK_WEBHOOK_ADMIN }} + SLACK_WEBHOOK: ${{ secrets.SLACK_RELEASE_ENDPOINT }} + PAT: ${{ secrets.PAT }} + SSH_KEY: ${{ secrets.SSH_KEY }} + SSH_PWD: ${{ secrets.SSH_PWD }} + BOT_KEY: ${{ secrets.BOT_KEY }} + AWS_ASSUME_ROLE_ARN: ${{ secrets.AWS_ASSUME_ROLE_ARN }} + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AKAMAI_HOST: ${{ secrets.AKAMAI_HOST }} + AKAMAI_CLIENT_TOKEN: ${{ secrets.AKAMAI_CLIENT_TOKEN }} + AKAMAI_CLIENT_SECRET: ${{ secrets.AKAMAI_CLIENT_SECRET }} + AKAMAI_ACCESS_TOKEN: ${{ secrets.AKAMAI_ACCESS_TOKEN }} + S3_BUCKET_NAME: ${{ secrets.S3_BUCKET_NAME }} diff --git a/.github/workflows/secrets-detector.yml b/.github/workflows/secrets-detector.yml new file mode 100644 index 0000000000000000000000000000000000000000..243cf5af32c178646cd90c1ab94d10e3c2a62d4c --- /dev/null +++ b/.github/workflows/secrets-detector.yml @@ -0,0 +1,43 @@ +# Copyright (c) 2020-2021, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: Secrets detector + +on: + pull_request_target: + branches: + - 'main' + +jobs: + main: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 0 + token: ${{ secrets.NEMO_REFORMAT_TOKEN }} + + - name: Install secrets detector + run: pip install detect-secrets + + - name: Run on change-set + run: | + git diff --name-only --diff-filter=d --merge-base origin/main -z | xargs -0 detect-secrets-hook --disable-plugin HexHighEntropyString --baseline .secrets.baseline + + - uses: EndBug/add-and-commit@v9 + # Commit changes. Nothing is committed if no changes. + if: always() + with: + message: Update baseline + commit: --signoff diff --git a/.github/workflows/update-buildcache.yml b/.github/workflows/update-buildcache.yml new file mode 100644 index 0000000000000000000000000000000000000000..209a1f5bdb968d9f9a23f165d6b7e99fec446dcf --- /dev/null +++ b/.github/workflows/update-buildcache.yml @@ -0,0 +1,110 @@ +# Copyright (c) 2020-2021, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: Update build cache +on: + schedule: + - cron: 0 0 * * * + push: + branches: + - main + workflow_dispatch: + inputs: + runner: + required: false + default: self-hosted-azure-builder + type: string + description: VM to use for build + +jobs: + pre-flight: + runs-on: ubuntu-latest + outputs: + build_args: ${{ steps.manifest.outputs.BUILD_ARGS }} + cache-from: ${{ steps.cache_from.outputs.LAST_PRS }} + steps: + - name: Checkout branch + uses: actions/checkout@v6 + + - name: Parse manifest.json + id: manifest + run: | + BUILD_ARGS=$(cat << EOF + BASE_IMAGE=$(cat requirements/manifest.json | jq -r '."ngc-pytorch"') + TRTLLM_REPO=$(cat requirements/manifest.json | jq -r '."vcs-dependencies"."trt-llm".repo') + TRTLLM_TAG=$(cat requirements/manifest.json | jq -r '."vcs-dependencies"."trt-llm".ref') + MLM_REPO=$(cat requirements/manifest.json | jq -r '."vcs-dependencies"."megatron-lm".repo') + MLM_TAG=$(cat requirements/manifest.json | jq -r '."vcs-dependencies"."megatron-lm".ref') + TE_REPO=$(cat requirements/manifest.json | jq -r '."vcs-dependencies".transformer_engine.repo') + TE_TAG=$(cat requirements/manifest.json | jq -r '."vcs-dependencies".transformer_engine.ref') + APEX_REPO=$(cat requirements/manifest.json | jq -r '."vcs-dependencies".apex.repo') + APEX_TAG=$(cat requirements/manifest.json | jq -r '."vcs-dependencies".apex.ref') + EOF + ) + + echo "BUILD_ARGS<> $GITHUB_OUTPUT + echo "$BUILD_ARGS" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + - name: Get last merged PR + id: cache_from + env: + GH_TOKEN: ${{ github.token }} + run: | + LAST_PRS=$(gh api graphql -f query=' + query { + repository(owner: "NVIDIA", name: "NeMo") { + pullRequests(states: MERGED, first: 100, orderBy: {field: UPDATED_AT, direction: DESC}) { + nodes { + number + } + } + } + }' | jq -r '.data.repository.pullRequests.nodes[].number' | while read -r number; do + echo "nemoci.azurecr.io/nemo_container-buildcache:$number" + done) + + echo "LAST_PRS<> $GITHUB_OUTPUT + echo "$LAST_PRS" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + cicd-test-container-build: + needs: [pre-flight] + uses: NVIDIA-NeMo/FW-CI-templates/.github/workflows/_build_container.yml@v0.27.0 + strategy: + fail-fast: false + matrix: + include: + - dockerfile: docker/Dockerfile.ci + image-name: nemo_container_automodel + - dockerfile: docker/Dockerfile.ci + image-name: nemo_container_nemo2 + - dockerfile: docker/Dockerfile.ci + image-name: nemo_container_speech + - dockerfile: docker/Dockerfile.ci + image-name: nemo_container + with: + image-name: ${{ matrix.image-name }} + dockerfile: ${{ matrix.dockerfile }} + image-label: nemo-core + build-args: | + IMAGE_LABEL=nemo-core + NEMO_TAG=${{ github.sha }} + NEMO_REPO=https://github.com/NVIDIA/NeMo + ${{ needs.pre-flight.outputs.BUILD_ARGS }} + runner: ${{ inputs.runner || 'self-hosted-azure-builder' }} + use-inline-cache: false + prune-filter-timerange: 24h + cache-from: | + nemoci.azurecr.io/${{ matrix.image-name }}-buildcache:main + ${{ needs.pre-flight.outputs.cache-from }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a6544cbf4216a172225e64bd95a11a86b7fdd05a --- /dev/null +++ b/.gitignore @@ -0,0 +1,194 @@ +# log and data files +*.model +*.pkl +#*.ipynb +output +output_2048 +result +*.pt +tests/data/asr +.DS_Store +bert.pt.json +work +runs +fastspeech_output +.hydra +.bash_history.local + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class +**.pyc + +# C extensions +*.so + +# Distribution / packaging +.idea +.Python +wandb +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +#parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/build +docs/source/_build + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# Override Jupyter in Github Language states for more accurate estimate of repo code. +# Reference: https://github.com/github/linguist/blob/master/docs/overrides.md#generated-code +*.ipynb linguist-generated + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don’t work, or not +# install all needed dependencies. +#Pipfile.lock + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# VSCode project settins +.vscode/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site +/docs/html +/docs/docs_zh/zh + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Emacs backup files +*~ + +cifar-10-batches-py +*.tar.gz + +# Test data. +tests/.data +tests/data + +# outputs folder +examples/*/outputs +examples/*/NeMo_experiments +examples/*/nemo_experiments +examples/*/.hydra +examples/*/wandb +examples/*/data +wandb +dump.py + +docs/sources/source/test_build/ + +# Checkpoints, config files and temporary files created in tutorials. +examples/neural_graphs/*.chkpt +examples/neural_graphs/*.yml + +.hydra/ +nemo_experiments/ + +slurm*.out + +# Onelogger +onelogger.* + +# voice agent +node_modules/ +.vite/ +bot_server.* +audio_logs/ +eval_results/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f22130628720e34500490ab2b12ef91fb6a36a0 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,52 @@ +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +default_language_version: + python: python3 + +ci: + autofix_prs: true + autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions' + autoupdate_schedule: quarterly + # skip all hooks that can change the files, use GitHub Action "code-formatting.yml" for this + skip: [black,isort] + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.3.0 + hooks: + - id: check-yaml + - id: check-case-conflict + - id: detect-private-key + - id: check-added-large-files + args: ['--maxkb=1000'] + - id: requirements-txt-fixer + + - repo: https://github.com/PyCQA/isort + rev: 5.13.2 + hooks: + - id: isort + name: Format imports + exclude: docs/ + + # Using this mirror lets us use mypyc-compiled black, which is about 2x faster + - repo: https://github.com/psf/black-pre-commit-mirror + rev: 24.3.0 + hooks: + - id: black + # It is recommended to specify the latest version of Python + # supported by your project here, or alternatively use + # pre-commit's default_language_version, see + # https://pre-commit.com/#top_level-default_language_version + language_version: python3.10 diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000000000000000000000000000000000000..0206951e05d2501e15555addd93b7fb8fb80d1e9 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,5 @@ +[MAIN] +ignore-paths=tests +max-line-length=119 +ignore-patterns=.*\.ipynb$ +recursive=y diff --git a/.pylintrc.other b/.pylintrc.other new file mode 100644 index 0000000000000000000000000000000000000000..64a576751e5ff592792e32896e01f248b3513bd7 --- /dev/null +++ b/.pylintrc.other @@ -0,0 +1,12 @@ +[MAIN] +ignore-paths=tests +max-line-length=119 + +[MESSAGES CONTROL] +disable=all + +enable=C0115,C0116,W0611,C0301 +# C0115: missing-class-docstring +# C0116: missing-function-docstring +# W0611: unused-import +# C0301: line-too-long diff --git a/.pylintrc.speech b/.pylintrc.speech new file mode 100644 index 0000000000000000000000000000000000000000..9c8830567460e63bdfe2a760c91076c02cddc188 --- /dev/null +++ b/.pylintrc.speech @@ -0,0 +1,9 @@ +[MAIN] +ignore-paths=tests +max-line-length=119 + +[MESSAGES CONTROL] +disable=all + +enable=W0611 +# W0611: unused-import diff --git a/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ee18e6dee1e0dd8859baeb76f46ea0677f0cbe9 --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,35 @@ +# ============================================================================= +# Copyright (c) 2020 NVIDIA. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required field. +version: 2 + +build: + os: ubuntu-22.04 + tools: + python: "3.10" + +# Build documentation in the docs/ directory with Sphinx. +sphinx: + configuration: docs/source/conf.py + +# Set the version of Python and requirements required to build your docs +python: + install: + - requirements: requirements/requirements_docs.txt diff --git a/.secrets.baseline b/.secrets.baseline new file mode 100644 index 0000000000000000000000000000000000000000..aa34e710656f3a9ad02ec9c78962ce6504d09ea2 --- /dev/null +++ b/.secrets.baseline @@ -0,0 +1,2082 @@ +{ + "version": "1.5.0", + "plugins_used": [ + { + "name": "ArtifactoryDetector" + }, + { + "name": "AWSKeyDetector" + }, + { + "name": "AzureStorageKeyDetector" + }, + { + "name": "Base64HighEntropyString", + "limit": 4.5 + }, + { + "name": "BasicAuthDetector" + }, + { + "name": "CloudantDetector" + }, + { + "name": "DiscordBotTokenDetector" + }, + { + "name": "GitHubTokenDetector" + }, + { + "name": "GitLabTokenDetector" + }, + { + "name": "HexHighEntropyString", + "limit": 3.0 + }, + { + "name": "IbmCloudIamDetector" + }, + { + "name": "IbmCosHmacDetector" + }, + { + "name": "IPPublicDetector" + }, + { + "name": "JwtTokenDetector" + }, + { + "name": "KeywordDetector", + "keyword_exclude": "" + }, + { + "name": "MailchimpDetector" + }, + { + "name": "NpmDetector" + }, + { + "name": "OpenAIDetector" + }, + { + "name": "PrivateKeyDetector" + }, + { + "name": "PypiTokenDetector" + }, + { + "name": "SendGridDetector" + }, + { + "name": "SlackDetector" + }, + { + "name": "SoftlayerDetector" + }, + { + "name": "SquareOAuthDetector" + }, + { + "name": "StripeDetector" + }, + { + "name": "TelegramBotTokenDetector" + }, + { + "name": "TwilioKeyDetector" + } + ], + "filters_used": [ + { + "path": "detect_secrets.filters.allowlist.is_line_allowlisted" + }, + { + "path": "detect_secrets.filters.common.is_baseline_file", + "filename": ".secrets.baseline" + }, + { + "path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies", + "min_level": 2 + }, + { + "path": "detect_secrets.filters.heuristic.is_indirect_reference" + }, + { + "path": "detect_secrets.filters.heuristic.is_likely_id_string" + }, + { + "path": "detect_secrets.filters.heuristic.is_lock_file" + }, + { + "path": "detect_secrets.filters.heuristic.is_not_alphanumeric_string" + }, + { + "path": "detect_secrets.filters.heuristic.is_potential_uuid" + }, + { + "path": "detect_secrets.filters.heuristic.is_prefixed_with_dollar_sign" + }, + { + "path": "detect_secrets.filters.heuristic.is_sequential_string" + }, + { + "path": "detect_secrets.filters.heuristic.is_swagger_file" + }, + { + "path": "detect_secrets.filters.heuristic.is_templated_secret" + } + ], + "results": { + ".github/workflows/node-reboot.yml": [ + { + "type": "Secret Keyword", + "filename": ".github/workflows/node-reboot.yml", + "hashed_secret": "3e26d6750975d678acb8fa35a0f69237881576b0", + "is_verified": false, + "line_number": 52 + } + ], + "docs/source/nlp/question_answering.rst": [ + { + "type": "Hex High Entropy String", + "filename": "docs/source/nlp/question_answering.rst", + "hashed_secret": "22e6f19f702bbd215acc1862da6acba7e874674e", + "is_verified": false, + "line_number": 130 + } + ], + "examples/multimodal/multimodal_llm/neva/conf/lita_config.yaml": [ + { + "type": "Base64 High Entropy String", + "filename": "examples/multimodal/multimodal_llm/neva/conf/lita_config.yaml", + "hashed_secret": "a90ca639abde504aba67797b0663923a0075fe6e", + "is_verified": false, + "line_number": 75 + } + ], + "examples/multimodal/multimodal_llm/neva/conf/neva_inference.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/multimodal/multimodal_llm/neva/conf/neva_inference.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 50 + } + ], + "examples/nlp/information_retrieval/conf/megatron_gpt_embedder_generate_config.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/information_retrieval/conf/megatron_gpt_embedder_generate_config.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 165 + } + ], + "examples/nlp/language_modeling/conf/megatron_baichuan2_inference.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/conf/megatron_baichuan2_inference.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 38 + } + ], + "examples/nlp/language_modeling/conf/megatron_chatglm_inference.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/conf/megatron_chatglm_inference.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 38 + } + ], + "examples/nlp/language_modeling/conf/megatron_falcon_inference.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/conf/megatron_falcon_inference.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 37 + } + ], + "examples/nlp/language_modeling/conf/megatron_gpt_inference.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/conf/megatron_gpt_inference.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 41 + } + ], + "examples/nlp/language_modeling/conf/megatron_griffin_generate_config.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/conf/megatron_griffin_generate_config.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 239 + } + ], + "examples/nlp/language_modeling/conf/megatron_llama_inference.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/conf/megatron_llama_inference.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 38 + } + ], + "examples/nlp/language_modeling/conf/megatron_mamba_inference.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/conf/megatron_mamba_inference.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 40 + } + ], + "examples/nlp/language_modeling/conf/megatron_qwen2_inference.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/conf/megatron_qwen2_inference.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 38 + } + ], + "examples/nlp/language_modeling/tuning/conf/megatron_gpt_generate_config.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/tuning/conf/megatron_gpt_generate_config.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 160 + } + ], + "examples/nlp/language_modeling/tuning/conf/megatron_mamba_generate_config.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/tuning/conf/megatron_mamba_generate_config.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 168 + } + ], + "examples/nlp/language_modeling/tuning/conf/megatron_t5_generate_config.yaml": [ + { + "type": "Secret Keyword", + "filename": "examples/nlp/language_modeling/tuning/conf/megatron_t5_generate_config.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 157 + } + ], + "scripts/checkpoint_converters/convert_mistral_7b_hf_to_nemo.py": [ + { + "type": "Hex High Entropy String", + "filename": "scripts/checkpoint_converters/convert_mistral_7b_hf_to_nemo.py", + "hashed_secret": "e0308bd21bffc156d79208f9ecf130370a015002", + "is_verified": false, + "line_number": 471 + } + ], + "scripts/dataset_processing/nlp/intent_and_slot/assistant_utils.py": [ + { + "type": "Base64 High Entropy String", + "filename": "scripts/dataset_processing/nlp/intent_and_slot/assistant_utils.py", + "hashed_secret": "adfce53cfc5a36ea58ba816ea6d005231db6455c", + "is_verified": false, + "line_number": 40 + } + ], + "scripts/nlp_language_modeling/service_launch_scripts/conf/retro_web_server.yaml": [ + { + "type": "Secret Keyword", + "filename": "scripts/nlp_language_modeling/service_launch_scripts/conf/retro_web_server.yaml", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 9 + } + ], + "scripts/nlp_language_modeling/service_launch_scripts/env_variables.sh": [ + { + "type": "Secret Keyword", + "filename": "scripts/nlp_language_modeling/service_launch_scripts/env_variables.sh", + "hashed_secret": "109f4b3c50d7b0df729d299bc6f8e9ef9066971f", + "is_verified": false, + "line_number": 33 + } + ], + "scripts/tts_dataset_files/cmudict-0.7b_nv22.10": [ + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/cmudict-0.7b_nv22.10", + "hashed_secret": "27b998c0976876189b861934085bba2964e49a11", + "is_verified": false, + "line_number": 4873 + } + ], + "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict": [ + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "6a1c698aa2f0b96b536710f5a2abd0ca64fdb2c1", + "is_verified": false, + "line_number": 8415 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "9a611ff964db23d7cd8a6f63beb7471144f6be92", + "is_verified": false, + "line_number": 8421 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "f2f0bc1252ccb8bbc113859849f8c36be203fd9e", + "is_verified": false, + "line_number": 8424 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "b65cab561c4acd1e20bafd08ce19a9e7b5ea9e1c", + "is_verified": false, + "line_number": 8431 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "c08ba5eff4953649130e83149817e1087c183358", + "is_verified": false, + "line_number": 8433 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "b182776899d0959f28f3d80c7d50317de5c0fb2b", + "is_verified": false, + "line_number": 8441 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "e466719c0309450475aa6b0e0c53a2211db0176d", + "is_verified": false, + "line_number": 8442 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "0e7ae57946d9c88ce5f017ac50640e2c93c5277b", + "is_verified": false, + "line_number": 8443 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "6d13086a143b48a00e3aa745a955095fbbc075b2", + "is_verified": false, + "line_number": 8444 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "d206dd2b79987f5989b23a7a43d6163ed48312f0", + "is_verified": false, + "line_number": 8446 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "be10bcbbe755bdd51e856af50af01bb4f95bfedb", + "is_verified": false, + "line_number": 8449 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "2f00d2108827b933019dbedc8cc3f9c84f3bfe1e", + "is_verified": false, + "line_number": 8451 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "a705c12d23346a892256fa95c892304bd8f4d265", + "is_verified": false, + "line_number": 8454 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "2471810862c167bed6c3a8383dd410aedb8cb7e1", + "is_verified": false, + "line_number": 8456 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "34befc5cf63e9c9259c7e75714c81db892419549", + "is_verified": false, + "line_number": 8464 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "343d4559dcb06080b6fc5a9f42fbb88b6e343526", + "is_verified": false, + "line_number": 8470 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "96631b5faaa50b4d24076072a357a13f48f1435f", + "is_verified": false, + "line_number": 8472 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "c5be9fd8c751b6d2ff6219c63de90e4aa9f97546", + "is_verified": false, + "line_number": 8477 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "4f68de76b2c605cb67d99b1e97b1461ef4618db2", + "is_verified": false, + "line_number": 8479 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "90d1db77f31a86c5e0081468e0dbda8172b70131", + "is_verified": false, + "line_number": 8508 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "6f3ce73b5dfbe7e4948bdad86c804ce74e17e0cf", + "is_verified": false, + "line_number": 8510 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "a1f22c6489b0cf0016b9364619a7d7eed95b6364", + "is_verified": false, + "line_number": 8512 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "b55ad569f88dc7e42868047f4f4a59c3cb6c110a", + "is_verified": false, + "line_number": 8519 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "f2c207cddfe45b6c893619c3757f264f721025c6", + "is_verified": false, + "line_number": 8521 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "d1371bfdfaf5d02731488ca6b6f12e51617813ab", + "is_verified": false, + "line_number": 8549 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "76d22e171aa272dbdd6d1d67c23d9f700362f09a", + "is_verified": false, + "line_number": 8555 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "0efe19de03cdaa4a382654246b4bff22dd79e518", + "is_verified": false, + "line_number": 8568 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "d318e8342db9deb2f6827f39fad6229ca4e4521a", + "is_verified": false, + "line_number": 8581 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "fb99a4a93e08e86cf5f4475aba66e85def711752", + "is_verified": false, + "line_number": 8586 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "04ebb8445e6050d78c4636b19a17221387216b0d", + "is_verified": false, + "line_number": 8588 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "2ec592daffb8a6e8c402690f7aadac6475c5f2ec", + "is_verified": false, + "line_number": 8591 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "f7df3933dce6e3f5843b7e55ccff8f2516302229", + "is_verified": false, + "line_number": 8601 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "fe860f7095f48e2f6a63b97124da4afd8c987895", + "is_verified": false, + "line_number": 8606 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "abd3d69f7d8c98bb7fe98cb6aa41bf3d42d23911", + "is_verified": false, + "line_number": 8609 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "2070834a550a6fbae2a3912e1117fa9f4270752b", + "is_verified": false, + "line_number": 8619 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "e7d64bf030b802c205af2832114589c141ea1f33", + "is_verified": false, + "line_number": 8622 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "c84bccf09830b2804e4d59e8bf82393ae76a8b03", + "is_verified": false, + "line_number": 8625 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "86888ce709ad4a2590221da4f4d602a254443470", + "is_verified": false, + "line_number": 8628 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "ae5da5b749fe3b2aea4957c7ee83938a75622bb7", + "is_verified": false, + "line_number": 8645 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "94ccf1bc68c1a19f5733d9ac6e5bb60166e6530d", + "is_verified": false, + "line_number": 8647 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "892dbf65134c4dfb554a16f5fc387ef153e269ed", + "is_verified": false, + "line_number": 8697 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "61bfa79fd6923bc44a8c8c500b8992a66f5ae340", + "is_verified": false, + "line_number": 8703 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "db880cb9754850e54f247dc1f7d1cce5f80ec056", + "is_verified": false, + "line_number": 8718 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "a020736e7f661dc0d7985bfdcfadb7dce8db6216", + "is_verified": false, + "line_number": 8719 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "ee8ddcdb18d90b8ddc8d9d4bb28e7fe700965ea8", + "is_verified": false, + "line_number": 8720 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "f5726d5cd941bc5fd7cd26fdbf6d1ed5750e55bd", + "is_verified": false, + "line_number": 8721 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "49e5b074ecc6a910f32617b1d2103849177a254e", + "is_verified": false, + "line_number": 8750 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "e0a73b397eafd55a2f9cac7b031bf8716bc2b79e", + "is_verified": false, + "line_number": 8751 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "9c593b1ecb2cfed50a12793d23fb3fc0cd5f5e21", + "is_verified": false, + "line_number": 8762 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "e1db0a80a43c626e55171566c5823588cfb02fd8", + "is_verified": false, + "line_number": 8764 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "a5f7d1f0a545e46e361e56191788d0f5fee625fb", + "is_verified": false, + "line_number": 8772 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "4d199d4ccaea5f654b23dbc22e54acd79cc76e8c", + "is_verified": false, + "line_number": 8774 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "865d1b874b4cd866febe48e024ed94af5303f808", + "is_verified": false, + "line_number": 8775 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "fa25b96c74c4f77bb3eb89c55a7ab88550d12de5", + "is_verified": false, + "line_number": 8776 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "a21fc67d6e3ff4d5f39596793a9e2b01c608d69f", + "is_verified": false, + "line_number": 8777 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "b2e00015ad1a9cb779655b48a19eff8c834bc36e", + "is_verified": false, + "line_number": 8778 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "ca51add4d292a3744a883a8844bcbf067b34b468", + "is_verified": false, + "line_number": 8779 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "8479cbf554082f4f4b3c9587f21c62f406940e93", + "is_verified": false, + "line_number": 8782 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "d1edb7ebbefe0dd0dfcddce8e0b7e63e74430a5b", + "is_verified": false, + "line_number": 8784 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "c8b9b705e819ebeba33d4ff4f6dc638a9ee1f47c", + "is_verified": false, + "line_number": 8787 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "250c748db4a13f7a3cff6ff0934bb0338e9f3190", + "is_verified": false, + "line_number": 8788 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "6035f3432d36e33f2a57c3c6ee62014a9fb95a19", + "is_verified": false, + "line_number": 8789 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_ES/es_ES_nv230301.dict", + "hashed_secret": "82b23ffc5cea766826613f29718bc1e3023f58e8", + "is_verified": false, + "line_number": 8790 + } + ], + "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict": [ + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "6a1c698aa2f0b96b536710f5a2abd0ca64fdb2c1", + "is_verified": false, + "line_number": 8743 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "9a611ff964db23d7cd8a6f63beb7471144f6be92", + "is_verified": false, + "line_number": 8751 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "f2f0bc1252ccb8bbc113859849f8c36be203fd9e", + "is_verified": false, + "line_number": 8755 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "b65cab561c4acd1e20bafd08ce19a9e7b5ea9e1c", + "is_verified": false, + "line_number": 8764 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "c08ba5eff4953649130e83149817e1087c183358", + "is_verified": false, + "line_number": 8766 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "b182776899d0959f28f3d80c7d50317de5c0fb2b", + "is_verified": false, + "line_number": 8774 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "e466719c0309450475aa6b0e0c53a2211db0176d", + "is_verified": false, + "line_number": 8775 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "0e7ae57946d9c88ce5f017ac50640e2c93c5277b", + "is_verified": false, + "line_number": 8776 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "6d13086a143b48a00e3aa745a955095fbbc075b2", + "is_verified": false, + "line_number": 8777 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "d206dd2b79987f5989b23a7a43d6163ed48312f0", + "is_verified": false, + "line_number": 8779 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "be10bcbbe755bdd51e856af50af01bb4f95bfedb", + "is_verified": false, + "line_number": 8782 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "2f00d2108827b933019dbedc8cc3f9c84f3bfe1e", + "is_verified": false, + "line_number": 8784 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "a705c12d23346a892256fa95c892304bd8f4d265", + "is_verified": false, + "line_number": 8787 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "2471810862c167bed6c3a8383dd410aedb8cb7e1", + "is_verified": false, + "line_number": 8789 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "34befc5cf63e9c9259c7e75714c81db892419549", + "is_verified": false, + "line_number": 8797 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "343d4559dcb06080b6fc5a9f42fbb88b6e343526", + "is_verified": false, + "line_number": 8803 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "96631b5faaa50b4d24076072a357a13f48f1435f", + "is_verified": false, + "line_number": 8805 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "c5be9fd8c751b6d2ff6219c63de90e4aa9f97546", + "is_verified": false, + "line_number": 8810 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "4f68de76b2c605cb67d99b1e97b1461ef4618db2", + "is_verified": false, + "line_number": 8812 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "90d1db77f31a86c5e0081468e0dbda8172b70131", + "is_verified": false, + "line_number": 8841 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "6f3ce73b5dfbe7e4948bdad86c804ce74e17e0cf", + "is_verified": false, + "line_number": 8843 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "a1f22c6489b0cf0016b9364619a7d7eed95b6364", + "is_verified": false, + "line_number": 8845 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "b55ad569f88dc7e42868047f4f4a59c3cb6c110a", + "is_verified": false, + "line_number": 8854 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "f2c207cddfe45b6c893619c3757f264f721025c6", + "is_verified": false, + "line_number": 8856 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "d1371bfdfaf5d02731488ca6b6f12e51617813ab", + "is_verified": false, + "line_number": 8884 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "76d22e171aa272dbdd6d1d67c23d9f700362f09a", + "is_verified": false, + "line_number": 8890 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "0efe19de03cdaa4a382654246b4bff22dd79e518", + "is_verified": false, + "line_number": 8903 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "d318e8342db9deb2f6827f39fad6229ca4e4521a", + "is_verified": false, + "line_number": 8916 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "fb99a4a93e08e86cf5f4475aba66e85def711752", + "is_verified": false, + "line_number": 8921 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "04ebb8445e6050d78c4636b19a17221387216b0d", + "is_verified": false, + "line_number": 8923 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "2ec592daffb8a6e8c402690f7aadac6475c5f2ec", + "is_verified": false, + "line_number": 8926 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "f7df3933dce6e3f5843b7e55ccff8f2516302229", + "is_verified": false, + "line_number": 8936 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "fe860f7095f48e2f6a63b97124da4afd8c987895", + "is_verified": false, + "line_number": 8941 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "abd3d69f7d8c98bb7fe98cb6aa41bf3d42d23911", + "is_verified": false, + "line_number": 8944 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "2070834a550a6fbae2a3912e1117fa9f4270752b", + "is_verified": false, + "line_number": 8954 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "e7d64bf030b802c205af2832114589c141ea1f33", + "is_verified": false, + "line_number": 8958 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "c84bccf09830b2804e4d59e8bf82393ae76a8b03", + "is_verified": false, + "line_number": 8962 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "86888ce709ad4a2590221da4f4d602a254443470", + "is_verified": false, + "line_number": 8966 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "ae5da5b749fe3b2aea4957c7ee83938a75622bb7", + "is_verified": false, + "line_number": 8997 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "94ccf1bc68c1a19f5733d9ac6e5bb60166e6530d", + "is_verified": false, + "line_number": 8999 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "892dbf65134c4dfb554a16f5fc387ef153e269ed", + "is_verified": false, + "line_number": 9050 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "61bfa79fd6923bc44a8c8c500b8992a66f5ae340", + "is_verified": false, + "line_number": 9058 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "db880cb9754850e54f247dc1f7d1cce5f80ec056", + "is_verified": false, + "line_number": 9076 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "a020736e7f661dc0d7985bfdcfadb7dce8db6216", + "is_verified": false, + "line_number": 9077 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "ee8ddcdb18d90b8ddc8d9d4bb28e7fe700965ea8", + "is_verified": false, + "line_number": 9078 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "f5726d5cd941bc5fd7cd26fdbf6d1ed5750e55bd", + "is_verified": false, + "line_number": 9079 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "49e5b074ecc6a910f32617b1d2103849177a254e", + "is_verified": false, + "line_number": 9108 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "e0a73b397eafd55a2f9cac7b031bf8716bc2b79e", + "is_verified": false, + "line_number": 9109 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "9c593b1ecb2cfed50a12793d23fb3fc0cd5f5e21", + "is_verified": false, + "line_number": 9120 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "e1db0a80a43c626e55171566c5823588cfb02fd8", + "is_verified": false, + "line_number": 9122 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "a5f7d1f0a545e46e361e56191788d0f5fee625fb", + "is_verified": false, + "line_number": 9130 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "4d199d4ccaea5f654b23dbc22e54acd79cc76e8c", + "is_verified": false, + "line_number": 9132 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "865d1b874b4cd866febe48e024ed94af5303f808", + "is_verified": false, + "line_number": 9133 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "fa25b96c74c4f77bb3eb89c55a7ab88550d12de5", + "is_verified": false, + "line_number": 9134 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "a21fc67d6e3ff4d5f39596793a9e2b01c608d69f", + "is_verified": false, + "line_number": 9135 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "b2e00015ad1a9cb779655b48a19eff8c834bc36e", + "is_verified": false, + "line_number": 9136 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "ca51add4d292a3744a883a8844bcbf067b34b468", + "is_verified": false, + "line_number": 9137 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "8479cbf554082f4f4b3c9587f21c62f406940e93", + "is_verified": false, + "line_number": 9140 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "d1edb7ebbefe0dd0dfcddce8e0b7e63e74430a5b", + "is_verified": false, + "line_number": 9142 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "c8b9b705e819ebeba33d4ff4f6dc638a9ee1f47c", + "is_verified": false, + "line_number": 9145 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "250c748db4a13f7a3cff6ff0934bb0338e9f3190", + "is_verified": false, + "line_number": 9146 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "6035f3432d36e33f2a57c3c6ee62014a9fb95a19", + "is_verified": false, + "line_number": 9147 + }, + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/es_LA/es_LA_nv230301.dict", + "hashed_secret": "82b23ffc5cea766826613f29718bc1e3023f58e8", + "is_verified": false, + "line_number": 9148 + } + ], + "scripts/tts_dataset_files/ipa_cmudict-0.7b_nv23.01.txt": [ + { + "type": "Artifactory Credentials", + "filename": "scripts/tts_dataset_files/ipa_cmudict-0.7b_nv23.01.txt", + "hashed_secret": "27b998c0976876189b861934085bba2964e49a11", + "is_verified": false, + "line_number": 4886 + } + ], + "tests/hydra/config1_invalid.yaml": [ + { + "type": "Secret Keyword", + "filename": "tests/hydra/config1_invalid.yaml", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 2 + } + ], + "tests/hydra/config_subdir/config2_invalid.yaml": [ + { + "type": "Secret Keyword", + "filename": "tests/hydra/config_subdir/config2_invalid.yaml", + "hashed_secret": "ebf1f14a3530cd22650b951908b5159f1f2a3ca8", + "is_verified": false, + "line_number": 2 + } + ], + "tutorials/asr/Multilang_ASR.ipynb": [ + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "23ab3508f39164c81139e2bc866ebe46b69248f3", + "is_verified": false, + "line_number": 562 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "bfbd2a23ecc348e67d5cb55f2db6bf9f9cebb325", + "is_verified": false, + "line_number": 563 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "81dee32e25f1d0c256140df030b2531dde332acb", + "is_verified": false, + "line_number": 564 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "4af542b2d6e243a440ad4cf2815d6e2237808df5", + "is_verified": false, + "line_number": 565 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "a67ed767388e7eece04b5c6f7b568ddf29edac7c", + "is_verified": false, + "line_number": 566 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "c022505b9f732f0cb352fe8ed5fc278912b46488", + "is_verified": false, + "line_number": 567 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "182d4019337b9c8786b6e34a83441a21bad1874b", + "is_verified": false, + "line_number": 568 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "740eb48367bc73edfc56bc4414e9b2662736566c", + "is_verified": false, + "line_number": 569 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "b1aef696788110cd1e18595d6cebb0959d36adfa", + "is_verified": false, + "line_number": 570 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "c7fe8bf177365ffe460c15da553c7368ddfdbaa7", + "is_verified": false, + "line_number": 571 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "f3112d03411e69f7a23d5d1582079e1173cd032e", + "is_verified": false, + "line_number": 572 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "46859f9c2007195e9762d88c36247d018859f09d", + "is_verified": false, + "line_number": 676 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "afc8f88c8c20204370c5f35925ef36fc71c71379", + "is_verified": false, + "line_number": 677 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "df94d52f84db3fa667993f544ea80aca4f9a2125", + "is_verified": false, + "line_number": 678 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "783c5002441b0a6225cc26f71864f7f8504ef819", + "is_verified": false, + "line_number": 679 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "469b7833ff898575016f6df77172c9fc910efdf7", + "is_verified": false, + "line_number": 680 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "90771a6f73123f8665fe199fa920d06ff407ec72", + "is_verified": false, + "line_number": 681 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "cbf4db9d163e190540825e529b55b551ba21733a", + "is_verified": false, + "line_number": 682 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "4f58de63d50f78243fadbf94a08fc58fb51d1428", + "is_verified": false, + "line_number": 683 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "2dc56a67a4ab217c7197c4ce468e0dbe7f20d54b", + "is_verified": false, + "line_number": 684 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "a4d526869e953d0eebcfd7948f798ba1d39397c4", + "is_verified": false, + "line_number": 685 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "8109bf627c2f367f0f75ec0fc4079040d46ea65b", + "is_verified": false, + "line_number": 686 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "05d48a4ba182e2966da054c756e527a7304b586e", + "is_verified": false, + "line_number": 1148 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "a091c7128789cea09adabf026a3dbd7b0febcfef", + "is_verified": false, + "line_number": 1149 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "38403bcc580ba265c4918eaea606399cf37689a2", + "is_verified": false, + "line_number": 1150 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "d572b2cd7c13cbb69a638f2b978da146b34340df", + "is_verified": false, + "line_number": 1151 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "f97db3647a1e5869756fc4019bf198e900034e67", + "is_verified": false, + "line_number": 1152 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "ae0722be63cd884e5788cc8153a9f7728d54f72c", + "is_verified": false, + "line_number": 1153 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "d694e89fef75e8d868accaba50c224a1f2dd8399", + "is_verified": false, + "line_number": 1154 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "8e2fe85dc67f14fa2f02ffa465974dec89655856", + "is_verified": false, + "line_number": 1155 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "e23d0990cdb54a3d1dc3c9bcf922242fc7bacc64", + "is_verified": false, + "line_number": 1156 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "d49a849228aa07e957274e8b1349405868626e56", + "is_verified": false, + "line_number": 1157 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "a32050f253ef8a9f61b37ac26180efb6acf0bb30", + "is_verified": false, + "line_number": 1158 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "834213b15871dbd6b30f517de52ec9df2730eb7b", + "is_verified": false, + "line_number": 1196 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "b0555871dc9fc34a149b82e62fc72fc654b84667", + "is_verified": false, + "line_number": 1197 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "32fe03ac71cc6c8a31c72e21c9aec64557cb4fba", + "is_verified": false, + "line_number": 1198 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "3e712f05fedce2068adf4f6ac44b3759a1fbbd59", + "is_verified": false, + "line_number": 1199 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "f8472c93db4afd582aafddcc5a2dd8d568cb3e43", + "is_verified": false, + "line_number": 1200 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "1d8c14b1e24558e9cdbd47644f36c5675edcdcca", + "is_verified": false, + "line_number": 1201 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "2a11395949beadb049a0cd129b6f5e3aa3782814", + "is_verified": false, + "line_number": 1202 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "edae2d92434824df126daa3340589b60da2afa67", + "is_verified": false, + "line_number": 1203 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "cc9e0c1b12b1abaffa7eb6cbccbee72f65ac1535", + "is_verified": false, + "line_number": 1204 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "e80f107771869ec656d0cf6e8486486b69f922ae", + "is_verified": false, + "line_number": 1205 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "160fb2093e3388000d26c76d25428170a035bdcf", + "is_verified": false, + "line_number": 1206 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "9488ce4f041c4c3b404ff21110170940ce5295f2", + "is_verified": false, + "line_number": 2028 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "4fb50b7293c24d257d3b39eec254517e73cd27be", + "is_verified": false, + "line_number": 2029 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "2d3ad63f96d6f447f63a2ec9d451ba34a8c8013e", + "is_verified": false, + "line_number": 2030 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "7c0a1424bcd4d5086497ba05ff5d2b5c11112655", + "is_verified": false, + "line_number": 2031 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "5582b5110b9376a45e2329d2d127f972673287a9", + "is_verified": false, + "line_number": 2032 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "e99b32711f4beb0cd40130d75016b45ec188eac0", + "is_verified": false, + "line_number": 2033 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "5cbed1a68bafa82a8a0ff59f03c8f28148081f1e", + "is_verified": false, + "line_number": 2034 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "d7604ec9987dc19cfd2e512d1fdab6f1ceb41a7c", + "is_verified": false, + "line_number": 2035 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "b329420ee2aa11facc5a652f2bb32ca0f186c442", + "is_verified": false, + "line_number": 2036 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "f16bb2651aa872a8d12dd98e11efb58bd23da895", + "is_verified": false, + "line_number": 2037 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "74032a5243a1cf863a7e84e1749a3fac81e7290f", + "is_verified": false, + "line_number": 2038 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "b5b39748fce09b60e94b21b466c52c791d627cba", + "is_verified": false, + "line_number": 2039 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "db98703d26bdf4616c4e65036986b6355611211f", + "is_verified": false, + "line_number": 2040 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "4d14a5871469d7490614a53cab3fbfc52a7279e5", + "is_verified": false, + "line_number": 2041 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "258ddab91bab22bd68bc3015ea889521fa3fdacd", + "is_verified": false, + "line_number": 2042 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "6d7a940238710f5f734f1816fc47959ef7f95636", + "is_verified": false, + "line_number": 2043 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "de52434f2efe55aed0df2256de9abd275539cf0b", + "is_verified": false, + "line_number": 2044 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "4cd4d2a18051aaad9320442a4377cd18577f73f9", + "is_verified": false, + "line_number": 2045 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "954ca4decf6425679bb28e223ff6b137c1e9ce6e", + "is_verified": false, + "line_number": 2046 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "f6b0d563b01f1250220b29dbdf5f70c14d206be7", + "is_verified": false, + "line_number": 2047 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "99285fb5e057fc901d1877f1f0c8b8c94ecd1358", + "is_verified": false, + "line_number": 2048 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "faa5674f871179e8abe110c410403b51893c917f", + "is_verified": false, + "line_number": 2049 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "92a0615e0edaf88003fb0b6f70dc77de93828bb8", + "is_verified": false, + "line_number": 2103 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "77351aa360f4c3e50ef4cd700bba74219d5b5aa2", + "is_verified": false, + "line_number": 2104 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "c7226bd151222bb3ab574a4d21d83d97ed054112", + "is_verified": false, + "line_number": 2105 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "f73edb9e83b0f41052050055ac563973a6850afb", + "is_verified": false, + "line_number": 2106 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "346a54ded37ddfd7de0b98b3f8a6fefb92c97ec5", + "is_verified": false, + "line_number": 2107 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "078cde4cd776c14c9166304412a643cff409faa0", + "is_verified": false, + "line_number": 2108 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "4a3c4394031a7842a72b787cf5b08a165e8b7206", + "is_verified": false, + "line_number": 2109 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "406aa8259676acb13859b17f5e1f94fcdb69c0d6", + "is_verified": false, + "line_number": 2110 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "3607002f0fabd7bbbe4e90715beb1c85a6ade333", + "is_verified": false, + "line_number": 2111 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "465ee282a0d7b2cf762d9dbce0b1f356d75bc15d", + "is_verified": false, + "line_number": 2112 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "44608c743318ec5489b23a388f4f6e0f724ac0a8", + "is_verified": false, + "line_number": 2113 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "1a4251d6b7ba19233f16766868ac29e3428db4f0", + "is_verified": false, + "line_number": 2203 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "55dd3f4c1b8682cf8ec7b21243cdffe0127f0e03", + "is_verified": false, + "line_number": 2204 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "220d1fa41654cb432843792dd63e8f446eedefa9", + "is_verified": false, + "line_number": 2205 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "35654d3cde31330d1e3fd05a04d4cbea41c1f993", + "is_verified": false, + "line_number": 2206 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "119aea04e3efd1c741bfd98fe51439d6bb280a95", + "is_verified": false, + "line_number": 2207 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "b5c60cd211f3aac2db08a223c0571d1e53e7c60d", + "is_verified": false, + "line_number": 2208 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "4039b99a1c2bdca7737ed4f7934e5a9db2e76f8c", + "is_verified": false, + "line_number": 2209 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "6c04b8e8560c27e7c586a92b046c532da6b1e50c", + "is_verified": false, + "line_number": 2210 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "6a76bf0f171be18b2c3bd53219235c3ab16fdc7f", + "is_verified": false, + "line_number": 2211 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "025bef6ec65b88f3999f1b25157b7a6e17f5bfcd", + "is_verified": false, + "line_number": 2212 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "026954128506e379050cbea083edbddd1c1777b6", + "is_verified": false, + "line_number": 2213 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "745cfb125e37dee46e2952e02a0a4d5d5d56f546", + "is_verified": false, + "line_number": 2314 + }, + { + "type": "Base64 High Entropy String", + "filename": "tutorials/asr/Multilang_ASR.ipynb", + "hashed_secret": "543a58dd6dadfca9bc28a7f164e6b36c0b6e9a96", + "is_verified": false, + "line_number": 4799 + } + ], + "tutorials/multimodal/DreamBooth Tutorial.ipynb": [ + { + "type": "Base64 High Entropy String", + "filename": "tutorials/multimodal/DreamBooth Tutorial.ipynb", + "hashed_secret": "effe1444a4c73d23e5fc2a9f28048e1dd0653e82", + "is_verified": false, + "line_number": 223 + } + ], + "tutorials/multimodal/Multimodal Data Preparation.ipynb": [ + { + "type": "Hex High Entropy String", + "filename": "tutorials/multimodal/Multimodal Data Preparation.ipynb", + "hashed_secret": "5251fc51eb9d18d0de87c87ea09e4af9d1bf7a9f", + "is_verified": false, + "line_number": 18 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/multimodal/Multimodal Data Preparation.ipynb", + "hashed_secret": "194c1dff6224941326fe1d95936ba0e22fd60bb2", + "is_verified": false, + "line_number": 65 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/multimodal/Multimodal Data Preparation.ipynb", + "hashed_secret": "fe852a949d021998ad30bdd6a73a20c82221d486", + "is_verified": false, + "line_number": 217 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/multimodal/Multimodal Data Preparation.ipynb", + "hashed_secret": "b641cbe299c9e27b480cc8a823bb020d45962236", + "is_verified": false, + "line_number": 658 + } + ], + "tutorials/nlp/ITN_with_Thutmose_Tagger.ipynb": [ + { + "type": "Artifactory Credentials", + "filename": "tutorials/nlp/ITN_with_Thutmose_Tagger.ipynb", + "hashed_secret": "b5077fe6f2a92ca029dc6b5c022321b3828a2998", + "is_verified": false, + "line_number": 876 + } + ], + "tutorials/nlp/Token_Classification-BioMegatron.ipynb": [ + { + "type": "Hex High Entropy String", + "filename": "tutorials/nlp/Token_Classification-BioMegatron.ipynb", + "hashed_secret": "308d692d0307f53df800c91720fb271d62078391", + "is_verified": false, + "line_number": 689 + } + ], + "tutorials/speaker_tasks/Speaker_Diarization_Inference.ipynb": [ + { + "type": "Hex High Entropy String", + "filename": "tutorials/speaker_tasks/Speaker_Diarization_Inference.ipynb", + "hashed_secret": "80903ddedcf4ec0a2ee5911cefa7e1ad52419dcc", + "is_verified": false, + "line_number": 990 + } + ], + "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb": [ + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "3d52dd8e15de7d018930a034453752599cecfb95", + "is_verified": false, + "line_number": 18 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "8dd2391af4e9a5dc76b28f46ff201e1e7c9942f0", + "is_verified": false, + "line_number": 38 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "af149e43b0d4f9e4554b6b7a3260eafbfe1b5d8e", + "is_verified": false, + "line_number": 89 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "bb0c7befac27daf54e33d8e8b179598866feae04", + "is_verified": false, + "line_number": 112 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "645a085cdd80cde400cc162bfa2c24a286ca24c8", + "is_verified": false, + "line_number": 132 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "592340cf9486ccc3b0eff57e8f78ccf1f90add85", + "is_verified": false, + "line_number": 147 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "a9fdd91c2d3e03d3a8f039126c275d27c4adc5b2", + "is_verified": false, + "line_number": 198 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "eb455e1717efd60ca3896632c94a2b41d87855f2", + "is_verified": false, + "line_number": 212 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "096179c125fa827fde3bb88f53873aeaa3f7709f", + "is_verified": false, + "line_number": 263 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "9b895d433fc031a41bf872d697038c218e909066", + "is_verified": false, + "line_number": 283 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "daf16ebe45194e3ebed5c2cc59f334279d51fa0f", + "is_verified": false, + "line_number": 334 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "0d39ffb347d6fcd6c7b3519310756c1020091c6c", + "is_verified": false, + "line_number": 357 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "8eedca919f4fb2dafb68c2afc1faf76088ab12e0", + "is_verified": false, + "line_number": 377 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "7bc61a4c215f078b7de911363bedd91b471fa213", + "is_verified": false, + "line_number": 392 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "3088c565074b06f94684576b96b4d5b59560497c", + "is_verified": false, + "line_number": 443 + }, + { + "type": "Hex High Entropy String", + "filename": "tutorials/tools/DefinedCrowd_x_NeMo_ASR_Training_Tutorial.ipynb", + "hashed_secret": "209b86707a2f8f8253ce09587ca7ac1f6eefd4da", + "is_verified": false, + "line_number": 457 + } + ], + "tutorials/tts/FastPitch_Finetuning.ipynb": [ + { + "type": "Hex High Entropy String", + "filename": "tutorials/tts/FastPitch_Finetuning.ipynb", + "hashed_secret": "e915298ac5414db160aada21c7a235431ddfa98d", + "is_verified": false, + "line_number": 717 + } + ], + "tutorials/tts/FastPitch_MixerTTS_Training.ipynb": [ + { + "type": "Hex High Entropy String", + "filename": "tutorials/tts/FastPitch_MixerTTS_Training.ipynb", + "hashed_secret": "e915298ac5414db160aada21c7a235431ddfa98d", + "is_verified": false, + "line_number": 611 + } + ], + "tutorials/tts/Inference_ModelSelect.ipynb": [ + { + "type": "Hex High Entropy String", + "filename": "tutorials/tts/Inference_ModelSelect.ipynb", + "hashed_secret": "98307baca81149afa8a07a7cbe7ebc48c447d4be", + "is_verified": false, + "line_number": 315 + } + ], + "tutorials/tts/NeMo_TTS_Primer.ipynb": [ + { + "type": "Hex High Entropy String", + "filename": "tutorials/tts/NeMo_TTS_Primer.ipynb", + "hashed_secret": "e915298ac5414db160aada21c7a235431ddfa98d", + "is_verified": false, + "line_number": 2063 + } + ] + }, + "generated_at": "2024-11-14T09:37:19Z" +} diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..436750dd0af057b8c4d701cfb2a01a4ca0d4365a --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,41 @@ +cff-version: 1.2.0 +message: "If you use this software, please cite it as below." +title: "NeMo: a toolkit for Conversational AI and Large Language Models" +url: https://nvidia.github.io/NeMo/ +repository-code: https://github.com/NVIDIA/NeMo +authors: + - family-names: Harper + given-names: Eric + - family-names: Majumdar + given-names: Somshubra + - family-names: Kuchaiev + given-names: Oleksii + - family-names: Jason + given-names: Li + - family-names: Zhang + given-names: Yang + - family-names: Bakhturina + given-names: Evelina + - family-names: Noroozi + given-names: Vahid + - family-names: Subramanian + given-names: Sandeep + - family-names: Nithin + given-names: Koluguri + - family-names: Jocelyn + given-names: Huang + - family-names: Jia + given-names: Fei + - family-names: Balam + given-names: Jagadeesh + - family-names: Yang + given-names: Xuesong + - family-names: Livne + given-names: Micha + - family-names: Dong + given-names: Yi + - family-names: Naren + given-names: Sean + - family-names: Ginsburg + given-names: Boris + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..7fc0d739d2563d7ad744b66d5b65a12e5b7635c5 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,91 @@ +# Contributions are welcome! + +We do all of NeMo's development in the open. Contributions from NeMo community are welcome. + + +# Pull Requests (PR) Guidelines + +**Send your PRs to the `main` branch** + +1) Make sure your PR does one thing. Have a clear answer to "What does this PR do?". +2) Read General Principles and style guide below +3) Make sure you sign your commits. E.g. use ``git commit -s`` when before your commit +4) Make sure relevant unittests finish successfully before sending PR +5) Send your PR and request a review + +## Unit tests +Quick tests (locally, while developing) +``` +pytest +# If you don't have NVIDIA GPU do: +# pytest -m "not pleasefixme" --cpu path/to/relevant_tests +``` +Full tests, including pre-trained model downloads +``` +pytest -m "not pleasefixme" --with_downloads path/to/relevant_tests +``` + +Replace `path/to/relevant_tests` with the test directory to run such as `tests/collections/asr`. Check the test scripts in `tests/functional_tests` +that begin with `L0_Unit_Tests_` for the specific test configuration used by different parts of the unit test suite. Different suites may expect +different environment variables to be set. + +## Running the Github CI + +The CI tests are not ran automatically when the PR is opened. When ready, add the "Run CICD" label to the PR. To re-run CI remove and add the label again. +To run CI for external contributors, a user with write access to the repo must also approve the Github CI to run. Approving the CI to run for external +contributors is different from approving the PR change to be merged. + +The CI test suites are selectively ran based on the files that are changed. In some cases, no tests may be ran such as when docs are updated. + +Lint checks using flake8 and pylint are ran on the code based on the files that were changed. Please resolve any lint errors. It is possible but discouraged +to ignore the lint errors by adding the "skip-linting" label to the PR. + +## Whom should you ask for review: +Please tag @nithinraok for NeMo core and ASR related PRs and @blisc for TTS related PRs. + +Note that some people may self-assign to review your PR - in which case, please wait for them to add a review. + +Your pull requests must pass all checks and peer-review before they can be merged. + +# General principles +1. **User-oriented**: make it easy for end users, even at the cost of writing more code in the background +1. **Robust**: make it hard for users to make mistakes. +1. **Well-tested**: please add simple, fast unittests. Consider adding CI tests for end-to-end functionality. +1. **Reusable**: for every piece of code, think about how it can be reused in the future and make it easy to be reused. +1. **Readable**: code should be easier to read. +1. **Legal**: if you copy even one line of code from the Internet, make sure that the code allows the license that NeMo supports. Give credit and link back to the code. +1. **Sensible**: code should make sense. If you think a piece of code might be confusing, write comments. + +## Class naming conventions +* No “I”, “Interface”, “NM” nor “NeMo” pre/postfixes anywhere +* Core interfaces have simple names: Typing, Cloud, Serialization, FileIO* +* Core classes have the simplest names ever: NeuralModule, Model, Graph, Dataset, Loss, Module* +* Abstract classes in the Model hierarchy have Model postfix +* A config class for MyModel should be called MyModelConfig +* Leaf Neural Module classes have simple names without any postfixes (e.g. AudioPreprocess) +* Leaf Datasets have Dataset postfix (e.g. AudioToSpeechLabelDataset) +* Leaf Losses have Loss postfix (e.g. CTCLoss) +* Leaf Models do not have any postfix, just name (e.g. QuartzNet) + +## Python style +We use ``black`` as our style guide. To check whether your code will pass style check (from the NeMo's repo folder) run: +``python setup.py style --scope path/to/changed/files`` and if it does not pass run ``python setup.py style --scope path/to/changed/files --fix``. + +1. Include docstrings for every class and method exposed to the user. +1. Use Python 3 type hints for every class and method exposed to the user. +1. Avoid wild import: ``from X import *`` unless in ``X.py``, ``__all__`` is defined. +1. Minimize the use of ``**kwargs``. +1. ``RaiseError`` is preferred to ``assert``. Write: ```if X: raise Error``` instead of ```assert X```. +1. Classes are preferred to standalone methods. +1. Methods should be atomic. A method shouldn't be longer than 75 lines, e.g. can be fit into the computer screen without scrolling. +1. If a method has arguments that don't fit into one line, each argument should be in its own line for readability. +1. Add ``__init__.py`` for every folder. +1. F-strings are prefered to formatted strings. +1. Loggers are preferred to print. In NeMo, you can use logger from ``from nemo.utils import logging`` +1. Private functions (functions start with ``_``) shouldn't be called outside its host file. +1. If a comment lasts multiple lines, use ``'''`` instead of ``#``. + +# Collections +Collection is a logical grouping of related Neural Modules. It is a grouping of modules that share a domain area or semantics. +When contributing module to a collection, please make sure it belongs to that category. +If you would like to start a new one and contribute back to the platform, you are very welcome to do so. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f49a4e16e68b128803cc2dcea614603632b04eac --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..6fd8c646327359d9264033d5ac812ce336e3bfdf --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1 @@ +include requirements/* diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4c926c9a9950ec9156e9c0f7a7e0c0c9c13ee6da --- /dev/null +++ b/README.md @@ -0,0 +1,78 @@ +[![Project Status: Active -- The project has reached a stable, usable state and is being actively developed.](http://www.repostatus.org/badges/latest/active.svg)](http://www.repostatus.org/#active) +[![Documentation](https://readthedocs.com/projects/nvidia-nemo/badge/?version=main)](https://docs.nvidia.com/nemo/speech/nightly/starthere/intro.html) +[![CodeQL](https://github.com/nvidia/nemo/actions/workflows/codeql.yml/badge.svg?branch=main&event=push)](https://github.com/nvidia/nemo/actions/workflows/codeql.yml) +[![NeMo core license and license for collections in this repo](https://img.shields.io/badge/License-Apache%202.0-brightgreen.svg)](https://github.com/NVIDIA/NeMo/blob/master/LICENSE) +[![Release version](https://badge.fury.io/py/nemo-toolkit.svg)](https://badge.fury.io/py/nemo-toolkit) +[![Python version](https://img.shields.io/pypi/pyversions/nemo-toolkit.svg)](https://badge.fury.io/py/nemo-toolkit) +[![PyPi total downloads](https://static.pepy.tech/personalized-badge/nemo-toolkit?period=total&units=international_system&left_color=grey&right_color=brightgreen&left_text=downloads)](https://pepy.tech/project/nemo-toolkit) +[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) + +# **NVIDIA NeMo Speech** +Checkout our [HuggingFace🤗 collection](https://huggingface.co/collections/nvidia/nemotron-speech) for the latest open +weight checkpoints and demos! + +## Updates + +- 2026-03: [Nemotron 3 VoiceChat](https://build.nvidia.com/nvidia/nemotron-voicechat/modelcard) is now released in Early Access. Built on the Nemotron Nano v2 LLM backbone with Nemotron speech and TTS decoder, VoiceChat delivers full-duplex, natural, interruptible conversations with low latency. Try out [the demo](https://build.nvidia.com/nvidia/nemotron-voicechat) and apply for [early access](https://developer.nvidia.com/nemotron-voicechat-early-access). +- 2026-03: [Nemotron-Speech-Streaming v2603](https://huggingface.co/nvidia/nemotron-speech-streaming-en-0.6b) has been + updated. It has been trained on a larger and more diverse corpus, resulting in lower WER across all latency modes. + Try out [the demo](https://huggingface.co/spaces/nvidia/nemotron-speech-streaming-en-0.6b) and check out + [the NIM](https://build.nvidia.com/nvidia/nemotron-asr-streaming). +- 2026-03: [MagpieTTS v2602](https://huggingface.co/nvidia/magpie_tts_multilingual_357m) has been released with support + for 9 languages(En, Es, De, Fr, Vi, It, Zh, Hi, Ja). Try out + [the demo](https://huggingface.co/nvidia/magpie_tts_multilingual_357m) and check out + [the NIM](https://build.nvidia.com/nvidia/magpie-tts-multilingual). +- 2026-01: Nemotron-Speech-Streaming was released: One checkpoint that enables users to pick their optimal point + on the latency-accuracy Pareto curve! +- 2026-01: MagpieTTS was released. +- 2026: This repo has pivoted to focus on audio, speech, and multimodal LLM. For the last NeMo release with support for more + modalities, see [v2.7.0](https://github.com/NVIDIA-NeMo/NeMo/releases/tag/v2.7.0) +- 2025-08: [Parakeet V3](https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3) and + [Canary V2](https://huggingface.co/nvidia/canary-1b-v2) have been released with speech recognition and translation + support for 25 European languages. +- 2025-06: [Canary-Qwen-2.5B](https://huggingface.co/nvidia/canary-qwen-2.5b) has been released with record-setting + 5.63% WER on English Open ASR Leaderboard. + +## Introduction + +NVIDIA NeMo Speech is built for researchers and PyTorch developers working on Speech models including Automatic Speech +Recognition (ASR), Text to Speech (TTS), and Speech LLMs. It is designed to help you efficiently create, customize, and +deploy new It is designed to help you efficiently create, customize, and deploy new AI models by leveraging existing +code and pre-trained model checkpoints. + +For technical documentation, please see the +[NeMo Framework User Guide](https://docs.nvidia.com/nemo/speech/nightly/starthere/intro.html). + +## Requirements + +- Python 3.12 or above +- Pytorch 2.6 or above +- NVIDIA GPU (if you intend to do model training) + +As of [Pytorch 2.6](https://docs.pytorch.org/docs/stable/notes/serialization.html#torch-load-with-weights-only-true), +`torch.load` defaults to using `weights_only=True`. Some model checkpoints may require using `weights_only=False`. +In this case, you can set the env var `TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1` before running code that uses `torch.load`. +However, this should only be done with trusted files. Loading files from untrusted sources with more than weights only +can have the risk of arbitrary code execution. + +## Developer Documentation + +| Version | Status | Description | +| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| Latest | [![Documentation Status](https://readthedocs.com/projects/nvidia-nemo/badge/?version=main)](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/) | [Documentation of the latest (i.e. main) branch.](https://docs.nvidia.com/nemo/speech/nightly/starthere/intro.html) | +| Stable | [![Documentation Status](https://readthedocs.com/projects/nvidia-nemo/badge/?version=stable)](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/) | Documentation of the stable (i.e. most recent release) - To be added | + +## Install NeMo Speech + +NeMo Speech is installable via pip: `pip install 'nemo-toolkit[all]'` +To install with extra dependencies for CUDA 12.x or 13.x, use `pip install 'nemo-toolkit[all,cu12]'` +or `pip install 'nemo-toolkit[all,cu13]'` respectively. + +## Contribute to NeMo + +We welcome community contributions! Please refer to +[CONTRIBUTING.md](https://github.com/NVIDIA-NeMo/NeMo/blob/main/CONTRIBUTING.md) for the process. + +## Licenses + +NeMo is licensed under the [Apache License 2.0](https://github.com/NVIDIA/NeMo?tab=Apache-2.0-1-ov-file). diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..1652b66f1719fff96bc69469b1cc43a5f7bbfa60 --- /dev/null +++ b/codecov.yml @@ -0,0 +1,23 @@ +comment: false +coverage: + status: + project: false + patch: + default: + target: 80% + threshold: 0% + base: auto + if_ci_failed: error + paths: + - "!nemo/collections/asr" + - "!nemo/collections/audio" + - "!nemo/collections/speechlm" + - "!nemo/collections/tts" + - "!nemo/core" + - "!nemo/collections/common" + - "!nemo/collections/multimodal_autoregressive" + - "!nemo/collections/diffusion" + - "!nemo/collections/nlp" + +fixes: + - "/workspace/::" diff --git a/docker/Dockerfile.ci b/docker/Dockerfile.ci new file mode 100644 index 0000000000000000000000000000000000000000..352c03a2a4bce3239a8d1f2e045e5421933c0d52 --- /dev/null +++ b/docker/Dockerfile.ci @@ -0,0 +1,84 @@ +# syntax=docker/dockerfile:1-labs + +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +ARG BASE_IMAGE=nvcr.io/nvidia/pytorch:24.07-py3 + +FROM ${BASE_IMAGE} as base-image +ENV PIP_CONSTRAINT="" +ENV TRANSFORMERS_OFFLINE=0 +ENV HYDRA_FULL_ERROR=1 +ENV PYTHONUNBUFFERED=1 + +# APT packages +RUN <<"EOF" bash -ex +apt-get update +apt-get install -y bc libsox-fmt-all +apt-get clean +EOF + +FROM base-image as te-wheel +WORKDIR /tmp/NeMo +ARG TE_REPO +ARG TE_TAG +RUN --mount=type=bind,source=docker/common/install_dep.sh,target=/tmp/NeMo/install_dep.sh \ + --mount=type=bind,source=external/patches,target=/tmp/NeMo/external/patches <<"EOF" bash -ex + + bash /tmp/NeMo/install_dep.sh --library te --mode build + ls -al /tmp/Megatron-LM || true +EOF + +FROM base-image as mcore-wheel +WORKDIR /tmp/NeMo +ARG MLM_REPO +ARG MLM_TAG +RUN --mount=type=bind,source=docker/common/install_dep.sh,target=/tmp/NeMo/install_dep.sh <<"EOF" bash -ex + + bash /tmp/NeMo/install_dep.sh --library mcore --mode build + ls -al /tmp/Megatron-LM || true +EOF + +FROM base-image +WORKDIR /tmp/NeMo +ENV INSTALL_DIR="/opt" +RUN \ + --mount=type=bind,from=te-wheel,source=/opt/wheels/te,target=/opt/wheels/te \ + --mount=type=bind,from=mcore-wheel,source=/opt/wheels/mcore,target=/opt/wheels/mcore \ + --mount=type=bind,source=requirements,target=/tmp/NeMo/requirements \ + --mount=type=bind,source=tools/ctc_segmentation/requirements.txt,target=/tmp/NeMo/tools/ctc_segmentation/requirements.txt \ + --mount=type=bind,source=docker/common/install_dep.sh,target=/tmp/NeMo/install_dep.sh \ + --mount=type=bind,source=setup.py,target=/tmp/NeMo/setup.py \ + --mount=type=bind,source=external/patches,target=/tmp/NeMo/external/patches \ + --mount=type=bind,source=README.md,target=/tmp/NeMo/README.md \ + --mount=type=bind,source=nemo/package_info.py,target=/tmp/NeMo/nemo/package_info.py \ + --mount=type=bind,source=nemo/__init__.py,target=/tmp/NeMo/nemo/__init__.py <<"EOF" bash -ex + + bash /tmp/NeMo/install_dep.sh --library te --mode install + bash /tmp/NeMo/install_dep.sh --library mcore --mode install + bash /tmp/NeMo/install_dep.sh --library extra --mode install + pip install --no-cache-dir ".[all,cu12]" + rm -rf $NEMO_DIR || true +EOF + + +WORKDIR /workspace +ENV PYTHONPATH="${PYTHONPATH}:/workspace/Megatron-LM" +ENV NEMO_HOME="/home/TestData/nemo_home" + +ARG IMAGE_LABEL +LABEL "nemo.library"=${IMAGE_LABEL} + +ARG PR_NUMBER +LABEL "nemo.pr_number"=${PR_NUMBER} diff --git a/docker/Dockerfile.speech b/docker/Dockerfile.speech new file mode 100644 index 0000000000000000000000000000000000000000..ba32799b00a5a50f305b581fe82d8f38f5b3bd1e --- /dev/null +++ b/docker/Dockerfile.speech @@ -0,0 +1,186 @@ +# syntax=docker/dockerfile:experimental + +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +ARG BASE_IMAGE=nvcr.io/nvidia/pytorch:25.12-py3 + +# build an image that includes only the nemo dependencies, ensures that dependencies +# are included first for optimal caching, and useful for building a development +# image (by specifying build target as `nemo-deps`) +FROM ${BASE_IMAGE} as nemo-deps + +# dependency flags; should be declared after FROM +# k2: not required by default +ARG REQUIRE_K2=false +# ais cli: not required by default, install only if required +ARG REQUIRE_AIS_CLI=false +# check imports: if flag is false, ignore result +ARG REQUIRE_CHECK_IMPORTS=true + +# Ensure apt-get won't prompt for selecting options +ENV DEBIAN_FRONTEND=noninteractive +# libavdevice-dev required for latest torchaudio +RUN apt-get update && \ + apt-get upgrade -y && \ + apt-get install -y \ + libsndfile1 sox \ + libfreetype6 \ + libsox-fmt-all \ + swig \ + ffmpeg \ + libavdevice-dev && \ + rm -rf /var/lib/apt/lists/* + +# libtool, ... , libgts-dev are required for graphviz +# graphviz is required for k2 and pynini visualization +RUN apt-get update && \ + apt-get install -y \ + libtool \ + libltdl-dev \ + automake \ + autoconf \ + bison \ + flex \ + tcl \ + ghostscript \ + libgd-dev \ + fontconfig \ + libcairo2-dev \ + libpango1.0-dev \ + libgts-dev && \ + rm -rf /var/lib/apt/lists/* + +WORKDIR /workspace/ + +ARG TE_TAG=7d576ed25266a17a7b651f2c12e8498f67e0baea +ARG MCORE_TAG=338af51452a53982d202e8386db6233adad1ce86 +ARG APEX_TAG=810ffae374a2b9cb4b5c5e28eaeca7d7998fca0c +# Install megatron core, this can be removed once 0.3 pip package is released +# We leave it here in case we need to work off of a specific commit in main +RUN git clone https://github.com/NVIDIA/Megatron-LM.git && \ + cd Megatron-LM && \ + git checkout ${MCORE_TAG} && \ + pip install . + +# Performance optimizations for distributed optimizer: https://github.com/NVIDIA/apex/pull/1771 +RUN git clone https://github.com/NVIDIA/apex.git && \ + cd apex && \ + git checkout ${APEX_TAG} && \ + pip install -v --no-build-isolation --disable-pip-version-check --no-cache-dir \ + --config-settings "--build-option=--cpp_ext --cuda_ext --fast_layer_norm --distributed_adam --deprecated_fused_adam" ./ + +# Transformer Engine 1.2.0 +RUN git clone https://github.com/NVIDIA/TransformerEngine.git && \ + cd TransformerEngine && \ + git fetch origin ${TE_TAG} && \ + git checkout FETCH_HEAD && \ + git submodule init && git submodule update && \ + NVTE_FRAMEWORK=pytorch NVTE_WITH_USERBUFFERS=1 MPI_HOME=/usr/local/mpi pip install . + +WORKDIR /tmp/ + +# uninstall stuff from base container +RUN pip3 uninstall -y sacrebleu torchtext + +COPY scripts /tmp/nemo/scripts/ +# install correct graphviz version (k2 and pynini visualization tool), skip if installation fails +RUN INSTALL_MSG=$(/bin/bash /tmp/nemo/scripts/installers/install_graphviz.sh --docker); INSTALL_CODE=$?; \ + echo ${INSTALL_MSG}; \ + if [ ${INSTALL_CODE} -ne 0 ]; then \ + echo "graphviz installation failed"; \ + if [ "${REQUIRE_K2}" = true ]; then \ + exit ${INSTALL_CODE}; \ + else echo "Skipping failed graphviz installation"; fi \ + else echo "graphviz installed successfully"; fi + +# install k2, skip if installation fails +COPY scripts /tmp/nemo/scripts/ +RUN INSTALL_MSG=$(/bin/bash /tmp/nemo/scripts/installers/install_k2.sh); INSTALL_CODE=$?; \ + echo ${INSTALL_MSG}; \ + if [ ${INSTALL_CODE} -ne 0 ]; then \ + echo "k2 installation failed"; \ + if [ "${REQUIRE_K2}" = true ]; then \ + exit ${INSTALL_CODE}; \ + else echo "Skipping failed k2 installation"; fi \ + else echo "k2 installed successfully"; fi + +# install nemo dependencies +WORKDIR /tmp/nemo +ENV LHOTSE_REQUIRE_TORCHAUDIO=0 +COPY requirements . +# exclude requirements_vllm.txt, since `vllm==0.5.x` breaks the container due to hardcoded requirements `torch==2.3.0` +RUN for f in $(ls requirements*.txt | grep -v 'requirements_vllm.txt'); do \ + pip3 install --disable-pip-version-check --no-cache-dir -r $f; done + +# install flash attention +RUN pip install flash-attn +# install numba for latest containers +RUN pip install numba>=0.57.1 + +# copy nemo source into a scratch image +FROM scratch as nemo-src +COPY . . + +# start building the final container +FROM nemo-deps as nemo +ARG NEMO_VERSION=2.0.0 + +# Check that NEMO_VERSION is set. Build will fail without this. Expose NEMO and base container +# version information as runtime environment variable for introspection purposes +RUN /usr/bin/test -n "$NEMO_VERSION" && \ + /bin/echo "export NEMO_VERSION=${NEMO_VERSION}" >> /root/.bashrc && \ + /bin/echo "export BASE_IMAGE=${BASE_IMAGE}" >> /root/.bashrc + +# Install NeMo +RUN --mount=from=nemo-src,target=/tmp/nemo,rw cd /tmp/nemo && pip install ".[all]" + +# Check install +# NB: adjusting LD_LIBRARY_PATH (only here, should not be persistent!) is a temporary hack +# to avoid failure if CUDA is unavailable (`docker build` does not expose GPUs) +# The error is raised in NeMo Core, and the main reason is reinstalled Transformer-Engine; +RUN CHECK_MSG=$(export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${CUDA_HOME}/compat/lib.real && \ + python -c "import nemo.collections.asr as nemo_asr" && \ + python -c "import nemo.collections.nlp as nemo_nlp" && \ + python -c "import nemo.collections.tts as nemo_tts" && \ + python -c "import nemo_text_processing.text_normalization as text_normalization"); CHECK_CODE=$?; \ + echo ${CHECK_MSG}; \ + if [ ${CHECK_CODE} -ne 0 ]; then \ + echo "Import check failed"; \ + if [ "${REQUIRE_CHECK_IMPORTS}" = true ]; then \ + exit ${CHECK_CODE}; \ + else echo "Skipping unsuccessful import check"; fi \ + else echo "Import check success"; fi + + +# copy scripts/examples/tests into container for end user +WORKDIR /workspace/nemo +COPY scripts /workspace/nemo/scripts +COPY examples /workspace/nemo/examples +COPY tests /workspace/nemo/tests +COPY tutorials /workspace/nemo/tutorials +# COPY README.rst LICENSE /workspace/nemo/ + +RUN printf "#!/bin/bash\njupyter lab --no-browser --allow-root --ip=0.0.0.0" >> start-jupyter.sh && \ + chmod +x start-jupyter.sh + +# If required, install AIS CLI and Python AIS SDK +RUN INSTALL_MSG=$(/bin/bash /tmp/nemo/scripts/installers/install_ais_cli_latest.sh && pip install aistore); INSTALL_CODE=$?; \ + echo ${INSTALL_MSG}; \ + if [ ${INSTALL_CODE} -ne 0 ]; then \ + echo "AIS CLI installation failed"; \ + if [ "${REQUIRE_AIS_CLI}" = true ]; then \ + exit ${INSTALL_CODE}; \ + else echo "Skipping AIS CLI installation"; fi \ + else echo "AIS CLI installed successfully"; fi diff --git a/docker/common/install_dep.sh b/docker/common/install_dep.sh new file mode 100644 index 0000000000000000000000000000000000000000..8675714b71685aa633746dd9fab0e43d2a07d14c --- /dev/null +++ b/docker/common/install_dep.sh @@ -0,0 +1,445 @@ +#!/usr/bin/env bash +set -exou pipefail + +# List of all supported libraries (update this list when adding new libraries) +# This also defines the order in which they will be installed by --libraries "all" + +ALL_LIBRARIES=( + "trtllm" + "te" + "mcore" + "vllm" + "extra" +) + +export INSTALL_OPTION=${1:-dev} +export HEAVY_DEPS=${HEAVY_DEPS:-false} +export INSTALL_DIR=${INSTALL_DIR:-"/opt"} +export CURR=$(pwd) +export WHEELS_DIR=${WHEELS_DIR:-"$INSTALL_DIR/wheels"} +export PIP=pip +export TRTLLM_REPO=${TRTLLM_REPO:-$(cat "$CURR/requirements/manifest.json" | jq -r '."vcs-dependencies"."trt-llm".repo')} +export TRTLLM_TAG=${TRTLLM_TAG:-$(cat "$CURR/requirements/manifest.json" | jq -r '."vcs-dependencies"."trt-llm".ref')} +export TRTLLM_DIR="$INSTALL_DIR/TensorRT-LLM" +export TE_REPO=${TE_REPO:-$(cat "$CURR/requirements/manifest.json" | jq -r '."vcs-dependencies"."transformer_engine".repo')} +export TE_TAG=${TE_TAG:-$(cat "$CURR/requirements/manifest.json" | jq -r '."vcs-dependencies"."transformer_engine".ref')} +export NVIDIA_PYTORCH_VERSION=${NVIDIA_PYTORCH_VERSION:-""} +export CONDA_PREFIX=${CONDA_PREFIX:-""} + +trt() { + local mode="$1" + local WHEELS_DIR=$WHEELS_DIR/trt/ + mkdir -p $WHEELS_DIR + + # Skip TRT installation on macOS ARM + if [[ "$(uname)" == "Darwin" ]] && [[ "$(uname -m)" == "arm64" ]]; then + echo "Skipping TRT installation on macOS ARM" + return + fi + + if [ "$(id -u)" -ne 0 ]; then + if ! command -v sudo &>/dev/null; then + echo "Not running as root and sudo is not available, skipping TRT installation" + return + fi + fi + + if [ "$(id -u)" -eq 0 ]; then + # Already root, run directly + curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | bash + apt-get install git-lfs + git lfs install + apt-get clean + else + # Need to gain sudo + curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash + sudo apt-get install git-lfs + git lfs install + sudo apt-get clean + fi + + if [ ! -d "$TRTLLM_DIR/.git" ]; then + rm -rf "$TRTLLM_DIR" + cd $(dirname "$TRTLLM_DIR") + git clone ${TRTLLM_REPO} + fi + + pushd $TRTLLM_DIR + git checkout -f $TRTLLM_TAG + git submodule update --init --recursive + sed -i "/torch/d" requirements.txt + git lfs pull + patch -p1 < $CURR/external/patches/trt_llm.patch + popd + + if [[ "$mode" == "install" ]]; then + if [[ "${NVIDIA_PYTORCH_VERSION}" != "" ]]; then + cd $TRTLLM_DIR + set +u + + bash docker/common/install_base.sh + bash docker/common/install_cmake.sh + bash docker/common/install_ccache.sh + + . docker/common/install_tensorrt.sh \ + --TRT_VER="10.10.0.31" \ + --CUDA_VER="12.9" \ + --CUDNN_VER="9.9.0.52-1" \ + --NCCL_VER="2.26.5-1+cuda12.9" \ + --CUBLAS_VER="12.9.0.13-1" \ + --NVRTC_VER="12.9.41-1" + set -u + fi + fi +} + +trtllm() { + local mode="$1" + local WHEELS_DIR=$WHEELS_DIR/trtllm/ + mkdir -p $WHEELS_DIR + + # Skip TRT installation on macOS ARM + if [[ "$(uname)" == "Darwin" ]] && [[ "$(uname -m)" == "arm64" ]]; then + echo "Skipping TRT installation on macOS ARM" + return + fi + + if [ "$(id -u)" -ne 0 ]; then + if ! command -v sudo &>/dev/null; then + echo "Not running as root and sudo is not available, skipping TRT installation" + return + fi + fi + + if [ "$(id -u)" -eq 0 ]; then + # Already root, run directly + curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | bash + apt-get install git-lfs + git lfs install + apt-get clean + else + # Need to gain sudo + curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash + sudo apt-get install git-lfs + git lfs install + sudo apt-get clean + fi + + if [ ! -d "$TRTLLM_DIR/.git" ]; then + rm -rf "$TRTLLM_DIR" + cd $(dirname "$TRTLLM_DIR") + git clone ${TRTLLM_REPO} + fi + pushd $TRTLLM_DIR + git checkout -f $TRTLLM_TAG + git submodule update --init --recursive + sed -i "/torch/d" requirements.txt + git lfs pull + patch -p1 < $CURR/external/patches/trt_llm.patch + popd + + build() { + if [[ "${NVIDIA_PYTORCH_VERSION}" != "" ]]; then + # CONDA_PREFIX causes an error in trt-llm's build script + unset CONDA_PREFIX + cd $TRTLLM_DIR + TORCH_CXX_FLAGS="-D_GLIBCXX_USE_CXX11_ABI=1" python3 ./scripts/build_wheel.py --job_count $(nproc) --clean --trt_root /usr/local/tensorrt --dist_dir $WHEELS_DIR --python_bindings --benchmarks + fi + } + + if [[ "$mode" == "build" ]]; then + build + else + if [ -d "$WHEELS_DIR" ] && [ -z "$(ls -A "$WHEELS_DIR")" ]; then + build + fi + + pip install --no-cache-dir $WHEELS_DIR/tensorrt_llm*.whl --extra-index-url https://pypi.nvidia.com || true + fi +} + +te() { + local mode="$1" + local WHEELS_DIR=$WHEELS_DIR/te/ + mkdir -p $WHEELS_DIR + + TE_DIR="$INSTALL_DIR/TransformerEngine" + if [ ! -d "$TE_DIR/.git" ]; then + rm -rf "$TE_DIR" && + cd $(dirname "$TE_DIR") + git clone ${TE_REPO} + fi + pushd $TE_DIR + git checkout -f $TE_TAG + popd + + build() { + if [[ "${NVIDIA_PYTORCH_VERSION}" != "" ]]; then + cd $TE_DIR + git submodule init + git submodule update + pip install nvidia-mathdx==25.1.1 + pip wheel --wheel-dir $WHEELS_DIR/ --no-build-isolation $TE_DIR + fi + } + + if [[ "$mode" == "build" ]]; then + build + else + if [ -d "$WHEELS_DIR" ] && [ -z "$(ls -A "$WHEELS_DIR")" ]; then + build + fi + + pip install --no-cache-dir $WHEELS_DIR/transformer_engine*.whl && patch -p1 --force $(python -c "import triton; print(triton.__path__[0])")/runtime/autotuner.py $CURR/external/patches/triton-lang_triton_6570_lazy_init.patch || true + + fi +} + +mcore() { + local mode="$1" + + local WHEELS_DIR=$WHEELS_DIR/mcore/ + mkdir -p $WHEELS_DIR + + export CAUSAL_CONV1D_FORCE_BUILD=TRUE + export CAUSAL_CONV_TAG=v1.5.3 + CAUSAL_CONV1D_DIR="$INSTALL_DIR/causal-conv1d" + if [ ! -d "$CAUSAL_CONV1D_DIR/.git" ]; then + rm -rf "$CAUSAL_CONV1D_DIR" + mkdir -p $(dirname "$CAUSAL_CONV1D_DIR") + cd $(dirname "$CAUSAL_CONV1D_DIR") + git clone https://github.com/Dao-AILab/$(basename $CAUSAL_CONV1D_DIR).git + fi + pushd $CAUSAL_CONV1D_DIR + git checkout -f $CAUSAL_CONV_TAG + popd + + export MAMBA_FORCE_BUILD=TRUE + export MAMBA_TAG=6b32be06d026e170b3fdaf3ae6282c5a6ff57b06 + MAMBA_DIR="$INSTALL_DIR/mamba" + if [ ! -d "$MAMBA_DIR/.git" ]; then + rm -rf "$MAMBA_DIR" + cd $(dirname "$MAMBA_DIR") + git clone https://github.com/state-spaces/$(basename $MAMBA_DIR).git + fi + pushd $MAMBA_DIR + git checkout -f $MAMBA_TAG + perl -ni -e 'print unless /triton/' setup.py + perl -ni -e 'print unless /triton/' pyproject.toml + popd + + MLM_REPO=${MLM_REPO:-$(cat "$CURR/requirements/manifest.json" | jq -r '."vcs-dependencies"."megatron-lm".repo')} + MLM_TAG=${MLM_TAG:-$(cat "$CURR/requirements/manifest.json" | jq -r '."vcs-dependencies"."megatron-lm".ref')} + MLM_DIR="$INSTALL_DIR/Megatron-LM" + if [ ! -d "$MLM_DIR/.git" ]; then + rm -rf "$MLM_DIR" + mkdir -p $(dirname "$MLM_DIR") + cd $(dirname "$MLM_DIR") + git clone ${MLM_REPO} + fi + pushd $MLM_DIR + git checkout -f $MLM_TAG + perl -ni -e 'print unless /triton==3.1.0/' requirements/pytorch_24.10/requirements.txt + perl -ni -e 'print unless /nvidia-resiliency-ext/' requirements/pytorch_24.10/requirements.txt + popd + + build() { + if [[ "${NVIDIA_PYTORCH_VERSION}" != "" ]]; then + pip wheel --no-deps --no-cache-dir --no-build-isolation --wheel-dir $WHEELS_DIR $MAMBA_DIR + pip wheel --no-deps --no-cache-dir --no-build-isolation --wheel-dir $WHEELS_DIR $CAUSAL_CONV1D_DIR + fi + + pip wheel --no-deps --wheel-dir $WHEELS_DIR $MLM_DIR + } + + if [[ "$mode" == "build" ]]; then + build + else + if [ -d "$WHEELS_DIR" ] && [ -z "$(ls -A "$WHEELS_DIR")" ]; then + build + fi + + pip install --no-cache-dir $WHEELS_DIR/*.whl "nvidia-pytriton ; platform_machine == 'x86_64'" || true + pip install --no-cache-dir -e $MLM_DIR + fi +} + +vllm() { + local mode="$1" + + local WHEELS_DIR=$WHEELS_DIR/vllm/ + mkdir -p $WHEELS_DIR + + VLLM_DIR="$INSTALL_DIR/vllm" + + build() { + if [[ "${NVIDIA_PYTORCH_VERSION}" != "" ]]; then + ${PIP} install --no-cache-dir virtualenv + virtualenv $INSTALL_DIR/venv + $INSTALL_DIR/venv/bin/pip install --no-cache-dir setuptools coverage + $INSTALL_DIR/venv/bin/pip wheel --no-cache-dir --no-build-isolation \ + --wheel-dir $WHEELS_DIR/ \ + -r $CURR/requirements/requirements_vllm.txt + fi + } + + if [[ "$mode" == "build" ]]; then + build + else + if [ -d "$WHEELS_DIR" ] && [ -z "$(ls -A "$WHEELS_DIR")" ]; then + build + fi + + ${PIP} install --no-cache-dir virtualenv + virtualenv $INSTALL_DIR/venv + $INSTALL_DIR/venv/bin/pip install --no-cache-dir coverage + $INSTALL_DIR/venv/bin/pip install --no-cache-dir --no-build-isolation $WHEELS_DIR/*.whl || true + fi + +} + +extra() { + local mode="$1" + DEPS=( + "llama-index==0.10.43" # incompatible with nvidia-pytriton + "nemo_run" + "nvidia-modelopt==0.37.0" # We want a specific version of nvidia-modelopt + ) + if [[ "${NVIDIA_PYTORCH_VERSION}" != "" ]]; then + DEPS+=( + "git+https://github.com/NVIDIA/nvidia-resiliency-ext.git@b6eb61dbf9fe272b1a943b1b0d9efdde99df0737 ; platform_machine == 'x86_64'" # Compiling NvRX requires CUDA + ) + fi + + if [[ "$mode" == "install" ]]; then + pip install --force-reinstall --no-deps --no-cache-dir "${DEPS[@]}" + pip install --no-cache-dir "${DEPS[@]}" + # needs no-deps to avoid installing triton on top of pytorch-triton. + pip install --no-deps --no-cache-dir "liger-kernel==0.5.8; (platform_machine == 'x86_64' and platform_system != 'Darwin')" + pip install --no-deps "cut-cross-entropy @ git+https://github.com/apple/ml-cross-entropy.git@87a86aba72cfd2f0d8abecaf81c13c4528ea07d8; (platform_machine == 'x86_64' and platform_system != 'Darwin')" + fi +} + +echo 'Uninstalling stuff' +# Some of these packages are uninstalled for legacy purposes +${PIP} uninstall -y nemo_toolkit sacrebleu nemo_asr nemo_nlp nemo_tts + +echo 'Upgrading tools' +${PIP} install -U --no-cache-dir "setuptools==76.0.0" pybind11 wheel ${PIP} + +if [ "${NVIDIA_PYTORCH_VERSION}" != "" ]; then + echo "Installing NeMo in NVIDIA PyTorch container: ${NVIDIA_PYTORCH_VERSION}" + echo "Will not install numba" + +else + if [ "${CONDA_PREFIX}" != "" ]; then + echo 'Installing numba' + conda install -y -c conda-forge numba + else + pip install --no-cache-dir --no-deps torch cython + fi +fi + +echo 'Installing nemo dependencies' +cd $CURR + +if [[ "$INSTALL_OPTION" == "dev" ]]; then + echo "Running in dev mode" + ${PIP} install --editable ".[all]" + +else + # -------------------------- + # Argument Parsing & Validation + # -------------------------- + + # Parse command-line arguments + while [[ $# -gt 0 ]]; do + case "$1" in + --library) + LIBRARY_ARG="$2" + shift 2 + ;; + --mode) + MODE="$2" + shift 2 + ;; + *) + echo "Unknown option: $1" + exit 1 + ;; + esac + done + + # Validate required arguments + if [[ -z "$LIBRARY_ARG" ]]; then + echo "Error: --library argument is required" + exit 1 + fi + + if [[ -z "$MODE" ]]; then + echo "Error: --mode argument is required" + exit 1 + fi + + # Validate mode + if [[ "$MODE" != "build" && "$MODE" != "install" ]]; then + echo "Error: Invalid mode. Must be 'build' or 'install'" + exit 1 + fi + + # Process library argument + declare -a LIBRARIES + if [[ "$LIBRARY_ARG" == "all" ]]; then + LIBRARIES=("${ALL_LIBRARIES[@]}") + else + IFS=',' read -ra TEMP_ARRAY <<<"$LIBRARY_ARG" + for lib in "${TEMP_ARRAY[@]}"; do + trimmed_lib=$(echo "$lib" | xargs) + if [[ -n "$trimmed_lib" ]]; then + LIBRARIES+=("$trimmed_lib") + fi + done + fi + + # Validate libraries array + if [[ ${#LIBRARIES[@]} -eq 0 ]]; then + echo "Error: No valid libraries specified" + exit 1 + fi + + # Validate each library is supported + for lib in "${LIBRARIES[@]}"; do + # "trt" is a valid option but not in ALL_LIBRARIES + # It does not get installed at the same time as the rest + if [[ "$lib" == "trt" ]]; then + continue + fi + + if [[ ! " ${ALL_LIBRARIES[@]} " =~ " ${lib} " ]]; then + echo "Error: Unsupported library '$lib'" + exit 1 + fi + done + + # -------------------------- + # Execution Logic + # -------------------------- + + # Run operations for each library + for library in "${LIBRARIES[@]}"; do + echo "Processing $library ($MODE)..." + "$library" "$MODE" + + # Check if function succeeded + if [[ $? -ne 0 ]]; then + echo "Error: Operation failed for $library" + exit 1 + fi + done + + echo "All operations completed successfully" + exit 0 + +fi + +echo 'All done!' diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..417fe2a0b149f603832abdd4dc070f30a331a502 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,216 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source + +.PHONY: help +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " applehelp to make an Apple Help Book" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + @echo " coverage to run coverage check of the documentation (if enabled)" + +.PHONY: clean +clean: + rm -rf $(BUILDDIR)/* + +.PHONY: html +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +.PHONY: dirhtml +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +.PHONY: singlehtml +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +.PHONY: pickle +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +.PHONY: json +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +.PHONY: htmlhelp +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +.PHONY: qthelp +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/OpenSeq2Seq.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/OpenSeq2Seq.qhc" + +.PHONY: applehelp +applehelp: + $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp + @echo + @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." + @echo "N.B. You won't be able to view it unless you put it in" \ + "~/Library/Documentation/Help or install it in your application" \ + "bundle." + +.PHONY: devhelp +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/OpenSeq2Seq" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/OpenSeq2Seq" + @echo "# devhelp" + +.PHONY: epub +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +.PHONY: latex +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +.PHONY: latexpdf +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +.PHONY: latexpdfja +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +.PHONY: text +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +.PHONY: man +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +.PHONY: texinfo +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +.PHONY: info +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +.PHONY: gettext +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +.PHONY: changes +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +.PHONY: linkcheck +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +.PHONY: doctest +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +.PHONY: coverage +coverage: + $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage + @echo "Testing of coverage in the sources finished, look at the " \ + "results in $(BUILDDIR)/coverage/python.txt." + +.PHONY: xml +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +.PHONY: pseudoxml +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6a7e282249ddc31f9877334aaae9b2f532fda069 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,63 @@ +# Documentation Process for NeMo + +## Building the Documentation + +1. Create and activate a virtual environment. + +1. Install the documentation dependencies: + + ```console + $ python3 -m pip install -r requirements/requirements_docs.txt + ``` + +1. Build the documentation: + + ```console + $ make -C docs html + ``` + +## Checking for Broken Links + +1. Build the documentation, as described in the preceding section, but use the following command: + + ```shell + make -C docs clean linkcheck + ``` + +1. Run the link-checking script: + + ```shell + ./docs/check_for_broken_links.sh + ``` + +If there are no broken links, then the script exits with `0`. + +If the script produces any output, cut and paste the `uri` value into your browser to confirm +that the link is broken. + +```json +{ + "filename": "nlp/text_normalization/nn_text_normalization.rst", + "lineno": 247, + "status": "broken", + "code": 0, + "uri": "https://research.fb.com/wp-content/uploads/2019/03/Neural-Models-of-Text-Normalization-for-Speech-Applications.pdf", + "info": "400 Client Error: Bad Request for url: https://research.facebook.com/wp-content/uploads/2019/03/Neural-Models-of-Text-Normalization-for-Speech-Applications.pdf" +} +``` + +If the link is OK, and this is the case with many URLs that reference GitHub repository file headings, +then cut and paste the JSON output and add it to `docs/false_positives.json`. +Run the script again to confirm that the URL is no longer reported as a broken link. + +There may be false positives due to Sphinx not being able to detect links from built html files. +Instead of adding those to the `docs/false_positives.json` file, it would be best to rewrite the +reference using a [:ref:](https://www.sphinx-doc.org/en/master/usage/referencing.html#role-ref). + +For example, instead of writing `Modules <../api.html#modules>` to link to the modules section of +a `api.rst` file, write it as ``:ref:`Modules ` ``. And in the `api.rst` file, add +this label before the section being linked to: + +``` +.. _asr-api-modules: +``` diff --git a/docs/check_for_broken_links.sh b/docs/check_for_broken_links.sh new file mode 100644 index 0000000000000000000000000000000000000000..db767aa6d1e852418dd49838a06986e4f18796a1 --- /dev/null +++ b/docs/check_for_broken_links.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash + +DOCS_DIR=$(dirname "${BASH_SOURCE[0]}") +FALSE_POSITIVES_JSON="${DOCS_DIR}/false_positives.json" +NEEDS_REVIEW_JSON="${DOCS_DIR}/links_needing_review.json" +LINKCHECK_JSON="${DOCS_DIR}/build/linkcheck/output.json" + +function check_environment { + local err=0 + if ! [ -x "$(command -v jq)" ]; then + >&2 echo "jq is required but is not found." + ((err++)) + fi + if [ ! -f "${FALSE_POSITIVES_JSON}" ]; then + >&2 echo "A JSON file with false positives is required: ${FALSE_POSITIVES_JSON}" + ((err++)) + fi + if [ ! -f "${LINKCHECK_JSON}" ]; then + >&2 echo "Did not find linkcheck output JSON file: ${LINKCHECK_JSON}." + >&2 echo "Run Sphinx with the linkcheck arg: make -C docs clean linkcheck" + ((err++)) + fi + if [ "${err}" -gt 0 ]; then + exit 2 + fi +} + +function check_links { + local err=0 + broken=$(jq -s 'map(select(.status=="broken"))' "$LINKCHECK_JSON") + count=$(echo "${broken}" | jq 'length') + for i in $(seq 0 $(($count - 1))) + do + entry=$(echo "${broken}" | jq ".[${i}]") + link=$(echo "${entry}" | jq -r '.uri') + [ -n "${DEBUG}" ] && { + echo >&2 "Checking for false positive: ${link}" + } + local false_positive_resp; false_positive_resp=$(jq --arg check "${link}" -s 'any(.uri == $check)' < "${FALSE_POSITIVES_JSON}") + local needs_review_resp; needs_review_resp=$(jq --arg check "${link}" -s 'any(.uri == $check)' < "${NEEDS_REVIEW_JSON}") + # "false" indicates that the URL did not match any of the URIs in the false positive file. + if [[ "false" = "${false_positive_resp}" && "false" = "${needs_review_resp}" ]]; then + ((err++)) + echo "${entry}" + fi + done + exit "${err}" +} + +check_environment +check_links diff --git a/docs/combined.json b/docs/combined.json new file mode 100644 index 0000000000000000000000000000000000000000..fe51488c7066f6687ef680d6bfaa4f7768ef205c --- /dev/null +++ b/docs/combined.json @@ -0,0 +1 @@ +[] diff --git a/docs/source/_static/css/custom.css b/docs/source/_static/css/custom.css new file mode 100644 index 0000000000000000000000000000000000000000..76b4fcafd3450dddfb0d59b66af5f54124849d2e --- /dev/null +++ b/docs/source/_static/css/custom.css @@ -0,0 +1,381 @@ +@import url("theme.css"); + +body { + font-size: 100%; + font-family: 'NVIDIA Sans', sans-serif; +} + + +/* Width of template */ + +.wy-nav-content { + max-width: 1200px !important; +} + + + +/* Standard Text Formatting */ + +h1 { + color: #76b900; + text-align: center; + /* background-color: #ffffff; */ +} + +h2 { + color: #ffffff; + /* background-color: #ffffff; */ + /* #76b900 */ + Padding: 5px; +} + +h3 { + padding-top: 0px; + border-top: solid 3px #000000; + /* #76b900 */ + border-bottom: solid 3px #000000; + /* #76b900 */ +} + +p { + margin-bottom: 24px; +} + +/* Link Colors */ +/* +a { + color: #76b900; +} +/* + +/* +a:visited { + color: #218219; +} +*/ + +.container-xl { + margin-right: unset; + margin-left: unset; +} + +section { + overflow-x: auto; +} + +/* ----------------------------------------------TABLES--------------------------------------- */ +section table { + overflow-x: auto; + display: block; +} + +table { + font-size: small; +} + +/* Table head Color */ +thead td { + background-color: #333333 !important; +} + +.row-odd p { + /*padding-bottom: 0px;*/ + /*margin-bottom: 0px;*/ +} + +/* even rows*/ + +.row-even tr { + background-color: #e5f1e6 !important; +} + +/* odd rows*/ + + +.wy-table-responsive table tr { + background-color: #ffffff !important; +} + + + +.wy-table-responsive table td { + white-space: normal; +} + + +/* Removes bottom margin in tables*/ + +.rst-content .line-block { + margin-bottom: 0px; +} + +.wy-table-responsive { + overflow: visible !important; +} + +/* reduces the size of text in multiline table columns. */ + +.rst-content table.docutils td { + font-size: 80%; +} + +.rst-content dl:not(.docutils) dt { + + background-color: inherit; + color: #000000; + border-top: solid 0px #000000; + +} + +.rst-content dl:not(.docutils) dt:before { + color: #333333; +} + +.rst-content .line-block { + margin-bottom: 0px; +} + +.wy-side-nav-search, +.wy-nav-top { + background-color: #000000; + padding: 0; +} + +.wy-side-nav-search img { + padding: 0px; + padding: 0px 0px; + margin-bottom: 0; +} + +.wy-side-nav-search input[type=text] { + border-radius: 0px; +} + + +.wy-menu-vertical p.caption { + color: #76b900; +} + + +.wy-side-nav-search>a img.logo, +.wy-side-nav-search .wy-dropdown>a img.logo { + margin: 0px 0px 0px 0px; +} + +.wy-nav-content { + margin: 0; + min-height: 100%; + height: 100%; + background: #ffffff; +} + +/* NVIDIA green hover on table rows */ +table tbody tr:hover, +table.table tbody tr:hover, +table.docutils tbody tr:hover, +.pst-scrollable-table-container table tbody tr:hover, +.rst-content table tbody tr:hover { + background-color: rgba(118, 185, 0, 0.15) !important; +} + +/* List (numbered, bulleted) padding Fix */ + + +.wy-plain-list-decimal li { + margin-top: -6px; + margin-bottom: -6px; +} + +.rst-content .section ol.loweralpha { + margin-top: -6px; + margin-bottom: 12px; +} + +.wy-plain-list-disc, +.rst-content .toctree-wrapper ul, +article ul { + margin-top: 0px !important; + margin-bottom: 12px; +} + +/* Alert Boxes */ +/* Background color of Alert Box Title */ + +.rst-content .section ul { + margin-top: -12px; + margin-bottom: 16px; +} + +.wy-alert.wy-alert-info .wy-alert-title, +.rst-content .note .wy-alert-title, +.rst-content .wy-alert-info.attention .wy-alert-title, +.rst-content .wy-alert-info.caution .wy-alert-title, +.rst-content .wy-alert-info.danger .wy-alert-title, +.rst-content .wy-alert-info.error .wy-alert-title, +.rst-content .wy-alert-info.hint .wy-alert-title, +.rst-content .wy-alert-info.important .wy-alert-title, +.rst-content .wy-alert-info.tip .wy-alert-title, +.rst-content .wy-alert-info.warning .wy-alert-title, +.rst-content .seealso .wy-alert-title, +.rst-content .wy-alert-info.admonition-todo .wy-alert-title, +.rst-content .wy-alert-info.admonition .wy-alert-title, +.wy-alert.wy-alert-info .rst-content .admonition-title, +.rst-content .wy-alert.wy-alert-info .admonition-title, +.rst-content .note .admonition-title, +.rst-content .wy-alert-info.attention .admonition-title, +.rst-content .wy-alert-info.caution .admonition-title, +.rst-content .wy-alert-info.danger .admonition-title, +.rst-content .wy-alert-info.error .admonition-title, +.rst-content .wy-alert-info.hint .admonition-title, +.rst-content .wy-alert-info.important .admonition-title, +.rst-content .wy-alert-info.tip .admonition-title, +.rst-content .wy-alert-info.warning .admonition-title, +.rst-content .seealso .admonition-title, +.rst-content .wy-alert-info.admonition-todo .admonition-title, +.rst-content .wy-alert-info.admonition .admonition-title { + background: #76b900; +} + +/* Background and Font Color of Alert Box Main Body*/ +.wy-alert.wy-alert-info, +.rst-content .note, +.rst-content .wy-alert-info.attention, +.rst-content .wy-alert-info.caution, +.rst-content .wy-alert-info.danger, +.rst-content .wy-alert-info.error, +.rst-content .wy-alert-info.hint, +.rst-content .wy-alert-info.important, +.rst-content .wy-alert-info.tip, +.rst-content .wy-alert-info.warning, +.rst-content .seealso, +.rst-content .wy-alert-info.admonition-todo, +.rst-content .wy-alert-info.admonition { + background: #333333; + color: #999999; +} + +.section { + margin-top: 50px; +} + +/* Logo */ +.navbar-brand-box { + background-color: #ffffff; +} + +/* ---------------------------------------------- Media Queries --------------------------------------- */ +@media (min-width: 1200px) { + .container-xl { + max-width: 100%; + } +} + +@media (min-width: none) { + body { + font-size: 18px; + } + + #site-navigation nav ul.nav { + font-size: 18px; + } + + #site-navigation nav.bd-links p { + font-size: 18px; + } + + #site-navigation { + width: 350px; + } + + .toc-h2 { + font-size: 18px; + } + + .toc-h3 { + font-size: 1rem; + } + + .toc-h4 { + font-size: 0.85rem; + } + + .header-article .bd-toc { + font-size: 18px; + } + + #main-content>div { + margin-left: 10%; + margin-right: 10%; + } +} + +/* ---------------------------------------------- NVIDIA Sans --------------------------------------- */ + +:root { + --md-text-font: "NVIDIA Sans"; + /* --md-code-font: "NVIDIA Sans"; */ +} + +@font-face { + font-family: "NVIDIA Sans"; + src: url(https://aws1.discourse-cdn.com/nvidia/original/3X/5/2/52891dda673228d54e5d57bf1e4a3880d4b22405.woff2) format("woff2"), + url(https://aws1.discourse-cdn.com/nvidia/original/3X/e/0/e090b7dda7a582522c7f9045c6ce949cce60134f.woff) format("woff"); + font-weight: 300; + font-style: normal; +} + +@font-face { + font-family: "NVIDIA Sans"; + src: url(https://aws1.discourse-cdn.com/nvidia/original/3X/a/1/a107baabcbf6b241099122336bce7429bcfd377a.woff2) format("woff2"), + url(https://aws1.discourse-cdn.com/nvidia/original/3X/3/a/3a6060a4e3bce70e5552ba0de8af4b22c6cf9144.woff) format("woff"); + font-weight: 300; + font-style: italic; +} + +@font-face { + font-family: "NVIDIA Sans"; + src: url(https://aws1.discourse-cdn.com/nvidia/original/3X/9/9/9920d2b172b01d92fc9c1c0e521dcf45b59c47c3.woff2) format("woff2"), + url(https://aws1.discourse-cdn.com/nvidia/original/3X/6/c/6c7d947928a7e4ef3e80ed409bef6c243f2148cb.woff) format("woff"); + font-weight: 400; + font-style: normal; +} + +@font-face { + font-family: "NVIDIA Sans"; + src: url(https://aws1.discourse-cdn.com/nvidia/original/3X/e/8/e8e63fe1244372cd942d957f44a5616a1eba0644.woff2) format("woff2"), + url(https://aws1.discourse-cdn.com/nvidia/original/3X/0/f/0f1fb2af0283ab09d36e7097bb07d895c3228f12.woff) format("woff"); + font-weight: 400; + font-style: italic; +} + +@font-face { + font-family: "NVIDIA Sans"; + src: url(https://aws1.discourse-cdn.com/nvidia/original/3X/7/9/79d3c513a9cd72c59f65354f39f89ca52dc17dd2.woff2) format("woff2"), + url(https://aws1.discourse-cdn.com/nvidia/original/3X/2/5/2581ac533f5d01f4985d8a7245b0766b4630ced8.woff) format("woff"); + font-weight: 500; + font-style: normal; +} + +@font-face { + font-family: "NVIDIA Sans"; + src: url(https://aws1.discourse-cdn.com/nvidia/original/3X/3/9/39d9ef1ee9770dd503f19bb2ace2fdb4eff3bb50.woff2) format("woff2"), + url(https://aws1.discourse-cdn.com/nvidia/original/3X/7/b/7bb5d5e2e71b2e13c8098b2e67c0a0ed9258e6c7.woff) format("woff"); + font-weight: 500; + font-style: italic; +} + +@font-face { + font-family: "NVIDIA Sans"; + src: url(https://aws1.discourse-cdn.com/nvidia/original/3X/0/5/05276a55a43eb3f74981ec1e93252727afcd9d16.woff2) format("woff2"), + url(https://aws1.discourse-cdn.com/nvidia/original/3X/9/c/9cfec7ed941b06564aa4d5ca14610e81542d070f.woff) format("woff"); + font-weight: 700; + font-style: normal; +} + +@font-face { + font-family: "NVIDIA Sans"; + src: url(https://aws1.discourse-cdn.com/nvidia/original/3X/a/e/aebd14d09ba56f541e1b8735fb051e33710f9ae7.woff2) format("woff2"), + url(https://aws1.discourse-cdn.com/nvidia/original/3X/e/d/edbdabef43acc5c12e84a94baaa5542c9404cfeb.woff) format("woff"); + font-weight: 700; + font-style: italic; +} \ No newline at end of file diff --git a/docs/source/_static/js/pk_scripts.js b/docs/source/_static/js/pk_scripts.js new file mode 100644 index 0000000000000000000000000000000000000000..23c74982d3aad11ab94c31e623b60e0ebe66972a --- /dev/null +++ b/docs/source/_static/js/pk_scripts.js @@ -0,0 +1,19 @@ +document.addEventListener("DOMContentLoaded", function () { + var params = window.location.search.substring(1).split("&").reduce(function (params, param) { + if (!param) { + return params; + } + + var values = param.split("="); + var name = values[0]; + var value = values[1]; + params[name] = value; + return params; + }, {}); + + var form = document.getElementById("feedback-form"); + for (var name in params) { + var input = form.querySelector("[name=" + name + "]"); + input.value = params[name]; + } +}); \ No newline at end of file diff --git a/docs/source/apis.rst b/docs/source/apis.rst new file mode 100644 index 0000000000000000000000000000000000000000..5bee094ac894f540720a75248319b1a06d28adc5 --- /dev/null +++ b/docs/source/apis.rst @@ -0,0 +1,46 @@ +========= +NeMo APIs +========= + +You can learn more about the underlying principles of the NeMo codebase in this section. + +The `NeMo Toolkit codebase `__ is composed of a `core `__ section which contains the main building blocks of the framework, and various `collections `__ which help you +build specialized AI models. + +You can learn more about aspects of the NeMo "core" by following the links below: + +.. toctree:: + :maxdepth: 1 + :name: core + :titlesonly: + + core/core + core/neural_modules + core/exp_manager + core/neural_types + core/adapters/intro + +You can learn more about aspects of the NeMo APIs by following the links below: + +.. toctree:: + :maxdepth: 1 + :name: API + :titlesonly: + + core/api + common/intro + asr/api + tts/api + audio/api + + +Alternatively, you can jump straight to the documentation for the individual collections: + +* :doc:`Automatic Speech Recognition (ASR) <../asr/intro>` + +* :doc:`Text-to-Speech (TTS) <../tts/intro>` + +* :doc:`Audio Processing <../audio/intro>` + +* :doc:`SpeechLM2 <../speechlm2/intro>` + diff --git a/docs/source/asr/all_chkpt.rst b/docs/source/asr/all_chkpt.rst new file mode 100644 index 0000000000000000000000000000000000000000..f9d236126cd5073029362de474a991828d440324 --- /dev/null +++ b/docs/source/asr/all_chkpt.rst @@ -0,0 +1,400 @@ +All Checkpoints +=============== +English +^^^^^^^ +.. csv-table:: + :file: data/benchmark_en.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +German +^^^^^^ +.. csv-table:: + :file: data/benchmark_de.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Spanish +^^^^^^^ +.. csv-table:: + :file: data/benchmark_es.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +French +^^^^^^ +.. csv-table:: + :file: data/benchmark_fr.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Arabic +^^^^^^^ +.. csv-table:: + :file: data/benchmark_ar.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +------------------------------ + +Russian +^^^^^^^ +.. csv-table:: + :file: data/benchmark_ru.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Portuguese +^^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_pt.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Belarusian +^^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_be.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Japanese +^^^^^^^^ +.. csv-table:: + :file: data/benchmark_jp.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Armenian +^^^^^^^^ +.. csv-table:: + :file: data/benchmark_hy.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Georgian +^^^^^^^^ +.. csv-table:: + :file: data/benchmark_ka.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Kazakh +^^^^^^ +.. csv-table:: + :file: data/benchmark_kz.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Persian +^^^^^^^ +.. csv-table:: + :file: data/benchmark_fa.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Uzbek +^^^^^ +.. csv-table:: + :file: data/benchmark_uz.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Ukrainian +^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_ua.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Polish +^^^^^^ +.. csv-table:: + :file: data/benchmark_pl.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Italian +^^^^^^^ +.. csv-table:: + :file: data/benchmark_it.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + + +Croatian +^^^^^^^^ +.. csv-table:: + :file: data/benchmark_hr.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Esperanto +^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_eo.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Kabyle +^^^^^^ +.. csv-table:: + :file: data/benchmark_kab.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Dutch +^^^^^ +.. csv-table:: + :file: data/benchmark_nl.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Catalan +^^^^^^^ +.. csv-table:: + :file: data/benchmark_ca.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Hindi +^^^^^^^ +.. csv-table:: + :file: data/benchmark_hi.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Marathi +^^^^^^^ +.. csv-table:: + :file: data/benchmark_mr.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Mandarin +^^^^^^^^ +.. csv-table:: + :file: data/benchmark_zh.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Czech +^^^^^ +.. csv-table:: + :file: data/benchmark_cs.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Bulgarian +^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_bg.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Danish +^^^^^^ +.. csv-table:: + :file: data/benchmark_da.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Estonian +^^^^^^^^ +.. csv-table:: + :file: data/benchmark_et.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Finnish +^^^^^^^ +.. csv-table:: + :file: data/benchmark_fi.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Greek +^^^^^ +.. csv-table:: + :file: data/benchmark_el.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Hungarian +^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_hu.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Latvian +^^^^^^^ +.. csv-table:: + :file: data/benchmark_lv.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Lithuanian +^^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_lt.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Maltese +^^^^^^^ +.. csv-table:: + :file: data/benchmark_mt.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Romanian +^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_ro.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Slovak +^^^^^^ +.. csv-table:: + :file: data/benchmark_sk.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Slovenian +^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_sl.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Swedish +^^^^^^^ +.. csv-table:: + :file: data/benchmark_sv.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +----------------------------- + +Kinyarwanda +^^^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_rw.csv + :align: left + :widths: 50,50 + :header-rows: 1 diff --git a/docs/source/asr/api.rst b/docs/source/asr/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..a8b4d9f287db7767686b4052bae979495d41bef7 --- /dev/null +++ b/docs/source/asr/api.rst @@ -0,0 +1,357 @@ +NeMo ASR API +============ + + +Model Classes +------------- + +.. autoclass:: nemo.collections.asr.models.EncDecCTCModel + :show-inheritance: + :members: transcribe, change_vocabulary, setup_training_data, setup_optimization, setup_validation_data, setup_test_data, register_artifact + + +.. autoclass:: nemo.collections.asr.models.EncDecCTCModelBPE + :show-inheritance: + :members: transcribe, change_vocabulary, setup_training_data, setup_optimization, setup_validation_data, setup_test_data, register_artifact + + +.. autoclass:: nemo.collections.asr.models.EncDecRNNTModel + :show-inheritance: + :members: transcribe, change_vocabulary, setup_training_data, setup_optimization, setup_validation_data, setup_test_data, register_artifact + + +.. autoclass:: nemo.collections.asr.models.EncDecRNNTBPEModel + :show-inheritance: + :members: transcribe, change_vocabulary, setup_training_data, setup_optimization, setup_validation_data, setup_test_data, register_artifact + + +.. autoclass:: nemo.collections.asr.models.EncDecMultiTalkerRNNTBPEModel + :show-inheritance: + :members: transcribe, change_vocabulary, setup_training_data, setup_optimization, setup_validation_data, setup_test_data, register_artifact + + +.. autoclass:: nemo.collections.asr.models.EncDecClassificationModel + :show-inheritance: + :members: setup_training_data, setup_optimization, setup_validation_data, setup_test_data, register_artifact + + +.. autoclass:: nemo.collections.asr.models.EncDecSpeakerLabelModel + :show-inheritance: + :members: setup_training_data, setup_optimization, setup_validation_data, setup_test_data, register_artifact + + +.. _asr-api-modules: + +Modules +------- + +.. autoclass:: nemo.collections.asr.modules.ConvASREncoder + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.modules.ConvASRDecoder + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.modules.ConvASRDecoderClassification + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.modules.SpeakerDecoder + :show-inheritance: + :members: + +.. _conformer-encoder-api: + +.. autoclass:: nemo.collections.asr.modules.ConformerEncoder + :show-inheritance: + :members: + + +.. _rnn-encoder-api: + +.. autoclass:: nemo.collections.asr.modules.RNNEncoder + :show-inheritance: + :members: + +.. _rnnt-decoder-api: + +.. autoclass:: nemo.collections.asr.modules.RNNTDecoder + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.modules.StatelessTransducerDecoder + :show-inheritance: + :members: + +.. _rnnt-joint-api: + +.. autoclass:: nemo.collections.asr.modules.RNNTJoint + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.modules.SampledRNNTJoint + :show-inheritance: + :members: + + +Mixins +------ + +.. autoclass:: nemo.collections.asr.parts.mixins.mixins.ASRBPEMixin + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.mixins.mixins.ASRModuleMixin + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.mixins.transcription.TranscriptionMixin + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.mixins.transcription.TranscribeConfig + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.mixins.interctc_mixin.InterCTCMixin + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.mixins.multitalker_asr_mixins.SpeakerKernelMixin + :show-inheritance: + :members: + +.. _asr-api-datasets: + +Datasets +-------- + +Character Encoding Datasets +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.data.audio_to_text.AudioToCharDataset + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset + :show-inheritance: + :members: + + +Text-to-Text Datasets +~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.data.text_to_text.TextToTextDataset + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.data.text_to_text.TextToTextIterableDataset + :show-inheritance: + :members: + + +Speaker-Tagged Datasets for Multitalker ASR models +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.data.audio_to_text_lhotse_speaker.LhotseSpeechToTextSpkBpeDataset + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.data.audio_to_diar_label_lhotse.LhotseAudioToSpeechE2ESpkDiarDataset + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.data.data_simulation.MultiSpeakerSimulator + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.data.data_simulation.RIRMultiSpeakerSimulator + :show-inheritance: + :members: + +Subword Encoding Datasets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.data.audio_to_text.AudioToBPEDataset + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset + :show-inheritance: + :members: + +.. _asr-audio-preprocessors: + +Audio Preprocessors +------------------- + +.. autoclass:: nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.modules.AudioToMFCCPreprocessor + :show-inheritance: + :members: + +.. _asr-api-audio-augmentors: + +Audio Augmentors +---------------- + +.. autoclass:: nemo.collections.asr.modules.SpectrogramAugmentation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.modules.CropOrPadSpectrogramAugmentation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.preprocessing.perturb.SpeedPerturbation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.preprocessing.perturb.TimeStretchPerturbation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.preprocessing.perturb.GainPerturbation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.preprocessing.perturb.ImpulsePerturbation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.preprocessing.perturb.ShiftPerturbation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.preprocessing.perturb.NoisePerturbation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.preprocessing.perturb.WhiteNoisePerturbation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.preprocessing.perturb.RirAndNoisePerturbation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.preprocessing.perturb.TranscodePerturbation + :show-inheritance: + :members: + +Miscellaneous Classes +--------------------- + +CTC Decoding +~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.parts.submodules.ctc_decoding.CTCDecoding + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.ctc_decoding.CTCBPEDecoding + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.ctc_greedy_decoding.GreedyCTCInfer + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.ctc_beam_decoding.BeamCTCInfer + :show-inheritance: + :members: + +RNNT Decoding +~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.parts.submodules.rnnt_decoding.RNNTDecoding + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.rnnt_decoding.RNNTBPEDecoding + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.rnnt_greedy_decoding.GreedyRNNTInfer + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.rnnt_greedy_decoding.GreedyBatchedRNNTInfer + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.rnnt_beam_decoding.BeamRNNTInfer + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.rnnt_beam_decoding.BeamBatchedRNNTInfer + :show-inheritance: + :members: + +TDT Decoding +~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.parts.submodules.rnnt_greedy_decoding.GreedyTDTInfer + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.rnnt_greedy_decoding.GreedyBatchedTDTInfer + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.tdt_beam_decoding.BeamTDTInfer + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.submodules.tdt_beam_decoding.BeamBatchedTDTInfer + :show-inheritance: + :members: + +Hypotheses +~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.parts.utils.rnnt_utils.Hypothesis + :show-inheritance: + :no-members: + +.. autoclass:: nemo.collections.asr.parts.utils.rnnt_utils.NBestHypotheses + :show-inheritance: + :no-members: + +Adapter Networks +~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module.MultiHeadAttentionAdapter + :show-inheritance: + :members: + :member-order: bysource + +.. autoclass:: nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module.RelPositionMultiHeadAttentionAdapter + :show-inheritance: + :members: + :member-order: bysource + +.. autoclass:: nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module.PositionalEncodingAdapter + :show-inheritance: + :members: + :member-order: bysource + +.. autoclass:: nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module.RelPositionalEncodingAdapter + :show-inheritance: + :members: + :member-order: bysource + + +Adapter Strategies +~~~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module.MHAResidualAddAdapterStrategy + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + diff --git a/docs/source/asr/asr_all.bib b/docs/source/asr/asr_all.bib new file mode 100644 index 0000000000000000000000000000000000000000..572fd611df0b741fba28db2194b2237c043a53a9 --- /dev/null +++ b/docs/source/asr/asr_all.bib @@ -0,0 +1,1093 @@ +@article{matchboxnet, + title={{MatchboxNet}: 1D Time-Channel Separable Convolutional Neural Network Architecture for Speech Commands Recognition}, + author={Majumdar, Somshubra and Ginsburg, Boris}, + journal={Proc. Interspeech 2020}, + year={2020} +} + +@article{marblenet, + title={MarbleNet: Deep 1D Time-Channel Separable Convolutional Neural Network for Voice Activity Detection}, + author={Jia, Fei and Majumdar, Somshubra and Ginsburg, Boris}, + journal={arXiv preprint arXiv:2010.13886}, + year={2020} +} + +@inproceedings{panayotov2015librispeech, + title={Librispeech: an ASR corpus based on public domain audio books}, + author={Panayotov, Vassil and Chen, Guoguo and Povey, Daniel and Khudanpur, Sanjeev}, + booktitle={Acoustics, Speech and Signal Processing (ICASSP), 2015 IEEE International Conference on}, + pages={5206--5210}, + year={2015}, + organization={IEEE} +} + +@article{luong17, + author = {Minh{-}Thang Luong and Eugene Brevdo and Rui Zhao}, + title = {Neural Machine Translation (seq2seq) Tutorial}, + journal = {https://github.com/tensorflow/nmt}, + year = {2017}, +} + +@INPROCEEDINGS{LaurentSeqWiseBN, +author={C. {Laurent} and G. {Pereyra} and P. {Brakel} and Y. {Zhang} and Y. {Bengio}}, +booktitle={2016 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)}, +title={Batch normalized recurrent neural networks}, +year={2016}, +volume={}, +number={}, +pages={2657-2661}, +keywords={feedforward neural nets;learning (artificial intelligence);recurrent neural nets;speech recognition;batch normalized recurrent neural networks;RNN;sequential data;long-term dependency learning;convergence rate improvement;intermediate representation normalization;feedforward neural networks;speech recognition task;language modeling;training criterion;Training;Recurrent neural networks;Convergence;Speech recognition;Computer architecture;Speech;batch normalization;RNN;LSTM;optimization}, +doi={10.1109/ICASSP.2016.7472159}, +ISSN={2379-190X}, +month={March},} + +@article{graves2005, + author = {Alex Graves and Jurgen Schmidhuber}, + title = {Framewise phoneme classification with bidirectional LSTM and other neural network architectures}, + journal = {Neural Networks, vol. 18}, + pages={602–-610}, + year = {2005}, +} + +@inproceedings{graves2006, + title={Connectionist temporal classification: labelling unsegmented sequence data with recurrent neural networks}, + author={Graves, Alex and Fern{\'a}ndez, Santiago and Gomez, Faustino and Schmidhuber, J{\"u}rgen}, + booktitle={Proceedings of the 23rd international conference on Machine learning}, + pages={369--376}, + year={2006}, + organization={ACM} +} + +@article{li2019jasper, + title={Jasper: An End-to-End Convolutional Neural Acoustic Model}, + author={Li, Jason and Lavrukhin, Vitaly and Ginsburg, Boris and Leary, Ryan and Kuchaiev, Oleksii and Cohen, Jonathan M and Nguyen, Huyen and Gadde, Ravi Teja}, + journal={arXiv preprint arXiv:1904.03288}, + year={2019} +} + +@misc{ardila2019common, + title={Common Voice: A Massively-Multilingual Speech Corpus}, + author={Rosana Ardila and Megan Branson and Kelly Davis and Michael Henretty and Michael Kohler and Josh Meyer and Reuben Morais and Lindsay Saunders and Francis M. Tyers and Gregor Weber}, + year={2019}, + eprint={1912.06670}, + archivePrefix={arXiv}, + primaryClass={cs.CL} +} + +@article{graves2012, + title={Sequence Transduction with Recurrent Neural Networks}, + author={Graves, Alex}, + journal={arXiv preprint arXiv:1211.3711}, + year={2012} +} + + +@article{graves2013, + title={Generating sequences with recurrent neural networks}, + author={Graves, Alex}, + journal={arXiv preprint arXiv:1308.0850}, + year={2013} +} + +@article{sergeev2018horovod, + title={Horovod: fast and easy distributed deep learning in TensorFlow}, + author={Sergeev, Alexander and Del Balso, Mike}, + journal={arXiv preprint arXiv:1802.05799}, + year={2018} +} + +@misc{NVVolta, + title = {NVIDIA TESLA V100 GPU ARCHITECTURE}, + howpublished = {\url{http://images.nvidia.com/content/volta-architecture/pdf/volta-architecture-whitepaper.pdf}}, + note = {Accessed: 2018-10-09} +} + +@article{NVTuring, + title = {NVIDIA TURING GPU ARCHITECTURE}, + howpublished = {\url{https://www.nvidia.com/content/dam/en-zz/Solutions/design-visualization/technologies/turing-architecture/NVIDIA-Turing-Architecture-Whitepaper.pdf}}, + author = {NVIDIA}, + year = {2018}, + note = {Accessed: 2018-10-09} +} + +@misc{Rygaard2015, + title = {Using Synthesized Speech to Improve Speech Recognition for Low-Resource Languages}, + author = {Luise Valentin Rygaard}, + howpublished = {\url{https://parasol.tamu.edu/dreu2015/Rygaard/report.pdf}}, + year = {2015}, +} + +@misc{OpenSeq2Seq, + title = {OpenSeq2Seq: extensible toolkit for distributed and mixed precision training of sequence-to-sequence models}, + author = {Kuchaiev, Oleksii and Ginsburg, Boris and Gitman, Igor and Lavrukhin,Vitaly and Case, Carl and Micikevicius, Paulius}, + howpublished = {\url{https://arxiv.org/abs/1805.10387}}, + year = {2018}, +} + +@misc{MPGuide, + title = {Training with Mixed Precision}, + howpublished = {\url{http://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/}}, + note = {Accessed: 2018-04-06}, +} + +@misc{Mozilla, + title = {Mozilla: A Journey to less than 10\% Word Error Rate}, + howpublished = {\url{https://hacks.mozilla.org/2017/11/a-journey-to-10-word-error-rate/}}, + note = {Accessed: 2018-04-06}, +} + +@article{Waibel1989, + title={A time-delay neural network architecture for isolated word recognition}, + author={Waibel, Alexander, and Hanazawa, Toshiyki and Hinton,Geoffrey and Shirano, Kiyohiro and Lang, Kevin }, + journal={IEEE Trans. on Acoustics, Speech and Signal Processing}, + year={1989} +} + +@article{Lang1990, + title={A time-delay neural network architecture for isolated word recognition}, + author={Lang, Kevin and Waibel, Alexander, and Hinton,Geoffrey }, + journal={Neural Networks}, + year={1990} +} + +@book{Bengio1996, + Author = {Bengio, Y.}, + Publisher = {International Thomson Computer Press}, + Title = {Neural Networks for Speech and Sequence Recognition}, + Year = {1996} +} + +@article{Bengio1992, + title={Global optimization of a neural network-hidden Markov model hybrid}, + author={Bengio, Y., and De Mori, R., and Flammia, G., and Kompe, R. }, + journal={IEEE Transactions on Neural Networks, 3(2), 252–259}, + year={1992} +} + +@article{Bourlard1994, + title={Connectionist speech recognition: a hybrid approach}, + author={Bourlard, H. A. and Morgan, N.}, + journal={volume 247 Springer }, + year={1994} +} + +@article{srivastava14a, + author = {Nitish Srivastava, and Geoffrey Hinton, and Alex Krizhevsky, and Ilya Sutskever, and Ruslan Salakhutdinov}, + title = {Dropout: A Simple Way to Prevent Neural Networks from Overfitting}, + journal = {Journal of Machine Learning Research}, + year = {2014}, + volume = {15}, + pages = {1929-1958}, + url = {http://jmlr.org/papers/v15/srivastava14a.html} +} + + +@article{Hinton2012, + title={Deep Neural Networks for Acoustic Modeling in Speech Recognition}, + author={ Hinton,Geoffrey and Deng, Li and Yu, Dong and Dahl,George and Mohamed,Abdel-rahman and Jaitly, Navdeep and Senior, Andrew and Vanhoucke, Vincent and Nguyen, Patrick and Kingsbury, Brian and Sainath, Tara}, + journal={IEEE Signal Processing Magazine}, + year={2012} +} + +@article{Graves2014, + title={Towards End-to-End Speech Recognition with Recurrent Neural Networks}, + author={Graves, Alex and Jaitly, Navdeep}, + journal={International Conference on Machine Learning}, + year={2014} +} + +@article{Chorowski2014, + title={End-to-end Continuous Speech Recognition using Attention-based Recurrent NN: First Results}, + author={ Chorowski, Jan, and Bahdanau, Dzmitry , and Cho, Kyunghyun , and Bengio, Yoshua }, + journal={Neural Information Processing Systems: Workshop Deep Learning and Representation Learning Workshop }, + year={2014} +} + +@article{Sak2014, + title={Long short-term memory recurrent neural network architectures for large scale acoustic modeling}, + author={Sak, Hasim and Senior, Andrew and Beaufays, Francoise }, + journal={Interspeech 2014}, + year={2014} +} + +@article{Ko2015, + title={Audio Augmentation for Speech Recognition}, + author={Tom, Ko and Vijayaditya, Peddinti and Daniel, Povey + and Sanjeev, Khudanpur }, + journal={Interspeech 2015}, + year={2015} +} + +@article{Tjandra2017, + title={Listening while Speaking: Speech Chain by Deep Learning}, + author={Andros, Tjandra and Sakriani, Sakti and Satoshi, Nakamura }, + journal={ASRU 2017}, + year={2017} +} + +@article{Tjandra2018, + title={Machine Speech Chain with One-shot Speaker Adaptation}, + author={Andros, Tjandra and Sakriani, Sakti and Satoshi, Nakamura }, + journal={Interspeech 2018}, + year={2018} +} + +@article{bahdanau2014neural, + title={Neural machine translation by jointly learning to align and translate}, + author={Bahdanau, Dzmitry and Cho, Kyunghyun and Bengio, Yoshua}, + journal={arXiv preprint arXiv:1409.0473}, + year={2014} +} + +@article{cho2014learning, + title={Learning phrase representations using RNN encoder-decoder for statistical machine translation}, + author={Cho, Kyunghyun and Van Merri{\"e}nboer, Bart and Gulcehre, Caglar and Bahdanau, Dzmitry and Bougares, Fethi and Schwenk, Holger and Bengio, Yoshua}, + journal={arXiv preprint arXiv:1406.1078}, + year={2014} +} + +@article{rush2015neural, + title={A neural attention model for abstractive sentence summarization}, + author={Rush, Alexander M and Chopra, Sumit and Weston, Jason}, + journal={arXiv preprint arXiv:1509.00685}, + year={2015} +} + +@article{micikevicius2017mixed, + title={Mixed precision training}, + author={Micikevicius, Paulius and Narang, Sharan and Alben, Jonah and Diamos, Gregory and Elsen, Erich and Garcia, David and Ginsburg, Boris and Houston, Michael and Kuchaev, Oleksii and Venkatesh, Ganesh and others}, + journal={arXiv preprint arXiv:1710.03740}, + year={2017} +} + +@ARTICLE{Britz:2017, + author = {{Britz}, Denny and {Goldie}, Anna and {Luong}, Thang and {Le}, Quoc}, + title = {Massive Exploration of Neural Machine Translation Architectures}, + journal = {ArXiv e-prints arXiv:1703.03906}, + archivePrefix = "arXiv", + eprinttype = {arxiv}, + eprint = {1703.03906}, + primaryClass = "cs.CL", + keywords = {Computer Science - Computation and Language}, + year = 2017, + month = mar +} + +@inproceedings{abadi2016tensorflow, + title={TensorFlow: A System for Large-Scale Machine Learning.}, + author={Abadi, Mart{\'\i}n and Barham, Paul and Chen, Jianmin and Chen, Zhifeng and Davis, Andy and Dean, Jeffrey and Devin, Matthieu and Ghemawat, Sanjay and Irving, Geoffrey and Isard, Michael and others}, + booktitle={OSDI}, + volume={16}, + pages={265--283}, + year={2016} +} + +@article{tensor2tensor, + author = {Ashish Vaswani and Samy Bengio and Eugene Brevdo and Francois Chollet and Aidan N. Gomez and Stephan Gouws and Llion Jones and \L{}ukasz Kaiser and Nal Kalchbrenner and Niki Parmar and Ryan Sepassi and + Noam Shazeer and Jakob Uszkoreit}, + title = {Tensor2Tensor for Neural Machine Translation}, + journal = {CoRR}, + volume = {abs/1803.07416}, + year = {2018}, + url = {http://arxiv.org/abs/1803.07416}, +} + +@article{gehring2017convs2s, + author = {Gehring, Jonas, and Auli, Michael and Grangier, David and Yarats, Denis and Dauphin, Yann N}, + title = "{Convolutional Sequence to Sequence Learning}", + journal = {ArXiv e-prints arXiv:1705.03122}, + archivePrefix = "arXiv", + eprinttype = {arxiv}, + eprint = {1705.03122}, + primaryClass = "cs.CL", + keywords = {Computer Science - Computation and Language}, + year = 2017, + month = May, +} + +@inproceedings{chan2015, + title={Listen, attend and spell}, + author={Chan, William and Jaitly, Navdeep and Le, Quoc V and Vinyals, Oriol}, + booktitle={Acoustics, Speech and Signal Processing (ICASSP), 2016 IEEE International Conference on}, + pages={5206--5210}, + year={2016}, + organization={IEEE} +} + +@inproceedings{xu2015show, + title={Show, attend and tell: Neural image caption generation with visual attention}, + author={Xu, Kelvin and Ba, Jimmy and Kiros, Ryan and Cho, Kyunghyun and Courville, Aaron and Salakhudinov, Ruslan and Zemel, Rich and Bengio, Yoshua}, + booktitle={International Conference on Machine Learning}, + pages={2048--2057}, + year={2015} +} + +@incollection{Sutskever2014, + title = {Sequence to Sequence Learning with Neural Networks}, + author = {Sutskever, Ilya and Vinyals, Oriol and Le, Quoc V}, + booktitle = {Advances in Neural Information Processing Systems 27}, + editor = {Z. Ghahramani and M. Welling and C. Cortes and N. D. Lawrence and K. Q. Weinberger}, + pages = {3104--3112}, + year = {2014}, + publisher = {Curran Associates, Inc.}, + url = {http://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf} +} + +@article{DeepSpeech2014, + title = {Deep Speech: Scaling up end-to-end speech recognition}, + author = {Awni Y. Hannun and Carl Case and Jared Casper and Bryan Catanzaro and Greg Diamos and Erich Elsen and Ryan Prenger and Sanjeev Satheesh and Shubho Sengupta and Adam Coates and Andrew Y. Ng}, + journal = {CoRR}, + volume = {abs/1412.5567}, + year = {2014}, + url = {http://arxiv.org/abs/1412.5567}, + archivePrefix = {arXiv}, + eprint = {1412.5567}, + timestamp = {Mon, 13 Aug 2018 16:48:07 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/HannunCCCDEPSSCN14}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@inproceedings{DeepSpeech2, + author = {Amodei, Dario and Ananthanarayanan, Sundaram and Anubhai, Rishita and Bai, Jingliang and Battenberg, Eric and Case, Carl and Casper, Jared and Catanzaro, Bryan and Cheng, Qiang and Chen, Guoliang and Chen, Jie and Chen, Jingdong and Chen, Zhijie and Chrzanowski, Mike and Coates, Adam and Diamos, Greg and Ding, Ke and Du, Niandong and Elsen, Erich and Engel, Jesse and Fang, Weiwei and Fan, Linxi and Fougner, Christopher and Gao, Liang and Gong, Caixia and Hannun, Awni and Han, Tony and Johannes, Lappi Vaino and Jiang, Bing and Ju, Cai and Jun, Billy and LeGresley, Patrick and Lin, Libby and Liu, Junjie and Liu, Yang and Li, Weigao and Li, Xiangang and Ma, Dongpeng and Narang, Sharan and Ng, Andrew and Ozair, Sherjil and Peng, Yiping and Prenger, Ryan and Qian, Sheng and Quan, Zongfeng and Raiman, Jonathan and Rao, Vinay and Satheesh, Sanjeev and Seetapun, David and Sengupta, Shubho and Srinet, Kavya and Sriram, Anuroop and Tang, Haiyuan and Tang, Liliang and Wang, Chong and Wang, Jidong and Wang, Kaifu and Wang, Yi and Wang, Zhijian and Wang, Zhiqian and Wu, Shuang and Wei, Likai and Xiao, Bo and Xie, Wen and Xie, Yan and Yogatama, Dani and Yuan, Bin and Zhan, Jun and Zhu, Zhenyao}, + title = {Deep Speech 2: End-to-end Speech Recognition in English and Mandarin}, + booktitle = {Proceedings of the 33rd International Conference on International Conference on Machine Learning - Volume 48}, + series = {ICML'16}, + year = {2016}, + location = {New York, NY, USA}, + pages = {173--182}, + numpages = {10}, + url = {http://dl.acm.org/citation.cfm?id=3045390.3045410}, + acmid = {3045410}, + publisher = {JMLR.org}, +} + +@inproceedings{prabhavalkar2017comparison, + title={A comparison of sequence-to-sequence models for speech recognition}, + author={Prabhavalkar, Rohit and Rao, Kanishka and Sainath, Tara N and Li, Bo and Johnson, Leif and Jaitly, Navdeep}, + booktitle={Proc. Interspeech}, + pages={939--943}, + year={2017} +} + +@article{chiu2017state, + title={State-of-the-art speech recognition with sequence-to-sequence models}, + author={Chiu, Chung-Cheng and Sainath, Tara N and Wu, Yonghui and Prabhavalkar, Rohit and Nguyen, Patrick and Chen, Zhifeng and Kannan, Anjuli and Weiss, Ron J and Rao, Kanishka and Gonina, Katya and others}, + journal={arXiv preprint arXiv:1712.01769}, + year={2017} +} + +@misc{NVMixed, + title = {{NVIDA's Mixed-Precision Training - TensorFlow example}}, + howpublished = {\url{https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/#example_tensorflow}}, + author={NVIDIA}, + note = {Accessed: 2018-10-09}, + year={2018} +} + +@article{gehring2017, + title={Convolutional sequence to sequence learning}, + author={Gehring, Jonas and Auli, Michael and Grangier, David and Yarats, Denis and Dauphin, Yann N}, + journal={arXiv preprint arXiv:1705.03122}, + year={2017} +} + +@article{collobert2016, + title={Wav2letter: an end-to-end convnet-based speech recognition system}, + author={Collobert, Ronan and Puhrsch, Christian and Synnaeve, Gabriel}, + journal={arXiv preprint arXiv:1609.03193}, + year={2016} +} + +@inproceedings{Zhang2016, +author={Ying Zhang and Mohammad Pezeshki and Philémon Brakel and Saizheng Zhang and César Laurent and Yoshua Bengio and Aaron Courville}, +title={Towards End-to-End Speech Recognition with Deep Convolutional Neural Networks}, +year=2016, +booktitle={Interspeech 2016}, +doi={10.21437/Interspeech.2016-1446}, +url={http://dx.doi.org/10.21437/Interspeech.2016-1446}, +pages={410--414} +} + +@inproceedings{Zhang2017, + title={Very deep convolutional networks for end-to-end speech recognition}, + author={Zhang, Yu, and Chan, William, and Jaitly, Navdeep}, + booktitle={Acoustics, Speech and Signal Processing (ICASSP), 2017 IEEE International Conference on}, + year={2017}, + organization={IEEE} +} + + +@article{Wang2017, + title={Tacotron: Towards End-to-End Speech Synthesis}, + author={ Wang, Yuxuan, and Skerry-Ryan, RJ, and Stanton, Daisy and Wu, Yonghui and Weiss, Ron, and Jaitly, Navdeep and Yang, Zongheng and Xiao, Ying and Chen,Zhifeng and Bengio, Samy and Le, Quoc and Agiomyrgiannakis, Yannis and Clark,Rob and Saurous, Rif A.}, + journal={arXiv preprint arXiv:1703.10135}, + year={2017} +} + +@article{griffin1984signal, + title={Signal estimation from modified short-time Fourier transform}, + author={Griffin, Daniel and Lim, Jae}, + journal={IEEE Transactions on Acoustics, Speech, and Signal Processing}, + volume={32}, + number={2}, + pages={236--243}, + year={1984}, + publisher={IEEE} +} + +@misc{ito2017lj, + title={The LJ speech dataset}, + author={Ito, Keith and others}, + year={2017} +} + +@misc{mailabs, + title = {{The M-AILABS Speech Dataset}}, + howpublished = {\url{http://www.m-ailabs.bayern/en/the-mailabs-speech-dataset/}}, + author={M-AILABS}, + note = {Accessed: 2018-10-09}, + year={2018} +} + +@article{merity2016pointer, + title={Pointer sentinel mixture models}, + author={Merity, Stephen and Xiong, Caiming and Bradbury, James and Socher, Richard}, + journal={arXiv preprint arXiv:1609.07843}, + year={2016} +} + +@inproceedings{socher2013recursive, + title={Recursive deep models for semantic compositionality over a sentiment treebank}, + author={Socher, Richard and Perelygin, Alex and Wu, Jean and Chuang, Jason and Manning, Christopher D and Ng, Andrew and Potts, Christopher}, + booktitle={Proceedings of the 2013 conference on empirical methods in natural language processing}, + pages={1631--1642}, + year={2013} +} + +@InProceedings{maas-EtAl:2011:ACL-HLT2011, + author = {Maas, Andrew L. and Daly, Raymond E. and Pham, Peter T. and Huang, Dan and Ng, Andrew Y. and Potts, Christopher}, + title = {Learning Word Vectors for Sentiment Analysis}, + booktitle = {Proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies}, + month = {June}, + year = {2011}, + address = {Portland, Oregon, USA}, + publisher = {Association for Computational Linguistics}, + pages = {142--150}, + url = {http://www.aclweb.org/anthology/P11-1015} +} + +@inproceedings{Povey2018SemiOrthogonalLM, + title={Semi-Orthogonal Low-Rank Matrix Factorization for Deep Neural Networks}, + author={Daniel Povey and Gaofeng Cheng and Yiming Wang and Ke Li and Hainan Xu and Mahsa Yarmohammadi and Sanjeev Khudanpur}, + booktitle={Interspeech}, + year={2018} +} + +@article{CAPIO2017, + author = {Kyu J. Han and Akshay Chandrashekaran and Jungsuk Kim and Ian R. Lane}, + title = {The {CAPIO} 2017 Conversational Speech Recognition System}, + journal = {CoRR}, + volume = {abs/1801.00059}, + year = {2018}, + url = {http://arxiv.org/abs/1801.00059}, + archivePrefix = {arXiv}, + eprint = {1801.00059}, + timestamp = {Mon, 13 Aug 2018 16:49:10 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/abs-1801-00059}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@article{WaveNet, + author = {A{\"{a}}ron van den Oord and Sander Dieleman and Heiga Zen and Karen Simonyan and Oriol Vinyals and Alex Graves and Nal Kalchbrenner and Andrew W. Senior and Koray Kavukcuoglu}, + title = {WaveNet: {A} Generative Model for Raw Audio}, + journal = {CoRR}, + volume = {abs/1609.03499}, + year = {2016}, + url = {http://arxiv.org/abs/1609.03499}, + archivePrefix = {arXiv}, + eprint = {1609.03499}, + timestamp = {Mon, 13 Aug 2018 16:49:15 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/OordDZSVGKSK16}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@article{FacebookGERENGBackTranslation, + author = {Rico Sennrich and Barry Haddow and Alexandra Birch}, + title = {Improving Neural Machine Translation Models with Monolingual Data}, + journal = {CoRR}, + volume = {abs/1511.06709}, + year = {2015}, + url = {http://arxiv.org/abs/1511.06709}, + archivePrefix = {arXiv}, + eprint = {1511.06709}, + timestamp = {Mon, 13 Aug 2018 16:47:05 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/SennrichHB15a}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@article{GlobalStyleTokens, + author = {Yuxuan Wang and Daisy Stanton and Yu Zhang and R. J. Skerry{-}Ryan and Eric Battenberg and Joel Shor and Ying Xiao and Fei Ren and Ye Jia and Rif A. Saurous}, + title = {Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis}, + journal = {CoRR}, + volume = {abs/1803.09017}, + year = {2018}, + url = {http://arxiv.org/abs/1803.09017}, + archivePrefix = {arXiv}, + eprint = {1803.09017}, + timestamp = {Mon, 13 Aug 2018 16:46:53 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/abs-1803-09017}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@article{IoffeS15BatchNorm, + author = {Sergey Ioffe and Christian Szegedy}, + title = {Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift}, + journal = {CoRR}, + volume = {abs/1502.03167}, + year = {2015}, + url = {http://arxiv.org/abs/1502.03167}, + archivePrefix = {arXiv}, + eprint = {1502.03167}, + timestamp = {Mon, 13 Aug 2018 16:47:06 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/IoffeS15}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@article{kingma, + author = {Diederik P. Kingma and + Jimmy Ba}, + title = {Adam: {A} Method for Stochastic Optimization}, + journal = {CoRR}, + volume = {abs/1412.6980}, + year = {2014}, + url = {http://arxiv.org/abs/1412.6980}, + archivePrefix = {arXiv}, + eprint = {1412.6980}, + timestamp = {Mon, 13 Aug 2018 01:00:00 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/KingmaB14}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@incollection{Salimans2016WeightNorm, + title = {Weight Normalization: A Simple Reparameterization to Accelerate Training of Deep Neural Networks}, + author = {Salimans, Tim and Kingma, Durk P}, + booktitle = {Advances in Neural Information Processing Systems 29}, + editor = {D. D. Lee and M. Sugiyama and U. V. Luxburg and I. Guyon and R. Garnett}, + pages = {901--909}, + year = {2016}, + publisher = {Curran Associates, Inc.}, + url = {http://papers.nips.cc/paper/6114-weight-normalization-a-simple-reparameterization-to-accelerate-training-of-deep-neural-networks.pdf} +} + +@article{wu2016google, + title={Google's neural machine translation system: Bridging the gap between human and machine translation}, + author={Wu, Yonghui and Schuster, Mike and Chen, Zhifeng and Le, Quoc V and Norouzi, Mohammad and Macherey, Zolfgang and Krikun, Maxim and Cao, Yuan and Gao, Qin and Macherey, Klaus and others}, + journal={arXiv preprint arXiv:1609.08144}, + year={2016} +} + +@inproceedings{opennmt, + author = {Guillaume Klein and Yoon Kim and Yuntian Deng and Jean Senellart and Alexander M. Rush}, + title = {OpenNMT: Open-Source Toolkit for Neural Machine Translation}, + booktitle = {Proc. ACL}, + year = {2017}, + url = {https://doi.org/10.18653/v1/P17-4012}, + doi = {10.18653/v1/P17-4012} +} + +@article{paszke2017automatic, + title={Automatic differentiation in PyTorch}, + author={Paszke, Adam and Gross, Sam and Chintala, Soumith and Chanan, Gregory and Yang, Edward and DeVito, Zachary and Lin, Zeming and Desmaison, Alban and Antiga, Luca and Lerer, Adam}, + year={2017} +} + +@article{yu2014introduction, + title={An introduction to computational networks and the computational network toolkit}, + author={Yu, Dong and Eversole, Adam and Seltzer, Mike and Yao, Kaisheng and Huang, Zhiheng and Guenter, Brian and Kuchaiev, Oleksii and Zhang, Yu and Seide, Frank and Wang, Huaming and others}, + journal={Microsoft Technical Report MSR-TR-2014--112}, + year={2014} +} + +@article{nvidia2017v100, + title={V100 GPU architecture. The world’s most advanced data center GPU. Version WP-08608-001\_v1. 1}, + author={NVIDIA, Tesla}, + journal={NVIDIA. Aug}, + pages={108}, + year={2017} +} + +@article{Ba2016LayerNorm, + author = {Jimmy Lei Ba and Jamie Ryan Kiros and Geoffrey E Hinton}, + title = {Layer normalization}, + journal = {CoRR}, + volume = {abs/1607.06450}, + year = {2016}, + url = {http://arxiv.org/abs/1607.06450}, + archivePrefix = {arXiv}, +} + +@inproceedings{Dauphin2017GLU, + author = {Dauphin, Yann N. and Fan, Angela and Auli, Michael and Grangier, David}, + title = {Language Modeling with Gated Convolutional Networks}, + booktitle = {Proceedings of the 34th International Conference on Machine Learning - Volume 70}, + series = {ICML'17}, + year = {2017}, + location = {Sydney, NSW, Australia}, + pages = {933--941}, + numpages = {9}, + url = {http://dl.acm.org/citation.cfm?id=3305381.3305478}, + acmid = {3305478}, + publisher = {JMLR.org}, +} + +@incollection{Oord2016PixelCNN, +title = {Conditional Image Generation with PixelCNN Decoders}, +author = {van den Oord, Aaron and Kalchbrenner, Nal and Espeholt, Lasse and kavukcuoglu, koray and Vinyals, Oriol and Graves, Alex}, +booktitle = {Advances in Neural Information Processing Systems 29}, +editor = {D. D. Lee and M. Sugiyama and U. V. Luxburg and I. Guyon and R. Garnett}, +pages = {4790--4798}, +year = {2016}, +publisher = {Curran Associates, Inc.}, +url = {http://papers.nips.cc/paper/6527-conditional-image-generation-with-pixelcnn-decoders.pdf} +} + +@article{he2015, + title={Deep residual learning for image recognition}, + author={K. He, and X. Zhang, and S. Ren, and J. Sun}, + journal={arXiv preprint arXiv:1512.03385}, + year={2015} +} + +@article{huang2016, + title={Densely Connected Convolutional Networks}, + author={Gao Huang, and Zhuang Liu, and Laurens van der Maaten, and Kilian Q. Weinberger}, + journal={arXiv preprint arXiv:1608.06993}, + year={2016} +} + +@inproceedings{heafield2011kenlm, + title={KenLM: Faster and smaller language model queries}, + author={Heafield, Kenneth}, + booktitle={Proceedings of the sixth workshop on statistical machine translation}, + pages={187--197}, + year={2011}, + organization={Association for Computational Linguistics} +} + +@article{dai2018transformer, + title={Transformer-XL: Language Modeling with Longer-Term Dependency}, + author={Dai, Zihang and Yang, Zhilin and Yang, Yiming and Cohen, William W and Carbonell, Jaime and Le, Quoc V and Salakhutdinov, Ruslan}, + year={2018}, + journal = {CoRR}, + volume = {abs/1901.02860}, + url = {http://arxiv.org/abs/1901.02860}, + archivePrefix = {arXiv}, + eprint = {1901.02860}, + timestamp = {Fri, 01 Feb 2019 13:39:59 +0100}, + biburl = {https://dblp.org/rec/bib/journals/corr/abs-1901-02860}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@inproceedings{Saon+2016, +author={George Saon and Tom Sercu and Steven Rennie and Hong-Kwang J. Kuo}, +title={The IBM 2016 English Conversational Telephone Speech Recognition System}, +year=2016, +booktitle={Interspeech 2016}, +doi={10.21437/Interspeech.2016-1460}, +url={http://dx.doi.org/10.21437/Interspeech.2016-1460}, +pages={7--11} +} + +@INPROCEEDINGS{Sercu-2016, +author={T. {Sercu} and C. {Puhrsch} and B. {Kingsbury} and Y. {LeCun}}, +booktitle={2016 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)}, +title={Very deep multilingual convolutional neural networks for LVCSR}, +year={2016}, +volume={}, +number={}, +pages={4955-4959}, +keywords={natural language processing;neural nets;speech recognition;very deep multilingual convolutional neural networks;LVCSR;CNN;large vocabulary continuous speech recognition systems;word error rate;Training;Context;Hidden Markov models;Neural networks;Computer architecture;Kernel;Training data;Convolutional Networks;Multilingual;Acoustic Modeling;Speech Recognition;Neural Networks}, +doi={10.1109/ICASSP.2016.7472620}, +ISSN={2379-190X}, +month={March},} + + +@inproceedings{Sercu+2016, +author={Tom Sercu and Vaibhava Goel}, +title={Advances in Very Deep Convolutional Neural Networks for LVCSR}, +year=2016, +booktitle={Interspeech 2016}, +doi={10.21437/Interspeech.2016-1033}, +url={http://dx.doi.org/10.21437/Interspeech.2016-1033}, +pages={3429--3433} +} + +@INPROCEEDINGS{Xiong-2018, +author={W. {Xiong} and L. {Wu} and F. {Alleva} and J. {Droppo} and X. {Huang} and A. {Stolcke}}, +booktitle={2018 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)}, +title={The Microsoft 2017 Conversational Speech Recognition System}, +year={2018}, +volume={}, +number={}, +pages={5934-5938}, +keywords={convolution;feedforward neural nets;natural language processing;speaker recognition;speech processing;language model rescoring step;senone level;switchboard domains;character-based LSTM language models;NIST 2000 switchboard test set;frame level;word-level voting;acoustic model posteriors;dialog session aware LSTM language models;CNN-BLSTM acoustic model;Microsoft 2017 conversational speech recognition system;Acoustics;Error analysis;Training;Speech recognition;Switches;Computational modeling;Context modeling;Conversational speech recognition;CNN;LACE;BLSTM;LSTM-LM;system combination;human parity}, +doi={10.1109/ICASSP.2018.8461870}, +ISSN={2379-190X}, +month={April},} + +@inproceedings{zeyer2018improved, + author={Albert Zeyer and Kazuki Irie and Ralf Schlüter and Hermann Ney}, + title={Improved Training of End-to-end Attention Models for Speech Recognition}, + year=2018, + booktitle={Proc. Interspeech 2018}, + pages={7--11}, + doi={10.21437/Interspeech.2018-1616}, + url={http://dx.doi.org/10.21437/Interspeech.2018-1616} +} + +@article{Wav2LetterV2, + author = {Vitaliy Liptchinsky and + Gabriel Synnaeve and + Ronan Collobert}, + title = {Letter-Based Speech Recognition with Gated ConvNets}, + journal = {CoRR}, + volume = {abs/1712.09444}, + year = {2017}, + url = {http://arxiv.org/abs/1712.09444}, + archivePrefix = {arXiv}, + eprint = {1712.09444}, + timestamp = {Mon, 13 Aug 2018 16:46:33 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/abs-1712-09444}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@article{zeghidour2018, + author = {Neil Zeghidour and + Qiantong Xu and + Vitaliy Liptchinsky and + Nicolas Usunier and + Gabriel Synnaeve and + Ronan Collobert}, + title = {Fully Convolutional Speech Recognition}, + journal = {CoRR}, + volume = {abs/1812.06864}, + year = {2018}, + url = {http://arxiv.org/abs/1812.06864}, + archivePrefix = {arXiv}, + eprint = {1812.06864}, + timestamp = {Tue, 01 Jan 2019 15:01:25 +0100}, + biburl = {https://dblp.org/rec/bib/journals/corr/abs-1812-06864}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@inproceedings{Hadian2018, + author={Hossein Hadian and Hossein Sameti and Daniel Povey and Sanjeev Khudanpur}, + title={End-to-end Speech Recognition Using Lattice-free MMI}, + year=2018, + booktitle={Proc. Interspeech 2018}, + pages={12--16}, + doi={10.21437/Interspeech.2018-1423}, + url={http://dx.doi.org/10.21437/Interspeech.2018-1423} +} + +@inproceedings{Tang2018, + author={Jian Tang and Yan Song and Lirong Dai and Ian McLoughlin}, + title={Acoustic Modeling with Densely Connected Residual Network for Multichannel Speech Recognition}, + year=2018, + booktitle={Proc. Interspeech 2018}, + pages={1783--1787}, + doi={10.21437/Interspeech.2018-1089}, + url={http://dx.doi.org/10.21437/Interspeech.2018-1089} +} + +@article{Kurata2017LanguageMW, + title={Language modeling with highway LSTM}, + author={Gakuto Kurata and Bhuvana Ramabhadran and George Saon and Abhinav Sethy}, + journal={2017 IEEE Automatic Speech Recognition and Understanding Workshop (ASRU)}, + year={2017}, + pages={244-251} +} + +@inproceedings{Saon2017, + author={George Saon and Gakuto Kurata and Tom Sercu and Kartik Audhkhasi and Samuel Thomas and Dimitrios Dimitriadis and Xiaodong Cui and Bhuvana Ramabhadran and Michael Picheny and Lynn-Li Lim and Bergul Roomi and Phil Hall}, + title={English Conversational Telephone Speech Recognition by Humans and Machines}, + year=2017, + booktitle={Proc. Interspeech 2017}, + pages={132--136}, + doi={10.21437/Interspeech.2017-405}, + url={http://dx.doi.org/10.21437/Interspeech.2017-405} +} + +@inproceedings{Povey+2016, +author={Daniel Povey and Vijayaditya Peddinti and Daniel Galvez and Pegah Ghahremani and Vimal Manohar and Xingyu Na and Yiming Wang and Sanjeev Khudanpur}, +title={Purely Sequence-Trained Neural Networks for ASR Based on Lattice-Free MMI}, +year=2016, +booktitle={Interspeech 2016}, +doi={10.21437/Interspeech.2016-595}, +url={http://dx.doi.org/10.21437/Interspeech.2016-595}, +pages={2751--2755} +} + +@article{Yang2018, + author = {Xuerui Yang and + Jiwei Li and + Xi Zhou}, + title = {A novel pyramidal-FSMN architecture with lattice-free {MMI} for speech + recognition}, + journal = {CoRR}, + volume = {abs/1810.11352}, + year = {2018}, + url = {http://arxiv.org/abs/1810.11352}, + archivePrefix = {arXiv}, + eprint = {1810.11352}, + timestamp = {Wed, 31 Oct 2018 14:24:29 +0100}, + biburl = {https://dblp.org/rec/bib/journals/corr/abs-1810-11352}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@article{liptchinsky2017based, + title={Letter-Based Speech Recognition with Gated ConvNets}, + author={Liptchinsky, Vitaliy and Synnaeve, Gabriel and Collobert, Ronan}, + journal={arXiv preprint arXiv:1712.09444}, + year={2017} +} + +@inproceedings{Weng2018, + author={Chao Weng and Jia Cui and Guangsen Wang and Jun Wang and Chengzhu Yu and Dan Su and Dong Yu}, + title={Improving Attention Based Sequence-to-Sequence Models for End-to-End English Conversational Speech Recognition}, + year=2018, + booktitle={Proc. Interspeech 2018}, + pages={761--765}, + doi={10.21437/Interspeech.2018-1030}, + url={http://dx.doi.org/10.21437/Interspeech.2018-1030} +} + +@INPROCEEDINGS{Battenberg2017, +author={E. {Battenberg} and J. {Chen} and R. {Child} and A. {Coates} and Y. G. Y. {Li} and H. {Liu} and S. {Satheesh} and A. {Sriram} and Z. {Zhu}}, +booktitle={2017 IEEE Automatic Speech Recognition and Understanding Workshop (ASRU)}, +title={Exploring neural transducers for end-to-end speech recognition}, +year={2017}, +volume={}, +number={}, +pages={206-213}, +keywords={recurrent neural nets;speech recognition;Hub500 benchmark;CTC models;speech recognition pipeline;RNN-Transducer models;language model;Seq2Seq models;end-to-end speech recognition;neural transducers;Decoding;Hidden Markov models;Transducers;Task analysis;Speech;Mathematical model;Neural networks}, +doi={10.1109/ASRU.2017.8268937}, +ISSN={}, +month={Dec}, +} + +@inproceedings{ +loshchilov2018, +title={Decoupled Weight Decay Regularization}, +author={Ilya Loshchilov and Frank Hutter}, +booktitle={International Conference on Learning Representations}, +year={2019}, +url={https://openreview.net/forum?id=Bkg6RiCqY7}, +} + +@article{zhang2017ndadam, + author = {Zijun Zhang and Lin Ma and Zongpeng Li and Chuan Wu}, + title = {Normalized Direction-preserving Adam}, + journal = {arXiv e-prints arXiv:1709.04546}, + year = {2017}, +} + +@article{park2019, + author = {{Park}, Daniel S. and {Chan}, William and {Zhang}, Yu and + {Chiu}, Chung-Cheng and {Zoph}, Barret and {Cubuk}, Ekin D. and + {Le}, Quoc V.}, + title = "{SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition}", + journal = {arXiv e-prints}, + year = "2019", + eid = {arXiv:1904.08779}, + eprint = {1904.08779}, +} + +@article{novograd2019, + author = {{Ginsburg}, Boris and {Castonguay}, Patrice and {Hrinchuk}, Oleksii and + {Kuchaiev}, Oleksii and {Lavrukhin}, Vitaly and {Leary}, Ryan and + {Li}, Jason and {Nguyen}, Huyen and {Cohen}, Jonathan M.}, + title = "{Stochastic Gradient Methods with Layer-wise Adaptive Moments for Training of Deep Networks}", + journal = {arXiv e-prints}, + year = "2019", + eid = {arXiv:1905.11286}, + eprint = {1905.11286}, +} + +@article{kriman2019quartznet, + title={Quartznet: {Deep} automatic speech recognition with 1d time-channel separable convolutions}, + author={Kriman, Samuel and Beliaev, Stanislav and Ginsburg, Boris and Huang, Jocelyn and Kuchaiev, Oleksii and Lavrukhin, Vitaly and Leary, Ryan and Li, Jason and Zhang, Yang}, + journal={arXiv preprint arXiv:1910.10261}, + year={2019} +} + +@misc{itu1988g711, + title={{ITU-T} {G.711} - {Pulse} code modulation ({PCM}) of voice frequencies}, + author={ITU-T Geneva Switzerland}, + year={1988}, +} + +@article{han2020contextnet, + title={ContextNet: Improving convolutional neural networks for automatic speech recognition with global context}, + author={Han, Wei and Zhang, Zhengdong and Zhang, Yu and Yu, Jiahui and Chiu, Chung-Cheng and Qin, James and Gulati, Anmol and Pang, Ruoming and Wu, Yonghui}, + journal={arXiv:2005.03191}, + year={2020} +} + +@inproceedings{hu2018squeeze, + title={Squeeze-and-excitation networks}, + author={Hu, Jie and Shen, Li and Sun, Gang}, + booktitle={ICVPR}, + year={2018} +} + +@article{koluguri2020speakernet, + title={SpeakerNet: 1D Depth-wise Separable Convolutional Network for Text-Independent Speaker Recognition and Verification}, + author={Koluguri, Nithin Rao and Li, Jason and Lavrukhin, Vitaly and Ginsburg, Boris}, + journal={arXiv preprint arXiv:2010.12653}, + year={2020} +} + +@article{gulati2020conformer, + title={Conformer: Convolution-augmented transformer for speech recognition}, + author={Gulati, Anmol and Qin, James and Chiu, Chung-Cheng and Parmar, Niki and Zhang, Yu and Yu, Jiahui and Han, Wei and Wang, Shibo and Zhang, Zhengdong and Wu, Yonghui and others}, + journal={arXiv preprint arXiv:2005.08100}, + year={2020} +} + +@article{koluguri2021titanet, + title={TitaNet: Neural Model for speaker representation with 1D Depth-wise separable convolutions and global context}, + author={Koluguri, Nithin Rao and Park, Taejin and Ginsburg, Boris}, + journal={arXiv preprint arXiv:2110.04410}, + year={2021} +} + +@article{Dawalatabad_2021, + title={ECAPA-TDNN Embeddings for Speaker Diarization}, + url={http://dx.doi.org/10.21437/Interspeech.2021-941}, + DOI={10.21437/interspeech.2021-941}, + journal={Interspeech 2021}, + publisher={ISCA}, + author={Dawalatabad, Nauman and Ravanelli, Mirco and Grondin, François and Thienpondt, Jenthe and Desplanques, Brecht and Na, Hwidong}, + year={2021}, + month={Aug} +} + +@inproceedings{he2019streaming, + title={Streaming end-to-end speech recognition for mobile devices}, + author={He, Yanzhang and Sainath, Tara N and Prabhavalkar, Rohit and McGraw, Ian and Alvarez, Raziel and Zhao, Ding and Rybach, David and Kannan, Anjuli and Wu, Yonghui and Pang, Ruoming and others}, + booktitle={ICASSP 2019-2019 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)}, + pages={6381--6385}, + year={2019}, + organization={IEEE} +} + +@misc{wav2vec2, + doi = {10.48550/ARXIV.2006.11477}, + url = {https://arxiv.org/abs/2006.11477}, + author = {Baevski, Alexei and Zhou, Henry and Mohamed, Abdelrahman and Auli, Michael}, + title = {wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations}, + publisher = {arXiv}, + year = {2020}, + copyright = {arXiv.org perpetual, non-exclusive license} +} + +@misc{w2v_bert, + doi = {10.48550/ARXIV.2108.06209}, + url = {https://arxiv.org/abs/2108.06209}, + author = {Chung, Yu-An and Zhang, Yu and Han, Wei and Chiu, Chung-Cheng and Qin, James and Pang, Ruoming and Wu, Yonghui}, + title = {W2v-BERT: Combining Contrastive Learning and Masked Language Modeling for Self-Supervised Speech Pre-Training}, + publisher = {arXiv}, + year = {2021}, + copyright = {arXiv.org perpetual, non-exclusive license} +} + +@misc{ssl_inter, + doi = {10.48550/ARXIV.2112.08778}, + url = {https://arxiv.org/abs/2112.08778}, + author = {Wang, Chengyi and Wu, Yu and Chen, Sanyuan and Liu, Shujie and Li, Jinyu and Qian, Yao and Yang, Zhenglu}, + title = {Self-Supervised Learning for speech recognition with Intermediate layer supervision}, + publisher = {arXiv}, + year = {2021}, + copyright = {arXiv.org perpetual, non-exclusive license} +} + +@misc{kim2022squeezeformer, + doi = {10.48550/ARXIV.2206.00888}, + url = {https://arxiv.org/abs/2206.00888}, + author = {Kim, Sehoon and Gholami, Amir and Shaw, Albert and Lee, Nicholas and Mangalam, Karttikeya and Malik, Jitendra and Mahoney, Michael W. and Keutzer, Kurt}, + keywords = {Audio and Speech Processing (eess.AS), Computation and Language (cs.CL), Sound (cs.SD), FOS: Electrical engineering, electronic engineering, information engineering, FOS: Electrical engineering, electronic engineering, information engineering, FOS: Computer and information sciences, FOS: Computer and information sciences}, + title = {Squeezeformer: An Efficient Transformer for Automatic Speech Recognition}, + publisher = {arXiv}, + year = {2022}, + copyright = {arXiv.org perpetual, non-exclusive license} +} + +@misc{park2022multi, + doi = {10.48550/ARXIV.2203.15974}, + url = {https://arxiv.org/abs/2203.15974}, + author = {Park, Tae Jin and Koluguri, Nithin Rao and Balam, Jagadeesh and Ginsburg, Boris}, + keywords = {Audio and Speech Processing (eess.AS), Computation and Language (cs.CL), FOS: Electrical engineering, electronic engineering, information engineering, FOS: Electrical engineering, electronic engineering, information engineering, FOS: Computer and information sciences, FOS: Computer and information sciences}, + title = {Multi-scale Speaker Diarization with Dynamic Scale Weighting}, + publisher = {arXiv}, + year = {2022}, + copyright = {Creative Commons Attribution 4.0 International} +} + +@inproceedings{vaswani2017aayn, + title={Attention is all you need}, + author={Vaswani, Ashish and Shazeer, Noam and Parmar, Niki and Uszkoreit, Jakob and Jones, Llion and Gomez, Aidan N and Kaiser, {\L}ukasz and Polosukhin, Illia}, + booktitle={Advances in Neural Information Processing Systems}, + pages={6000--6010}, + year={2017} +} + +@inproceedings{rekesh2023fastconformer, + title={Fast conformer with linearly scalable attention for efficient speech recognition}, + author={Rekesh, Dima and Koluguri, Nithin Rao and Kriman, Samuel and Majumdar, Somshubra and Noroozi, Vahid and Huang, He and Hrinchuk, Oleksii and Puvvada, Krishna and Kumar, Ankur and Balam, Jagadeesh and others}, + booktitle={2023 IEEE Automatic Speech Recognition and Understanding Workshop (ASRU)}, + pages={1--8}, + year={2023}, + organization={IEEE} +} + +@inproceedings{park2025sortformer, + title = {{Sortformer: A Novel Approach for Permutation-Resolved Speaker Supervision in Speech-to-Text Systems}}, + author = {Taejin Park and Ivan Medennikov and Kunal Dhawan and Weiqing Wang and He Huang and Nithin Rao Koluguri and Krishna C. Puvvada and Jagadeesh Balam and Boris Ginsburg}, + booktitle = {Proceedings of the Forty-second International Conference on Machine Learning (ICML)}, + year = {2025}, + month = {July}, + address = {Vienna, Austria}, + publisher = {PMLR}, + url = {https://openreview.net/forum?id=AyYjRvrbDx}, +} + +@inproceedings{medennikov25_interspeech, + title = {{Streaming Sortformer: Speaker Cache-Based Online Speaker Diarization with Arrival-Time Ordering}}, + author = {Ivan Medennikov and Taejin Park and Weiqing Wang and He Huang and Kunal Dhawan and Jinhan Wang and Jagadeesh Balam and Boris Ginsburg}, + year = {2025}, + booktitle = {{Interspeech 2025}}, + pages = {5238--5242}, + doi = {10.21437/Interspeech.2025-2244}, + issn = {2958-1796}, +} + +@inproceedings{wang25y_interspeech, + title = {{Speaker Targeting via Self-Speaker Adaptation for Multi-talker ASR}}, + author = {Weiqing Wang and Taejin Park and Ivan Medennikov and Jinhan Wang and Kunal Dhawan and He Huang and Nithin {Rao Koluguri} and Jagadeesh Balam and Boris Ginsburg}, + year = {2025}, + booktitle = {{Interspeech 2025}}, + pages = {5498--5502}, + doi = {10.21437/Interspeech.2025-2142}, + issn = {2958-1796}, +} + +@inproceedings{huang2025nest, + title={{NEST}: {S}elf-supervised fast conformer as all-purpose seasoning to speech processing tasks}, + author={Huang, He and Park, Taejin and Dhawan, Kunal and Medennikov, Ivan and Puvvada, Krishna C and Koluguri, Nithin Rao and Wang, Weiqing and Balam, Jagadeesh and Ginsburg, Boris}, + booktitle={ICASSP 2025-2025 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)}, + pages={1--5}, + year={2025}, + organization={IEEE} +} + diff --git a/docs/source/asr/asr_customization/legacy_language_modeling_and_customization.rst b/docs/source/asr/asr_customization/legacy_language_modeling_and_customization.rst new file mode 100644 index 0000000000000000000000000000000000000000..5a2265a397573b64ecaceb9e3c7fc35d9ffafd81 --- /dev/null +++ b/docs/source/asr/asr_customization/legacy_language_modeling_and_customization.rst @@ -0,0 +1,297 @@ +.. _ngram_modeling: + +**************************** +N-gram Language Model Fusion +**************************** + +In this approach, an N-gram LM is trained on text data, then it is used in fusion with beam search decoding to find the +best candidates. The beam search decoders in NeMo support language models trained with KenLM library ( +`https://github.com/kpu/kenlm `__). +The beam search decoders and KenLM library are not installed by default in NeMo. +You need to install them to be able to use beam search decoding and N-gram LM. +Please refer to `scripts/asr_language_modeling/ngram_lm/install_beamsearch_decoders.sh `__ +on how to install them. Alternatively, you can build Docker image +`scripts/installers/Dockerfile.ngramtools `__ with all the necessary dependencies. + +Please, refer to :ref:`train-ngram-lm` for more details on how to train an N-gram LM using KenLM library. + +NeMo supports both character-based and BPE-based models for N-gram LMs. An N-gram LM can be used with beam search +decoders on top of the ASR models to produce more accurate candidates. The beam search decoder would incorporate +the scores produced by the N-gram LM into its score calculations as the following: + +.. code-block:: + + final_score = acoustic_score + beam_alpha*lm_score + beam_beta*seq_length + +where acoustic_score is the score predicted by the acoustic encoder and lm_score is the one estimated by the LM. +The parameter 'beam_alpha' determines the weight given to the N-gram language model, while 'beam_beta' is a penalty term that accounts for sequence length in the scores. A larger 'beam_alpha' places more emphasis on the language model and less on the acoustic model. Negative values for 'beam_beta' penalize longer sequences, encouraging the decoder to prefer shorter predictions. Conversely, positive values for 'beam_beta' favor longer candidates. + +Evaluate by Beam Search Decoding and N-gram LM +============================================== + +NeMo's beam search decoders are capable of using the KenLM's N-gram models to find the best candidates. +The script to evaluate an ASR model with beam search decoding and N-gram models can be found at +`scripts/asr_language_modeling/ngram_lm/eval_beamsearch_ngram_ctc.py `__. + +This script has a large number of possible argument overrides; therefore, it is recommended that you use ``python eval_beamsearch_ngram_ctc.py --help`` to see the full list of arguments. + +You can evaluate an ASR model using the following: + +.. code-block:: + + python eval_beamsearch_ngram_ctc.py nemo_model_file= \ + input_manifest= \ + beam_width=[] \ + beam_alpha=[] \ + beam_beta=[] \ + preds_output_folder= \ + probs_cache_file=null \ + decoding_mode=beamsearch_ngram \ + decoding_strategy="" + +It can evaluate a model in the following three modes by setting the argument ``--decoding_mode``: + +* greedy: Just greedy decoding is done and no beam search decoding is performed. +* beamsearch: The beam search decoding is done, but without using the N-gram language model. Final results are equivalent to setting the weight of LM (beam_beta) to zero. +* beamsearch_ngram: The beam search decoding is done with N-gram LM. + +In ``beamsearch`` mode, the evaluation is performed using beam search decoding without any language model. The performance is reported in terms of Word Error Rate (WER) and Character Error Rate (CER). Moreover, when the best candidate is selected among the candidates, it is also reported as the best WER/CER. This can serve as an indicator of the quality of the predicted candidates. + + +The script initially loads the ASR model and predicts the outputs of the model's encoder as log probabilities. This part is computed in batches on a device specified by --device, which can be either a CPU (`--device=cpu`) or a single GPU (`--device=cuda:0`). +The batch size for this part is specified by ``--acoustic_batch_size``. Using the largest feasible batch size can speed up the calculation of log probabilities. Additionally, you can use `--use_amp` to accelerate the calculation and allow for larger --acoustic_batch_size values. +Currently, multi-GPU support is not available for calculating log probabilities. However, using ``--probs_cache_file`` can help. This option stores the log probabilities produced by the model's encoder in a pickle file, allowing you to skip the first step in future runs. + +The following is the list of the important arguments for the evaluation script: + ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| **Argument** | **Type** | **Default** | **Description** | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| nemo_model_file | str | Required | The path of the `.nemo` file of the ASR model to extract the tokenizer. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| input_manifest | str | Required | Path to the training file, it can be a text file or JSON manifest. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| kenlm_model_file | str | Required | The path to store the KenLM binary model file. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| preds_output_folder | str | None | The path to an optional folder to store the predictions. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| probs_cache_file | str | None | The cache file for storing the outputs of the model. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| acoustic_batch_size | int | 16 | The batch size to calculate log probabilities. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| use_amp | bool | False | Whether to use AMP if available to calculate log probabilities. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| device | str | cuda | The device to load the model onto to calculate log probabilities. | +| | | | It can `cpu`, `cuda`, `cuda:0`, `cuda:1`, ... | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| decoding_mode | str | beamsearch_ngram | The decoding scheme to be used for evaluation. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| beam_width | float | Required | List of the width or list of the widths of the beam search decoding. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| beam_alpha | float | Required | List of the alpha parameter for the beam search decoding. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| beam_beta | float | Required | List of the beta parameter for the beam search decoding. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| beam_batch_size | int | 128 | The batch size to be used for beam search decoding. | +| | | | Larger batch size can be a little faster, but uses larger memory. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| decoding_strategy | str | beam | String argument for type of decoding strategy for the model. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| decoding | Dict | BeamCTC | Subdict of beam search configs. Values found via | +| | Config | InferConfig | python eval_beamsearch_ngram_ctc.py --help | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| text_processing.do_lowercase | bool | ``False`` | Whether to make the training text all lower case. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| text_processing.punctuation_marks | str | ``""`` | String with punctuation marks to process. Example: ".\,?" | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| text_processing.rm_punctuation | bool | ``False`` | Whether to remove punctuation marks from text. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ +| text_processing.separate_punctuation | bool | ``True`` | Whether to separate punctuation with the previous word by space. | ++--------------------------------------+----------+------------------+-------------------------------------------------------------------------+ + +The width of the beam search (``--beam_width``) specifies the number of top candidates or predictions the beam search decoder will consider. Larger beam widths result in more accurate but slower predictions. + +.. note:: + + The ``eval_beamsearch_ngram_ctc.py`` script contains the entire subconfig used for CTC Beam Decoding. + Therefore it is possible to forward arguments for various beam search libraries such as ``flashlight`` + and ``pyctcdecode`` via the ``decoding`` subconfig. + +To learn more about evaluating the ASR models with N-gram LM, refer to the tutorial here: Offline ASR Inference with Beam Search and External Language Model Rescoring +`Offline ASR Inference with Beam Search and External Language Model Rescoring `_ + +Beam Search Engines +------------------- + +NeMo ASR CTC supports multiple beam search engines for decoding. The default engine is beam, which is the OpenSeq2Seq decoding library. + +OpenSeq2Seq (``beam``) +~~~~~~~~~~~~~~~~~~~~~~ + +CPU-based beam search engine that is quite efficient and supports char and subword models. It requires a character/subword +KenLM model to be provided. + +The config for this decoding library is described above. + +Flashlight (``flashlight``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Flashlight is a C++ library for ASR decoding provided at `https://github.com/flashlight/flashlight `_. It is a CPU- and CUDA-based beam search engine that is quite efficient and supports char and subword models. It requires an ARPA KenLM file. + +It supports several advanced features, such as lexicon-based decoding, lexicon-free decoding, beam pruning threshold, and more. + +.. code-block:: python + + @dataclass + class FlashlightConfig: + lexicon_path: Optional[str] = None + boost_path: Optional[str] = None + beam_size_token: int = 16 + beam_threshold: float = 20.0 + unk_weight: float = -math.inf + sil_weight: float = 0.0 + +.. code-block:: + + # Lexicon-based decoding + python eval_beamsearch_ngram_ctc.py ... \ + decoding_strategy="flashlight" \ + decoding.beam.flashlight_cfg.lexicon_path='/path/to/lexicon.lexicon' \ + decoding.beam.flashlight_cfg.beam_size_token = 32 \ + decoding.beam.flashlight_cfg.beam_threshold = 25.0 + + # Lexicon-free decoding + python eval_beamsearch_ngram_ctc.py ... \ + decoding_strategy="flashlight" \ + decoding.beam.flashlight_cfg.beam_size_token = 32 \ + decoding.beam.flashlight_cfg.beam_threshold = 25.0 + +PyCTCDecode (``pyctcdecode``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +PyCTCDecode is a Python library for ASR decoding provided at `https://github.com/kensho-technologies/pyctcdecode `_. It is a CPU-based beam search engine that is somewhat efficient for a pure Python library, and supports char and subword models. It requires a character/subword KenLM ARPA / BINARY model to be provided. + + +It has advanced features, such as word boosting, which can be useful for transcript customization. + +.. code-block:: python + + @dataclass + class PyCTCDecodeConfig: + beam_prune_logp: float = -10.0 + token_min_logp: float = -5.0 + prune_history: bool = False + hotwords: Optional[List[str]] = None + hotword_weight: float = 10.0 + +.. code-block:: + + # PyCTCDecoding + python eval_beamsearch_ngram_ctc.py ... \ + decoding_strategy="pyctcdecode" \ + decoding.beam.pyctcdecode_cfg.beam_prune_logp = -10. \ + decoding.beam.pyctcdecode_cfg.token_min_logp = -5. \ + decoding.beam.pyctcdecode_cfg.hotwords=[] \ + decoding.beam.pyctcdecode_cfg.hotword_weight=10.0 + + +Hyperparameter Grid Search +-------------------------- + +Beam search decoding with N-gram LM has three main hyperparameters: `beam_width`, `beam_alpha`, and `beam_beta`. +The accuracy of the model is dependent on the values of these parameters, specifically, beam_alpha and beam_beta. To perform grid search, you can specify a single value or a list of values for each of these parameters. In this case, it would perform the beam search decoding on all combinations of the three hyperparameters. +For example, the following set of parameters would result in 212=4 beam search decodings: + +.. code-block:: + + python eval_beamsearch_ngram_ctc.py ... \ + beam_width=[64,128] \ + beam_alpha=[1.0] \ + beam_beta=[1.0,0.5] + + +Beam Search ngram Decoding for Transducer Models (RNNT and HAT) +=============================================================== + +You can also find a similar script to evaluate an RNNT/HAT model with beam search decoding and N-gram models at: +`scripts/asr_language_modeling/ngram_lm/eval_beamsearch_ngram_transducer.py `_ + +.. code-block:: + + python eval_beamsearch_ngram_transducer.py nemo_model_file= \ + input_manifest= \ + beam_width=[] \ + beam_alpha=[] \ + preds_output_folder= \ + probs_cache_file=null \ + decoding_strategy= + maes_prefix_alpha=[] \ + maes_expansion_gamma=[] \ + hat_subtract_ilm= \ + hat_ilm_weight=[] \ + + +.. _wfst-ctc-decoding: + +WFST CTC decoding +================= +Weighted Finite-State Transducers (WFST) are finite-state machines with input and output symbols on each transition and some weight element of a semiring. WFSTs can act as N-gram LMs in a special type of LM-forced beam search, called WFST decoding. + +.. note:: + + More precisely, WFST decoding is more of a greedy N-depth search with LM. + Thus, it is asymptotically worse than conventional beam search decoding algorithms, but faster. + +**WARNING** +At the moment, NeMo supports WFST decoding only for CTC models and word-based LMs. + +To run WFST decoding in NeMo, one needs to provide a NeMo ASR model and either an ARPA LM or a WFST LM (advanced). An ARPA LM can be built from source text with KenLM as follows: ``/lmplz -o --arpa --prune ``. + +The script to evaluate an ASR model with WFST decoding and N-gram models can be found at +`scripts/asr_language_modeling/ngram_lm/eval_wfst_decoding_ctc.py +`__. + +This script has a large number of possible argument overrides, therefore it is advised to use ``python eval_wfst_decoding_ctc.py --help`` to see the full list of arguments. + +You may evaluate an ASR model as the following: + +.. code-block:: + + python eval_wfst_decoding_ctc.py nemo_model_file= \ + input_manifest= \ + arpa_model_file= \ + decoding_wfst_file= \ + beam_width=[] \ + lm_weight=[] \ + open_vocabulary_decoding= \ + decoding_mode= \ + decoding_search_type= \ + preds_output_folder= \ + probs_cache_file=null + +.. note:: + + Since WFST decoding is LM-forced (the search goes over the WIDEST graph), only word sequences accepted by the WFST can appear in the decoding results. + To circumvent this restriction, one can pass ``open_vocabulary_decoding=true`` (experimental feature). + + +Quick start example +------------------- + +.. code-block:: + + wget -O - https://www.openslr.org/resources/11/3-gram.pruned.1e-7.arpa.gz | \ + gunzip -c | tr '[:upper:]' '[:lower:]' > 3-gram.pruned.1e-7.arpa && \ + python eval_wfst_decoding_ctc.py nemo_model_file="stt_en_conformer_ctc_small_ls" \ + input_manifest="/Librispeech/test_other.json" \ + arpa_model_file="3-gram.pruned.1e-7.arpa" \ + decoding_wfst_file="3-gram.pruned.1e-7.fst" \ + beam_width=[8] \ + lm_weight=[0.5,0.6,0.7,0.8,0.9] + +.. note:: + + Building a decoding WFST is a long process, so it is better to provide a ``decoding_wfst_file`` path even if you don't have it. + This way, the decoding WFST will be buffered to the specified file path and there will be no need to re-build it on the next run. diff --git a/docs/source/asr/asr_customization/neural_rescoring.rst b/docs/source/asr/asr_customization/neural_rescoring.rst new file mode 100644 index 0000000000000000000000000000000000000000..b0c1899ed08999ad66e5e62202067656f262284d --- /dev/null +++ b/docs/source/asr/asr_customization/neural_rescoring.rst @@ -0,0 +1,105 @@ +.. _neural_rescoring: + +**************** +Neural Rescoring +**************** + +When using the neural rescoring approach, a neural network is used to score candidates. A candidate is the text transcript predicted by the ASR model's decoder. The top K candidates produced by beam search decoding (with a beam width of K) are given to a neural language model for ranking. The language model assigns a score to each candidate, which is usually combined with the scores from beam search decoding to produce the final scores and rankings. + +Train Neural Rescorer +===================== + +An example script to train such a language model with Transformer can be found at `examples/nlp/language_modeling/transformer_lm.py `__. +It trains a ``TransformerLMModel`` which can be used as a neural rescorer for an ASR system. For more information on language models training, see LLM/NLP documentation. + + +You can also use a pretrained language model from the Hugging Face library, such as Transformer-XL and GPT, instead of training your model. +Models like BERT and RoBERTa are not supported by this script because they are trained as Masked Language Models. As a result, they are not efficient or effective for scoring sentences out of the box. + + +Evaluation +========== + +Given a trained TransformerLMModel `.nemo` file or a pretrained HF model, the script available at +`scripts/asr_language_modeling/neural_rescorer/eval_neural_rescorer.py `__ +can be used to re-score beams obtained with ASR model. You need the `.tsv` file containing the candidates produced +by the acoustic model and the beam search decoding to use this script. The candidates can be the result of just the beam +search decoding or the result of fusion with an N-gram LM. You can generate this file by specifying `--preds_output_folder` for +`scripts/asr_language_modeling/ngram_lm/eval_beamsearch_ngram_ctc.py `__. + +The neural rescorer would rescore the beams/candidates by using two parameters of `rescorer_alpha` and `rescorer_beta`, as follows: + +.. code-block:: + + final_score = beam_search_score + rescorer_alpha*neural_rescorer_score + rescorer_beta*seq_length + +The parameter `rescorer_alpha` specifies the importance placed on the neural rescorer model, while `rescorer_beta` is a penalty term that accounts for sequence length in the scores. These parameters have similar effects to `beam_alpha` and `beam_beta` in the beam search decoder and N-gram language model. + +Use the following steps to evaluate a neural LM: + +#. Obtain `.tsv` file with beams and their corresponding scores. Scores can be from a regular beam search decoder or + in fusion with an N-gram LM scores. For a given beam size `beam_size` and a number of examples + for evaluation `num_eval_examples`, it should contain (`num_eval_examples` x `beam_size`) lines of + form `beam_candidate_text \t score`. This file can be generated by `scripts/asr_language_modeling/ngram_lm/eval_beamsearch_ngram_ctc.py `__ + +#. Rescore the candidates by `scripts/asr_language_modeling/neural_rescorer/eval_neural_rescorer.py `__. + +.. code-block:: + + python eval_neural_rescorer.py + --lm_model=[path to .nemo file of the LM or the name of a HF pretrained model] + --beams_file=[path to beams .tsv file] + --beam_size=[size of the beams] + --eval_manifest=[path to eval manifest .json file] + --batch_size=[batch size used for inference on the LM model] + --alpha=[the value for the parameter rescorer_alpha] + --beta=[the value for the parameter rescorer_beta] + --scores_output_file=[the optional path to store the rescored candidates] + +The candidates, along with their new scores, are stored at the file specified by `--scores_output_file`. + +The following is the list of the arguments for the evaluation script: + ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| **Argument** |**Type**| **Default** | **Description** | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| lm_model | str | Required | The path of the '.nemo' file of an ASR model, or the name of a | +| | | | Hugging Face pretrained model like 'transfo-xl-wt103' or 'gpt2'. | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| eval_manifest | str | Required | Path to the evaluation manifest file (.json manifest file). | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| beams_file | str | Required | Path to beams file (.tsv) containing the candidates and their scores. | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| beam_size | int | Required | The width of the beams (number of candidates) generated by the decoder. | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| alpha | float | None | The value for parameter rescorer_alpha | +| | | | Not passing value would enable linear search for rescorer_alpha. | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| beta | float | None | The value for parameter rescorer_beta | +| | | | Not passing value would enable linear search for rescorer_beta. | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| batch_size | int | 16 | The batch size used to calculate the scores. | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| max_seq_length | int | 512 | Maximum sequence length (in tokens) for the input. | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| scores_output_file | str | None | The optional file to store the rescored beams. | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| use_amp | bool | ``False`` | Whether to use AMP if available calculate the scores. | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ +| device | str | cuda | The device to load LM model onto to calculate the scores | +| | | | It can be 'cpu', 'cuda', 'cuda:0', 'cuda:1', ... | ++---------------------+--------+------------------+-------------------------------------------------------------------------+ + + +Hyperparameter Linear Search +---------------------------- + +The hyperparameter linear search script also supports linear search for parameters `alpha` and `beta`. If any of the two is not +provided, a linear search is performed to find the best value for that parameter. When linear search is used, initially +`beta` is set to zero and the best value for `alpha` is found, then `alpha` is fixed with +that value and another linear search is done to find the best value for `beta`. +If any of the of these two parameters is already specified, then search for that one is skipped. After each search for a +parameter, the plot of WER% for different values of the parameter is also shown. + +It is recommended to first use the linear search for both parameters on a validation set by not providing any values for `--alpha` and `--beta`. +Then check the WER curves and decide on the best values for each parameter. Finally, evaluate the best values on the test set. diff --git a/docs/source/asr/asr_customization/ngpulm_language_modeling_and_customization.rst b/docs/source/asr/asr_customization/ngpulm_language_modeling_and_customization.rst new file mode 100644 index 0000000000000000000000000000000000000000..fb8c22b5cee571dd66eb80747480afb005413f33 --- /dev/null +++ b/docs/source/asr/asr_customization/ngpulm_language_modeling_and_customization.rst @@ -0,0 +1,346 @@ +.. _ngpulm_ngram_modeling: + +*************************************************************** +NGPU-LM (GPU-based N-gram Language Model) Language Model Fusion +*************************************************************** + +ASR systems can achieve significantly improved accuracy by leveraging **external language model (LM) shallow fusion** during the decoding process. +This technique integrates knowledge from an external LM without requiring the ASR model itself to be retrained. + +**How Shallow Fusion Works:** + +During shallow fusion, the output probabilities generated by the ASR model are combined with those from a separate, external language model. +The final transcription is then determined by selecting the word sequence that yields the highest combined score. +These external LMs are typically trained on vast text datasets, allowing them to capture the statistical patterns, syntactic structures, and contextual dependencies of language. +This enables them to predict more plausible word sequences, thereby correcting potential errors from the ASR model. + +**Domain Adaptation Benefits:** + +Shallow fusion is particularly valuable for **adapting ASR systems to new or specialized domains**. +By training the external LM on domain-specific text-such as medical, legal, or technical documents-it learns the vocabulary of that field. +This specialized knowledge guides the ASR decoding process towards more accurate and contextually relevant transcriptions. + +Traditionally, shallow fusion has been performed during **beam search decoding**, a method that explores multiple promising hypotheses to find the most likely transcription. + + +NGPU-LM +======= + +A widely used library for training traditional n-gram language models is KenLM. +While KenLM (https://github.com/kpu/kenlm) is known for its efficient CPU-based implementation, its reliance on the CPU can limit performance in high-throughput scenarios, especially when dealing with large-scale data. + +NGPU-LM on contrast is a GPU-accelerated implementation of a statistical n-gram language model. +It uses a **universal trie-based data structure**, which enables fast, batched queries. For full details, please refer to the paper [ngpulm]_. + +This enables shallow fusion during **greedy decoding**, creating a middle ground between standard greedy decoding and full beam search with a language model. +It preserves the speed and simplicity of greedy decoding while regaining much of the accuracy typically achieved with beam search with external LM fusion. +While not as accurate as full beam search, greedy decoding with NGPU-LM fusion offers a compelling balance between speed and accuracy. + +NeMo provides efficient, fully GPU-based beam search implementations for all major ASR model types, +allowing **beam decoding to operate with real-time factors (RTFx) close to those of greedy decoding**. +At a batch size of 32, the RTFx difference between beam and greedy decoding is only about 20%. +These implementations incorporate NGPU-LM, enabling fast, fully GPU-based decoding and customization. +This enables users to customize decoding while maintaining reasonable speed, even in beam search mode. +For full details, please refer to the [beamsearch]_. + +NGPU-LM fusion is supported for BPE-based ASR models (CTC, RNNT, TDT, AED) during both greedy and beam decoding. + +Train NGPU-LM +============= + +NGPU-LM is built using `.ARPA` files generated by the KenLM library. You can train an n-gram LM using the following script: +`train_kenlm.py `__. + +The generated `.ARPA` files can be directly used for GPU-based decoding. +However, for faster performance, it is recommended to convert the model to the `.nemo` format by setting the ``save_nemo`` flag to ``true``. + +.. code-block:: + + python train_kenlm.py nemo_model_file= \ + train_paths= \ + kenlm_bin_path= \ + kenlm_model_file= \ + ngram_length= \ + preserve_arpa=true \ + save_nemo=True + +For a complete list of arguments and usage details, refer to the :ref:`train-ngram-lm`. + + +.. note:: + + It is recommended that you use 6 as the order of the N-gram model for BPE-based models. Higher orders may require re-compiling KenLM to support them. + +.. _ctc-decoding-with-ngpulm: + +Decoding with NGPU-LM +===================== + +To run inference with NGPU-LM fusion, the ``ngram_lm_model`` and ``ngram_lm_alpha`` fields must be specified in the decoding configuration. + +.. note:: + + For CTC, RNNT, and TDT models, these fields should be set within the respective ``greedy`` or ``beam`` sub-configurations. + For AED models running in greedy mode, set the beam size to 1 and specify these fields under the ``beam`` sub-configuration. + +Examples for different model types are provided below. + + + +CTC Decoding with NGPU-LM +------------------------- + +**Greedy Search:** + +You can run NGPU-LM shallow fusion during greedy CTC decoding using the following command: + +.. code-block:: bash + + python examples/asr/speech_to_text_eval.py \ + pretrained_name=nvidia/parakeet-ctc-1.1b \ + amp=false \ + amp_dtype=bfloat16 \ + matmul_precision=high \ + compute_dtype=bfloat16 \ + presort_manifest=true \ + cuda=0 \ + batch_size=32 \ + dataset_manifest= \ + ctc_decoding.greedy.ngram_lm_model= \ + ctc_decoding.greedy.ngram_lm_alpha=0.2 \ + ctc_decoding.greedy.allow_cuda_graphs=True \ + ctc_decoding.strategy="greedy_batch" + +**Beam Search:** + +During CTC beam search, each hypothesis is scored using the following formula: + +.. code-block:: + + final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length + +where: + - ``acoustic_score`` is the score predicted by the ASR. + - ``lm_score`` is the score predicted by the NGPU-LM LM. + - ``ngram_lm_alpha`` is the weight given to the language model. + - ``beam_beta`` is a penalty term that accounts for sequence length in the scores. + +For running fully batched GPU-based CTC decoding with NGPU-LM, you can use the following command: + +The following is the list of the adjustable arguments of batched CTC decoding algorithm ``beam_batch``: + ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| **Argument** | **Type** | **Default** | **Description** | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| ngram_lm_alpha | float | Required | Weight factor applied to the language model scores. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| beam_size | int | 4 | Beam size. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| beam_beta | float | 1 | Penalty applied to word insertions to control the trade-off between insertion and deletion errors during beam search decoding. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| beam_threshold | float | 20 | Threshold used to prune candidate hypotheses by comparing their scores to the best hypothesis. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ + +.. code-block:: bash + + python examples/asr/speech_to_text_eval.py \ + pretrained_name=nvidia/parakeet-ctc-1.1b \ + amp=false \ + amp_dtype=bfloat16 \ + matmul_precision=high \ + compute_dtype=bfloat16 \ + presort_manifest=true \ + cuda=0 \ + batch_size=32 \ + dataset_manifest= \ + ctc_decoding.beam.ngram_lm_model= \ + ctc_decoding.beam.ngram_lm_alpha=0.2 \ + ctc_decoding.beam.beam_size=12 \ + ctc_decoding.beam.beam_beta=1.0 \ + ctc_decoding.strategy="beam_batch" \ + ctc_decoding.beam.allow_cuda_graphs=True + + +RNN-T/TDT decoding with NGPU-LM +------------------------------- + +**Greedy Search:** + +You can run NGPU-LM shallow fusion during greedy RNN-T / TDT decoding using the following command: + +.. code-block:: bash + + python examples/asr/speech_to_text_eval.py \ + pretrained_name=nvidia/parakeet-rnnt-1.1b \ + amp=false \ + amp_dtype=bfloat16 \ + matmul_precision=high \ + compute_dtype=bfloat16 \ + presort_manifest=true \ + cuda=0 \ + batch_size=32 \ + dataset_manifest= \ + rnnt_decoding.greedy.ngram_lm_model= \ + rnnt_decoding.greedy.ngram_lm_alpha=0.2 \ + rnnt_decoding.greedy.allow_cuda_graphs=True \ + rnnt_decoding.strategy="greedy_batch" + +.. note:: + + To run the inference with TDT model, you need to provide pretrained TDT model in ``pretrained_name`` field (for example ``nvidia/parakeet-tdt_ctc-1.1b`` ). + + +**Beam Search:** + +During RNN-T / TDT beam search, each hypothesis is scored using the following formula: + +.. code-block:: + + final_score = acoustic_score + ngram_lm_alpha * lm_score + +where: + - ``acoustic_score`` is the score predicted by the ASR. + - ``lm_score`` is the score predicted by the NGPU-LM LM. + - ``ngram_lm_alpha`` is the weight given to the language model. + +Final hypotheses is chosen based on the normalized score ``final_score / seq_length``. + + +*Blank Scoring in Transducer Models* + +Transducer models include a blank symbol (``∅``) for frame transitions, while LMs do not model blanks. +During shallow fusion, the LM is typically applied only to non-blank tokens: + +.. math:: + + \ln p_{\text{tot}}[k] = + \begin{cases} + \ln p[k] + \lambda \ln p_{\text{LM}}[k], & k \in V \\ + \ln p[\emptyset], & k = \emptyset + \end{cases} + +This can lead to excessive blank predictions at higher LM weights, increasing deletion errors. +NeMo supports a blank-aware scoring method that adjusts LM contributions to better balance predictions: + +.. math:: + + \ln p_{\text{tot}}[k] = + \begin{cases} + \ln p[k] + \lambda \ln((1 - p[\emptyset]) \cdot p_{\text{LM}}[k]), & k \in V \\ + (1 + \lambda) \ln p[\emptyset], & k = \emptyset + \end{cases} + +*Early vs. Late Pruning* + +In shallow fusion, LM and ASR scores can be combined at different stages: + +- **Early pruning:** ASR selects top hypotheses, then LM rescoring is applied. Efficient for small beams. +- **Late pruning:** ASR and LM scores are combined before pruning. More accurate but requires full-vocab LM queries. + +For Transducer models, late pruning with the blank-aware scoring method generally yields better performance than the standard approach. + +*Beam Search Strategies:* + +In NeMo fully batched implementation of following strategies are supported: + +- **malsd_batch:** fully batched implemention of modified Alignment-Length Synchronous Decoding [alsd]_, supporting both RNNT and TDT models. +- **maes_batch:** fully batched implemention of modified Adaptive Expansion Search [aes]_, supporting for only RNNT models. CudaGraphs are not supported. + +The following is the list of the adjustable arguments of batched CTC decoding algorithm ``beam_batch``: + ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ +| **Argument** | **Type** | **Strategy** | **Default** | **Description** | ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ +| ngram_lm_alpha | float | malsd_batch, maes_batch | Required | Weight factor applied to the language model scores. | ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ +| beam_size | int | malsd_batch, maes_batch | 4 | Beam size. | ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ +| pruning_mode | str | malsd_batch, maes_batch | late | Mode for hypotheses pruning. Can be ``early`` or ``late``. | ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ +| blank_lm_score_mode | str | malsd_batch, maes_batch | lm_weighted_full | Mode for blank symbol scoring. Can be ``no_score`` or ``lm_weighted_full`` | ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ +| max_symbols_per_step | int | malsd_batch | 10 | Max symbols to emit on each step to avoid infinite looping. | ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ +| maes_num_step | int | maes_batch | 2 | Number of adaptive steps to take. | ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ +| maes_expansion_beta | float | maes_batch | 1.0 | Maximum number of prefix expansions allowed, in addition to the beam size. | ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ +| maes_expansion_gamma | float | maes_batch | 2.3 | Threshold used to prune candidate hypotheses by comparing their scores to the best hypothesis. | ++-----------------------+-----------+-------------------------+------------------+--------------------------------------------------------------------------------------------------------------------------------+ + +You can run NGPU-LM shallow fusion during beam RNN-T / TDT decoding using the following command: + + +.. code-block:: bash + + python examples/asr/speech_to_text_eval.py \ + pretrained_name=nvidia/parakeet-rnnt-1.1b \ + amp=false \ + amp_dtype=bfloat16 \ + matmul_precision=high \ + compute_dtype=bfloat16 \ + presort_manifest=true \ + cuda=0 \ + batch_size=32 \ + dataset_manifest= \ + rnnt_decoding.beam.ngram_lm_model= \ + rnnt_decoding.beam.ngram_lm_alpha=0.2 \ + rnnt_decoding.beam.beam_size=12 \ + rnnt_decoding.beam.pruning_mode="late" \ + rnnt_decoding.beam.blank_lm_score_mode="lm_weighted_full" \ + rnnt_decoding.beam.allow_cuda_graphs=True \ + rnnt_decoding.strategy="malsd_batch" + +.. note:: + + To run the inference with TDT model, you need to provide pretrained TDT model in ``pretrained_name`` field (for example ``nvidia/parakeet-tdt_ctc-1.1b`` ). + +AED Decoding with NGPU-LM +------------------------- + +**Beam Search:** + +You can run NGPU-LM shallow fusion during greedy CTC decoding using the following command: + +.. code-block:: bash + + python examples/asr/speech_to_text_eval.py \ + pretrained_name="nvidia/canary-1b" \ + amp=false \ + amp_dtype=bfloat16 \ + matmul_precision=high \ + compute_dtype=bfloat16 \ + presort_manifest=true \ + cuda=0 \ + batch_size=32 \ + dataset_manifest= \ + multitask_decoding.beam.beam_size=4 \ + multitask_decoding.beam.ngram_lm_model= \ + multitask_decoding.beam.ngram_lm_alpha=0.2 \ + multitask_decoding.strategy="beam" + +.. note:: + + For greedy decoding with NGPU-LM, use beam search with beam_size=1. + + +References +========== + +.. [ngpulm] V. Bataev, A. Andrusenko, L. Grigoryan, A. Laptev, V. Lavrukhin, and B. Ginsburg. + *NGPU-LM: GPU-Accelerated N-Gram Language Model for Context-Biasing in Greedy ASR Decoding*. + arXiv:2505.22857, 2025. Available at: https://arxiv.org/abs/2505.22857 + +.. [beamsearch] L. Grigoryan, V. Bataev, A. Andrusenko, H. Xu, V. Lavrukhin, and B. Ginsburg. + *Pushing the Limits of Beam Search Decoding for Transducer-based ASR Models*. + arXiv:2506.00185, 2025. Available at: https://arxiv.org/abs/2506.00185 + +.. [alsd] G. Saon, Z. Tüske, and K. Audhkhasi. + *Alignment-Length Synchronous Decoding for RNN Transducer*. + In: ICASSP 2020 – IEEE International Conference on Acoustics, Speech and Signal Processing, pp. 7804–7808, 2020. + doi: https://doi.org/10.1109/ICASSP40776.2020.9053040 + +.. [aes] J. Kim, Y. Lee, and E. Kim. + *Accelerating RNN Transducer Inference via Adaptive Expansion Search*. + IEEE Signal Processing Letters, vol. 27, pp. 2019–2023, 2020. + doi: https://doi.org/10.1109/LSP.2020.3036335 diff --git a/docs/source/asr/asr_customization/ngram_utils.rst b/docs/source/asr/asr_customization/ngram_utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..caca1671ac1f6ead4bce18fcad6cf1e6e6c49187 --- /dev/null +++ b/docs/source/asr/asr_customization/ngram_utils.rst @@ -0,0 +1,151 @@ +.. _ngram-utils: + +Scripts for building and merging N-gram Language Models +======================================================= + +.. _train-ngram-lm: + +Train N-gram LM +=============== + +NeMo utilizes the KenLM library (`https://github.com/kpu/kenlm`) for building efficient n-gram language models. + +.. note:: + + KenLM is not installed by default in NeMo. + Please see the installation instructions in the script: + `scripts/asr_language_modeling/ngram_lm/install_beamsearch_decoders.sh `__. + + Alternatively, you can build a Docker image with all required dependencies using: + `scripts/installers/Dockerfile.ngramtools `__. + +The script for training an n-gram language model with KenLM is available here: +`scripts/asr_language_modeling/ngram_lm/train_kenlm.py `__. + +This script supports training n-gram LMs on both character-level and BPE-level encodings, which are automatically detected from the model type. The resulting language models can then be used with beam search decoders integrated on top of ASR models. + +You can train an n-gram model using the following command: + +.. code-block:: + + python train_kenlm.py nemo_model_file= \ + train_paths= \ + kenlm_bin_path= \ + kenlm_model_file= \ + ngram_length= \ + preserve_arpa=true + +The `train_paths` parameter allows for various input types, such as a list of text files, JSON manifests, or directories, to be used as the training data. +If the file's extension is anything other than `.json`, it assumes that data format is plain text. For plain text format, each line should contain one +sample. For the JSON manifests, the file must contain JSON-formatted samples per each line like this: + +.. code-block:: + + {"audio_filepath": "/data_path/file1.wav", "text": "The transcript of the audio file."} + +This code extracts the `text` field from each line to create the training text file. After the N-gram model is trained, it is stored at the path specified by `kenlm_model_file`. + +The following is the list of the arguments for the training script: + ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| **Argument** | **Type** | **Default** | **Description** | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| nemo_model_file | str | Required | The path to `.nemo` file of the ASR model, or name of a pretrained NeMo model to extract a tokenizer. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| train_paths | List[str] | Required | List of training files or folders. Files can be a plain text file or ".json" manifest or ".json.gz". | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| kenlm_model_file | str | Required | The path to store the KenLM binary model file. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| kenlm_bin_path | str | Required | The path to the bin folder of KenLM. It is a folder named `bin` under where KenLM is installed. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| ngram_length** | int | Required | Specifies order of N-gram LM. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| ngram_prune | List[int] | [0] | List of thresholds to prune N-grams. Example: [0,0,1]. See Pruning section on the https://kheafield.com/code/kenlm/estimation | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| cache_path | str | ``""`` | Cache path to save tokenized files. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| preserve_arpa | bool | ``False`` | Whether to preserve the intermediate ARPA file after construction of the BIN file. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| verbose | int | 1 | Verbose level. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ +| save_nemo | bool | ``False`` | Whether to save LM in .nemo format. | ++------------------+-----------+-------------+--------------------------------------------------------------------------------------------------------------------------------+ + +..note:: +It is recommended that you use 6 as the order of the N-gram model for BPE-based models. Higher orders may require re-compiling KenLM to support them. + + +Combine N-gram Language Models +============================== + +Before combining N-gram LMs, install the required OpenGrm NGram library using `scripts/installers/install_opengrm.sh `__. +Alternatively, you can use Docker image `scripts/installers/Dockerfile.ngramtools `__ with all the necessary dependencies. + +Alternatively, you can use the Docker image at: +`scripts/asr_language_modeling/ngram_lm/ngram_merge.py `__, which includes all the necessary dependencies. + +This script interpolates two ARPA N-gram language models and creates a KenLM binary file that can be used with the beam search decoders on top of ASR models. +You can specify weights (`--alpha` and `--beta`) for each of the models (`--ngram_a` and `--ngram_b`) correspondingly: `alpha` * `ngram_a` + `beta` * `ngram_b`. +This script supports both character level and BPE level encodings and models which are detected automatically from the type of the model. + +To combine two N-gram models, you can use the following command: + +.. code-block:: + + python ngram_merge.py --kenlm_bin_path \ + --ngram_bin_path \ + --arpa_a \ + --alpha \ + --ar + pa_b \ + --beta \ + --out_path + + + +If you provide `--test_file` and `--nemo_model_file`, This script supports both character-level and BPE-level encodings and models, which are detected automatically based on the type of the model. +Note, the result of each step during the process is cached in the temporary file in the `--out_path`, to speed up further run. +You can use the `--force` flag to discard the cache and recalculate everything from scratch. + +.. code-block:: + + python ngram_merge.py --kenlm_bin_path \ + --ngram_bin_path \ + --arpa_a \ + --alpha \ + --arpa_b \ + --beta \ + --out_path + --nemo_model_file \ + --test_file \ + --symbols \ + --force + + +The following is the list of the arguments for the opengrm script: + ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| **Argument** |**Type**| **Default** | **Description** | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| kenlm_bin_path | str | Required | The path to the bin folder of KenLM library. It is a folder named `bin` under where KenLM is installed. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| ngram_bin_path | str | Required | The path to the bin folder of OpenGrm Ngram. It is a folder named `bin` under where OpenGrm Ngram is installed. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| arpa_a | str | Required | Path to the ARPA N-gram model file A. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| alpha | float | Required | Weight of N-gram model A. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| arpa_b | int | Required | Path to the ARPA N-gram model file B. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| beta | float | Required | Weight of N-gram model B. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| out_path | str | Required | Path for writing temporary and resulting files. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| test_file | str | None | Path to test file to count perplexity if provided. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| symbols | str | None | Path to symbols (.syms) file. Could be calculated if it is not provided. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| nemo_model_file | str | None | The path to '.nemo' file of the ASR model, or name of a pretrained NeMo model. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ +| force | bool | ``False`` | Whether to recompile and rewrite all files. | ++----------------------+--------+------------------+-----------------------------------------------------------------------------------------------------------------+ \ No newline at end of file diff --git a/docs/source/asr/asr_customization/word_boosting.rst b/docs/source/asr/asr_customization/word_boosting.rst new file mode 100644 index 0000000000000000000000000000000000000000..58912539560fdb5b3c6cb901d52a61a37728deaf --- /dev/null +++ b/docs/source/asr/asr_customization/word_boosting.rst @@ -0,0 +1,264 @@ +.. _word_boosting: + +**************************************************** +Word Boosting +**************************************************** + +.. _word_boosting_gpupb: + +GPU-PB +======================== + +GPU-PB is a GPU-accelerated Phrase-Boosting method supported for CTC, RNN-T/TDT, and AED (Canary) models based on NGPU-LM infrastructure. +The method supports greedy and beam search decoding, including CUDA graphs mode. GPU-PB is compatible with NGPU-LM at the same decoding run. + +GPU-PB is applied only at the decoding step in shallow fusion mode. You do not need to retrain the ASR model. +During greedy or beam search decoding, GPU-PB rescales ASR model scores with a boosting tree at the token level. +The boosting tree is built from a context phrases list, which is provided by the user. + +**NOTE**: for ASR models that support capitalization by default (e.g., Canary or parakeet-tdt-0.6b-v2), you need to capitalize all the key phrases in advance (and capitalize the full word for abbreviations). +You can use LLM for this task. + +More details about GPU-PB method can be found in the `original paper `__. + +Usage +----- +We support three ways to pass the context phrases into the decoding script: + +1. Build a boosting tree for a specific ASR model (step 0.0) and use it for all the decoding evaluation by ``boosting_tree.model_path`` (step 1.1-3.1). +2. Provide a file with context phrases ``boosting_tree.key_phrases_file`` - one phrase per line (step 1.1-3.1). +3. Provide a python list of context phrases ``boosting_tree.key_phrases_list`` (step 1.1-3.1). + +The use of the Phrase-Boosting tree is controlled by ``boosting_tree`` config (``BoostingTreeModelConfig``) for all the models. +For prepared boosting tree use ``boosting_tree.model_path=${PATH_TO_BTREE}``. +We recommend to provide the list of context phrases directly into ``speech_to_text_eval.py`` by ``boosting_tree.key_phrases_file=${KEY_WORDS_LIST}``. + +List of the most important parameters: + +* ``strategy`` - The strategy to use for decoding depending on the model type (CTC - greedy_batch or beam_batch; RNN-T/TDT - greedy_batch or malsd_batch; AED - beam). +* ``model_path``, ``key_phrases_file``, ``key_phrases_list`` - The way to pass the context phrases into the decoding script. +* ``context_score`` - The score for each arc transition in the context graph (1.0 is recommended). +* ``depth_scaling`` - The scaling factor for the depth of the context graph (2.0 is recommended for CTC, RNN-T and TDT, 1.0 for Canary). +* ``boosting_tree_alpha`` - Weight of the GPU-PB boosting tree during shallow fusion decoding (tune it according to your data). + +**0.0. [Optional] Build the boosting tree for a specific ASR model:** + +.. code-block:: + + python scripts/asr_context_biasing/build_gpu_boosting_tree.py \ + asr_model_path=${ASR_NEMO_MODEL_FILE} \ + key_phrases_file=${CONTEXT_BIASING_LIST} \ + save_to=${PATH_TO_SAVE_BTREE} \ + context_score=${CONTEXT_SCORE} \ + depth_scaling=${DEPTH_SCALING} \ + use_triton=True + +**1.1. CTC greedy batch decoding:** + +.. code-block:: + + python examples/asr/speech_to_text_eval.py \ + model_path=${MODEL_NAME} \ + dataset_manifest=${EVAL_MANIFEST} \ + batch_size=${BATCH_SIZE} \ + output_filename=${OUT_MANIFEST} \ + ctc_decoding.strategy="greedy_batch" \ + ctc_decoding.greedy.boosting_tree.key_phrases_file=${KEY_WORDS_LIST} \ + ctc_decoding.greedy.boosting_tree.context_score=1.0 \ + ctc_decoding.greedy.boosting_tree.depth_scaling=2.0 \ + ctc_decoding.greedy.boosting_tree_alpha=${BT_ALPHA} + + +**1.2. CTC beam batch decoding:** + +.. code-block:: + + python examples/asr/speech_to_text_eval.py \ + model_path=${MODEL_NAME} \ + dataset_manifest=${EVAL_MANIFEST} \ + batch_size=${BATCH_SIZE} \ + output_filename=${OUT_MANIFEST} \ + ctc_decoding.strategy="beam_batch" \ + ctc_decoding.beam.beam_size=${BEAM_SIZE} \ + ctc_decoding.beam.boosting_tree.key_phrases_file=${KEY_WORDS_LIST} \ + ctc_decoding.beam.boosting_tree.context_score=1.0 \ + ctc_decoding.beam.boosting_tree.depth_scaling=2.0 \ + ctc_decoding.beam.boosting_tree_alpha=${BT_ALPHA} + +**2.1. RNN-T/TDT greedy batch decoding:** + +.. code-block:: + + python examples/asr/speech_to_text_eval.py \ + model_path=${MODEL_NAME} \ + dataset_manifest=${EVAL_MANIFEST} \ + batch_size=${BATCH_SIZE} \ + output_filename=${OUT_MANIFEST} \ + rnnt_decoding.strategy="greedy_batch" \ + rnnt_decoding.greedy.boosting_tree.key_phrases_file=${KEY_WORDS_LIST} \ + rnnt_decoding.greedy.boosting_tree.context_score=1.0 \ + rnnt_decoding.greedy.boosting_tree.depth_scaling=2.0 \ + rnnt_decoding.greedy.boosting_tree_alpha=${BT_ALPHA} + +**2.2. RNN-T/TDT beam (malsd_batch) decoding:** + +.. code-block:: + + python examples/asr/speech_to_text_eval.py \ + model_path=${MODEL_NAME} \ + dataset_manifest=${EVAL_MANIFEST} \ + batch_size=${BATCH_SIZE} \ + output_filename=${OUT_MANIFEST} \ + rnnt_decoding.strategy="malsd_batch" \ + rnnt_decoding.beam.beam_size=${BEAM_SIZE} \ + rnnt_decoding.beam.boosting_tree.key_phrases_file=${KEY_WORDS_LIST} \ + rnnt_decoding.beam.boosting_tree.context_score=1.0 \ + rnnt_decoding.beam.boosting_tree.depth_scaling=2.0 \ + rnnt_decoding.beam.boosting_tree_alpha=${BT_ALPHA} + +**3.1. AED (Canary) greedy (beam_size=1) or beam (beam_size>1) decoding:** + +.. code-block:: + + python examples/asr/speech_to_text_eval.py \ + model_path=${MODEL_NAME} \ + dataset_manifest=${EVAL_MANIFEST} \ + batch_size=${BATCH_SIZE} \ + output_filename=${OUT_MANIFEST} \ + multitask_decoding.strategy="beam" \ + multitask_decoding.beam.beam_size=${BEAM_SIZE} \ + multitask_decoding.beam.boosting_tree.key_phrases_file=${CONTEXT_BIASING_LIST} \ + multitask_decoding.beam.boosting_tree.context_score=1.0 \ + multitask_decoding.beam.boosting_tree.depth_scaling=1.0 \ + multitask_decoding.beam.boosting_tree_alpha=${BT_ALPHA} \ + gt_lang_attr_name="target_lang" \ + gt_text_attr_name="text" + +Results evaluation +------------------ + +You can compute the F-score for the list of context phrases directly from the decoding manifest. + +.. code-block:: + + python scripts/asr_context_biasing/compute_key_words_fscore.py \ + --input_manifest=${DECODING_MANIFEST} \ + --key_words_file=${CONTEXT_PHRASES_LIST} + + +.. _word_boosting_flashlight: + +Flashlight-based Word Boosting +============================== + + +The Flashlight decoder supports word boosting during CTC decoding using a KenLM binary and corresponding lexicon. Word boosting only works in lexicon-decoding mode and does not function in lexicon-free mode. It allows you to bias the decoder for certain words by manually increasing or decreasing the probability of emitting specific words. This can be very helpful if you have uncommon or industry-specific terms that you want to ensure are transcribed correctly. + +For more information, go to `word boosting `__ + +To use word boosting in NeMo, create a simple tab-separated text file. Each line should contain a word to be boosted, followed by a tab, and then the boosted score for that word. + +For example: + +.. code-block:: + + nvidia 40 + geforce 50 + riva 80 + turing 30 + badword -100 + +Positive scores boost words higher in the LM decoding step so they show up more frequently, whereas negative scores +squelch words so they show up less frequently. The recommended range for the boost score is +/- 20 to 100. + +The boost file handles both in-vocabulary words and OOV words just fine, so you can specify both IV and OOV words with corresponding scores. + +You can then pass this file to your Flashlight config object during decoding: + +.. code-block:: + + # Lexicon-based decoding + python eval_beamsearch_ngram_ctc.py ... \ + decoding_strategy="flashlight" \ + decoding.beam.flashlight_cfg.lexicon_path='/path/to/lexicon.lexicon' \ + decoding.beam.flashlight_cfg.boost_path='/path/to/my_boost_file.boost' \ + decoding.beam.flashlight_cfg.beam_size_token = 32 \ + decoding.beam.flashlight_cfg.beam_threshold = 25.0 + +.. _word_boosting_ctcws: + +CTC-WS: Context-biasing (Word Boosting) without External LM +=========================================================== + +NeMo toolkit supports a fast context-biasing method for CTC and Transducer (RNN-T) ASR models with CTC-based Word Spotter. +The method involves decoding CTC log probabilities with a context graph built for words and phrases from the context-biasing list. +The spotted context-biasing candidates (with their scores and time intervals) are compared by scores with words from the greedy CTC decoding results to improve recognition accuracy and prevent false accepts of context-biasing. + +A Hybrid Transducer-CTC model (a shared encoder trained together with CTC and Transducer output heads) enables the use of the CTC-WS method for the Transducer model. +Context-biasing candidates obtained by CTC-WS are also filtered by the scores with greedy CTC predictions and then merged with greedy Transducer results. + +Scheme of the CTC-WS method: + +.. image:: https://github.com/NVIDIA/NeMo/releases/download/v1.22.0/asset-post-v1.22.0-ctcws_scheme_1.png + :align: center + :alt: CTC-WS scheme + :width: 80% + +High-level overview of the context-biasing words replacement with CTC-WS method: + +.. image:: https://github.com/NVIDIA/NeMo/releases/download/v1.22.0/asset-post-v1.22.0-ctcws_scheme_2.png + :align: center + :alt: CTC-WS high level overview + :width: 80% + +More details about CTC-WS context-biasing can be found in the `tutorial `__. + +To use CTC-WS context-biasing, you need to create a context-biasing text file that contains words/phrases to be boosted, with its transcriptions (spellings) separated by underscore. +Multiple transcriptions can be useful for abbreviations ("gpu" -> "g p u"), compound words ("nvlink" -> "nv link"), +or words with common mistakes in the case of our ASR model ("nvidia" -> "n video"). + +Example of the context-biasing file: + +.. code-block:: + + nvidia_nvidia + omniverse_omniverse + gpu_gpu_g p u + dgx_dgx_d g x_d gx + nvlink_nvlink_nv link + ray tracing_ray tracing + +The main script for CTC-WS context-biasing in NeMo is: + +.. code-block:: + + {NEMO_DIR_PATH}/scripts/asr_context_biasing/eval_greedy_decoding_with_context_biasing.py + +Context-biasing is managed by ``apply_context_biasing`` parameter [true or false]. +Other important context-biasing parameters are: + +* ``beam_threshold`` - threshold for CTC-WS beam pruning. +* ``context_score`` - per token weight for context biasing. +* ``ctc_ali_token_weight`` - per token weight for CTC alignment (prevents false acceptances of context-biasing words). + +All the context-biasing parameters are selected according to the default values in the script. +You can tune them according to your data and ASR model (list all the values in the [] separated by commas) +for example: ``beam_threshold=[7.0,8.0,9.0]``, ``context_score=[3.0,4.0,5.0]``, ``ctc_ali_token_weight=[0.5,0.6,0.7]``. +The script will run the recognition with all the combinations of the parameters and will select the best one based on WER value. + +.. code-block:: + + # Context-biasing with the CTC-WS method for CTC ASR model + python {NEMO_DIR_PATH}/scripts/asr_context_biasing/eval_greedy_decoding_with_context_biasing.py \ + nemo_model_file={ctc_model_name} \ + input_manifest={test_nemo_manifest} \ + preds_output_folder={exp_dir} \ + decoder_type="ctc" \ + acoustic_batch_size=64 \ + apply_context_biasing=true \ + context_file={cb_list_file_modified} \ + beam_threshold=[7.0] \ + context_score=[3.0] \ + ctc_ali_token_weight=[0.5] + +To use Transducer head of the Hybrid Transducer-CTC model, you need to set ``decoder_type=rnnt``. diff --git a/docs/source/asr/asr_language_modeling_and_customization.rst b/docs/source/asr/asr_language_modeling_and_customization.rst new file mode 100644 index 0000000000000000000000000000000000000000..125797a31a81dd15db30be9889688100edfeb81e --- /dev/null +++ b/docs/source/asr/asr_language_modeling_and_customization.rst @@ -0,0 +1,80 @@ +.. _asr_language_modeling_and_customization: + +####################################### +ASR Language Modeling and Customization +####################################### + +NeMo supports decoding-time customization techniques such as *language modeling* and *word boosting*, +which improve transcription accuracy by incorporating external knowledge or domain-specific vocabulary—without retraining the model. + +Language Modeling +----------------- + +In NeMo two approaches of external language modeling are supported: + +- **Language Model Fusion:** + Language model (LM) fusion integrates scores from an external statistical n-gram model into the ASR decoder. + This helps guide decoding toward more likely word sequences based on text corpora. + + NeMo provides two approaches for language model shallow fusion with ASR systems: + + **1. NGPU-LM (Recommended for Production)** + GPU-accelerated LM fusion for all major model types: CTC, RNN-T, TDT, and AED models. + + - Customization during both greedy and beam decoding. + + - Fast beam decoding for all major model types, offering only 20% RTFx difference between beam and greedy decoding. + + - Integration with NGPU-LM GPU-based ngram LM. + + For details, please refer to :ref:`ngpulm_ngram_modeling` + + **2. KenLM (Traditional CPU-based)** + CPU-based LM fusion using the KenLM library. + + .. note:: + + These approaches, especially beam decoding, can be extremely slow and are retained in the repository primarily for backward compatibility. + If possible, we recommend using NGPU-LM for improved performance. + + For details, please refer to :ref:`ngram_modeling` + +- **Neural Rescoring:** + When using the neural rescoring approach, a neural network is used to score candidates. A candidate is the text transcript predicted by the ASR model’s decoder. + The top K candidates produced by beam search decoding (with a beam width of K) are given to a neural language model for ranking. + The language model assigns a score to each candidate, which is usually combined with the scores from beam search decoding to produce the final scores and rankings. + + For details, please refer to :ref:`neural_rescoring`. + + +Word Boosting +------------- + +Word boosting increases the likelihood of specific words or phrases during decoding by applying a positive bias, helping the model better recognize names, +uncommon terms, and custom vocabulary. + +- :ref:`word_boosting_gpupb` (preferred): GPU-accelerated phrase-boosting for CTC, RNN-T/TDT, and AED (Canary) models supporting greedy and beam search decoding. + +- :ref:`word_boosting_flashlight`: Word-boosting method for CTC models with external n-gram LM. + +- :ref:`word_boosting_ctcws`: Word-boosting method for hybrid (Transducer-CTC) models without LM. + +For details, please refer to: :ref:`word_boosting`. + + +LM Training +----------- + +NeMo provides tools for training n-gram language models that can be used for language model fusion or word-boosting. +For details, please refer to: :ref:`ngram-utils`. + + +.. toctree:: + :maxdepth: 1 + :hidden: + + asr_customization/ngpulm_language_modeling_and_customization + asr_customization/neural_rescoring + asr_customization/legacy_language_modeling_and_customization + asr_customization/ngram_utils + asr_customization/word_boosting \ No newline at end of file diff --git a/docs/source/asr/configs.rst b/docs/source/asr/configs.rst new file mode 100644 index 0000000000000000000000000000000000000000..88ee9a8df08122231d5e3ec5a51ed29dff56ffc7 --- /dev/null +++ b/docs/source/asr/configs.rst @@ -0,0 +1,929 @@ +NeMo ASR Configuration Files +============================ + +This section describes the NeMo configuration file setup that is specific to models in the ASR collection. For general information +about how to set up and run experiments that is common to all NeMo models (e.g. Experiment Manager and PyTorch Lightning trainer +parameters), see the :doc:`../core/core` section. + +The model section of the NeMo ASR configuration files generally requires information about the dataset(s) being used, the preprocessor +for audio files, parameters for any augmentation being performed, as well as the model architecture specification. The sections on +this page cover each of these in more detail. + +Example configuration files for all of the NeMo ASR scripts can be found in the +`config directory of the examples `_. + +.. _asr-configs-dataset-configuration: + +Dataset Configuration +--------------------- + +Training, validation, and test parameters are specified using the ``train_ds``, ``validation_ds``, and +``test_ds`` sections in the configuration file, respectively. Depending on the task, there may be arguments specifying the sample rate +of the audio files, the vocabulary of the dataset (for character prediction), whether or not to shuffle the dataset, and so on. You may +also decide to leave fields such as the ``manifest_filepath`` blank, to be specified via the command-line at runtime. + +Any initialization parameter that is accepted for the Dataset class used in the experiment can be set in the config file. +Refer to the :ref:`Datasets ` section of the API for a list of Datasets and their respective parameters. + +An example ASR train and validation configuration should look similar to the following: + +.. code-block:: yaml + + # Specified at the beginning of the config file + labels: &labels [" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "'"] + + model: + train_ds: + manifest_filepath: ??? + sample_rate: 16000 + labels: *labels # Uses the labels above + batch_size: 32 + trim_silence: True + max_duration: 16.7 + shuffle: True + num_workers: 8 + pin_memory: true + # tarred datasets + is_tarred: false # If set to true, uses the tarred version of the Dataset + tarred_audio_filepaths: null # Not used if is_tarred is false + shuffle_n: 2048 # Not used if is_tarred is false + # bucketing params + bucketing_strategy: "synced_randomized" + bucketing_batch_size: null + bucketing_weights: null + + validation_ds: + manifest_filepath: ??? + sample_rate: 16000 + labels: *labels # Uses the labels above + batch_size: 32 + shuffle: False # No need to shuffle the validation data + num_workers: 8 + pin_memory: true + +There are two ways to test/validate on more than one manifest: + +- Specify a list in the `manifest_filepath` field. Results will be reported for each, the first one being used for overall loss / WER (specify `val_dl_idx` if you wish to change that). In this case, all manifests will share configuration parameters. +- Use the ds_item key and pass a list of config objects to it. This allows you to use differently configured datasets for validation, e.g. + +.. code-block:: yaml + + model: + validation_ds: + ds_item: + - name: dataset1 + manifest_filepath: ??? + # Config parameters for dataset1 + ... + - name: dataset2 + manifest_filepath: ??? + # Config parameters for dataset2 + ... + +By default, dataloaders are set up when the model is instantiated. However, dataloader setup can be deferred to +model's `setup()` method by setting ``defer_setup`` in the configuration. + +For example, training data setup can be deferred as follows: + +.. code-block:: yaml + + model: + train_ds: + # Configure training data as usual + ... + # Defer train dataloader setup from `__init__` to `setup` + defer_setup: true + + +.. _asr-configs-metric-configuration: + +Metric Configurations +--------------------- + +NeMo ASR models supports WER and BLEU metric logging during training and validation. All metrics are based on the TorchMetrics backend, allowing for distributed training without additional code. + +Word Error Rate (WER) +~~~~~~~~~~~~~~~~~~~~~ + +WER is the default metric for all ASR models and measures transcription accuracy at the word or character level. + +.. code-block:: yaml + + model: + use_cer: false # Set to true for Character Error Rate instead (default: false) + log_prediction: true # Whether to log a sample prediction during training (default: true) + batch_dim_index: 0 # Index of batch dimension in prediction tensors output. Set to 1 for RNNT models. + +BLEU Score +~~~~~~~~~~ + +BLEU score can be used for ASR models to evaluate translation quality. NeMo's BLEU implementation is based on SacreBLEU for standardized, reproducible scoring: + +.. code-block:: yaml + + model: + bleu_tokenizer: "13a" # SacreBLEU tokenizer type (see below). (default: "13a") + n_gram: 4 # Maximum n-gram order for BLEU calculation. (default: 4) + lowercase: false # Whether to lowercase before computing BLEU. (default: False) + weights: null # Optional custom weights for n-gram orders. (default: null) + smooth: false # Whether to apply smoothing to BLEU calculation. (default: False) + check_cuts_for_bleu_tokenizers: false # Enable per-sample tokenizer selection. (See below for more details.) (default: False) + log_prediction: true # Whether to log sample predictions. (default: True) + batch_dim_index: 0 # Index of batch dimension in prediction tensors output. Set to 1 for RNNT models. (default: 0) + +BLEU score relies on TorchMetrics' SacreBLEU implementation and supports all SacreBLEU tokenization options. Valid strings may be passed to ``bleu_tokenizer`` parameter to configure base tokenizer behavior during BLEU calculation. Available options are: + +* ``"13a"`` - Default WMT tokenizer (mteval-v13a script compatible) +* ``"none"`` - No tokenization applied +* ``"intl"`` - International tokenization (mteval-v14 script compatible) +* ``"char"`` - Character-level tokenization (language-agnostic) +* ``"zh"`` - Chinese tokenization (separates Chinese characters, uses 13a for non-Chinese) +* ``"ja-mecab"`` - Japanese tokenization using MeCab morphological analyzer +* ``"ko-mecab"`` - Korean tokenization using MeCab-ko morphological analyzer +* ``"flores101"`` / ``"flores200"`` - SentencePiece models from Flores datasets + +**Note** Due to their unique orthographies, it is highly recommended to use ``zh``, ``ja-mecab``, or ``ko-mecab`` tokenizers for Chinese, Japanese, and Korean target evaluations, respectively. For more information on SacreBLEU tokenizers, please refer to the `SacreBLEU documentation `__. + +**Dynamic Tokenizer Selection** + +In multilingual training scenarios, it is somtimes desireable to configure the BLEU tokenizer per sample to avoid sub-optimal parsing (e.g. tokenizing Chinese characters as English words). This can be toggled with ``check_cuts_for_bleu_tokenizers: true``. When enabled with Lhotse dataloading, BLEU will check individual ``cuts`` in a batch's Lhotse ``CutSet`` for the ``bleu_tokenizer`` attribute. If found, the tokenizer will be used for that sample. If not, the default ``bleu_tokenizer`` from config will be used. + +MultiTask Metrics +~~~~~~~~~~~~~~~~~ + +Multiple metrics can be configured simultaneously using a ``MultiTaskMetric`` config. This is done by specifying in the config each desired metric as a DictConfig entry with a custom key name and ``_target_`` path, along with desired properties. All properties specified within a metric config will be passed only to the metric class. All properties specified at the top level of the config will be inherited by all submetrics. + +.. code-block:: yaml + + model: + multitask_metrics_config: + log_prediction: true + metrics: + wer: + _target_: nemo.collections.asr.metrics.wer.WER + use_cer: true + constraint: ".task==transcribe" # Only apply WER to transcription samples + bleu: + _target_: nemo.collections.asr.metrics.bleu.BLEU + bleu_tokenizer: flores101 + lowercase: true + check_cuts_for_bleu_tokenizers: true + constraint: ".task==translate" # Only apply BLEU to translation samples + +**Metric Constraints** + +Each metric within ``MultiTaskMetric`` can be configured with an optional boolean ``constraint`` pattern that filters batch samples before metric computation. This allows validation to be limited to only applicable samples in a batch (e.g. only apply WER to transcription samples, only apply BLEU to translation samples). Constraint patterns match against property keywords in the batch's Lhotse CutSet. + +.. code-block:: yaml + + model: + multitask_metrics_config: + metrics: + pnc_wer: + _target_: nemo.collections.asr.metrics.wer.WER + constraint: ".task==transcribe and .pnc==true" + + multilingual_bleu: + _target_: nemo.collections.asr.metrics.bleu.BLEU + constraint: "(.source_lang!=.target_lang) or .task==translate" + +**Note:** MultiTaskMetric is currently only supported for AED multitask models. + + +.. _asr-configs-preprocessor-configuration: + +Preprocessor Configuration +-------------------------- + +If you are loading audio files for your experiment, you will likely want to use a preprocessor to convert from the +raw audio signal to features (e.g. mel-spectrogram or MFCC). The ``preprocessor`` section of the config specifies the audio +preprocessor to be used via the ``_target_`` field, as well as any initialization parameters for that preprocessor. + +An example of specifying a preprocessor is as follows: + +.. code-block:: yaml + + model: + ... + preprocessor: + # _target_ is the audio preprocessor module you want to use + _target_: nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor + normalize: "per_feature" + window_size: 0.02 + ... + # Other parameters for the preprocessor + +Refer to the :ref:`Audio Preprocessors ` API section for the preprocessor options, expected arguments, +and defaults. + +.. _asr-configs-augmentation-configurations: + +Augmentation Configurations +--------------------------- + +There are a few on-the-fly spectrogram augmentation options for NeMo ASR, which can be specified by the +configuration file using a ``spec_augment`` section. + +For example, there are options for `Cutout `_ and +`SpecAugment `_ available via the ``SpectrogramAugmentation`` module. + +The following example sets up both ``Cutout`` (via the ``rect_*`` parameters) and ``SpecAugment`` (via the ``freq_*`` +and ``time_*`` parameters). + +.. code-block:: yaml + + model: + ... + spec_augment: + _target_: nemo.collections.asr.modules.SpectrogramAugmentation + # Cutout parameters + rect_masks: 5 # Number of rectangles to cut from any given spectrogram + rect_freq: 50 # Max cut of size 50 along the frequency dimension + rect_time: 120 # Max cut of size 120 along the time dimension + # SpecAugment parameters + freq_masks: 2 # Cut two frequency bands + freq_width: 15 # ... of width 15 at maximum + time_masks: 5 # Cut out 10 time bands + time_width: 25 # ... of width 25 at maximum + +You can use any combination of ``Cutout``, frequency/time ``SpecAugment``, or neither of them. + +With NeMo ASR, you can also add augmentation pipelines that can be used to simulate various kinds of noise +added to audio in the channel. Augmentors in a pipeline are applied on the audio data read in the data layer. Online +augmentors can be specified in the config file using an ``augmentor`` section in ``train_ds``. The following example +adds an augmentation pipeline that first adds white noise to an audio sample with a probability of 0.5 and at a level +randomly picked between -50 dB and -10 dB and then passes the resultant samples through a room impulse response randomly +picked from the manifest file provided for ``impulse`` augmentation in the config file. + +.. code-block:: yaml + + model: + ... + train_ds: + ... + augmentor: + white_noise: + prob: 0.5 + min_level: -50 + max_level: -10 + impulse: + prob: 0.3 + manifest_path: /path/to/impulse_manifest.json + +Refer to the :ref:`Audio Augmentors ` API section for more details. + +Tokenizer Configurations +------------------------ + +Some models utilize sub-word encoding via an external tokenizer instead of explicitly defining their vocabulary. + +For such models, a ``tokenizer`` section is added to the model config. ASR models currently support two types of +custom tokenizers: + +- Google Sentencepiece tokenizers (tokenizer type of ``bpe`` in the config) +- HuggingFace WordPiece tokenizers (tokenizer type of ``wpe`` in the config) +- Aggregate tokenizers ((tokenizer type of ``agg`` in the config), see below) + +In order to build custom tokenizers, refer to the ``ASR_with_Subword_Tokenization`` notebook available in the +ASR tutorials directory. + +The following example sets up a ``SentencePiece Tokenizer`` at a path specified by the user: + +.. code-block:: yaml + + model: + ... + tokenizer: + dir: "" + type: "bpe" # can be "bpe" or "wpe" + +The Aggregate (``agg``) tokenizer feature makes it possible to combine tokenizers in order to train multilingual +models. The config file would look like this: + +.. code-block:: yaml + + model: + ... + tokenizer: + type: "agg" # aggregate tokenizer + langs: + en: + dir: "" + type: "bpe" # can be "bpe" or "wpe" + es: + dir: "" + type: "bpe" # can be "bpe" or "wpe" + +In the above config file, each language is associated with its own pre-trained tokenizer, which gets assigned +a token id range in the order the tokenizers are listed. To train a multilingual model, one needs to populate the +``lang`` field in the manifest file, allowing the routing of each sample to the correct tokenizer. At inference time, +the routing is done based on the inferred token id range. + +For models which utilize sub-word tokenization, we share the decoder module (``ConvASRDecoder``) with character tokenization models. +All parameters are shared, but for models which utilize sub-word encoding, there are minor differences when setting up the config. For +such models, the tokenizer is utilized to fill in the missing information when the model is constructed automatically. + +For example, a decoder config corresponding to a sub-word tokenization model should look similar to the following: + +.. code-block:: yaml + + model: + ... + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoder + feat_in: *enc_final + num_classes: -1 # filled with vocabulary size from tokenizer at runtime + vocabulary: [] # filled with vocabulary from tokenizer at runtime + + +On-the-fly Code Switching +------------------------- + +Nemo supports creating code-switched synthetic utterances on-the-fly during training/validation/testing. This allows you to create ASR models which +support intra-utterance code switching. If you have Nemo formatted audio data on disk (either JSON manifests or tarred audio data), you +can easily mix as many of these audio sources together as desired by adding some extra parameters to your `train_ds`, `validation_ds`, and `test_ds`. + +Please note that this allows you to mix any kind of audio sources together to create synthetic utterances which sample from all sources. The most +common use case for this is blending different languages together to create a multilingual code-switched model, but you can also blend +together different audio sources from the same languages (or language families), to create noise robust data, or mix fast and slow speech from the +same language. + +For multilingual code-switched models, we recommend using AggTokenizer for your Tokenizer if mixing different languages. + +The following example shows how to mix 3 different languages: English (en), German (de), and Japanese (ja) added to the `train_ds` model block, however +you can add similar logic to your `validation_ds` and `test_ds` blocks for on-the-fly code-switched validation and test data too. This example mixes +together 3 languages, but you can use as many as you want. However, be advised that the more languages you add, the higher your `min_duration` and `max_duration` +need to be set to ensure all languages are sampled into each synthetic utterance, and setting these hyperparameters higher will use more VRAM per mini-batch during +training and evaluation. + +.. code-block:: yaml + + model: + train_ds: + manifest_filepath: [/path/to/EN/tarred_manifest.json, /path/to/DE/tarred_manifest.json, /path/to/JA/tarred_manifest.json] + tarred_audio_filepaths: ['/path/to/EN/tars/audio__OP_0..511_CL_.tar', '/path/to/DE/tars/audio__OP_0..1023_CL_.tar', '/path/to/JA/tars/audio__OP_0..2047_CL_.tar'] + is_code_switched: true + is_tarred: true + shuffle: true + code_switched: # add this block for code-switching + min_duration: 12 # the minimum number of seconds for each synthetic code-switched utterance + max_duration: 20 # the maximum number of seconds for each synthetic code-switched utterance + min_monolingual: 0.3 # the minimum percentage of utterances which will be pure monolingual (0.3 = 30%) + probs: [0.25, 0.5, 0.25] # the probability to sample each language (matches order of `language` above) if not provided, assumes uniform distribution + force_monochannel: true # if your source data is multi-channel, then setting this to True will force the synthetic utterances to be mono-channel + sampling_scales: 0.75 # allows you to down/up sample individual languages. Can set this as an array for individual languages, or a scalar for all languages + seed: 123 # add a seed for replicability in future runs (highly useful for `validation_ds` and `test_ds`) + + +Model Architecture Configurations +--------------------------------- + +Each configuration file should describe the model architecture being used for the experiment. Models in the NeMo ASR collection need +an ``encoder`` section and a ``decoder`` section, with the ``_target_`` field specifying the module to use for each. + +Here is the list of the parameters in the model section which are shared among most of the ASR models: + ++-------------------------+------------------+---------------------------------------------------------------------------------------------------------------+---------------------------------+ +| **Parameter** | **Datatype** | **Description** | **Supported Values** | ++=========================+==================+===============================================================================================================+=================================+ +| :code:`log_prediction` | bool | Whether a random sample should be printed in the output at each step, along with its predicted transcript. | | ++-------------------------+------------------+---------------------------------------------------------------------------------------------------------------+---------------------------------+ +| :code:`ctc_reduction` | string | Specifies the reduction type of CTC loss. Defaults to ``mean_batch`` which would take the average over the | :code:`none`, | +| | | batch after taking the average over the length of each sample. | :code:`mean_batch` | +| | | | :code:`mean`, :code:`sum` | ++-------------------------+------------------+---------------------------------------------------------------------------------------------------------------+---------------------------------+ + +The following sections go into more detail about the specific configurations of each model architecture. + +For more information about the ASR models, refer to the :doc:`Models <./models>` section. + + +.. _asr-configs-conformer-ctc: + +Conformer-CTC +~~~~~~~~~~~~~ + +The config files for Conformer-CTC model contain character-based encoding and sub-word encoding at +``/examples/asr/conf/conformer/conformer_ctc_char.yaml`` and ``/examples/asr/conf/conformer/conformer_ctc_bpe.yaml`` +respectively. Some components of the configs of :ref:`Conformer-CTC ` include the following datasets: + +* ``train_ds``, ``validation_ds``, and ``test_ds`` +* opimizer (``optim``) +* augmentation (``spec_augment``) +* ``decoder`` +* ``trainer`` +* ``exp_manager`` + +There should be a tokenizer section where you can +specify the tokenizer if you want to use sub-word encoding instead of character-based encoding. + + +The encoder section includes the details about the Conformer-CTC encoder architecture. You may find more information in the +config files and also :ref:`nemo.collections.asr.modules.ConformerEncoder `. + + +Conformer-Transducer +~~~~~~~~~~~~~~~~~~~~ + +Please refer to the model page of :ref:`Conformer-Transducer ` for more information on this model. + +.. _asr-configs-lstm-transducer-and-ctc: + +LSTM-Transducer and LSTM-CTC +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The config files for LSTM-Transducer and LSTM-CTC models can be found at ``/examples/asr/conf/lstm/lstm_transducer_bpe.yaml`` and ``/examples/asr/conf/lstm/lstm_ctc_bpe.yaml`` respectively. +Most of the of the configs of are similar to other ctc or transducer models. The main difference is the encoder part. +The encoder section includes the details about the RNN-based encoder architecture. You may find more information in the +config files and also :ref:`nemo.collections.asr.modules.RNNEncoder `. + + +InterCTC Config +--------------- + +All CTC-based models also support `InterCTC loss `_. To use it, you need to specify +2 parameters as in example below + +.. code-block:: yaml + + model: + # ... + interctc: + loss_weights: [0.3] + apply_at_layers: [8] + +which can be used to reproduce the default setup from the paper (assuming the total number of layers is 18). +You can also specify multiple CTC losses from different layers, e.g., to get 2 losses from layers 3 and 8 with +weights 0.1 and 0.3, specify: + +.. code-block:: yaml + + model: + # ... + interctc: + loss_weights: [0.1, 0.3] + apply_at_layers: [3, 8] + +Note that the final-layer CTC loss weight is automatically computed to normalize +all weight to 1 (0.6 in the example above). + + +Stochastic Depth Config +----------------------- + +`Stochastic Depth `_ is a useful technique for regularizing ASR model training. +Currently it's only supported for :ref:`nemo.collections.asr.modules.ConformerEncoder `. To +use it, specify the following parameters in the encoder config file to reproduce the default setup from the paper: + +.. code-block:: yaml + + model: + # ... + encoder: + # ... + stochastic_depth_drop_prob: 0.3 + stochastic_depth_mode: linear # linear or uniform + stochastic_depth_start_layer: 1 + +See :ref:`documentation of ConformerEncoder ` for more details. Note that stochastic depth +is supported for both CTC and Transducer model variations (or any other kind of model/loss that's using +conformer as encoder). + + +Transducer Configurations +------------------------- + +All CTC-based ASR model configs can be modified to support Transducer loss training. Below, we discuss the modifications required in the config to enable Transducer training. All modifications are made to the ``model`` config. + +Model Defaults +~~~~~~~~~~~~~~ + +It is a subsection to the model config representing the default values shared across the entire model represented as ``model.model_defaults``. + +There are three values that are primary components of a transducer model. They are : + +* ``enc_hidden``: The hidden dimension of the final layer of the Encoder network. +* ``pred_hidden``: The hidden dimension of the final layer of the Prediction network. +* ``joint_hidden``: The hidden dimension of the intermediate layer of the Joint network. + +One can access these values inside the config by using OmegaConf interpolation as follows : + +.. code-block:: yaml + + model: + ... + model_defaults: + enc_hidden: 256 + pred_hidden: 256 + joint_hidden: 256 + ... + decoder: + ... + prednet: + pred_hidden: ${model.model_defaults.pred_hidden} + +Acoustic Encoder Model +~~~~~~~~~~~~~~~~~~~~~~ + +The transducer model is comprised of three models combined. One of these models is the Acoustic (encoder) model. We should be able to drop in any CTC Acoustic model config into this section of the transducer config. + +The only condition that needs to be met is that **the final layer of the acoustic model must have the hidden dimension defined in ``model_defaults.enc_hidden``**. + +Decoder / Prediction Model +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Prediction model is generally an autoregressive, causal model that consumes text tokens and returns embeddings that will be used by the Joint model. The base config for an LSTM based Prediction network can be found in the ``decoder`` section of Transducer architectures. For further information refer to the ``Intro to Transducers`` tutorial in the ASR tutorial section. + +**This config can be copy-pasted into any custom transducer model with no modification.** + +Let us discuss some of the important arguments: + +* ``blank_as_pad``: In ordinary transducer models, the embedding matrix does not acknowledge the ``Transducer Blank`` token (similar to CTC Blank). However, this causes the autoregressive loop to be more complicated and less efficient. Instead, this flag which is set by default, will add the ``Transducer Blank`` token to the embedding matrix - and use it as a pad value (zeros tensor). This enables more efficient inference without harming training. For further information refer to the ``Intro to Transducers`` tutorial in the ASR tutorial section. + +* ``prednet.pred_hidden``: The hidden dimension of the LSTM and the output dimension of the Prediction network. + +.. code-block:: yaml + + decoder: + _target_: nemo.collections.asr.modules.RNNTDecoder + normalization_mode: null + random_state_sampling: false + blank_as_pad: true + + prednet: + pred_hidden: ${model.model_defaults.pred_hidden} + pred_rnn_layers: 1 + t_max: null + dropout: 0.0 + +Joint Model +~~~~~~~~~~~ + +The Joint model is a simple feed-forward Multi-Layer Perceptron network. This MLP accepts the output of the Acoustic and Prediction models and computes a joint probability distribution over the entire vocabulary space. The base config for the Joint network can be found in the ``joint`` section of Transducer architectures. For further information refer to the ``Intro to Transducers`` tutorial in the ASR tutorial section. + +**This config can be copy-pasted into any custom transducer model with no modification.** + +The Joint model config has several essential components which we discuss below : + +* ``log_softmax``: Due to the cost of computing softmax on such large tensors, the Numba CUDA implementation of RNNT loss will implicitly compute the log softmax when called (so its inputs should be logits). The CPU version of the loss doesn't face such memory issues so it requires log-probabilities instead. Since the behaviour is different for CPU-GPU, the ``None`` value will automatically switch behaviour dependent on whether the input tensor is on a CPU or GPU device. + +* ``preserve_memory``: This flag will call ``torch.cuda.empty_cache()`` at certain critical sections when computing the Joint tensor. While this operation might allow us to preserve some memory, the empty_cache() operation is tremendously slow and will slow down training by an order of magnitude or more. It is available to use but not recommended. + +* ``fuse_loss_wer``: This flag performs "batch splitting" and then "fused loss + metric" calculation. It will be discussed in detail in the next tutorial that will train a Transducer model. + +* ``fused_batch_size``: When the above flag is set to True, the model will have two distinct "batch sizes". The batch size provided in the three data loader configs (``model.*_ds.batch_size``) will now be the ``Acoustic model`` batch size, whereas the ``fused_batch_size`` will be the batch size of the ``Prediction model``, the ``Joint model``, the ``transducer loss`` module and the ``decoding`` module. + +* ``jointnet.joint_hidden``: The hidden intermediate dimension of the joint network. + +.. code-block:: yaml + + joint: + _target_: nemo.collections.asr.modules.RNNTJoint + log_softmax: null # sets it according to cpu/gpu device + + # fused mode + fuse_loss_wer: false + fused_batch_size: 16 + + jointnet: + joint_hidden: ${model.model_defaults.joint_hidden} + activation: "relu" + dropout: 0.0 + +Sampled Softmax Joint Model +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There are some situations where a large vocabulary with a Transducer model - such as for multilingual models with a large +number of languages. In this setting, we need to consider the cost of memory of training Transducer networks which does +not allow large vocabulary. + +For such cases, one can instead utilize the ``SampledRNNTJoint`` module instead of the usual ``RNNTJoint`` module, in order +to compute the loss using a sampled subset of the vocabulary rather than the full vocabulary file. + +It adds only one additional parameter : + +* ``n_samples``: Specifies the minimum number of tokens to sample from the vocabulary space, + excluding the RNNT blank token. If a given value is larger than the entire vocabulary size, + then the full vocabulary will be used. + +The only difference in config required is to replace ``nemo.collections.asr.modules.RNNTJoint`` with ``nemo.collections.asr.modules.SampledRNNTJoint`` + +.. code-block:: yaml + + joint: + _target_: nemo.collections.asr.modules.SampledRNNTJoint + n_samples: 500 + ... # All other arguments from RNNTJoint can be used after this. + + +Effect of Batch Splitting / Fused Batch step +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following information below explain why memory is an issue when training Transducer models and how NeMo tackles the issue with its Fused Batch step. The material can be read for a thorough understanding, otherwise, it can be skipped. You can also follow these steps in the "ASR_with_Transducers" tutorial. + +**Diving deeper into the memory costs of Transducer Joint** + +One of the significant limitations of Transducers is the exorbitant memory cost of computing the Joint module. The Joint module is comprised of two steps. + +1) Projecting the Acoustic and Transcription feature dimensions to some standard hidden dimension (specified by model.model_defaults.joint_hidden) + +2) Projecting this intermediate hidden dimension to the final vocabulary space to obtain the transcription. + +Take the following example. + +BS=32 ; T (after 2x stride) = 800, U (with character encoding) = 400-450 tokens, Vocabulary size V = 28 (26 alphabet chars, space and apostrophe). Let the hidden dimension of the Joint model be 640 (Most Google Transducer papers use hidden dimension of 640). + +* :math:`Memory \, (Hidden, \, gb) = 32 \times 800 \times 450 \times 640 \times 4 = 29.49` gigabytes (4 bytes per float). + +* :math:`Memory \, (Joint, \, gb) = 32 \times 800 \times 450 \times 28 \times 4 = 1.290` gigabytes (4 bytes per float) + +**NOTE**: This is just for the forward pass! We need to double this memory to store gradients! This much memory is also just for the Joint model **alone**. Far more memory is required for the Prediction model as well as the large Acoustic model itself and its gradients! + +Even with mixed precision, that's $\sim 30$ GB of GPU RAM for just 1 part of the network + its gradients. + +Effect of Fused Batch Step +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The fundamental problem is that the joint tensor grows in size when ``[T x U]`` grows in size. This growth in memory cost is due to many reasons - either by model construction (downsampling) or the choice of dataset preprocessing (character tokenization vs. sub-word tokenization). + +Another dimension that NeMo can control is **batch**. Due to how we batch our samples, small and large samples all get clumped together into a single batch. So even though the individual samples are not all as long as the maximum length of T and U in that batch, when a batch of such samples is constructed, it will consume a significant amount of memory for the sake of compute efficiency. + +So as is always the case - **trade-off compute speed for memory savings**. + +The fused operation goes as follows : + +1) Forward the entire acoustic model in a single pass. (Use global batch size here for acoustic model - found in ``model.*_ds.batch_size``) + +2) Split the Acoustic Model's logits by ``fused_batch_size`` and loop over these sub-batches. + +3) Construct a sub-batch of same ``fused_batch_size`` for the Prediction model. Now the target sequence length is :math:`U_{sub-batch} < U`. + +4) Feed this :math:`U_{sub-batch}` into the Joint model, along with a sub-batch from the Acoustic model (with :math:`T_{sub-batch} < T)`. Remember, we only have to slice off a part of the acoustic model here since we have the full batch of samples :math:`(B, T, D)` from the acoustic model. + +5) Performing steps (3) and (4) yields :math:`T_{sub-batch}` and :math:`U_{sub-batch}`. Perform sub-batch joint step - costing an intermediate :math:`(B, T_{sub-batch}, U_{sub-batch}, V)` in memory. + +6) Compute loss on sub-batch and preserve in a list to be later concatenated. + +7) Compute sub-batch metrics (such as Character / Word Error Rate) using the above Joint tensor and sub-batch of ground truth labels. Preserve the scores to be averaged across the entire batch later. + +8) Delete the sub-batch joint matrix :math:`(B, T_{sub-batch}, U_{sub-batch}, V)`. Only gradients from .backward() are preserved now in the computation graph. + +9) Repeat steps (3) - (8) until all sub-batches are consumed. + +10) Cleanup step. Compute full batch WER and log. Concatenate loss list and pass to PTL to compute the equivalent of the original (full batch) Joint step. Delete ancillary objects necessary for sub-batching. + +Transducer Decoding +~~~~~~~~~~~~~~~~~~~ + +Models which have been trained with CTC can transcribe text simply by performing a regular argmax over the output of their decoder. For transducer-based models, the three networks must operate in a synchronized manner in order to transcribe the acoustic features. The base config for the Transducer decoding step can be found in the ``decoding`` section of Transducer architectures. For further information refer to the ``Intro to Transducers`` tutorial in the ASR tutorial section. + +**This config can be copy-pasted into any custom transducer model with no modification.** + +The most important component at the top level is the ``strategy``. It can take one of many values: + +* ``greedy``: This is sample-level greedy decoding. It is generally exceptionally slow as each sample in the batch will be decoded independently. For publications, this should be used alongside batch size of 1 for exact results. + +* ``greedy_batch``: This is the general default and should nearly match the ``greedy`` decoding scores (if the acoustic features are not affected by feature mixing in batch mode). Even for small batch sizes, this strategy is significantly faster than ``greedy``. + +* ``beam``: Runs beam search with the implicit language model of the Prediction model. It will generally be quite slow, and might need some tuning of the beam size to get better transcriptions. + +* ``tsd``: Time synchronous decoding. Please refer to the paper: `Alignment-Length Synchronous Decoding for RNN Transducer `_ for details on the algorithm implemented. Time synchronous decoding (TSD) execution time grows by the factor T * max_symmetric_expansions. For longer sequences, T is greater and can therefore take a long time for beams to obtain good results. TSD also requires more memory to execute. + +* ``alsd``: Alignment-length synchronous decoding. Please refer to the paper: `Alignment-Length Synchronous Decoding for RNN Transducer `_ for details on the algorithm implemented. Alignment-length synchronous decoding (ALSD) execution time is faster than TSD, with a growth factor of T + U_max, where U_max is the maximum target length expected during execution. Generally, T + U_max < T * max_symmetric_expansions. However, ALSD beams are non-unique. Therefore it is required to use larger beam sizes to achieve the same (or close to the same) decoding accuracy as TSD. For a given decoding accuracy, it is possible to attain faster decoding via ALSD than TSD. + +* ``maes``: Modified Adaptive Expansion Search Decoding. Please refer to the paper `Accelerating RNN Transducer Inference via Adaptive Expansion Search `_. Modified Adaptive Synchronous Decoding (mAES) execution time is adaptive w.r.t the number of expansions (for tokens) required per timestep. The number of expansions can usually be constrained to 1 or 2, and in most cases 2 is sufficient. This beam search technique can possibly obtain superior WER while sacrificing some evaluation time. + +.. code-block:: yaml + + decoding: + strategy: "greedy_batch" + + # preserve decoding alignments + preserve_alignments: false + + # Overrides the fused batch size after training. + # Setting it to -1 will process whole batch at once when combined with `greedy_batch` decoding strategy + fused_batch_size: Optional[int] = -1 + + # greedy strategy config + greedy: + max_symbols: 10 + + # beam strategy config + beam: + beam_size: 2 + score_norm: true + softmax_temperature: 1.0 # scale the logits by some temperature prior to softmax + tsd_max_sym_exp: 10 # for Time Synchronous Decoding, int > 0 + alsd_max_target_len: 5.0 # for Alignment-Length Synchronous Decoding, float > 1.0 + maes_num_steps: 2 # for modified Adaptive Expansion Search, int > 0 + maes_prefix_alpha: 1 # for modified Adaptive Expansion Search, int > 0 + maes_expansion_beta: 2 # for modified Adaptive Expansion Search, int >= 0 + maes_expansion_gamma: 2.3 # for modified Adaptive Expansion Search, float >= 0 + +Transducer Loss +~~~~~~~~~~~~~~~ + +This section configures the type of Transducer loss itself, along with possible sub-sections. By default, an optimized implementation of Transducer loss will be used which depends on Numba for CUDA acceleration. The base config for the Transducer loss section can be found in the ``loss`` section of Transducer architectures. For further information refer to the ``Intro to Transducers`` tutorial in the ASR tutorial section. + +**This config can be copy-pasted into any custom transducer model with no modification.** + +The loss config is based on a resolver pattern and can be used as follows: + +1) ``loss_name``: ``default`` is generally a good option. Will select one of the available resolved losses and match the kwargs from a sub-configs passed via explicit ``{loss_name}_kwargs`` sub-config. + +2) ``{loss_name}_kwargs``: This sub-config is passed to the resolved loss above and can be used to configure the resolved loss. + + +.. code-block:: yaml + + loss: + loss_name: "default" + warprnnt_numba_kwargs: + fastemit_lambda: 0.0 + +FastEmit Regularization +^^^^^^^^^^^^^^^^^^^^^^^ + +FastEmit Regularization is supported for the default Numba based WarpRNNT loss. Recently proposed regularization approach - `FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization `_ allows us near-direct control over the latency of transducer models. + +Refer to the above paper for results and recommendations of ``fastemit_lambda``. + + +.. _Hybrid-Transducer-CTC-Prompt_model__Config: + +Hybrid-Transducer-CTC with Prompt Conditioning Configuration +------------------------------------------------------------ + +The :ref:`Hybrid-Transducer-CTC model with prompt conditioning ` +(``EncDecHybridRNNTCTCBPEModelWithPrompt``) extends the base hybrid model to support prompt-based multilingual ASR/AST. + +**Key Configuration Parameters:** + +The model introduces several prompt-specific configuration parameters in the ``model_defaults`` section: + +.. code-block:: yaml + + model: + model_defaults: + # Prompt Feature Configuration + initialize_prompt_feature: true # Enable prompt conditioning + num_prompts: 128 # Number of supported prompt categories + prompt_dictionary: { # Mapping from identifiers to prompt indices + # Language prompts (0-99) + 'en-US': 0, + 'de-DE': 1, + 'fr-FR': 2, + 'es-ES': 3, + # Task/domain prompts (100-127) + 'pnc': 100, # Punctuation mode + 'no_pnc': 101, # No punctuation mode + } + +**Dataset Configuration:** + +The model requires training data with prompt annotations when using Lhotse datasets: + +.. code-block:: yaml + + model: + train_ds: + use_lhotse: true + initialize_prompt_feature: true + prompt_field: "target_lang" # Field name for prompt extraction + prompt_dictionary: ${model.model_defaults.prompt_dictionary} + num_prompts: ${model.model_defaults.num_prompts} + + validation_ds: + use_lhotse: true + initialize_prompt_feature: true + prompt_field: "target_lang" + prompt_dictionary: ${model.model_defaults.prompt_dictionary} + num_prompts: ${model.model_defaults.num_prompts} + +**Manifest Format:** + +Training manifests should include prompt information: + +.. code-block:: json + + { + "audio_filepath": "/path/to/audio.wav", + "text": "transcription text", + "duration": 10.5, + "target_lang": "en-US" + } + +**Example Configuration:** + +A complete example configuration can be found at: +``/examples/asr/conf/fastconformer/hybrid_transducer_ctc/fastconformer_hybrid_transducer_ctc_bpe_prompt.yaml`` + +**Training Command:** + +.. code-block:: bash + + python /examples/asr/asr_hybrid_transducer_ctc/speech_to_text_hybrid_rnnt_ctc_bpe_prompt.py \ + --config-path=/examples/asr/conf/fastconformer/hybrid_transducer_ctc/ \ + --config-name=fastconformer_hybrid_transducer_ctc_bpe_prompt.yaml \ + model.train_ds.manifest_filepath= \ + model.validation_ds.manifest_filepath= \ + model.tokenizer.dir= \ + model.test_ds.manifest_filepath= + +Fine-tuning Configurations +-------------------------- + +All ASR scripts support easy fine-tuning by partially/fully loading the pretrained weights from a checkpoint into the **currently instantiated model**. Note that the currently instantiated model should have parameters that match the pre-trained checkpoint (such that weights may load properly). In order to directly fine-tune a pre-existing checkpoint, please follow the tutorial `ASR Language Fine-tuning. `_ + +Models can be fine-tuned in two ways: +* By updating or retaining current tokenizer alone +* By updating model architecture and tokenizer + +Fine-tuning by updating or retaining current tokenizer +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In this case, the model architecture is not updated. The model is initialized with the pre-trained weights by +two ways: + +1) Providing a path to a NeMo model (via ``init_from_nemo_model``) +2) Providing a name of a pretrained NeMo model (which will be downloaded via the cloud) (via ``init_from_pretrained_model``) + +Then users can use existing tokenizer or update the tokenizer with new vocabulary. This is useful when users don't want to update the model architecture +but want to update the tokenizer with new vocabulary. + +The same script can be used to finetune CTC, RNNT or Hybrid models as well. + +/examples/asr/speech_to_text_finetune.py script supports this type of fine-tuning with the following arguments: + +.. code-block:: sh + + python examples/asr/speech_to_text_finetune.py \ + --config-path= \ + --config-name=) \ + model.train_ds.manifest_filepath="" \ + model.validation_ds.manifest_filepath="" \ + model.tokenizer.update_tokenizer= \ # True to update tokenizer, False to retain existing tokenizer + model.tokenizer.dir= \ # Path to tokenizer dir when update_tokenizer=True + model.tokenizer.type= \ # tokenizer type when update_tokenizer=True + trainer.devices=-1 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 \ + +init_from_nemo_model="" (or +init_from_pretrained_model="") + + +Refer to /examples/asr/conf/asr_finetune/speech_to_text_finetune.yaml for more details. + +Finetune ASR Models using HuggingFace Datasets +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Users can utilize HuggingFace Datasets for finetuning NeMo ASR models. The following config file can be used for this purpose: +`/examples/asr/conf/asr_finetune/speech_to_text_hf_finetune.yaml` + +As mentioned earlier, users can update the tokenizer or use an existing one based on their requirements. If users want to create a new tokenizer +from HuggingFace Datasets, they can use the following script: +`/scripts/tokenizers/get_hf_text_data.py` + +Fine-tuning by changing model architecture and tokenizer +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If users want to update the model architecture as well they can use the following script: + +For providing pretrained model, users can provide Pre-trained weights in multiple ways - + +1) Providing a path to a NeMo model (via ``init_from_nemo_model``) +2) Providing a name of a pretrained NeMo model (which will be downloaded via the cloud) (via ``init_from_pretrained_model``) +3) Providing a path to a Pytorch Lightning checkpoint file (via ``init_from_ptl_ckpt``) + +There are multiple ASR subtasks inside the ``examples/asr/`` directory, you can substitute the ```` tag below. + +.. code-block:: sh + + python examples/asr//script_to_.py \ + --config-path= \ + --config-name=) \ + model.train_ds.manifest_filepath="" \ + model.validation_ds.manifest_filepath="" \ + trainer.devices=-1 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 \ + +init_from_nemo_model="" # (or +init_from_pretrained_model, +init_from_ptl_ckpt ) + +To reinitialize part of the model, to make it different from the pretrained model, users can mention them through config: + +.. code-block:: yaml + + init_from_nemo_model: "" + asr_model: + include: ["preprocessor","encoder"] + exclude: ["decoder"] + +Fine-tuning Execution Flow Diagram +---------------------------------- + +When preparing your own training or fine-tuning scripts, please follow the execution flow diagram order for correct inference. + +Depending on the type of model, there may be extra steps that must be performed - + +* CTC Models - `Examples directory for CTC Models `_ +* RNN Transducer Models - `Examples directory for Transducer Models `_ diff --git a/docs/source/asr/data/asrlm_results.csv b/docs/source/asr/data/asrlm_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..d9a395cb8b75ffc59300341feeeba2c8be2aa5fa --- /dev/null +++ b/docs/source/asr/data/asrlm_results.csv @@ -0,0 +1,2 @@ +Model Name,Model Base Class,Model Card +asrlm_en_transformer_large_ls,TransformerLMModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:asrlm_en_transformer_large_ls" diff --git a/docs/source/asr/data/benchmark_ar.csv b/docs/source/asr/data/benchmark_ar.csv new file mode 100644 index 0000000000000000000000000000000000000000..ae8b2a58762129045a236e15e5e56a68fd37f750 --- /dev/null +++ b/docs/source/asr/data/benchmark_ar.csv @@ -0,0 +1,3 @@ +Model,Model Base Class +`stt_ar_fastconformer_hybrid_large_pcd_v1.0 `_,EncDecHybridRNNTCTCBPEModel +`stt_ar_fastconformer_hybrid_large_pc_v1.0 `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_be.csv b/docs/source/asr/data/benchmark_be.csv new file mode 100644 index 0000000000000000000000000000000000000000..ec3c53c7f92240fa00993ccc1f787c0ef7424c92 --- /dev/null +++ b/docs/source/asr/data/benchmark_be.csv @@ -0,0 +1,4 @@ +Model,Model Base Class +`stt_be_conformer_transducer_large `_,EncDecRNNTBPEModel +`stt_be_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_be_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_bg.csv b/docs/source/asr/data/benchmark_bg.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_bg.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_by.csv b/docs/source/asr/data/benchmark_by.csv new file mode 100644 index 0000000000000000000000000000000000000000..f580f2499f0a05e4c5fa1f7a0b2b00f40710fa4f --- /dev/null +++ b/docs/source/asr/data/benchmark_by.csv @@ -0,0 +1,3 @@ +Model,Model Base Class +`stt_ua_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_ca.csv b/docs/source/asr/data/benchmark_ca.csv new file mode 100644 index 0000000000000000000000000000000000000000..288baa7883cb27339752976f394768edda0ae932 --- /dev/null +++ b/docs/source/asr/data/benchmark_ca.csv @@ -0,0 +1,3 @@ +Model,Model Base Class +`stt_ca_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_ca_conformer_transducer_large `_,EncDecRNNTBPEModel diff --git a/docs/source/asr/data/benchmark_canary.csv b/docs/source/asr/data/benchmark_canary.csv new file mode 100644 index 0000000000000000000000000000000000000000..781b961b73eb230b8b9a987a6e2520fde2727136 --- /dev/null +++ b/docs/source/asr/data/benchmark_canary.csv @@ -0,0 +1,4 @@ +Model,Language +`canary-1b-flash `_,"English, French, German, Spanish" +`canary-180m-flash `_,"English, French, German, Spanish" +`canary-1b `_ ,"English, French, German, Spanish" diff --git a/docs/source/asr/data/benchmark_cn.csv b/docs/source/asr/data/benchmark_cn.csv new file mode 100644 index 0000000000000000000000000000000000000000..fd3315d7b071f09763387082a27b477e1b41de20 --- /dev/null +++ b/docs/source/asr/data/benchmark_cn.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`stt_zh_conformer_transducer_large `_,EncDecRNNTBPEModel diff --git a/docs/source/asr/data/benchmark_code_switching.csv b/docs/source/asr/data/benchmark_code_switching.csv new file mode 100644 index 0000000000000000000000000000000000000000..62f5c880b2e6e4797dfc40d9b813b5ef23f30798 --- /dev/null +++ b/docs/source/asr/data/benchmark_code_switching.csv @@ -0,0 +1,3 @@ +Model,Language +`stt_enes_conformer_ctc_large_codesw `_,"English, Spanish" +`stt_enes_conformer_transducer_large_codesw `_,"English, Spanish" \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_cs.csv b/docs/source/asr/data/benchmark_cs.csv new file mode 100644 index 0000000000000000000000000000000000000000..d32a3532961a86299f4bac18248d653b4cbd43ea --- /dev/null +++ b/docs/source/asr/data/benchmark_cs.csv @@ -0,0 +1,4 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`stt_ca_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_ca_conformer_transducer_large `_,EncDecRNNTBPEModel diff --git a/docs/source/asr/data/benchmark_da.csv b/docs/source/asr/data/benchmark_da.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_da.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_de.csv b/docs/source/asr/data/benchmark_de.csv new file mode 100644 index 0000000000000000000000000000000000000000..3bc6a9cf8ab861b186f08a9309185a3dab35eb30 --- /dev/null +++ b/docs/source/asr/data/benchmark_de.csv @@ -0,0 +1,10 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`canary-1b `_,EncDecMultiTaskModel +`stt_de_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_de_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_de_conformer_transducer_large `_,EncDecRNNTBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc_blend_eu `_,EncDecHybridRNNTCTCBPEModel +`canary-1b-flash `_,EncDecMultiTaskModel +`canary-180m-flash `_,EncDecMultiTaskModel diff --git a/docs/source/asr/data/benchmark_el.csv b/docs/source/asr/data/benchmark_el.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_el.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_en.csv b/docs/source/asr/data/benchmark_en.csv new file mode 100644 index 0000000000000000000000000000000000000000..00ebd462f37ec3b68125460237fd3270f7721471 --- /dev/null +++ b/docs/source/asr/data/benchmark_en.csv @@ -0,0 +1,35 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`parakeet-tdt-1.1b `_, EncDecRNNTBPEModel +`parakeet-tdt_ctc-1.1b `_, ASRModel +`parakeet-tdt_ctc-110m `_, ASRModel +`canary-1b `_, EncDecMultiTaskModel +`stt_en_conformer_ctc_large `_, EncDecCTCModelBPE +`parakeet-ctc-0.6b `_, EncDecCTCModelBPE +`parakeet-ctc-1.1b `_, EncDecCTCModelBPE +`stt_en_conformer_transducer_xlarge `_, EncDecRNNTBPEModel +`stt_en_fastconformer_ctc_large `_, EncDecCTCModelBPE +`stt_en_fastconformer_hybrid_large_streaming_multi `_, EncDecHybridRNNTCTCBPEModel +`stt_en_fastconformer_ctc_xxlarge `_, EncDecCTCTBPEModel +`stt_en_conformer_transducer_large `_, EncDecRNNTBPEModel +`stt_en_fastconformer_hybrid_large_pc `_, EncDecHybridRNNTCTCBPEModel +`stt_en_conformer_ctc_small `_, EncDecCTCModelBPE +`stt_en_fastconformer_transducer_large `_, EncDecRNNTBPEModel +`stt_en_fastconformer_transducer_xlarge `_, EncDecRNNTBPEModel +`stt_en_fastconformer_transducer_xxlarge `_, EncDecRNNTBPEModel +`stt_en_fastconformer_ctc_xlarge `_, EncDecCTCTBPEModel +`stt_enes_conformer_ctc_large `_, EncDecCTCModelBPE +`stt_enes_conformer_transducer_large `_, EncDecRNNTBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc `_, EncDecHybridRNNTCTCBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc_blend_eu `_, EncDecHybridRNNTCTCBPEModel +`canary-1b-flash `_, EncDecMultiTaskModel +`low-frame-rate-speech-codec-22khz `_, EncDecCTCModelBPE +`stt_en_fastconformer_hybrid_medium_streaming_80ms_pc `_, EncDecHybridRNNTCTCBPEModel +`parakeet-tdt_ctc-0.6b-ja `_, ASRModel +`parakeet-tdt-0.6b-v2 `_, ASRModel +`multitalker-parakeet-streaming-0.6b-v1 `_, EncDecMultiTalkerRNNTBPEModel +`canary-180m-flash `_, EncDecMultiTaskModel +`parakeet-rnnt-1.1b `_, EncDecRNNTBPEModel +`stt_en_fastconformer_hybrid_medium_streaming_80ms `_, EncDecHybridRNNTCTCBPEModel +`parakeet-rnnt-0.6b `_, EncDecRNNTBPEModel +`stt_en_fastconformer_tdt_large `_, EncDecRNNTModel diff --git a/docs/source/asr/data/benchmark_eo.csv b/docs/source/asr/data/benchmark_eo.csv new file mode 100644 index 0000000000000000000000000000000000000000..c9544455eb2ebb0fb1af8db738d871020c082911 --- /dev/null +++ b/docs/source/asr/data/benchmark_eo.csv @@ -0,0 +1,3 @@ +Model,Model Base Class +`stt_eo_conformer_transducer_large `_,EncDecRNNTBPEModel +`stt_eo_conformer_ctc_large `_,EncDecCTCModelBPE \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_es.csv b/docs/source/asr/data/benchmark_es.csv new file mode 100644 index 0000000000000000000000000000000000000000..911c43896690f89541e38eb4e070aff2caec8167 --- /dev/null +++ b/docs/source/asr/data/benchmark_es.csv @@ -0,0 +1,13 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`canary-1b `_,EncDecMultiTaskModel +`stt_es_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_es_conformer_transducer_large `_,EncDecRNNTBPEModel +`stt_es_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_enes_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_enes_conformer_transducer_large `_,EncDecRNNTBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc_blend_eu `_,EncDecHybridRNNTCTCBPEModel +`stt_es_fastconformer_hybrid_large_pc_nc `_,EncDecHybridRNNTCTCBPEModel +`canary-1b-flash `_,EncDecMultiTaskModel +`canary-180m-flash `_,EncDecMultiTaskModel diff --git a/docs/source/asr/data/benchmark_et.csv b/docs/source/asr/data/benchmark_et.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_et.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_fa.csv b/docs/source/asr/data/benchmark_fa.csv new file mode 100644 index 0000000000000000000000000000000000000000..7c28dd7ac338b4d00eeacc3e01f0f2f7ea584940 --- /dev/null +++ b/docs/source/asr/data/benchmark_fa.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`stt_fa_fastconformer_hybrid_large `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_fastconformer_hybrid.csv b/docs/source/asr/data/benchmark_fastconformer_hybrid.csv new file mode 100644 index 0000000000000000000000000000000000000000..73ccc5408c4cc1b4bd00d2d0df93e992b10312ae --- /dev/null +++ b/docs/source/asr/data/benchmark_fastconformer_hybrid.csv @@ -0,0 +1,19 @@ +Model,Language +`stt_ar_fastconformer_hybrid_large_pc_v1.0 `_,Arabic +`stt_hy_fastconformer_hybrid_large_pc `_,Armenian +`stt_be_fastconformer_hybrid_large_pc `_,Belarusian +`stt_hr_fastconformer_hybrid_large_pc `_,Croatian +`stt_nl_fastconformer_hybrid_large_pc `_,Dutch +`stt_en_fastconformer_hybrid_large_pc `_,English +`stt_fr_fastconformer_hybrid_large_pc `_,French +`stt_ka_fastconformer_hybrid_large_pc `_,Georgian +`stt_de_fastconformer_hybrid_large_pc `_,German +`stt_it_fastconformer_hybrid_large_pc `_,Italian +`stt_kk_ru_fastconformer_hybrid_large `_,"Kazakh, Russian" +`stt_pt_fastconformer_hybrid_large_pc `_,Portugese +`stt_fa_fastconformer_hybrid_large `_,Persian +`stt_pl_fastconformer_hybrid_large_pc `_,Polish +`stt_ru_fastconformer_hybrid_large_pc `_,Russian +`stt_es_fastconformer_hybrid_large_pc `_,Spanish +`stt_ua_fastconformer_hybrid_large_pc `_,Ukrainian +`stt_uz_fastconformer_hybrid_large_pc `_,Uzbek diff --git a/docs/source/asr/data/benchmark_fi.csv b/docs/source/asr/data/benchmark_fi.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_fi.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_fr.csv b/docs/source/asr/data/benchmark_fr.csv new file mode 100644 index 0000000000000000000000000000000000000000..34b29a4d4df54df0a6e2cbd0319c860bfb7d4536 --- /dev/null +++ b/docs/source/asr/data/benchmark_fr.csv @@ -0,0 +1,11 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`canary-1b `_,EncDecMultiTaskModel +`stt_fr_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_fr_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_fr_conformer_transducer_large `_,EncDecRNNTBPEModel +`stt_fr_no_hyphen_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_multilingual_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc_blend_eu `_,EncDecHybridRNNTCTCBPEModel +`canary-1b-flash `_,EncDecMultiTaskModel +`canary-180m-flash `_,EncDecMultiTaskModel diff --git a/docs/source/asr/data/benchmark_hi.csv b/docs/source/asr/data/benchmark_hi.csv new file mode 100644 index 0000000000000000000000000000000000000000..3350633f3496132c3610414884d079d3166b04d2 --- /dev/null +++ b/docs/source/asr/data/benchmark_hi.csv @@ -0,0 +1,2 @@ +Model Name,Model Base Class +`stt_hi_conformer_ctc_medium `_,EncDecCTCModelBPE \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_hr.csv b/docs/source/asr/data/benchmark_hr.csv new file mode 100644 index 0000000000000000000000000000000000000000..bd9761613c8b1386c8620b7cdfdef47cd0c47f39 --- /dev/null +++ b/docs/source/asr/data/benchmark_hr.csv @@ -0,0 +1,6 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`stt_hr_conformer_transducer_large `_,EncDecRNNTBPEModel +`stt_hr_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_hr_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_hu.csv b/docs/source/asr/data/benchmark_hu.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_hu.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_hy.csv b/docs/source/asr/data/benchmark_hy.csv new file mode 100644 index 0000000000000000000000000000000000000000..c07f2e43227ad1371e25f6c26912cb0c6208e5af --- /dev/null +++ b/docs/source/asr/data/benchmark_hy.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`stt_hy_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_it.csv b/docs/source/asr/data/benchmark_it.csv new file mode 100644 index 0000000000000000000000000000000000000000..a2433a37f768bffd0b06bf944796adecf6722ac5 --- /dev/null +++ b/docs/source/asr/data/benchmark_it.csv @@ -0,0 +1,6 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`stt_it_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_it_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_it_conformer_transducer_large `_,EncDecRNNTBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_jp.csv b/docs/source/asr/data/benchmark_jp.csv new file mode 100644 index 0000000000000000000000000000000000000000..5e81e4ba4defe69a2207c54d71ca4ea0825dee4f --- /dev/null +++ b/docs/source/asr/data/benchmark_jp.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`parakeet-tdt_ctc-0.6b-ja `_,ASRModel diff --git a/docs/source/asr/data/benchmark_ka.csv b/docs/source/asr/data/benchmark_ka.csv new file mode 100644 index 0000000000000000000000000000000000000000..63c588542b1b37569f73bddefb44f5fbe83a4db8 --- /dev/null +++ b/docs/source/asr/data/benchmark_ka.csv @@ -0,0 +1,3 @@ +Model,Model Base Class +`stt_ka_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_ka_fastconformer_hybrid_transducer_ctc_large_streaming_80ms_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_kab.csv b/docs/source/asr/data/benchmark_kab.csv new file mode 100644 index 0000000000000000000000000000000000000000..311ccd469e65b81c03a88b3ca5f8327df4bd650f --- /dev/null +++ b/docs/source/asr/data/benchmark_kab.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`stt_kab_conformer_transducer_large `_,EncDecRNNTBPEModel diff --git a/docs/source/asr/data/benchmark_kz.csv b/docs/source/asr/data/benchmark_kz.csv new file mode 100644 index 0000000000000000000000000000000000000000..a55a3aa88bc6163a5b18cb114b897f7e455d3df4 --- /dev/null +++ b/docs/source/asr/data/benchmark_kz.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`stt_kk_ru_fastconformer_hybrid_large `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_lt.csv b/docs/source/asr/data/benchmark_lt.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_lt.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_lv.csv b/docs/source/asr/data/benchmark_lv.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_lv.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_mr.csv b/docs/source/asr/data/benchmark_mr.csv new file mode 100644 index 0000000000000000000000000000000000000000..bc35c0c993781f2a0c737ceccfb238bf5eb1d41e --- /dev/null +++ b/docs/source/asr/data/benchmark_mr.csv @@ -0,0 +1,2 @@ +Model Name,Model Base Class +`stt_mr_conformer_ctc_medium `_,EncDecCTCModelBPE \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_mt.csv b/docs/source/asr/data/benchmark_mt.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_mt.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_multilingual.csv b/docs/source/asr/data/benchmark_multilingual.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5e7bd4a55eac53b44f4bcdc0ead43c89eaafa78 --- /dev/null +++ b/docs/source/asr/data/benchmark_multilingual.csv @@ -0,0 +1,7 @@ +Model,Model Base Class,Model Card +stt_enes_conformer_ctc_large,EncDecCTCModelBPE,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_enes_conformer_ctc_large" +stt_enes_conformer_transducer_large,EncDecRNNTBPEModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_enes_conformer_transducer_large" +stt_multilingual_fastconformer_hybrid_large_pc,EncDecHybridRNNTCTCBPEModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_multilingual_fastconformer_hybrid_large_pc" +stt_multilingual_fastconformer_hybrid_large_pc_blend_eu,EncDecHybridRNNTCTCBPEModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_multilingual_fastconformer_hybrid_large_pc_blend_eu"`canary-1b `_,EncDecMultiTaskModel +`canary-1b-flash `_,EncDecMultiTaskModel +`canary-180m-flash `_,EncDecMultiTaskModel diff --git a/docs/source/asr/data/benchmark_nl.csv b/docs/source/asr/data/benchmark_nl.csv new file mode 100644 index 0000000000000000000000000000000000000000..a362301db508c42a529133aee57fb5174070fdc1 --- /dev/null +++ b/docs/source/asr/data/benchmark_nl.csv @@ -0,0 +1,3 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`stt_nl_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_parakeet.csv b/docs/source/asr/data/benchmark_parakeet.csv new file mode 100644 index 0000000000000000000000000000000000000000..3b9a80bf39d10e740ced2cc83947486069341dba --- /dev/null +++ b/docs/source/asr/data/benchmark_parakeet.csv @@ -0,0 +1,10 @@ +Model,Model Base Class +`parakeet-tdt-0.6b-v3 `_, ASRModel +`parakeet-tdt-0.6b-v2 `_,ASRModel +`parakeet-rnnt-0.6b `_,EncDecRNNTBPEModel +`parakeet-rnnt-1.1b `_,EncDecRNNTBPEModel +`parakeet-ctc-0.6b `_,EncDecCTCModelBPE +`parakeet-tdt-1.1b `_,EncDecRNNTBPEModel +`parakeet-ctc-1.1b `_,EncDecCTCModelBPE +`parakeet-tdt_ctc-1.1b `_,ASRModel +`parakeet-tdt_ctc-0.6b-ja `_,ASRModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_pl.csv b/docs/source/asr/data/benchmark_pl.csv new file mode 100644 index 0000000000000000000000000000000000000000..a80a02b0f6bd21c9ec3a1b3cdea03a73d882f5b8 --- /dev/null +++ b/docs/source/asr/data/benchmark_pl.csv @@ -0,0 +1,4 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`stt_pl_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_pt.csv b/docs/source/asr/data/benchmark_pt.csv new file mode 100644 index 0000000000000000000000000000000000000000..fdfeb2be8a470a3c74176d3989dbe4ff42a58496 --- /dev/null +++ b/docs/source/asr/data/benchmark_pt.csv @@ -0,0 +1,3 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`stt_pt_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_ro.csv b/docs/source/asr/data/benchmark_ro.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_ro.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_ru.csv b/docs/source/asr/data/benchmark_ru.csv new file mode 100644 index 0000000000000000000000000000000000000000..78fb79d664a7fe1f519124407b0481cacc675489 --- /dev/null +++ b/docs/source/asr/data/benchmark_ru.csv @@ -0,0 +1,7 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`stt_ru_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_ru_conformer_transducer_large `_,EncDecRNNTBPEModel +`stt_kk_ru_fastconformer_hybrid_large `_,EncDecHybridRNNTCTCBPEModel +`stt_ru_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_multilingual_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_rw.csv b/docs/source/asr/data/benchmark_rw.csv new file mode 100644 index 0000000000000000000000000000000000000000..6fc08536d7e81870e0fca260019f3fcf8b2bb8fc --- /dev/null +++ b/docs/source/asr/data/benchmark_rw.csv @@ -0,0 +1,3 @@ +Model,Model Base Class +`stt_rw_conformer_ctc_large `_,EncDecCTCModelBPE +`stt_rw_conformer_transducer_large `_,EncDecRNNTBPEModel diff --git a/docs/source/asr/data/benchmark_sk.csv b/docs/source/asr/data/benchmark_sk.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_sk.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_sl.csv b/docs/source/asr/data/benchmark_sl.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_sl.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_sv.csv b/docs/source/asr/data/benchmark_sv.csv new file mode 100644 index 0000000000000000000000000000000000000000..090863035c79929239f2c0d879116f270f9d5663 --- /dev/null +++ b/docs/source/asr/data/benchmark_sv.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel \ No newline at end of file diff --git a/docs/source/asr/data/benchmark_ua.csv b/docs/source/asr/data/benchmark_ua.csv new file mode 100644 index 0000000000000000000000000000000000000000..28b0b9200c3816b80a8e19084cb4c7bc54ba06f8 --- /dev/null +++ b/docs/source/asr/data/benchmark_ua.csv @@ -0,0 +1,4 @@ +Model,Model Base Class +`canary-1b-v2 `_,EncDecMultiTaskModel +`stt_ua_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel +`stt_multilingual_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_uz.csv b/docs/source/asr/data/benchmark_uz.csv new file mode 100644 index 0000000000000000000000000000000000000000..a7c1875e27ff5e9be7959c582b3219d0b9a87c4b --- /dev/null +++ b/docs/source/asr/data/benchmark_uz.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`stt_uz_fastconformer_hybrid_large_pc `_,EncDecHybridRNNTCTCBPEModel diff --git a/docs/source/asr/data/benchmark_zh.csv b/docs/source/asr/data/benchmark_zh.csv new file mode 100644 index 0000000000000000000000000000000000000000..691192c9c36e93a6dbd38939cd62f97f1d8f0e24 --- /dev/null +++ b/docs/source/asr/data/benchmark_zh.csv @@ -0,0 +1,2 @@ +Model,Model Base Class +`stt_zh_conformer_transducer_large `_,EncDecRNNTModel diff --git a/docs/source/asr/data/scores/be/conformer_be.csv b/docs/source/asr/data/scores/be/conformer_be.csv new file mode 100644 index 0000000000000000000000000000000000000000..12fcfe0e554bced7865e409b5ad57e6557441425 --- /dev/null +++ b/docs/source/asr/data/scores/be/conformer_be.csv @@ -0,0 +1,3 @@ +Model Name,Language,MCV Test-Set v10 (be) +stt_be_conformer_ctc_large,be,4.7 % +stt_be_conformer_transducer_large,be,3.8 % diff --git a/docs/source/asr/data/scores/by/fastconformer_by.csv b/docs/source/asr/data/scores/by/fastconformer_by.csv new file mode 100644 index 0000000000000000000000000000000000000000..c03cc945d99dde5c272d45f6960ccd4a3eadde06 --- /dev/null +++ b/docs/source/asr/data/scores/by/fastconformer_by.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Dev-Set v12.0 (be),MCV Test-Set v12.0 (be) +stt_by_fastconformer_hybrid_large_pc,by,2.7 %,2.7 % diff --git a/docs/source/asr/data/scores/ca/conformer_ca.csv b/docs/source/asr/data/scores/ca/conformer_ca.csv new file mode 100644 index 0000000000000000000000000000000000000000..bc30b90a25b4f9dcf1d782fe2e4b44484b265b2c --- /dev/null +++ b/docs/source/asr/data/scores/ca/conformer_ca.csv @@ -0,0 +1,3 @@ +Model Name,Language,MCV Dev-Set (v??) (ca),MCV Dev-Set v9.0 (ca),MCV Test-Set v9.0 (ca) +stt_ca_conformer_ctc_large,ca,,4.70,4.27 +stt_ca_conformer_transducer_large,ca,,4.43,3.85 diff --git a/docs/source/asr/data/scores/de/conformer_de.csv b/docs/source/asr/data/scores/de/conformer_de.csv new file mode 100644 index 0000000000000000000000000000000000000000..1bd1443de00e3d424b0a5aa5988c036b7a16137d --- /dev/null +++ b/docs/source/asr/data/scores/de/conformer_de.csv @@ -0,0 +1,3 @@ +Model Name,Language,MCV Dev-Set (v??) (de),MCV Dev-Set v12.0 (de),MCV Dev-Set v7.0 (de),MCV Test-Set v12.0 (de),MCV Test-Set v7.0 (de),MLS Dev (en),MLS Test (en),VoxPopuli Dev (de),VoxPopuli Test (de) +stt_de_conformer_ctc_large,de,,,5.84,,6.68,3.85,4.63,12.56,10.51 +stt_de_conformer_transducer_large,de,,,4.75,,5.36,3.46,4.19,11.21,9.14 diff --git a/docs/source/asr/data/scores/de/fastconformer_de.csv b/docs/source/asr/data/scores/de/fastconformer_de.csv new file mode 100644 index 0000000000000000000000000000000000000000..fe6e6491f4438af2b1dd84d86010a650c07e0692 --- /dev/null +++ b/docs/source/asr/data/scores/de/fastconformer_de.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Dev-Set (v??) (de),MCV Dev-Set v12.0 (de),MCV Dev-Set v7.0 (de),MCV Test-Set v12.0 (de),MCV Test-Set v7.0 (de),MLS Dev (en),MLS Test (en),VoxPopuli Dev (de),VoxPopuli Test (de) +stt_de_fastconformer_hybrid_large_pc,de,,4.2 %,,4.9 %,,3.3 %,3.8 %,10.8 %,8.7 % diff --git a/docs/source/asr/data/scores/en/conformer_en.csv b/docs/source/asr/data/scores/en/conformer_en.csv new file mode 100644 index 0000000000000000000000000000000000000000..2b31a07b842a3a4f1db291931f167f6873fc652e --- /dev/null +++ b/docs/source/asr/data/scores/en/conformer_en.csv @@ -0,0 +1,28 @@ +Model Name,Language,EuroParl Test Set (en),Fisher Test Set (en),Librispeech Dev-Clean,Librispeech Dev-Other,Librispeech Test-Clean,Librispeech Test-Other,MCV Test-Set v11.0 (en),MCV Test-Set v8.0 (en),MLS Dev (en),MLS Test (en),NSC Part1,NSC Part6,Peoples Speech Test v1,SLR 83 Test,SPGI Test,VoxPopuli Test (en),WSJ Dev 93,WSJ Eval 92 +stt_en_conformer_ctc_small,en,,,3.6,8.1,3.7,8.1,,,,,,,,,,,, +stt_en_conformer_ctc_medium,en,,,2.5,5.8,2.6,5.9,,,,,,,,,,,, +stt_en_conformer_ctc_large,en,,,1.9,4.4,2.1,4.5,,,,,,,,,,,, +stt_en_conformer_ctc_xlarge,en,,,1.77 %,3.79 %,2.00 %,3.74 %,,7.88 %,,5.99 %,,6.44 %,22.90 %,5.50 %,,,2.36 %, +stt_en_conformer_ctc_small_ls,en,,,3.3,8.8,3.4,8.8,,,,,,,,,,,, +stt_en_conformer_ctc_medium_ls,en,,,2.7,7.4,3.0,7.3,,,,,,,,,,,, +stt_en_conformer_ctc_large_ls,en,,,2.4,6.2,2.7,6.0,,,,,,,,,,,, +stt_en_conformer_transducer_small,en,,,2.8,6.6,2.5,6.6,,,,,,,,,,,, +stt_en_conformer_transducer_medium,en,,,2.0,4.6,2.1,4.7,,,,,,,,,,,, +stt_en_conformer_transducer_large,en,,,1.6,3.5,1.7,3.7,,,,,,,,,,,, +stt_en_conformer_transducer_large_ls,en,,,2.1,5.0,2.3,5.1,,,,,,,,,,,, +stt_en_conformer_transducer_xlarge,en,,,1.48 %,2.95 %,1.62 %,3.01 %,,6.46 %,4.59 %,5.32 %,5.70 %,6.47 %,21.32 %,,,,2.05 %,1.17 % +stt_en_conformer_transducer_xxlarge,en,,,1.52 %,3.09 %,1.72 %,3.14 %,,,5.29 %,5.85 %,6.64 %,,,,,,2.42 %,1.49 % +stt_en_fastconformer_hybrid_large_streaming_80ms (CTC),en,,,,,3.5 %,8.1 %,,,10.2 %,7.2 %,,,,,,,3.5 %,2.3 % +stt_en_fastconformer_hybrid_large_streaming_480ms (CTC),en,,,,,3.6 %,7.5 %,,,9.8 %,7.0 %,,,,,,,3.5 %,2.1 % +stt_en_fastconformer_hybrid_large_streaming_1040ms (CTC),en,,,,,2.7 %,6.4 %,,,9.0 %,7.0 %,,,,,,,3.2 %,1.9 % +stt_en_fastconformer_hybrid_large_streaming_80ms (RNNT),en,,,,,2.7 %,6.5 %,,,9.1 %,6.9 %,,,,,,,3.2 %,1.9 % +stt_en_fastconformer_hybrid_large_streaming_480ms (RNNT),en,,,,,2.7 %,6.1 %,,,8.5 %,6.7 %,,,,,,,3.1 %,1.8 % +stt_en_fastconformer_hybrid_large_streaming_1040ms (RNNT),en,,,,,2.3 %,5.5 %,,,8.0 %,6.6 %,,,,,,,2.9 %,1.6 % +stt_en_fastconformer_hybrid_large_streaming_multi (RNNT - 0ms),en,,,,,,7.0 %,,,,,,,,,,,, +stt_en_fastconformer_hybrid_large_streaming_multi (RNNT - 80ms),en,,,,,,6.4 %,,,,,,,,,,,, +stt_en_fastconformer_hybrid_large_streaming_multi (RNNT - 480),en,,,,,,5.7 %,,,,,,,,,,,, +stt_en_fastconformer_hybrid_large_streaming_multi (RNNT - 1040),en,,,,,,5.4 %,,,,,,,,,,,, +stt_en_fastconformer_hybrid_large_streaming_multi (CTC - 0ms),en,,,,,,8.4 %,,,,,,,,,,,, +stt_en_fastconformer_hybrid_large_streaming_multi (CTC - 80ms),en,,,,,,7.8 %,,,,,,,,,,,, +stt_en_fastconformer_hybrid_large_streaming_multi (CTC - 480),en,,,,,,6.7 %,,,,,,,,,,,, +stt_en_fastconformer_hybrid_large_streaming_multi (CTC - 1040),en,,,,,,6.2 %,,,,,,,,,,,, diff --git a/docs/source/asr/data/scores/en/fastconformer_en.csv b/docs/source/asr/data/scores/en/fastconformer_en.csv new file mode 100644 index 0000000000000000000000000000000000000000..e993273dfbf42a2aceae5c3a5938fd6f97aa58fa --- /dev/null +++ b/docs/source/asr/data/scores/en/fastconformer_en.csv @@ -0,0 +1,4 @@ +Model Name,Language,EuroParl Test Set (en),Fisher Test Set (en),Librispeech Dev-Clean,Librispeech Dev-Other,Librispeech Test-Clean,Librispeech Test-Other,MCV Test-Set v11.0 (en),MCV Test-Set v8.0 (en),MLS Dev (en),MLS Test (en),NSC Part1,NSC Part6,Peoples Speech Test v1,SLR 83 Test,SPGI Test,VoxPopuli Test (en),WSJ Dev 93,WSJ Eval 92 +stt_en_fastconformer_ctc_large,en,,,1.9,4.2,2.1,4.2,,,,,,,,,,,, +stt_en_fastconformer_transducer_large,en,,,2.0,3.8,1.8,3.8,,,,,,,,,,,, +stt_en_fastconformer_hybrid_large_pc,en,8.0 %,10.3 %,,,2.0 %,4.1 %,8.2 %,,,4.5 %,4.6 %,,,,2.3 %,4.5 %,, diff --git a/docs/source/asr/data/scores/enes/conformer_enes.csv b/docs/source/asr/data/scores/enes/conformer_enes.csv new file mode 100644 index 0000000000000000000000000000000000000000..983e664d4de1b60053cb43a039b0c4ceafe10a00 --- /dev/null +++ b/docs/source/asr/data/scores/enes/conformer_enes.csv @@ -0,0 +1,5 @@ +Model Name,Language,Fisher-Dev-En,Fisher-Dev-Es,Fisher-Test-En,Fisher-Test-Es,Librispeech Dev-Clean,Librispeech Dev-Other,Librispeech Test-Clean,Librispeech Test-Other,MCV Dev-Set v7.0 (en),MCV Dev-Set v7.0 (es),MCV Test-Set v7.0 (en),MCV Test-Set v7.0 (es),MLS Dev (en),MLS Dev (es),MLS Test (en),MLS Test (es),VoxPopuli Dev (en),VoxPopuli Dev (es),VoxPopuli Test (en),VoxPopuli Test (es) +stt_enes_conformer_ctc_large,enes,,16.7 %,,,2.2 %,5.5 %,2.6 %,5.5 %,5.8 %,,,,,3.5 %,,,,5.7 %,, +stt_enes_conformer_ctc_large_codesw,enes,,16.51 %,,16.31 %,2.22 %,5.36 %,2.55 %,5.38 %,,5.00 %,,5.51 %,,3.46 %,,3.73 %,,5.58 %,,6.63 % +stt_enes_conformer_transducer_large,enes,,16.2 %,,,2.0 %,4.6 %,2.2 %,4.6 %,5.0 %,,,,,3.3 %,,,,5.3 %,, +stt_enes_conformer_transducer_large_codesw,enes,15.70 %,,15.66 %,,1.97 %,4.54 %,2.17 %,4.53 %,4.51 %,,5.06 %,,3.27 %,,3.67 %,,5.28 %,,6.54 %, diff --git a/docs/source/asr/data/scores/eo/conformer_eo.csv b/docs/source/asr/data/scores/eo/conformer_eo.csv new file mode 100644 index 0000000000000000000000000000000000000000..f77d4c0eadfcc5d7b954a06df2036cfbbcf50f3d --- /dev/null +++ b/docs/source/asr/data/scores/eo/conformer_eo.csv @@ -0,0 +1,3 @@ +Model Name,Language,MCV Dev-Set v11.0 (eo),MCV Test-Set v11.0 (eo) +stt_eo_conformer_ctc_large,eo,2.9 %,4.8 % +stt_eo_conformer_transducer_large,eo,2.4 %,4.0 % diff --git a/docs/source/asr/data/scores/es/conformer_es.csv b/docs/source/asr/data/scores/es/conformer_es.csv new file mode 100644 index 0000000000000000000000000000000000000000..e7e47cbdc068e6361ac511e43b83b9a306c5ea3c --- /dev/null +++ b/docs/source/asr/data/scores/es/conformer_es.csv @@ -0,0 +1,3 @@ +Model Name,Language,Call Home Dev Test (es),Call Home Eval Test (es),Call Home Train (es),Fisher Dev Set (es),Fisher Test Set (es),MCV Dev-Set (v??) (es),MCV Dev-Set v12.0 (es),MCV Dev-Set v7.0 (es),MCV Test-Set (v??) (es),MCV Test-Set v12.0 (es),MCV Test-Set v7.0 (es),MLS Dev (en),MLS Test (en),VoxPopuli Dev (es),VoxPopuli Test (es) +stt_es_conformer_ctc_large,es,23.7 %,25.3 %,22.4 %,18.3 %,18.5 %,,,6.3 %,,,6.9 %,4.3 %,4.2 %,6.1 %,7.5 % +stt_es_conformer_transducer_large,es,18.0 %,19.4 %,17.2 %,14.7 %,14.8 %,,,4.6 %,,,5.2 %,2.7 %,3.2 %,4.7 %,6.0 % diff --git a/docs/source/asr/data/scores/es/fastconformer_es.csv b/docs/source/asr/data/scores/es/fastconformer_es.csv new file mode 100644 index 0000000000000000000000000000000000000000..a6c12afe95e1f7cf42d6090d80805c13ac038881 --- /dev/null +++ b/docs/source/asr/data/scores/es/fastconformer_es.csv @@ -0,0 +1,2 @@ +Model Name,Language,Call Home Dev Test (es),Call Home Eval Test (es),Call Home Train (es),Fisher Dev Set (es),Fisher Test Set (es),MCV Dev-Set (v??) (es),MCV Dev-Set v12.0 (es),MCV Dev-Set v7.0 (es),MCV Test-Set (v??) (es),MCV Test-Set v12.0 (es),MCV Test-Set v7.0 (es),MLS Dev (en),MLS Test (en),VoxPopuli Dev (es),VoxPopuli Test (es) +stt_es_fastconformer_hybrid_large_pc,es,,,,29.4 %,28.9 %,,7.1 %,,,7.5 %,,10.6 %,11.8 %,8.6 %,9.8 % diff --git a/docs/source/asr/data/scores/fr/conformer_fr.csv b/docs/source/asr/data/scores/fr/conformer_fr.csv new file mode 100644 index 0000000000000000000000000000000000000000..8f74dfe8cae047091e8c7f6081dcc24aca37df10 --- /dev/null +++ b/docs/source/asr/data/scores/fr/conformer_fr.csv @@ -0,0 +1,3 @@ +Model Name,Language,MCV Dev-Set (v??) (fr),MCV Dev-Set v7.0 (fr),MCV Dev-Set v7.0 (fr) (No Hyphen),MCV Test-Set v7.0 (fr),MCV Test-Set v7.0 (fr) (No Hyphen),MLS Dev (en),MLS Dev (en) (No Hyphen),MLS Test (en),MLS Test (en) (No Hyphen) +stt_fr_conformer_ctc_large,fr,,8.35,7.88,9.63,9.01,5.88,5.90,4.91,4.63 +stt_fr_conformer_transducer_large,fr,,6.85,,7.95,,5.05,,4.10, diff --git a/docs/source/asr/data/scores/hr/conformer_hr.csv b/docs/source/asr/data/scores/hr/conformer_hr.csv new file mode 100644 index 0000000000000000000000000000000000000000..4cfd3f79a89fd55cfdfc964b2b8dd82f34cb978b --- /dev/null +++ b/docs/source/asr/data/scores/hr/conformer_hr.csv @@ -0,0 +1,3 @@ +Model Name,Language,ParlaSpeech Dev-Set v1.0 (hr),ParlaSpeech Test-Set v1.0 (hr),Parlaspeech Dev-Set (v??) (hr),Parlaspeech Test-Set (v??) (hr) +stt_hr_conformer_ctc_large,hr,4.43,4.70,, +stt_hr_conformer_transducer_large,hr,4.56,4.69,, diff --git a/docs/source/asr/data/scores/hr/fastconformer_hr.csv b/docs/source/asr/data/scores/hr/fastconformer_hr.csv new file mode 100644 index 0000000000000000000000000000000000000000..ee54e981e7aa3763a795ba74483e027e405a27d1 --- /dev/null +++ b/docs/source/asr/data/scores/hr/fastconformer_hr.csv @@ -0,0 +1,2 @@ +Model Name,Language,ParlaSpeech Dev-Set v1.0 (hr),ParlaSpeech Test-Set v1.0 (hr),Parlaspeech Dev-Set (v??) (hr),Parlaspeech Test-Set (v??) (hr) +stt_hr_fastconformer_hybrid_large_pc,hr,,,4.5 %,4.2 % diff --git a/docs/source/asr/data/scores/it/conformer_it.csv b/docs/source/asr/data/scores/it/conformer_it.csv new file mode 100644 index 0000000000000000000000000000000000000000..c86a906e982ceac07cfab57c747aab174bcba327 --- /dev/null +++ b/docs/source/asr/data/scores/it/conformer_it.csv @@ -0,0 +1,3 @@ +Model Name,Language,MCV Dev-Set (v??) (it),MCV Dev-Set v11.0 (it),MCV Dev-Set v12.0 (it),MCV Test-Set v11.0 (it),MCV Test-Set v12.0 (it),MLS Dev (en),MLS Test (en),VoxPopuli Dev (it),VoxPopuli Test (it) +stt_it_conformer_ctc_large,it,,5.38,,5.92,,13.16,10.62,13.43,16.75 +stt_it_conformer_transducer_large,it,,4.80,,5.24,,14.62,12.18,12.00,15.15 diff --git a/docs/source/asr/data/scores/it/fastconformer_it.csv b/docs/source/asr/data/scores/it/fastconformer_it.csv new file mode 100644 index 0000000000000000000000000000000000000000..3a684662295e60377ca7db25f57ba66c42805eb7 --- /dev/null +++ b/docs/source/asr/data/scores/it/fastconformer_it.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Dev-Set (v??) (it),MCV Dev-Set v11.0 (it),MCV Dev-Set v12.0 (it),MCV Test-Set v11.0 (it),MCV Test-Set v12.0 (it),MLS Dev (en),MLS Test (en),VoxPopuli Dev (it),VoxPopuli Test (it) +stt_it_fastconformer_hybrid_large_pc,it,,,5.2 %,,5.8 %,13.6 %,11.5 %,12.7 %,15.6 % diff --git a/docs/source/asr/data/scores/kab/conformer_kab.csv b/docs/source/asr/data/scores/kab/conformer_kab.csv new file mode 100644 index 0000000000000000000000000000000000000000..9db989dc23778d02a380c391f9c78c7b0b0694a8 --- /dev/null +++ b/docs/source/asr/data/scores/kab/conformer_kab.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Test-Set v10.0 (kab) +stt_kab_conformer_transducer_large,kab,18.86 diff --git a/docs/source/asr/data/scores/nl/fastconformer_nl.csv b/docs/source/asr/data/scores/nl/fastconformer_nl.csv new file mode 100644 index 0000000000000000000000000000000000000000..a0f2d61b0a9bc8e2d55070aecde6163f3c13e95c --- /dev/null +++ b/docs/source/asr/data/scores/nl/fastconformer_nl.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Test-Set v12.0 (nl),MLS Test (nl) +stt_nl_fastconformer_hybrid_large_pc,nl,9.2 %,12.1 % \ No newline at end of file diff --git a/docs/source/asr/data/scores/pl/fastconformer_pl.csv b/docs/source/asr/data/scores/pl/fastconformer_pl.csv new file mode 100644 index 0000000000000000000000000000000000000000..8cf9a506b70468c59b03c7194ae0eb46f44fbf70 --- /dev/null +++ b/docs/source/asr/data/scores/pl/fastconformer_pl.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Dev-Set (v??) (pl),MCV Dev-Set v12.0 (pl),MCV Test-Set v12.0 (pl),MLS Dev (en),MLS Test (en),VoxPopuli Dev (pl),VoxPopuli Test (pl) +stt_pl_fastconformer_hybrid_large_pc,pl,,6.0 %,8.7 %,7.1 %,5.8 %,11.3 %,8.5 % diff --git a/docs/source/asr/data/scores/ru/conformer_ru.csv b/docs/source/asr/data/scores/ru/conformer_ru.csv new file mode 100644 index 0000000000000000000000000000000000000000..a4f2c20a2726a8cd55a79578edf4497dee88838b --- /dev/null +++ b/docs/source/asr/data/scores/ru/conformer_ru.csv @@ -0,0 +1,3 @@ +Model Name,Language,GOLOS Crowd Test-Set (v??) (ru),GOLOS Farfield Test-Set (v??) (ru),Librispeech Test,MCV Dev-Set (v??) (ru),MCV Dev-Set v10.0 (ru),MCV Test-Set v10.0 (ru) +stt_ru_conformer_ctc_large,ru,2.8 %,7.1 %,13.5 %,,3.9 %,4.3 % +stt_ru_conformer_transducer_large,ru,2.7%,7.6%,12.0%,,3.5%,4.0% diff --git a/docs/source/asr/data/scores/rw/conformer_rw.csv b/docs/source/asr/data/scores/rw/conformer_rw.csv new file mode 100644 index 0000000000000000000000000000000000000000..e5544a8067d55fc7d9753391e7dfefa90cca5336 --- /dev/null +++ b/docs/source/asr/data/scores/rw/conformer_rw.csv @@ -0,0 +1,3 @@ +Model Name,Language,MCV Test-Set v9.0 (rw) +stt_rw_conformer_ctc_large,rw,18.2 % +stt_rw_conformer_transducer_large,rw,16.2 % diff --git a/docs/source/asr/data/scores/ua/fastconformer_ua.csv b/docs/source/asr/data/scores/ua/fastconformer_ua.csv new file mode 100644 index 0000000000000000000000000000000000000000..c325a73c5f53647a416841fc0b83422736362e7d --- /dev/null +++ b/docs/source/asr/data/scores/ua/fastconformer_ua.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Test-Set v12.0 (ua) +stt_ua_fastconformer_hybrid_large_pc,ua,5.2 % diff --git a/docs/source/asr/data/scores/zh/conformer_zh.csv b/docs/source/asr/data/scores/zh/conformer_zh.csv new file mode 100644 index 0000000000000000000000000000000000000000..8d0ef96dc8d9d7766eb13fc7c6d08717c129132a --- /dev/null +++ b/docs/source/asr/data/scores/zh/conformer_zh.csv @@ -0,0 +1,2 @@ +Model Name,Language,AIShell Dev-Android v2,AIShell Dev-Ios v1,AIShell Dev-Ios v2,AIShell Dev-Mic v2,AIShell Test-Android v2,AIShell Test-Ios v1,AIShell Test-Ios v2,AIShell Test-Mic v2 +stt_zh_conformer_transducer_large,zh,3.4,,3.2,3.4,3.4,,3.2,3.4 diff --git a/docs/source/asr/data/scores_pc/by/fastconformer_by.csv b/docs/source/asr/data/scores_pc/by/fastconformer_by.csv new file mode 100644 index 0000000000000000000000000000000000000000..88f5e320f088545ee617f8a1be399ff583b1e9e6 --- /dev/null +++ b/docs/source/asr/data/scores_pc/by/fastconformer_by.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Dev-Set v12.0 (be),MCV Test-Set v12.0 (be) +stt_by_fastconformer_hybrid_large_pc,by,3.8 %,3.9 % diff --git a/docs/source/asr/data/scores_pc/de/fastconformer_de.csv b/docs/source/asr/data/scores_pc/de/fastconformer_de.csv new file mode 100644 index 0000000000000000000000000000000000000000..f862289184600b29ad00eed52a8357273fe122e9 --- /dev/null +++ b/docs/source/asr/data/scores_pc/de/fastconformer_de.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Dev-Set v12.0 (de),MCV Test-Set v12.0 (de),MLS Dev (en),MLS Test (en),VoxPopuli Dev (de),VoxPopuli Test (de) +stt_de_fastconformer_hybrid_large_pc,de,4.7 %,5.4 %,10.1 %,11.1 %,12.6 %,10.4 % diff --git a/docs/source/asr/data/scores_pc/en/fastconformer_en.csv b/docs/source/asr/data/scores_pc/en/fastconformer_en.csv new file mode 100644 index 0000000000000000000000000000000000000000..9495643af30df3c2fdd4e37fb4d71add382e4bfb --- /dev/null +++ b/docs/source/asr/data/scores_pc/en/fastconformer_en.csv @@ -0,0 +1,2 @@ +Model Name,Language,EuroParl Test Set (en),Fisher Test Set (en),Librispeech Test-Clean,Librispeech Test-Other,MCV Test-Set v11.0 (en),MLS Test (en),NSC Part1,SPGI Test,VoxPopuli Test (en) +stt_en_fastconformer_hybrid_large_pc,en,12.5 %,19.0 %,7.3 %,9.2 %,10.1 %,12.7 %,7.2 %,5.1 %,6.7 % diff --git a/docs/source/asr/data/scores_pc/es/fastconformer_es.csv b/docs/source/asr/data/scores_pc/es/fastconformer_es.csv new file mode 100644 index 0000000000000000000000000000000000000000..501771865ed8495b9f90d524222e08ebf0ab3a65 --- /dev/null +++ b/docs/source/asr/data/scores_pc/es/fastconformer_es.csv @@ -0,0 +1,2 @@ +Model Name,Language,Fisher Dev Set (es),Fisher Test Set (es),MCV Dev-Set v12.0 (es),MCV Test-Set v12.0 (es),MLS Dev (en),MLS Test (en),VoxPopuli Dev (es),VoxPopuli Test (es) +stt_es_fastconformer_hybrid_large_pc,es,14.7 %,14.6 %,4.5 %,5.0 %,3.1 %,3.9 %,4.4 %,5.6 % diff --git a/docs/source/asr/data/scores_pc/hr/fastconformer_hr.csv b/docs/source/asr/data/scores_pc/hr/fastconformer_hr.csv new file mode 100644 index 0000000000000000000000000000000000000000..3c024c09f329d2aa2f3bff642aca1e10140681aa --- /dev/null +++ b/docs/source/asr/data/scores_pc/hr/fastconformer_hr.csv @@ -0,0 +1,2 @@ +Model Name,Language,Parlaspeech Dev-Set (v??) (hr),Parlaspeech Test-Set (v??) (hr) +stt_hr_fastconformer_hybrid_large_pc,hr,10.4 %,8.7 % diff --git a/docs/source/asr/data/scores_pc/it/fastconformer_it.csv b/docs/source/asr/data/scores_pc/it/fastconformer_it.csv new file mode 100644 index 0000000000000000000000000000000000000000..6bcf2c0b44001ec8c2f00638aec85a400e782d2c --- /dev/null +++ b/docs/source/asr/data/scores_pc/it/fastconformer_it.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Dev-Set v12.0 (it),MCV Test-Set v12.0 (it),MLS Dev (en),MLS Test (en),VoxPopuli Dev (it),VoxPopuli Test (it) +stt_it_fastconformer_hybrid_large_pc,it,7.8 %,8.2 %,26.4 %,22.5 %,16.8 %,19.6 % diff --git a/docs/source/asr/data/scores_pc/nl/fastconformer_nl.csv b/docs/source/asr/data/scores_pc/nl/fastconformer_nl.csv new file mode 100644 index 0000000000000000000000000000000000000000..8faf0d52f9ff1b84591e55c546cc6b616a2f496f --- /dev/null +++ b/docs/source/asr/data/scores_pc/nl/fastconformer_nl.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Test-Set v12.0 (nl),MLS Test (nl) +stt_nl_fastconformer_hybrid_large_pc,nl,32.1 %,25.1 % \ No newline at end of file diff --git a/docs/source/asr/data/scores_pc/pl/fastconformer_pl.csv b/docs/source/asr/data/scores_pc/pl/fastconformer_pl.csv new file mode 100644 index 0000000000000000000000000000000000000000..5cbadae40b599924eab259da979d7a368e426925 --- /dev/null +++ b/docs/source/asr/data/scores_pc/pl/fastconformer_pl.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Dev-Set v12.0 (pl),MCV Test-Set v12.0 (pl),MLS Dev (en),MLS Test (en),VoxPopuli Dev (pl),VoxPopuli Test (pl) +stt_pl_fastconformer_hybrid_large_pc,pl,8.9 %,11.0 %,16.0 %,11.0 %,14.0 %,11.4 % diff --git a/docs/source/asr/data/scores_pc/ua/fastconformer_ua.csv b/docs/source/asr/data/scores_pc/ua/fastconformer_ua.csv new file mode 100644 index 0000000000000000000000000000000000000000..b486fa23aeb3bea1186976515a488b5a38a9bac1 --- /dev/null +++ b/docs/source/asr/data/scores_pc/ua/fastconformer_ua.csv @@ -0,0 +1,2 @@ +Model Name,Language,MCV Test-Set v12.0 (ua) +stt_ua_fastconformer_hybrid_large_pc,ua,7.3 % diff --git a/docs/source/asr/datasets.rst b/docs/source/asr/datasets.rst new file mode 100644 index 0000000000000000000000000000000000000000..edf4205fd78ad40f0969e8ebaffaf074602cc35f --- /dev/null +++ b/docs/source/asr/datasets.rst @@ -0,0 +1,1222 @@ +Datasets +======== + +NeMo has scripts to convert several common ASR datasets into the format expected by the ``nemo_asr`` collection. You can get started +with those datasets by following the instructions to run those scripts in the section appropriate to each dataset below. + +If the user has their own data and want to preprocess it to use with NeMo ASR models, refer to the `Preparing Custom ASR Data`_ section. + +If the user already has a dataset that you want to convert to a tarred format, refer to the :ref:`Tarred Datasets ` section. + +.. _LibriSpeech_dataset: + +LibriSpeech +----------- + +Run the following scripts to download the LibriSpeech data and convert it into the format expected by `nemo_asr`. At least 250GB free +space is required. + +.. code-block:: bash + + # install sox + sudo apt-get install sox + mkdir data + python get_librispeech_data.py --data_root=data --data_set=ALL + +After this, the ``data`` folder should contain wav files and ``.json`` manifests for NeMo ASR datalayer. + +Each line is a training example. ``audio_filepath`` contains the path to the wav file, ``duration`` is the duration in seconds, and ``text`` is the transcript: + +.. code-block:: json + + {"audio_filepath": "/1355-39947-0000.wav", "duration": 11.3, "text": "psychotherapy and the community both the physician and the patient find their place in the community the life interests of which are superior to the interests of the individual"} + {"audio_filepath": "/1355-39947-0001.wav", "duration": 15.905, "text": "it is an unavoidable question how far from the higher point of view of the social mind the psychotherapeutic efforts should be encouraged or suppressed are there any conditions which suggest suspicion of or direct opposition to such curative work"} + +Fisher English Training Speech +------------------------------ + +Run these scripts to convert the Fisher English Training Speech data into a format expected by the ``nemo_asr`` collection. + +In brief, the following scripts convert the ``.sph`` files to ``.wav``, slices those files into smaller audio samples, matches the +smaller slices with their corresponding transcripts, and splits the resulting audio segments into train, validation, and test sets +(with one manifest each). + +.. note:: + - 106 GB of space is required to run the ``.wav`` conversion + - additional 105 GB is required for the slicing and matching + - ``sph2pipe`` is required in order to run the ``.wav`` conversion + +**Instructions** + +The following scripts assume that you already have the Fisher dataset from the Linguistic Data Consortium, with a directory structure +that looks similar to the following: + +.. code-block:: bash + + FisherEnglishTrainingSpeech/ + ├── LDC2004S13-Part1 + │   ├── fe_03_p1_transcripts + │   ├── fisher_eng_tr_sp_d1 + │   ├── fisher_eng_tr_sp_d2 + │   ├── fisher_eng_tr_sp_d3 + │   └── ... + └── LDC2005S13-Part2 + ├── fe_03_p2_transcripts + ├── fe_03_p2_sph1 + ├── fe_03_p2_sph2 + ├── fe_03_p2_sph3 + └── ... + +The transcripts that will be used are located in the ``fe_03_p<1,2>_transcripts/data/trans`` directory. The audio files (``.sph``) +are located in the remaining directories in an ``audio`` subdirectory. + +#. Convert the audio files from ``.sph`` to ``.wav`` by running: + + .. code-block:: bash + + cd /scripts/dataset_processing + python fisher_audio_to_wav.py \ + --data_root= --dest_root= + + This will place the unsliced ``.wav`` files in ``/LDC200[4,5]S13-Part[1,2]/audio-wav/``. It will take several + minutes to run. + +#. Process the transcripts and slice the audio data. + + .. code-block:: bash + + python process_fisher_data.py \ + --audio_root= --transcript_root= \ + --dest_root= \ + --remove_noises + + This script splits the full dataset into train, validation, test sets, and places the audio slices in the corresponding folders + in the destination directory. One manifest is written out per set, which includes each slice's transcript, duration, and path. + + This will likely take around 20 minutes to run. Once finished, delete the 10 minute long ``.wav`` files. + +2000 HUB5 English Evaluation Speech +----------------------------------- + +Run the following script to convert the HUB5 data into a format expected by the ``nemo_asr`` collection. + +Similarly, to the Fisher dataset processing scripts, this script converts the ``.sph`` files to ``.wav``, slices the audio files and +transcripts into utterances, and combines them into segments of some minimum length (default is 10 seconds). The resulting segments +are all written out to an audio directory and the corresponding transcripts are written to a manifest JSON file. + +.. note:: + - 5 GB of free space is required to run this script + - ``sph2pipe`` is also required to be installed + +This script assumes you already have the 2000 HUB5 dataset from the Linguistic Data Consortium. + +Run the following command to process the 2000 HUB5 English Evaluation Speech samples: + +.. code-block:: bash + + python process_hub5_data.py \ + --data_root= \ + --dest_root= + +You can optionally include ``--min_slice_duration=`` if you would like to change the minimum audio segment duration. + +AN4 Dataset +----------- + +This is a small dataset recorded and distributed by Carnegie Mellon University. It consists of recordings of people spelling out +addresses, names, etc. + +#. `Download and extract the dataset `_ (which is labeled "NIST's Sphere audio (.sph) format (64M)". + +#. Convert the ``.sph`` files to ``.wav`` using sox, and build one training and one test manifest. + + .. code-block:: bash + + python process_an4_data.py --data_root= + +After the script finishes, the ``train_manifest.json`` and ``test_manifest.json`` can be found in the ``/an4/`` directory. + +Aishell-1 +--------- + +To download the Aishell-1 data and convert it into a format expected by ``nemo_asr``, run: + +.. code-block:: bash + + # install sox + sudo apt-get install sox + mkdir data + python get_aishell_data.py --data_root=data + +After the script finishes, the ``data`` folder should contain a ``data_aishell`` folder which contains a wav file, a transcript folder, and related ``.json`` and ``vocab.txt`` files. + +Aishell-2 +--------- + +To process the AIShell-2 dataset, in the command below, set the data folder of AIShell-2 using ``--audio_folder`` and where to push +these files using ``--dest_folder``. In order to generate files in the supported format of ``nemo_asr``, run: + +.. code-block:: bash + + python process_aishell2_data.py --audio_folder= --dest_folder= + +After the script finishes, the ``train.json``, ``dev.json``, ``test.json``, and ``vocab.txt`` files can be found in the ``dest_folder`` directory. + +.. _section-with-manifest-format-explanation: + +Preparing Custom ASR Data +------------------------- + +The ``nemo_asr`` collection expects each dataset to consist of a set of utterances in individual audio files plus +a manifest that describes the dataset, with information about one utterance per line (``.json``). +The audio files can be of any format supported by `Pydub `_, though we recommend +WAV files as they are the default and have been most thoroughly tested. + +There should be one manifest file per dataset that will be passed in, therefore, if the user wants separate training and validation +datasets, they should also have separate manifests. Otherwise, they will be loading validation data with their training data and vice +versa. + +Each line of the manifest should be in the following format: + +.. code-block:: json + + {"audio_filepath": "/path/to/audio.wav", "text": "the transcription of the utterance", "duration": 23.147} + +The :code:`audio_filepath` field should provide an absolute path to the ``.wav`` file corresponding to the utterance. +The :code:`text` field should contain the full transcript for the utterance, and the :code:`duration` field should +reflect the duration of the utterance in seconds. + +Each entry in the manifest (describing one audio file) should be bordered by '{' and '}' and must +be contained on one line. The fields that describe the file should be separated by commas, and have the form :code:`"field_name": value`, +as shown above. There should be no extra lines in the manifest, i.e. there should be exactly as many lines in the manifest as +there are audio files in the dataset. + +Since the manifest specifies the path for each utterance, the audio files do not have to be located +in the same directory as the manifest, or even in any specific directory structure. + +Once there is a manifest that describes each audio file in the dataset, use the dataset by passing +in the manifest file path in the experiment config file, e.g. as ``training_ds.manifest_filepath=``. + +.. _Tarred_Datasets: + +Tarred Datasets +--------------- + +If experiments are run on a cluster with datasets stored on a distributed file system, the user will likely +want to avoid constantly reading multiple small files and would prefer tarring their audio files. +There are tarred versions of some NeMo ASR dataset classes for this case, such as the ``TarredAudioToCharDataset`` +(corresponding to the ``AudioToCharDataset``) and the ``TarredAudioToBPEDataset`` (corresponding to the +``AudioToBPEDataset``). The tarred audio dataset classes in NeMo use `WebDataset `_. + +To use an existing tarred dataset instead of a non-tarred dataset, set ``is_tarred: true`` in +the experiment config file. Then, pass in the paths to all of the audio tarballs in ``tarred_audio_filepaths``, either as a list +of filepaths, e.g. ``['/data/shard1.tar', '/data/shard2.tar']``, or in a single brace-expandable string, e.g. +``'/data/shard_{1..64}.tar'`` or ``'/data/shard__OP_1..64_CL_'`` (recommended, see note below). + +.. note:: + For brace expansion, there may be cases where ``{x..y}`` syntax cannot be used due to shell interference. This occurs most commonly + inside SLURM scripts. Therefore, we provide a few equivalent replacements. Supported opening braces (equivalent to ``{``) are ``(``, + ``[``, ``<`` and the special tag ``_OP_``. Supported closing braces (equivalent to ``}``) are ``)``, ``]``, ``>`` and the special + tag ``_CL_``. For SLURM based tasks, we suggest the use of the special tags for ease of use. + +As with non-tarred datasets, the manifest file should be passed in ``manifest_filepath``. The dataloader assumes that the length +of the manifest after filtering is the correct size of the dataset for reporting training progress. + +The ``tarred_shard_strategy`` field of the config file can be set if you have multiple shards and are running an experiment with +multiple workers. It defaults to ``scatter``, which preallocates a set of shards per worker which do not change during runtime. +Note that this strategy, on specific occasions (when the number of shards is not divisible with ``world_size``), will not sample +the entire dataset. As an alternative the ``replicate`` strategy, will preallocate the entire set of shards to every worker and not +change it during runtime. The benefit of this strategy is that it allows each worker to sample data points from the entire dataset +independently of others. Note, though, that more than one worker may sample the same shard, and even sample the same data points! +As such, there is no assured guarantee that all samples in the dataset will be sampled at least once during 1 epoch. Note that +for these reasons it is not advisable to use tarred datasets as validation and test datasets. + +For more information about the individual tarred datasets and the parameters available, including shuffling options, +see the corresponding class APIs in the :ref:`Datasets ` section. + +.. warning:: + If using multiple workers, the number of shards should be divisible by the world size to ensure an even + split among workers. If it is not divisible, logging will give a warning but training will proceed, but likely hang at the last epoch. + In addition, if using distributed processing, each shard must have the same number of entries after filtering is + applied such that each worker ends up with the same number of files. We currently do not check for this in any dataloader, but the user's + program may hang if the shards are uneven. + +Sharded Manifests +~~~~~~~~~~~~~~~~~ +If your dataset / manifest is large, you may wish to use sharded manifest files instead of a single manifest file. The naming convention +is identical to the audio tarballs and there should be a 1:1 relationship between a sharded audio tarfile and its manifest shard; e.g. +``'/data/sharded_manifests/manifest__OP_1..64_CL_'`` in the above example. Using sharded manifests improves job startup times and +decreases memory usage, as each worker only loads manifest shards for the corresponding audio shards instead of the entire manifest. + +To enable sharded manifest filename expansion, set the ``shard_manifests`` field of the config file to true. In addition, the +``defer_setup`` flag needs to be true as well, so that the dataloader will be initialized after the DDP and its length can be collected from +the distributed workers. + +Batching strategies +--------------------- + +For training ASR models, audios with different lengths may be grouped into a batch. It would make it necessary to use paddings to make all the same length. +These extra paddings is a significant source of computation waste. + +Semi Sorted Batching +--------------------- + +Sorting samples by duration and spliting them into batches speeds up training, but can degrade the quality of the model. To avoid quality degradation and maintain some randomness in the partitioning process, we add pseudo noise to the sample length when sorting. + +It may result into training speedup of more than 40 percent with the same quality. To enable and use semi sorted batching add some lines in config. + + .. code:: + + ++model.train_ds.use_semi_sorted_batching=true + ++model.train_ds.randomization_factor=0.1 + +Semi sorted batching is supported by the following models: + + .. code:: + + nemo.collections.asr.models.EncDecCTCModel + nemo.collections.asr.models.EncDecCTCModelBPE + nemo.collections.asr.models.EncDecRNNTModel + nemo.collections.asr.models.EncDecRNNTBPEModel + nemo.collections.asr.models.EncDecHybridRNNTCTCModel + nemo.collections.asr.models.EncDecHybridRNNTCTCBPEModel + +For more details about this algorithm, see the `paper `_ . + +.. _Bucketing_Datasets: + +Bucketing Datasets +--------------------- + +Splitting the training samples into buckets with different lengths and sampling from the same bucket for each batch would increase the computation efficiency. +It may result into training speedup of more than 2X. To enable and use the bucketing feature, you need to create the bucketing version of the dataset by using `conversion script here `_. +You may use --buckets_num to specify the number of buckets (Recommend to use 4 to 8 buckets). It creates multiple tarred datasets, one per bucket, based on the audio durations. The range of [min_duration, max_duration) is split into equal sized buckets. + +To enable the bucketing feature in the dataset section of the config files, you need to pass the multiple tarred datasets as a list of lists. +If user passes just a list of strings, then the datasets would simply get concatenated which would be different from bucketing. +Here is an example for 4 buckets and 512 shards: + +.. code:: + + python speech_to_text_bpe.py + ... + model.train_ds.manifest_filepath=[[PATH_TO_TARS/bucket1/tarred_audio_manifest.json], + [PATH_TO_TARS/bucket2/tarred_audio_manifest.json], + [PATH_TO_TARS/bucket3/tarred_audio_manifest.json], + [PATH_TO_TARS/bucket4/tarred_audio_manifest.json]] + model.train_ds.tarred_audio_filepaths=[[PATH_TO_TARS/bucket1/audio__OP_0..511_CL_.tar], + [PATH_TO_TARS/bucket2/audio__OP_0..511_CL_.tar], + [PATH_TO_TARS/bucket3/audio__OP_0..511_CL_.tar], + [PATH_TO_TARS/bucket4/audio__OP_0..511_CL_.tar]] + +When bucketing is enabled, in each epoch, first all GPUs would use the first bucket, then go to the second bucket, and so on. It guarantees that all GPUs are using the same bucket at the same time. It reduces the number of paddings in each batch and speedup the training significantly without hurting the accuracy significantly. + +There are two types of batching: + +* Fixed-size bucketing: all batches would have the same number of samples specified by train_ds.batch_size +* Adaptive-size bucketing: uses different batch sizes for each bucket. + +Adaptive-size bucketing helps to increase the GPU utilization and speedup the training. +Batches sampled from buckets with smaller audio lengths can be larger which would increase the GPU utilization and speedup the training. +You may use train_ds.bucketing_batch_size to enable the adaptive batching and specify the batch sizes for the buckets. +When bucketing_batch_size is not set, train_ds.batch_size is going to be used for all buckets (fixed-size bucketing). + +bucketing_batch_size can be set as an integer or a list of integers to explicitly specify the batch size for each bucket. +if bucketing_batch_size is set to be an integer, then linear scaling is being used to scale-up the batch sizes for batches with shorted audio size. For example, setting train_ds.bucketing_batch_size=8 for 4 buckets would use these sizes [32,24,16,8] for different buckets. +When bucketing_batch_size is set, train_ds.batch_size need to be set to 1. + +Training an ASR model on audios sorted based on length may affect the accuracy of the model. We introduced some strategies to mitigate it. +We support three types of bucketing strategies: + +* fixed_order: the same order of buckets are used for all epochs +* synced_randomized (default): each epoch would have a different order of buckets. Order of the buckets is shuffled every epoch. +* fully_randomized: similar to synced_randomized but each GPU has its own random order. So GPUs would not be synced. + +The parameter train_ds.bucketing_strategy can be set to specify one of these strategies. The recommended strategy is synced_randomized which gives the highest training speedup. +The fully_randomized strategy would have lower speedup than synced_randomized but may give better accuracy. + +Bucketing may improve the training speed more than 2x but may affect the final accuracy of the model slightly. Training for more epochs and using 'synced_randomized' strategy help to fill this gap. +Currently bucketing feature is just supported for tarred datasets. + + +Conversion to Tarred Datasets +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can easily convert your existing NeMo-compatible ASR datasets using the +`conversion script here `_. + +.. code:: bash + + python convert_to_tarred_audio_dataset.py \ + --manifest_path= \ + --target_dir= \ + --num_shards= + --max_duration= \ + --min_duration= \ + --shuffle --shuffle_seed=0 + +This script shuffles the entries in the given manifest (if ``--shuffle`` is set, which we recommend), filter +audio files according to ``min_duration`` and ``max_duration``, and tar the remaining audio files to the directory +``--target_dir`` in ``n`` shards, along with separate manifest and metadata files. + +The files in the target directory should look similar to the following: + +.. code:: + + target_dir/ + ├── audio_1.tar + ├── audio_2.tar + ├── ... + ├── metadata.yaml + ├── tarred_audio_manifest.json + ├── sharded_manifests/ + ├── manifest_1.json + ├── ... + └── manifest_N.json + + +Note that file structures are flattened such that all audio files are at the top level in each tarball. This ensures that +filenames are unique in the tarred dataset and the filepaths do not contain "-sub" and forward slashes in each ``audio_filepath`` are +simply converted to underscores. For example, a manifest entry for ``/data/directory1/file.wav`` would be ``_data_directory1_file.wav`` +in the tarred dataset manifest, and ``/data/directory2/file.wav`` would be converted to ``_data_directory2_file.wav``. + +Sharded manifests are generated by default; this behavior can be toggled via the ``no_shard_manifests`` flag. + +Upsampling Datasets +------------------- + +Buckets may also be 'weighted' to allow multiple runs through a target dataset during each training epoch. This can be beneficial in cases when a dataset is composed of several component sets of unequal sizes and one desires to mitigate bias towards the larger sets through oversampling. + +Weighting is managed with the `bucketing_weights` parameter. After passing your composite tarred datasets in the format described above for bucketing, pass a list of integers (one per bucket) to indicate how many times a manifest should be read during training. + +For example, by passing `[2,1,1,3]` to the code below: + +.. code:: + + python speech_to_text_bpe.py + ... + model.train_ds.manifest_filepath=[[PATH_TO_TARS/bucket1/tarred_audio_manifest.json], + [PATH_TO_TARS/bucket2/tarred_audio_manifest.json], + [PATH_TO_TARS/bucket3/tarred_audio_manifest.json], + [PATH_TO_TARS/bucket4/tarred_audio_manifest.json]] + model.train_ds.tarred_audio_filepaths=[[PATH_TO_TARS/bucket1/audio__OP_0..511_CL_.tar], + [PATH_TO_TARS/bucket2/audio__OP_0..511_CL_.tar], + [PATH_TO_TARS/bucket3/audio__OP_0..511_CL_.tar], + [PATH_TO_TARS/bucket4/audio__OP_0..511_CL_.tar]] + ... + model.train_ds.bucketing_weights=[2,1,1,3] + +NeMo will configure training so that all data in `bucket1` will be present twice in a training epoch, `bucket4` will be present three times, and that of `bucket2` and `bucket3` will occur only once each. Note that this will increase the effective amount of data present during training and thus affect training time per epoch. + +If using adaptive bucketing, note that the same batch size will be assigned to each instance of the upsampled data. That is, given the following: + +.. code:: + + python speech_to_text_bpe.py + ... + model.train_ds.manifest_filepath=[[PATH_TO_TARS/bucket1/tarred_audio_manifest.json], + [PATH_TO_TARS/bucket2/tarred_audio_manifest.json], + [PATH_TO_TARS/bucket3/tarred_audio_manifest.json], + [PATH_TO_TARS/bucket4/tarred_audio_manifest.json]] + ... + ... + model.train_ds.bucketing_weights=[2,1,1,3] + model.train_ds.bucketing_batch_size=[4,4,4,2] + +All instances of data from `bucket4` will still be trained with a batch size of 2 while all others would have a batch size of 4. As with standard bucketing, this requires `batch_size`` to be set to 1. +If `bucketing_batch_size` is not specified, all datasets will be passed with the same fixed batch size as specified by the `batch_size` parameter. + +It is recommended to set bucketing strategies to `fully_randomized` during multi-GPU training to prevent possible dataset bias during training. + + +Datasets on AIStore +------------------- + +`AIStore `_ is an open-source lightweight object storage system focused on large-scale deep learning. +AIStore is aimed to scale linearly with each added storage node, can be deployed on any Linux machine and can provide a unified namespace across multiple remote backends, such as Amazon S3, Google Cloud, and Microsoft Azure. +More details are provided in the `documentation `_ and the `repository `_ of the AIStore project. + +NeMo currently supports datasets from an AIStore bucket provider under ``ais://`` namespace. + +AIStore Setup +~~~~~~~~~~~~~ + +NeMo is currently relying on the AIStore (AIS) command-line interface (CLI) to handle the supported datasets. +The CLI is available in current NeMo Docker containers. +If necessary, the CLI can be configured using the instructions provided in `AIStore CLI `_ documentation. + +To start using the AIS CLI to access data on an AIS cluster, an endpoint needs to be configured. +The endpoint is configured by setting ``AIS_ENDPOINT`` environment variable before using the CLI + +.. code:: + + export AIS_ENDPOINT=http://hostname:port + ais --help + +In the above, ``hostname:port`` denotes the address of an AIS gateway. +For example, the address could be ``localhost:51080`` if testing using a local `minimal production-ready standalone Docker container `_. + +Dataset Setup +~~~~~~~~~~~~~ + +Currently, both tarred and non-tarred datasets are supported. +For any dataset, the corresponding manifest file is cached locally and processed as a regular manifest file. +For non-tarred datasets, the audio data is also cached locally. +For tarred datasets, shards from the AIS cluster are used by piping ``ais get`` to WebDataset. + +Tarred Dataset from AIS +^^^^^^^^^^^^^^^^^^^^^^^ + +A tarred dataset can be easily used as described in the :ref:`Tarred Datasets ` section by providing paths to manifests on an AIS cluster. +For example, a tarred dataset from an AIS cluster can be configured as + +.. code:: + + manifest_filepath='ais://bucket/tarred_audio_manifest.json' + tarred_audio_filepaths='ais://bucket/shard_{1..64}.tar' + +:ref:`Bucketing Datasets ` are configured in a similar way by providing paths on an AIS cluster. + +Non-tarred Dataset from AIS +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A non-tarred dataset can be easly used by providing a manifest file path on an AIS cluster + +.. code:: + + manifest_filepath='ais://bucket/dataset_manifest.json' + +Note that it is assumed that the manifest file path contains audio file paths relative to the manifest locations. +For example the manifest file may have lines in the following format + +.. code-block:: json + + {"audio_filepath": "path/to/audio.wav", "text": "transcription of the uterance", "duration": 23.147} + +The corresponding audio file would be downloaded from ``ais://bucket/path/to/audio.wav``. + +Cache configuration +^^^^^^^^^^^^^^^^^^^ + +Manifests and audio files from non-tarred datasets will be cached locally. +Location of the cache can be configured by setting two environment variables + +- ``NEMO_DATA_STORE_CACHE_DIR``: path to a location which can be used to cache the data +- ``NEMO_DATA_STORE_CACHE_SHARED``: flag to denote whether the cache location is shared between the compute nodes + +In a multi-node environment, the cache location may or may be not shared between the nodes. +This can be configured by setting ``NEMO_DATA_STORE_CACHE_SHARED`` to ``1`` when the location is shared between the nodes or to ``0`` when each node has a separate cache. + +When a globally shared cache is available, the data should be cached only once from the global rank zero node. +When a node-specific cache is used, the data should be cached only once by each local rank zero node. +To control this behavior using `torch.distributed.barrier`, instantiation of the corresponding dataloader needs to be deferred ``ModelPT::setup``, to ensure a distributed environment has been initialized. +This can be achieved by setting ``defer_setup`` as + +.. code:: shell + + ++model.train_ds.defer_setup=true + ++model.validation_ds.defer_setup=true + ++model.test_ds.defer_setup=true + + +Complete Example +^^^^^^^^^^^^^^^^ + +An example using an AIS cluster at ``hostname:port`` with a tarred dataset for training, a non-tarred dataset for validation and node-specific caching is given below + +.. code:: shell + + export AIS_ENDPOINT=http://hostname:port \ + && export NEMO_DATA_STORE_CACHE_DIR=/tmp \ + && export NEMO_DATA_STORE_CACHE_SHARED=0 \ + python speech_to_text_bpe.py \ + ... + model.train_ds.manifest_filepath=ais://train_bucket/tarred_audio_manifest.json \ + model.train_ds.tarred_audio_filepaths=ais://train_bucket/audio__OP_0..511_CL_.tar \ + ++model.train_ds.defer_setup=true \ + model.validation_ds.manifest_filepath=ais://validation_bucket/validation_manifest.json \ + ++model.validation_ds.defer_setup=true + + +Lhotse Dataloading +------------------ + +NeMo supports using `Lhotse`_, a speech data handling library, as a dataloading option. The key features of Lhotse used in NeMo are: + +* Dynamic batch sizes + Lhotse samples mini-batches to satisfy the constraint of total speech duration in a mini-batch (``batch_duration``), + rather than a specific number of examples (i.e., batch size). +* Dynamic bucketing + Instead of statically pre-bucketing the data, Lhotse allocates training examples to buckets dynamically. + This allows more rapid experimentation with bucketing settings (number of buckets, specific placement of bucket duration bins) + to minimize the amount of padding and accelerate training. +* Quadratic duration penalty + Adding a quadratic penalty to an utterance's duration allows to sample mini-batches so that the + GPU utilization is more consistent across big batches of short utterances and small batches of long utterances when using + models with quadratic time/memory complexity (such as transformer). +* Dynamic weighted data source multiplexing + An approach to combining diverse data sources (e.g. multiple domains, languages, tasks) + where each data source is treated as a separate stream with its own sampling probability. The resulting data stream is a + multiplexer that samples from each sub-stream. This approach ensures that the distribution of different sources is approximately + constant in time (i.e., stationary); in fact, each mini-batch will have roughly the same ratio of data coming from each source. + Since the multiplexing is done dynamically, it is very easy to tune the sampling weights. + +Lhotse dataloading supports the following types of inputs: + +* NeMo manifests + Regular NeMo JSON manifests. +* NeMo tarred data + Tarred NeMo JSON manifests + audio tar files; we also support combination of multiple NeMo + tarred data sources (e.g., multiple buckets of NeMo data or multiple datasets) via dynamic multiplexing. + + We support using a subset of Tarred NeMo JSON manifests along with audio tar files without disrupting the alignment between the tarred files and their corresponding manifests. + This feature is essential because large datasets often consist of numerous tar files and multiple versions of Tarred NeMo JSON manifest subsets, which may contain only a portion of the audio files due to filtering for various reasons. + To skip specific entries in the manifests without repeatedly copying and retarring audio files, the entries must include a ``_skipme`` key. This key should be set to ``True``, ``1``, or a reason for skipping (e.g., ``low character-rate``). + +* Lhotse CutSet manifests + Regular Lhotse CutSet manifests (typically gzipped JSONL). + See `Lhotse Cuts documentation`_ to learn more about Lhotse data formats. +* Lhotse Shar data + Lhotse Shar is a data format that also uses tar files for sequential data loading, + but is designed to be modular (i.e., easily extensible with new data sources and with new feature fields). + More details can be found here: |tutorial_shar| + +.. caution:: As of now, Lhotse is mainly supported in most ASR model configurations. We aim to gradually extend this support to other speech tasks. + +.. _Lhotse: https://github.com/lhotse-speech/lhotse +.. _Lhotse Cuts documentation: https://lhotse.readthedocs.io/en/latest/cuts.html +.. |tutorial_shar| image:: https://colab.research.google.com/assets/colab-badge.svg + :target: https://colab.research.google.com/github/lhotse-speech/lhotse/blob/master/examples/04-lhotse-shar.ipynb + +Enabling Lhotse via configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: Using Lhotse with tarred datasets will make the dataloader infinite, ditching the notion of an "epoch". "Epoch" may still be logged in W&B/TensorBoard, but it will correspond to the number of executed training loops between validation loops. + +Start with an existing NeMo experiment YAML configuration. Typically, you'll only need to add a few options to enable Lhotse. +These options are:: + + # NeMo generic dataloading arguments + model.train_ds.manifest_filepath=... + model.train_ds.tarred_audio_filepaths=... # for tarred datasets only + model.train_ds.num_workers=4 + model.train_ds.min_duration=0.3 # optional + model.train_ds.max_duration=30.0 # optional + model.train_ds.shuffle=true # optional + + # Lhotse dataloading related arguments + ++model.train_ds.use_lhotse=True + ++model.train_ds.batch_duration=1100 + ++model.train_ds.quadratic_duration=30 + ++model.train_ds.num_buckets=30 + ++model.train_ds.num_cuts_for_bins_estimate=10000 + ++model.train_ds.bucket_buffer_size=10000 + ++model.train_ds.shuffle_buffer_size=10000 + + # PyTorch Lightning related arguments + ++trainer.use_distributed_sampler=false + ++trainer.limit_train_batches=1000 + trainer.val_check_interval=1000 + trainer.max_steps=300000 + +.. note:: The default values above are a reasonable starting point for a hybrid RNN-T + CTC ASR model on a 32GB GPU with a data distribution dominated by 15s long utterances. + +Let's briefly go over each of the Lhotse dataloading arguments: + +* ``use_lhotse`` enables Lhotse dataloading +* ``batch_duration`` is the total max duration of utterances in a mini-batch and controls the batch size; the more shorter utterances, the bigger the batch size, and vice versa. +* ``quadratic_duration`` adds a quadratically growing penalty for long utterances; useful in bucketing and transformer type of models. The value set here means utterances this long will count as if with a doubled duration. +* ``num_buckets`` is the number of buckets in the bucketing sampler. Bigger value means less padding but also less randomization. +* ``num_cuts_for_bins_estimate`` is the number of utterance we will sample before the start of the training to estimate the duration bins for buckets. Larger number results in a more accurate estimatation but also a bigger lag before starting the training. +* ``bucket_buffer_size`` is the number of utterances (data and metadata) we will hold in memory to be distributed between buckets. With bigger ``batch_duration``, this number may need to be increased for dynamic bucketing sampler to work properly (typically it will emit a warning if this is too low). +* ``shuffle_buffer_size`` is an extra number of utterances we will hold in memory to perform approximate shuffling (via reservoir-like sampling). Bigger number means more memory usage but also better randomness. + +The PyTorch Lightning ``trainer`` related arguments: + +* ``use_distributed_sampler=false`` is required because Lhotse has its own handling of distributed sampling. +* ``val_check_interval``/``limit_train_batches`` + These are required for dataloaders with tarred/Shar datasets + because Lhotse makes the dataloader infinite, so we'd never go past epoch 0. This approach guarantees + we will never hang the training because the dataloader in some node has less mini-batches than the others + in some epochs. The value provided here will be the effective length of each "pseudo-epoch" after which we'll + trigger the validation loop. +* ``max_steps`` is the total number of steps we expect to be training for. It is required for the same reason as ``limit_train_batches``; since we'd never go past epoch 0, the training would have never finished. + +Some other Lhotse related arguments we support: + +* ``cuts_path`` can be provided to read data from a Lhotse CutSet manifest instead of a NeMo manifest. + Specifying this option will result in ``manifest_filepaths`` and ``tarred_audio_filepaths`` being ignored. +* ``shar_path`` + Can be provided to read data from a Lhotse Shar manifest instead of a NeMo manifest. + Specifying this option will result in ``manifest_filepaths`` and ``tarred_audio_filepaths`` being ignored. + This argument can be a string (single Shar directory), a list of strings (Shar directories), + or a list of 2-item lists, where the first item is a Shar directory path, and the other is a sampling weight. + The user can also provide a dict mapping Lhotse Shar fields to a list of shard paths with data for that field. + For details about Lhotse Shar format, see: |tutorial_shar| +* ``bucket_duration_bins`` + Duration bins are a list of float values (seconds) that when provided, will skip the initial bucket bin estimation + and save some time. It has to have a length of ``num_buckets - 1``. An optimal value can be obtained by running CLI: + ``lhotse cut estimate-bucket-bins -b $num_buckets my-cuts.jsonl.gz`` +* ``use_bucketing`` is a boolean which indicates if we want to enable/disable dynamic bucketing. By defalt it's enabled. +* ``text_field`` is the name of the key in the JSON (NeMo) manifest from which we should be reading text (default="text"). +* ``lang_field`` is the name of the key in the JSON (NeMo) manifest from which we should be reading language tag (default="lang"). This is useful when working e.g. with ``AggregateTokenizer``. +* ``batch_size`` + Limits the number of examples in a mini-batch to this number, when combined with ``batch_duration``. + When ``batch_duration`` is not set, it acts as a static batch size. +* ``seed`` sets a random seed for the shuffle buffer. + +The full and always up-to-date list of supported options can be found in ``LhotseDataLoadingConfig`` class. + +.. _asr-dataset-config-format: + +Extended multi-dataset configuration format +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Combining a large number of datasets and defining weights for them can be tricky. +We offer an extended configuration format that allows you to explicitly define datasets, +dataset groups, and their weights either inline in the experiment configuration, +or as a path to a separate YAML file. + +In addition to the features above, this format introduces a special ``tags`` dict-like field. +The keys and values in ``tags`` are automatically attached to every sampled example, which +is very useful when combining multiple datasets with different properties. +The dataset class which converts these examples to tensors can partition the mini-batch and apply +different processing to each group. +For example, you may want to construct different prompts for the model using metadata in ``tags``. + +.. note:: When fine-tuning a model that was trained with ``input_cfg`` option, typically you'd only need + to override the following options: ``input_cfg=null`` and ``manifest_filepath=path/to/manifest.json``. + +Example 1. Combine two datasets with equal weights and attach custom metadata in ``tags`` to each cut: + +.. code-block:: yaml + + input_cfg: + - type: nemo_tarred + manifest_filepath: /path/to/manifest__OP_0..512_CL_.json + tarred_audio_filepath: /path/to/tarred_audio/audio__OP_0..512_CL_.tar + weight: 0.4 + tags: + lang: en + pnc: no + - type: nemo_tarred + manifest_filepath: /path/to/other/manifest__OP_0..512_CL_.json + tarred_audio_filepath: /path/to/other/tarred_audio/audio__OP_0..512_CL_.tar + weight: 0.6 + tags: + lang: pl + pnc: yes + +Example 2. Combine multiple (4) datasets, corresponding to different tasks (ASR, AST). +Each task gets its own group and its own weight. +Then within each task, each dataset get its own within-group weight as well. +The final weight is the product of outer and inner weight: + +.. code-block:: yaml + + input_cfg: + - type: group + weight: 0.7 + tags: + task: asr + input_cfg: + - type: nemo_tarred + manifest_filepath: /path/to/asr1/manifest__OP_0..512_CL_.json + tarred_audio_filepath: /path/to/tarred_audio/asr1/audio__OP_0..512_CL_.tar + weight: 0.6 + tags: + source_lang: en + target_lang: en + - type: nemo_tarred + manifest_filepath: /path/to/asr2/manifest__OP_0..512_CL_.json + tarred_audio_filepath: /path/to/asr2/tarred_audio/audio__OP_0..512_CL_.tar + weight: 0.4 + tags: + source_lang: pl + target_lang: pl + - type: group + weight: 0.3 + tags: + task: ast + input_cfg: + - type: nemo_tarred + manifest_filepath: /path/to/ast1/manifest__OP_0..512_CL_.json + tarred_audio_filepath: /path/to/ast1/tarred_audio/audio__OP_0..512_CL_.tar + weight: 0.2 + tags: + source_lang: en + target_lang: pl + - type: nemo_tarred + manifest_filepath: /path/to/ast2/manifest__OP_0..512_CL_.json + tarred_audio_filepath: /path/to/ast2/tarred_audio/audio__OP_0..512_CL_.tar + weight: 0.8 + tags: + source_lang: pl + target_lang: en + +Configuring multimodal dataloading +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Our configuration format supports specifying data sources from other modalities than just audio. +At this time, this support is extended to audio and text modalities. We provide the following parser types: + +**Raw text files.** Simple text files where each line is an individual text example. This can represent standard language modeling data. +This parser is registered under ``type: txt``. + +Data format examples:: + + # file: document_0.txt + This is a language modeling example. + Wall Street is expecting major news tomorrow. + + # file: document_1.txt + Invisible bats have stormed the city. + What an incredible event! + +Dataloading configuration example:: + + input_cfg: + - type: txt + paths: /path/to/document_{0..1}.txt + language: en # optional + +Python object example:: + + from nemo.collections.common.data.lhotse.text_adapters import TextExample + + example = TextExample( + text="This is a language modeling example.", + language="en", # optional + ) + +Python dataloader instantiation example:: + + from nemo.collections.common.data.lhotse.dataloader import get_lhotse_dataloader_from_config + + dl = get_lhotse_dataloader_from_config({ + "input_cfg": [ + {"type": "txt", "paths": "/path/to/document_{0..1}.txt", "language": "en"}, + ], + "use_multimodal_dataloading": True, + "batch_size": 4, + }, + global_rank=0, + world_size=1, + dataset=MyDatasetClass(), # converts CutSet -> dict[str, Tensor] + tokenizer=my_tokenizer, + ) + +**Raw text file pairs.** Pairs of raw text files with corresponding lines. This can represent machine translation data. +This parser is registered under ``type: txt_pair``. + +Data format examples:: + + # file: document_en_0.txt + This is a machine translation example. + Wall Street is expecting major news tomorrow. + + # file: document_pl_0.txt + To jest przykład tłumaczenia maszynowego. + Wall Street spodziewa się jutro ważnych wiadomości. + +Dataloading configuration example:: + + input_cfg: + - type: txt_pair + source_path: /path/to/document_en_{0..N}.txt + target_path: /path/to/document_pl_{0..N}.txt + source_language: en # optional + target_language: pl # optional + +Python object example:: + + from nemo.collections.common.data.lhotse.text_adapters import SourceTargetTextExample + + example = SourceTargetTextExample( + source=TextExample( + text="This is a language modeling example.", + language="en", # optional + ), + target=TextExample( + text="To jest przykład tłumaczenia maszynowego.", + language="pl", # optional + ), + ) + +Python dataloader instantiation example:: + + from nemo.collections.common.data.lhotse.dataloader import get_lhotse_dataloader_from_config + + dl = get_lhotse_dataloader_from_config({ + "input_cfg": [ + { + "type": "txt_pair", + "source_path": "/path/to/document_en_{0..N}.txt", + "target_path": "/path/to/document_pl_{0..N}.txt", + "source_language": "en" + "target_language": "en" + }, + ], + "use_multimodal_dataloading": True, + "prompt_format": "t5nmt", + "batch_size": 4, + }, + global_rank=0, + world_size=1, + dataset=MyDatasetClass(), # converts CutSet -> dict[str, Tensor] + tokenizer=my_tokenizer, + ) + +**NeMo multimodal conversations.** A JSON-Lines (JSONL) file that defines multi-turn conversations with mixed text and audio turns. +This parser is registered under ``type: multimodal_conversation``. + +Data format examples:: + + # file: chat_0.jsonl + {"id": "conv-0", "conversations": [{"from": "user", "value": "speak to me", "type": "text"}, {"from": "assistant": "value": "/path/to/audio.wav", "duration": 17.1, "type": "audio"}]} + {"id": "conv-1", "conversations": [{"from": "user", "value": "speak to me", "type": "text"}, {"from": "assistant": "value": "/path/to/audio.wav", "duration": 5, "offset": 17.1, "type": "audio"}]} + +Dataloading configuration example:: + + token_equivalent_duration: 0.08 + input_cfg: + - type: multimodal_conversation + manifest_filepath: /path/to/chat_{0..N}.jsonl + audio_locator_tag: [audio] + +Python object example:: + + from lhotse import Recording + from nemo.collections.common.data.lhotse.text_adapters import MultimodalConversation, TextTurn, AudioTurn + + conversation = NeMoMultimodalConversation( + id="conv-0", + turns=[ + TextTurn(value="speak to me", role="user"), + AudioTurn(cut=Recording.from_file("/path/to/audio.wav").to_cut(), role="assistant", audio_locator_tag="[audio]"), + ], + token_equivalent_duration=0.08, # this value will be auto-inserted by the dataloader + ) + +Python dataloader instantiation example:: + + from nemo.collections.common.data.lhotse.dataloader import get_lhotse_dataloader_from_config + + dl = get_lhotse_dataloader_from_config({ + "input_cfg": [ + { + "type": "multimodal_conversation", + "manifest_filepath": "/path/to/chat_{0..N}.jsonl", + "audio_locator_tag": "[audio]", + }, + ], + "use_multimodal_dataloading": True, + "token_equivalent_duration": 0.08, + "prompt_format": "llama2", + "batch_size": 4, + }, + global_rank=0, + world_size=1, + dataset=MyDatasetClass(), # converts CutSet -> dict[str, Tensor] + tokenizer=my_tokenizer, + ) + +**Dataloading and bucketing of text and multimodal data.** When dataloading text or multimodal data, pay attention to the following config options (we provide example values for convenience): + +* ``use_multimodal_sampling: true`` tells Lhotse to switch from measuring audio duration to measuring token counts; required for text. + +* ``prompt_format: "prompt-name"`` will apply a specified PromptFormatter during data sampling to accurately reflect its token counts. + +* ``measure_total_length: true`` customizes length measurement for decoder-only and encoder-decoder models. Decoder-only models consume a linear sequence of context + answer, so we should measure the total length (``true``). On the other hand, encoder-decoder models deal with two different sequence lengths: input (context) sequence length for the encoder, and output (answer) sequence length for the decoder. For such models set this to ``false``. + +* ``min_tokens: 1``/``max_tokens: 4096`` filters examples based on their token count (after applying the prompt format). + +* ``min_tpt: 0.1``/``max_tpt: 10`` filter examples based on their output-token-per-input-token-ratio. For example, a ``max_tpt: 10`` means we'll filter every example that has more than 10 output tokens per 1 input token. Very useful for removing sequence length outliers that lead to OOM. Use ``estimate_token_bins.py`` to view token count distributions for calbirating this value. + +* (multimodal-only) ``token_equivalent_duration: 0.08`` is used to be able to measure audio examples in the number of "tokens". For example, if we're using fbank with 0.01s frame shift and an acoustic model that has a subsampling factor of 0.08, then a reasonable setting for this could be 0.08 (which means every subsampled frame counts as one token). Calibrate this value to fit your needs. + +**Text/multimodal bucketing and OOMptimizer.** Analogous to bucketing for audio data, we provide two scripts to support efficient bucketing: + +* ``scripts/speech_llm/estimate_token_bins.py`` which estimates 1D or 2D buckets based on the input config, tokenizer, and prompt format. It also estimates input/output token count distribution and suggested ``max_tpt`` (token-per-token) filtering values. + +* (experimental) ``scripts/speech_llm/oomptimizer.py`` which works with SALM/BESTOW GPT/T5 models and estimates the optimal ``bucket_batch_size`` for a given model config and bucket bins value. Given the complexity of Speech LLM some configurations may not be supported yet at the time of writing (e.g., model parallelism). + +To enable bucketing, set ``batch_size: null`` and use the following options: + +* ``use_bucketing: true`` + +* ``bucket_duration_bins`` - the output of ``estimate_token_bins.py``. If ``null``, it will be estimated at the start of training at the cost of some run time (not recommended). + +* (oomptimizer-only) ``bucket_batch_size`` - the output of OOMptimizer. + +* (non-oomptimizer-only) ``batch_tokens`` is the maximum number of tokens we want to find inside a mini-batch. Similarly to ``batch_duration``, this number does consider padding tokens too, therefore enabling bucketing is recommended to maximize the ratio of real vs padding tokens. Note that it's just a heuristic for determining the optimal batch sizes for different buckets, and may be less efficient than using OOMptimizer. + +* (non-oomptimizer-only) ``quadratic_factor`` is a quadratic penalty to equalize the GPU memory usage between buckets of short and long sequence lengths for models with quadratic memory usage. It is only a heuristic and may not be as efficient as using OOMptimizer. + +**Joint dataloading of text/audio/multimodal data.** The key strength of this approach is that we can easily combine audio datasets and text datasets, +and benefit from every other technique we described in this doc, such as: dynamic data mixing, data weighting, dynamic bucketing, and so on. + +This approach is described in the `EMMeTT`_ paper. There's also a notebook tutorial called Multimodal Lhotse Dataloading. We construct a separate sampler (with its own batching settings) for each modality, +and specify how the samplers should be fused together via the option ``sampler_fusion``: + +* ``sampler_fusion: "round_robin"`` will iterate single sampler per step, taking turns. For example: step 0 - audio batch, step 1 - text batch, step 2 - audio batch, etc. + +* ``sampler_fusion: "randomized_round_robin"`` is similar, but at each chooses a sampler randomly using ``sampler_weights: [w0, w1]`` (weights can be unnormalized). + +* ``sampler_fusion: "zip"`` will draw a mini-batch from each sampler at every step, and merge them into a single ``CutSet``. This approach combines well with multimodal gradient accumulation (run forward+backward for one modality, then the other, then the update step). + +.. _EMMeTT: https://arxiv.org/abs/2409.13523 + +Example. Combine an ASR (audio-text) dataset with an MT (text-only) dataset so that mini-batches have some examples from both datasets: + +.. code-block:: yaml + + model: + ... + train_ds: + multi_config: True, + sampler_fusion: zip + shuffle: true + num_workers: 4 + + audio: + prompt_format: t5nmt + use_bucketing: true + min_duration: 0.5 + max_duration: 30.0 + max_tps: 12.0 + bucket_duration_bins: [[3.16, 10], [3.16, 22], [5.18, 15], ...] + bucket_batch_size: [1024, 768, 832, ...] + input_cfg: + - type: nemo_tarred + manifest_filepath: /path/to/manifest__OP_0..512_CL_.json + tarred_audio_filepath: /path/to/tarred_audio/audio__OP_0..512_CL_.tar + weight: 0.5 + tags: + context: "Translate the following to English" + + text: + prompt_format: t5nmt + use_multimodal_sampling: true + min_tokens: 1 + max_tokens: 256 + min_tpt: 0.333 + max_tpt: 3.0 + measure_total_length: false + use_bucketing: true + bucket_duration_bins: [[10, 4], [10, 26], [15, 10], ...] + bucket_batch_size: [512, 128, 192, ...] + input_cfg: + - type: txt_pair + source_path: /path/to/en__OP_0..512_CL_.txt + target_path: /path/to/pl__OP_0..512_CL_.txt + source_language: en + target_language: pl + weight: 0.5 + tags: + question: "Translate the following to Polish" + +.. caution:: We strongly recommend to use multiple shards for text files as well so that different nodes and dataloading workers are able to randomize the order of text iteration. Otherwise, multi-GPU training has a high risk of duplication of text examples. + +Pre-computing bucket duration bins +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We recommend to pre-compute the bucket duration bins in order to accelerate the start of the training -- otherwise, the dynamic bucketing sampler will have to spend some time estimating them before the training starts. +The following script may be used: + +.. code-block:: bash + + $ python scripts/speech_recognition/estimate_duration_bins.py -b 30 manifest.json + + # The script's output: + Use the following options in your config: + num_buckets=30 + bucket_duration_bins=[1.78,2.34,2.69,... + + +For multi-dataset setups, one may provide a dataset config directly: + +.. code-block:: bash + + $ python scripts/speech_recognition/estimate_duration_bins.py -b 30 input_cfg.yaml + + # The script's output: + Use the following options in your config: + num_buckets=30 + bucket_duration_bins=[1.91,3.02,3.56,... + + +It's also possible to manually specify the list of data manifests (optionally together with weights): + +.. code-block:: bash + + $ python scripts/speech_recognition/estimate_duration_bins.py -b 30 [[manifest.json,0.7],[other.json,0.3]] + + # The script's output: + Use the following options in your config: + num_buckets=30 + bucket_duration_bins=[1.91,3.02,3.56,... + + +2D bucketing +~~~~~~~~~~~~ + +To achieve maximum training efficiency for some classes of models it is necessary to stratify the sampling +both on the input sequence lengths and the output sequence lengths. +One such example are attention encoder-decoder models, where the overall GPU memory usage can be factorized +into two main components: input-sequence-length bound (encoder activations) and output-sequence-length bound +(decoder activations). +Classical bucketing techniques only stratify on the input sequence length (e.g. duration in speech), +which leverages encoder effectively but leads to excessive padding on on decoder's side. + +To amend this we support a 2D bucketing technique which estimates the buckets in two stages. +The first stage is identical to 1D bucketing, i.e. we determine the input-sequence bucket bins so that +every bin holds roughly an equal duration of audio. +In the second stage, we use a tokenizer and optionally a prompt formatter (for prompted models) to +estimate the total number of tokens in each duration bin, and sub-divide it into several sub-buckets, +where each sub-bucket again holds roughly an equal number of tokens. + +To run 2D bucketing with 30 buckets sub-divided into 5 sub-buckets each (150 buckets total), use the following script: + +.. code-block:: bash + + $ python scripts/speech_recognition/estimate_duration_bins_2d.py \ + --tokenizer path/to/tokenizer.model \ + --buckets 30 \ + --sub-buckets 5 \ + input_cfg.yaml + + # The script's output: + Use the following options in your config: + use_bucketing=1 + num_buckets=30 + bucket_duration_bins=[[1.91,10],[1.91,17],[1.91,25],... + The max_tps setting below is optional, use it if your data has low quality long transcript outliers: + max_tps=[13.2,13.2,11.8,11.8,...] + +Note that the output in ``bucket_duration_bins`` is a nested list, where every bin specifies +the maximum duration and the maximum number of tokens that go into the bucket. +Passing this option to Lhotse dataloader will automatically enable 2D bucketing. + +Note the presence of ``max_tps`` (token-per-second) option. +It is optional to include it in the dataloader configuration: if you do, we will apply an extra filter +that discards examples which have more tokens per second than the threshold value. +The threshold is determined for each bucket separately based on data distribution, and can be controlled +with the option ``--token_outlier_threshold``. +This filtering is useful primarily for noisy datasets to discard low quality examples / outliers. + +We also support aggregate tokenizers for 2D bucketing estimation: + +.. code-block:: bash + + $ python scripts/speech_recognition/estimate_duration_bins_2d.py \ + --tokenizer path/to/en/tokenizer.model path/to/pl/tokenizer1.model \ + --langs en pl \ + --buckets 30 \ + --sub-buckets 5 \ + input_cfg.yaml + +To estimate 2D buckets for a prompted model such as Canary-1B, provide prompt format name and an example prompt. +For Canary-1B, we'll also provide the special tokens tokenizer. Example: + +.. code-block:: bash + + $ python scripts/speech_recognition/estimate_duration_bins_2d.py \ + --prompt-format canary \ + --prompt "[{'role':'user','slots':{'source_lang':'en','target_lang':'de','task':'ast','pnc':'yes'}}]" \ + --tokenizer path/to/spl_tokens/tokenizer.model path/to/en/tokenizer.model path/to/de/tokenizer1.model \ + --langs spl_tokens en de \ + --buckets 30 \ + --sub-buckets 5 \ + input_cfg.yaml + +Pushing GPU utilization to the limits with bucketing and OOMptimizer +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The default approach of specifying a ``batch_duration``, ``bucket_duration_bins`` and ``quadratic_duration`` +is quite flexible, but is not maximally efficient. We observed that in practice it often leads to under-utilization +of GPU memory and compute for most buckets (especially those with shorter durations). +While it is impossible to estimate GPU memory usage up-front, we can determine it empirically with a bit of search. + +OOMptimizer is an approach that given a NeMo model, optimizer, and a list of buckets (1D or 2D) +estimates the maximum possible batch size to use for each bucket. +It performs a binary search over batch sizes that succeed or lead to CUDA OOM until convergence. +We find that the resulting bucketing batch size profiles enable full GPU utilization in training, +while it only takes a couple of minutes to complete the search. + +In order to run OOMptimizer, you only need the bucketing bins (from previous sections) and a model configuration: + +.. code-block:: bash + + $ python scripts/speech_recognition/oomptimizer.py \ + --config-path fast-conformer_aed.yaml \ + --module-name nemo.collections.asr.models.EncDecMultiTaskModel \ + --buckets '[[3.975,30],[3.975,48],[4.97,37],[4.97,60],[5.851,42],[5.851,71],[6.563,46],[6.563,79],[7.32,49],[7.32,88],[8.19,54],[8.19,99],[8.88,61],[8.88,107],[9.75,66],[9.75,117],[10.55,72],[10.55,127],[11.21,76],[11.21,135],[11.87,79],[11.87,143],[12.54,82],[12.54,151],[13.08,87],[13.08,157],[13.62,91],[13.62,164],[14.16,93],[14.16,170],[14.7,96],[14.7,177],[15.19,99],[15.19,183],[15.67,101],[15.67,189],[16.13,103],[16.13,194],[16.66,105],[16.66,200],[17.2,108],[17.2,207],[17.73,111],[17.73,213],[18.2,114],[18.2,219],[18.69,117],[18.69,225],[19.15,120],[19.15,230],[19.62,123],[19.62,236],[20.264,122],[20.264,244],[32.547,173],[32.547,391],[36.587,227],[36.587,440],[40.0,253],[40.0,480]]' + + # The script's output: + + The final profile is: + bucket_duration_bins=[[3.975,30],[3.975,48],[4.97,37],[4.97,60],[5.851,42],[5.851,71],[6.563,46],[6.563,79],[7.32,49],[7.32,88],[8.19,54],[8.19,99],[8.88,61],[8.88,107],[9.75,66],[9.75,117],[10.55,72],[10.55,127],[11.21,76],[11.21,135],[11.87,79],[11.87,143],[12.54,82],[12.54,151],[13.08,87],[13.08,157],[13.62,91],[13.62,164],[14.16,93],[14.16,170],[14.7,96],[14.7,177],[15.19,99],[15.19,183],[15.67,101],[15.67,189],[16.13,103],[16.13,194],[16.66,105],[16.66,200],[17.2,108],[17.2,207],[17.73,111],[17.73,213],[18.2,114],[18.2,219],[18.69,117],[18.69,225],[19.15,120],[19.15,230],[19.62,123],[19.62,236],[20.264,122],[20.264,244],[32.547,173],[32.547,391],[36.587,227],[36.587,440],[40.0,253],[40.0,480]] + bucket_batch_size=[352,308,280,245,245,206,206,180,186,163,168,142,151,132,136,119,126,106,116,98,110,92,104,88,99,83,94,79,90,76,86,72,86,72,81,68,80,65,78,63,74,60,72,58,70,58,68,54,66,52,65,52,62,50,37,28,31,24,28,21] + max_tps=12.0 + max_duration=40.0 + +Use the resulting options in your training configuration (typically under namespace ``model.train_ds``) to apply the profile. + +It's also possible to run OOMptimizer using a pretrained model's name and bucket bins corresponding +to your fine-tuning data: + + $ python scripts/speech_recognition/oomptimizer.py \ + --pretrained-name nvidia/canary-1b \ + --buckets '[2.0,3.1,5.6,6.6,...]' + +Note that your training script can perform some additional actions using GPU RAM that cannot be anticipated by the OOMptimizer. +By default, we let the script use up to 90% of GPU's RAM for this estimation to account for that. +In the unlikely case you run into an OutOfMemoryError during training, you can try re-estimating the profile with the option ``--memory-fraction 0.75`` (or another value) that will further cap OOMptimizer's available GPU RAM. + +Seeds and randomness +~~~~~~~~~~~~~~~~~~~~ + +In Lhotse dataloading configuration we have two parameters controlling randomness: ``seed`` and ``shard_seed``. +Both of them can be either set to a fixed number, or one of two string options ``"randomized"`` and ``"trng"``. +Their roles are: + +* ``seed`` is the base random seed, and is one of several factors used to initialize various RNGs participating in dataloading. + +* ``shard_seed`` controls the shard randomization strategy in distributed data parallel setups when using sharded tarred datasets. + +Below are the typical examples of configuration with an explanation of the expected outcome. + +Case 1 (default): ``seed=`` and ``shard_seed="trng"``: + +* The ``trng`` setting discards ``seed`` and causes the actual random seed to be drawn using OS's true RNG. Each node/GPU/dataloading worker draws its own unique random seed when it first needs it. + +* Each node/GPU/dataloading worker yields data in a different order (no mini-batch duplication). + +* On each training script run, the order of dataloader examples are **different**. + +* Since the random seed is unpredictable, the exact dataloading order is not replicable. + +Case 2: ``seed=`` and ``shard_seed="randomized"``: + +* The ``randomized`` setting uses ``seed`` along with DDP ``rank`` and dataloading ``worker_id`` to set a unique but deterministic random seed in each dataloading process across all GPUs. + +* Each node/GPU/dataloading worker yields data in a different order (no mini-batch duplication). + +* On each training script run, the order of dataloader examples are **identical** as long as ``seed`` is the same. + +* This setup guarantees 100% dataloading reproducibility. + +* Resuming training without changing of the ``seed`` value will cause the model to train on data it has already seen. For large data setups, not managing the ``seed`` may cause the model to never be trained on a majority of data. This is why this mode is not the default. + +* If you're combining DDP with model parallelism techniques (Tensor Parallel, Pipeline Parallel, etc.) you need to use ``shard_seed="randomized"``. Using ``"trng"`` will cause different model parallel ranks to desynchronize and cause a deadlock. + +* Generally the seed can be managed by the user by providing a different value each time the training script is launched. For example, for most models the option to override would be ``model.train_ds.seed=``. If you're launching multiple tasks queued one after another on a grid system, you can generate a different random seed for each task, e.g. on most Unix systems ``RSEED=$(od -An -N4 -tu4 < /dev/urandom | tr -d ' ')`` would generate a random uint32 number that can be provided as the seed. + +Other, more exotic configurations: + +* With ``shard_seed=``, all dataloading workers will yield the same results. This is only useful for unit testing and maybe debugging. + +* With ``seed="trng"``, the base random seed itself will be drawn using a TRNG. It will be different on each GPU training process. This setting is not recommended. + +* With ``seed="randomized"``, the base random seed is set to Python's global RNG seed. It might be different on each GPU training process. This setting is not recommended. diff --git a/docs/source/asr/examples/kinyarwanda_asr.rst b/docs/source/asr/examples/kinyarwanda_asr.rst new file mode 100644 index 0000000000000000000000000000000000000000..5a708f6a10a2b133f36de22a5d99077d609b5328 --- /dev/null +++ b/docs/source/asr/examples/kinyarwanda_asr.rst @@ -0,0 +1,635 @@ + +Example With MCV +================ + +######################################################################## +Kinyarwanda ASR using Mozilla Common Voice Dataset +######################################################################## + +In this example, we describe essential steps of training an ASR model for a new language (Kinyarwanda). Namely, + +* Data preprocessing +* Building tokenizers +* Tarred datasets and bucketing +* Training from scratch and finetuning +* Inference and evaluation + + +************************** +Kinyarwanda Speech Dataset +************************** +We use `Mozilla Common Voice `_ dataset for Kinyarwanda which is a large dataset with 2000+ hours of audio data. + +**Note**: You should download this dataset by yourself. + +Mozilla distributes the dataset in tsv+mp3 format. +After downloading and unpacking, the dataset has the following structure + +.. code-block:: bash + + ├── cv-corpus-9.0-2022-04-27 + │ └── rw + │ ├── clips [here are all audio files, e.g. common_voice_rw_26260276.mp3] + │ ├── dev.tsv + │ ├── invalidated.tsv + │ ├── other.tsv + │ ├── reported.tsv + │ ├── test.tsv + │ ├── train.tsv + │ └── validated.tsv + +Mozilla provides **train/dev/test** split of the data, so we can just use it. +Let's look at the format of a .tsv file + +.. code-block:: bash + + head train.tsv + +.. code-block:: bash + + client_id path sentence up_votes down_votes age gender accents locale segment + e2a04c0ecacf81302f4270a3dddaa7a131420f6b7319208473af17d4adf3724ad9a3b6cdee107e2f321495db86f114a50c396e0928464a58dfad472130e7514a common_voice_rw_26273273.mp3 kandi tuguwe neza kugira ngo twakire amagambo y’ukuri, 2 0 twenties male rw + e2a04c0ecacf81302f4270a3dddaa7a131420f6b7319208473af17d4adf3724ad9a3b6cdee107e2f321495db86f114a50c396e0928464a58dfad472130e7514a common_voice_rw_26273478.mp3 Simbi na we akajya kwiga nubwo byari bigoye 2 0 twenties male rw + e2a04c0ecacf81302f4270a3dddaa7a131420f6b7319208473af17d4adf3724ad9a3b6cdee107e2f321495db86f114a50c396e0928464a58dfad472130e7514a common_voice_rw_26273483.mp3 Inshuti yanjye yaje kunsura ku biro byanjye. 2 0 twenties male rw + e2a04c0ecacf81302f4270a3dddaa7a131420f6b7319208473af17d4adf3724ad9a3b6cdee107e2f321495db86f114a50c396e0928464a58dfad472130e7514a common_voice_rw_26273488.mp3 Grand Canyon ni ahantu hazwi cyane ba mukerarugendo. 2 0 twenties male rw + +Each line corresponds to one record (usually one sentence) and contains: + +* name of the audio file +* corresponding transcription +* meta information: client_id, age, gender, etc. + + +Resampling and creating manifests +################################# + +To be able to use a dataset with NeMo Toolkit, we first need to + +* Convert *.tsv* files to *.json* manifests +* Convert *.mp3* files to *.wav* with sample rate of 16000 + +To convert a .tsv file to .json manifest, we used the following script + +.. code-block:: bash + + python tsv_to_json.py \ + --tsv=cv-corpus-9.0-2022-04-27/rw/train.tsv \ + --folder=cv-corpus-9.0-2022-04-27/rw/clips \ + --sampling_count=-1 + +**tsv_to_json.py**: + +.. code-block:: python + + import pandas as pd + import json + import tqdm + import argparse + + parser = argparse.ArgumentParser("MCV TSV-to-JSON converter") + parser.add_argument("--tsv", required=True, type=str, help="Input TSV file") + parser.add_argument("--sampling_count", required=True, type=int, help="Number of examples, you want, use -1 for all examples") + parser.add_argument("--folder", required=True, type=str, help="Relative path to folder with audio files") + args = parser.parse_args() + + df = pd.read_csv(args.tsv, sep='\t') + with open(args.tsv.replace('.tsv', '.json'), 'w') as fo: + mod = 1 + if args.sampling_count > 0: + mod = len(df) // args.sampling_count + for idx in tqdm.tqdm(range(len(df))): + if idx % mod != 0: + continue + item = { + 'audio_filepath': args.folder + "/" + df['path'][idx], + 'text': df['sentence'][idx], + 'up_votes': int(df['up_votes'][idx]), 'down_votes': int(df['down_votes'][idx]), + 'age': df['age'][idx], 'gender': df['gender'][idx], 'accents': df['accents'][idx], + 'client_id': df['client_id'][idx] + } + fo.write(json.dumps(item) + "\n") + +This script will create a corresponding **train.json** manifest near the initial **train.tsv**. It will look like this: + +.. code-block:: bash + + {"audio_filepath": "cv-corpus-9.0-2022-04-27/rw/clips/common_voice_rw_26273273.mp3", "text": "kandi tuguwe neza kugira ngo twakire amagambo y\u2019ukuri,", "up_votes": 2, "down_votes": 0, "age": "twenties", "gender": "male", "accents": NaN, "client_id": "e2a04c0ecacf81302f4270a3dddaa7a131420f6b7319208473af17d4adf3724ad9a3b6cdee107e2f321495db86f114a50c396e0928464a58dfad472130e7514a"} + {"audio_filepath": "cv-corpus-9.0-2022-04-27/rw/clips/common_voice_rw_26273478.mp3", "text": "Simbi na we akajya kwiga nubwo byari bigoye", "up_votes": 2, "down_votes": 0, "age": "twenties", "gender": "male", "accents": NaN, "client_id": "e2a04c0ecacf81302f4270a3dddaa7a131420f6b7319208473af17d4adf3724ad9a3b6cdee107e2f321495db86f114a50c396e0928464a58dfad472130e7514a"} + {"audio_filepath": "cv-corpus-9.0-2022-04-27/rw/clips/common_voice_rw_26273483.mp3", "text": "Inshuti yanjye yaje kunsura ku biro byanjye.", "up_votes": 2, "down_votes": 0, "age": "twenties", "gender": "male", "accents": NaN, "client_id": "e2a04c0ecacf81302f4270a3dddaa7a131420f6b7319208473af17d4adf3724ad9a3b6cdee107e2f321495db86f114a50c396e0928464a58dfad472130e7514a"} + {"audio_filepath": "cv-corpus-9.0-2022-04-27/rw/clips/common_voice_rw_26273488.mp3", "text": "Grand Canyon ni ahantu hazwi cyane ba mukerarugendo.", "up_votes": 2, "down_votes": 0, "age": "twenties", "gender": "male", "accents": NaN, "client_id": "e2a04c0ecacf81302f4270a3dddaa7a131420f6b7319208473af17d4adf3724ad9a3b6cdee107e2f321495db86f114a50c396e0928464a58dfad472130e7514a"} + +For resampling we used the following script: + +.. code-block:: bash + + mkdir train + python ../decode_resample.py \ + --manifest=cv-corpus-9.0-2022-04-27/rw/train.json \ + --destination_folder=./train + +**decode_resample.py**: + +.. code-block:: python + + import argparse + import os + import json + + import sox + from sox import Transformer + import tqdm + import multiprocessing + from tqdm.contrib.concurrent import process_map + + + parser = argparse.ArgumentParser() + parser.add_argument('--manifest', required=True, type=str, help='path to the original manifest') + parser.add_argument("--num_workers", default=multiprocessing.cpu_count(), type=int, help="Workers to process dataset.") + parser.add_argument("--destination_folder", required=True, type=str, help="Destination folder where audio files will be stored") + args = parser.parse_args() + + + def process(x): + if not isinstance(x['text'], str): + x['text'] = '' + else: + x['text'] = x['text'].lower().strip() + _, file_with_ext = os.path.split(x['audio_filepath']) + name, ext = os.path.splitext(file_with_ext) + output_wav_path = args.destination_folder + "/" + name + '.wav' + if not os.path.exists(output_wav_path): + tfm = Transformer() + tfm.rate(samplerate=16000) + tfm.channels(n_channels=1) + tfm.build(input_filepath=x['audio_filepath'], + output_filepath=output_wav_path) + x['duration'] = sox.file_info.duration(output_wav_path) + x['audio_filepath'] = output_wav_path + return x + + + def load_data(manifest): + data = [] + with open(manifest, 'r') as f: + for line in tqdm.tqdm(f): + item = json.loads(line) + data.append(item) + return data + + + data = load_data(args.manifest) + + data_new = process_map(process, data, max_workers=args.num_workers, chunksize=100) + + with open(args.manifest.replace('.json', '_decoded.json'), 'w') as f: + for item in tqdm.tqdm(data_new): + f.write(json.dumps(item) + '\n') + +It will write the resampled .wav-files to the specified directory and save a new json manifest with corrected audiopaths. + +**Note:** You need to repeat these steps for **test.tsv** and **dev.tsv** as well. + +****************** +Data Preprocessing +****************** + +Before we start training the model on the above manifest files, we need to preprocess the text data. Data pre-processing is done to reduce ambiguity in transcripts. This is an essential step, and often requires moderate expertise in the language. + +We used the following script +**prepare_dataset_kinyarwanda.py**: + +.. code-block:: python + + import json + import os + import re + from collections import defaultdict + from nemo.collections.asr.parts.utils.manifest_utils import read_manifest, write_manifest + from tqdm.auto import tqdm + + def write_processed_manifest(data, original_path): + original_manifest_name = os.path.basename(original_path) + new_manifest_name = original_manifest_name.replace(".json", "_processed.json") + + manifest_dir = os.path.split(original_path)[0] + filepath = os.path.join(manifest_dir, new_manifest_name) + write_manifest(filepath, data) + print(f"Finished writing manifest: {filepath}") + return filepath + + + # calculate the character set + def get_charset(manifest_data): + charset = defaultdict(int) + for row in tqdm(manifest_data, desc="Computing character set"): + text = row['text'] + for character in text: + charset[character] += 1 + return charset + + + # Preprocessing steps + def remove_special_characters(data): + chars_to_ignore_regex = "[\.\,\?\:\-!;()«»…\]\[/\*–‽+&_\\½√>€™$•¼}{~—=“\"”″‟„]" + apostrophes_regex = "[’'‘`ʽ']" + data["text"] = re.sub(chars_to_ignore_regex, " ", data["text"]) # replace punctuation by space + data["text"] = re.sub(apostrophes_regex, "'", data["text"]) # replace different apostrophes by one + data["text"] = re.sub(r"'+", "'", data["text"]) # merge multiple apostrophes + + # remove spaces where apostrophe marks a deleted vowel + # this rule is taken from https://huggingface.co/lucio/wav2vec2-large-xlsr-kinyarwanda-apostrophied + data["text"] = re.sub(r"([b-df-hj-np-tv-z])' ([aeiou])", r"\1'\2", data["text"]) + + data["text"] = re.sub(r" '", " ", data["text"]) # delete apostrophes at the beginning of word + data["text"] = re.sub(r"' ", " ", data["text"]) # delete apostrophes at the end of word + data["text"] = re.sub(r" +", " ", data["text"]) # merge multiple spaces + return data + + + def replace_diacritics(data): + data["text"] = re.sub(r"[éèëēê]", "e", data["text"]) + data["text"] = re.sub(r"[ãâāá]", "a", data["text"]) + data["text"] = re.sub(r"[úūü]", "u", data["text"]) + data["text"] = re.sub(r"[ôōó]", "o", data["text"]) + data["text"] = re.sub(r"[ćç]", "c", data["text"]) + data["text"] = re.sub(r"[ïī]", "i", data["text"]) + data["text"] = re.sub(r"[ñ]", "n", data["text"]) + return data + + + def remove_oov_characters(data): + oov_regex = "[^ 'aiuenrbomkygwthszdcjfvplxq]" + data["text"] = re.sub(oov_regex, "", data["text"]) # delete oov characters + data["text"] = data["text"].strip() + return data + + + # Processing pipeline + def apply_preprocessors(manifest, preprocessors): + for processor in preprocessors: + for idx in tqdm(range(len(manifest)), desc=f"Applying {processor.__name__}"): + manifest[idx] = processor(manifest[idx]) + + print("Finished processing manifest !") + return manifest + + + # List of pre-processing functions + PREPROCESSORS = [ + remove_special_characters, + replace_diacritics, + remove_oov_characters, + ] + + train_manifest = "train_decoded.json" + dev_manifest = "dev_decoded.json" + test_manifest = "test_decoded.json" + + train_data = read_manifest(train_manifest) + dev_data = read_manifest(dev_manifest) + test_data = read_manifest(test_manifest) + + # Apply preprocessing + train_data_processed = apply_preprocessors(train_data, PREPROCESSORS) + dev_data_processed = apply_preprocessors(dev_data, PREPROCESSORS) + test_data_processed = apply_preprocessors(test_data, PREPROCESSORS) + + # Write new manifests + train_manifest_cleaned = write_processed_manifest(train_data_processed, train_manifest) + dev_manifest_cleaned = write_processed_manifest(dev_data_processed, dev_manifest) + test_manifest_cleaned = write_processed_manifest(test_data_processed, test_manifest) + +It performs the following operations: + +* Remove all punctuation except for apostrophes +* Replace different kinds of apostrophes by one +* Lowercase +* Replace rare characters with diacritics (e.g. [éèëēê] => e) +* Delete all remaining out-of-vocabulary (OOV) characters + +The final Kinyarwanda alphabet in all trancripts consists of Latin letters, space and apostrophe. + +******************* +Building Tokenizers +******************* + +Though it is possible to train character-based ASR model, usually we get some improvement in quality and speed if we predict longer units. The commonly used tokenization algorithm is called `Byte-pair encoding `_. This is a deterministic tokenization algorithm based on corpus statistics. It splits the words to subtokens and the beginning of word is marked by special symbol so it's easy to restore the original words. +NeMo toolkit supports on-the-fly subword tokenization, so you need not modify the transcripts, but need to pass your tokenizer via the model config. NeMo supports both Word Piece Tokenizer (via HuggingFace) and Sentence Piece Tokenizer (via Google SentencePiece library) +For Kinyarwanda experiments we used 128 subtokens for the CTC model and 1024 subtokens for the Transducer model. The tokenizers for these models were built using the text transcripts of the train set with this script. For vocabulary of size 1024 we restrict maximum subtoken length to 4 symbols (2 symbols for size 128) to avoid populating vocabulary with specific frequent words from the dataset. This does not affect the model performance and potentially helps to adapt to other domain without retraining tokenizer. +We used the following script from NeMo toolkit to create `Sentencepiece `_ tokenizers with different vocabulary sizes (128 and 1024 subtokens) + +.. code-block:: bash + + python ${NEMO_ROOT}/scripts/tokenizers/process_asr_text_tokenizer.py \ + --manifest=dev_decoded_processed.json,train_decoded_processed.json \ + --vocab_size=1024 \ + --data_root=tokenizer_bpe_maxlen_4 \ + --tokenizer="spe" \ + --spe_type=bpe \ + --spe_character_coverage=1.0 \ + --spe_max_sentencepiece_length=4 \ + --log + + python ${NEMO_ROOT}/scripts/tokenizers/process_asr_text_tokenizer.py \ + --manifest=dev_decoded_processed.json,train_decoded_processed.json \ + --vocab_size=128 \ + --data_root=tokenizer_bpe_maxlen_2 \ + --tokenizer="spe" \ + --spe_type=bpe \ + --spe_character_coverage=1.0 \ + --spe_max_sentencepiece_length=2 \ + --log + +Most of the arguments are similar to those explained in the `ASR with Subword Tokenization tutorial `_. + +The resulting tokenizer is a folder like that: + +.. code-block:: bash + + ├── tokenizer_spe_bpe_v1024_max_4 + │ ├── tokenizer.model + │ ├── tokenizer.vocab + │ └── vocab.txt + +Remember that you will need to pass the path to tokenizer in the model config. +You can see all the subtokens in the **vocab.txt** file. + +***************************** +Tarred datasets and bucketing +***************************** + +There are two useful techniques for training on large datasets. + +* Tarred dataset allows to store the dataset as large .tar files instead of small separate audio files. It speeds up the training and minimizes the load on the network in the cluster. +* Bucketing groups utterances with similar duration. It reduces padding and speeds up the training. + +The NeMo toolkit provides a script to implement both of these techniques. + +.. code-block:: bash + + ## create tarred dataset with 1 bucket + python ${NEMO_ROOT}/scripts/speech_recognition/convert_to_tarred_audio_dataset.py \ + --manifest_path=train_decoded_processed.json \ + --target_dir=train_tarred_1bk \ + --num_shards=1024 \ + --max_duration=11.0 \ + --min_duration=1.0 \ + --shuffle \ + --shuffle_seed=1 \ + --sort_in_shards \ + --workers=-1 + + + ## create tarred dataset with 4 buckets + python ${NEMO_ROOT}/scripts/speech_recognition/convert_to_tarred_audio_dataset.py \ + --manifest_path=train_decoded_processed.json \ + --target_dir=train_tarred_4bk \ + --num_shards=1024 \ + --max_duration=11.0 \ + --min_duration=1.0 \ + --shuffle \ + --shuffle_seed=1 \ + --sort_in_shards \ + --workers=-1 \ + --buckets_num=4 + +**Note**: we only need to process train data, dev and test are usually much smaller and can be used as is. + +Our final dataset folder looks like this: + +.. code-block:: bash + + ├── dev [15988 .wav files] + ├── dev_decoded_processed.json (dev manifest) + ├── test [16213 .wav files] + ├── test_decoded_processed.json (test manifest) + └── train_tarred_1bk + ├── metadata.yaml + ├── tarred_audio_manifest.json + └── [1024 .tar files] + +In case of 4 buckets it will look like: + +.. code-block:: bash + + └── train_tarred_4bk + ├── bucket1 + ├── metadata.yaml + ├── tarred_audio_manifest.json + └── [1024 .tar files] + ├── bucket2 + ... + ├── bucket3 + └── bucket4 + +************************************ +Training from scratch and finetuning +************************************ + +ASR models +########## + +Our goal was to train two ASR models with different architectures: :ref:`Conformer-CTC ` and :ref:`Conformer-Transducer `, with around 120 million parameters. +The CTC model predicts output tokens for each timestep. The outputs are assumed to be independent of each other. As a result the CTC models work faster but they can produce outputs that are inconsistent with each other. CTC models are often combined with external language models in production. In contrast, the Transducer models contain the decoding part which generates the output tokens one by one and the next token prediction depends on this history. Due to autoregressive nature of decoding the inference speed is several times slower than that of CTC models, but the quality is usually better because it can incorporate language model information within the same model. + +Training scripts and configs +############################ + +To train a Conformer-CTC model, we use `speech_to_text_ctc_bpe.py `_ with the default config `conformer_ctc_bpe.yaml `_. +To train a Conformer-Transducer model, we use `speech_to_text_rnnt_bpe.py `_ with the default config `conformer_transducer_bpe.yaml `_. +Any options of default config can be overwritten from command line. +Usually we should provide the options related to the dataset and tokenizer. + +This is an example of how we can run the training script: + +.. code-block:: bash + + TOKENIZER=tokenizers/tokenizer_spe_bpe_v1024_max_4/ + TRAIN_MANIFEST=data/train_tarred_1bk/tarred_audio_manifest.json + TRAIN_FILEPATHS=data/train_tarred_1bk/audio__OP_0..1023_CL_.tar + VAL_MANIFEST=data/dev_decoded_processed.json + TEST_MANIFEST=data/test_decoded_processed.json + + python ${NEMO_ROOT}/examples/asr/asr_ctc/speech_to_text_ctc_bpe.py \ + --config-path=../conf/conformer/ \ + --config-name=conformer_ctc_bpe \ + exp_manager.name="Some name of our experiment" \ + exp_manager.resume_if_exists=true \ + exp_manager.resume_ignore_no_checkpoint=true \ + exp_manager.exp_dir=results/ \ + model.tokenizer.dir=$TOKENIZER \ + model.train_ds.is_tarred=true \ + model.train_ds.tarred_audio_filepaths=$TRAIN_FILEPATHS \ + model.train_ds.manifest_filepath=$TRAIN_MANIFEST \ + model.validation_ds.manifest_filepath=$VAL_MANIFEST \ + model.test_ds.manifest_filepath=$TEST_MANIFEST + +The option *exp_manager.resume_if_exists=true* allows to resume training. Actually you can stop training at any moment and then continue from the last checkpoint. +When the training is finished, the final model will be saved as *.nemo* file inside the folder that we specified in *exp_manager.exp_dir*. + +Training dynamics +################# + +The figure below shows the training dynamics when we train Kinyarwanda models **from scratch**. In these experiments we used the hyperparameters from the default configs, the training was run on 2 nodes with 16 gpus per node, training batch size was 32. We see that Transducer model achieves better quality than CTC. + + .. image:: ../images/kinyarwanda_from_scratch.png + :align: center + :alt: Training dynamics of Kinyarwanda models trained from scratch + :width: 800px + +Finetuning from another model +############################# + +Often it's a good idea to initialize our ASR model with the weights of some other pretrained model, for example, a model for another language. It usually makes our model to converge faster and achieve better quality, especially if the dataset for our target language is small. + +Though Kinyarwanda dataset is rather large, we also tried finetuning Kinyarwanda Conformer-Transducer model from different pretrained checkpoints, namely: + +* English Conformer-Transducer checkpoint +* Self-supervised Learning (SSL) checkpoint trained on English data +* SSL checkpoint trained on multilingual data + +To initialize from **non-SSL checkpoint** we should simply add the option `+init_from_pretrained_model`: + +.. code-block:: bash + + INIT_MODEL='stt_en_conformer_ctc_large' + + python ${NEMO_ROOT}/examples/asr/asr_ctc/speech_to_text_ctc_bpe.py + ...[same options as in the previous example]... + +init_from_pretrained_model=${INIT_MODEL} + +In that case the pretrained model `stt_en_conformer_ctc_large `_ will be automatically downloaded from NVIDIA GPU Cloud(NGC) and used to initialize weights before training. + +To initialize from **SSL checkpoint** we should edit our training script like the following code: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + ssl_model = nemo_asr.models.ssl_models.SpeechEncDecSelfSupervisedModel.from_pretrained(model_name='ssl_en_conformer_large') + + # define fine-tune model + asr_model = nemo_asr.models.EncDecCTCModelBPE(cfg=cfg.model, trainer=trainer) + + # load ssl checkpoint + asr_model.load_state_dict(ssl_model.state_dict(), strict=False) + + del ssl_model + +When using finetuning you probably will need to change the some hyperparameters from the default config, especially the learning rate and learning rate policy. In the experiments below we used *model.optim.sched.name=CosineAnnealing* and *model.optim.lr=1e-3*. + +The figure below compares the training dynamics for three Conformer-Transducer models. They differ only by how they are initialized. We see that finetuning leads to faster convergence and better quality. Initializing from SSL gives lowest WER at earlier stages, but in a longer period it performs worse. + + .. image:: ../images/kinyarwanda_finetuning.png + :align: center + :alt: Training dynamics of Kinyarwanda models trained from scratch and finetuned from different pretrained checkpoints + :width: 800px + +************************ +Inference and evaluation +************************ + +Running the inference +##################### + +To run the inference we need a pretrained model. This can be either a `.nemo` file that we get after the training is finished, or any published ASR model from `HF `__ or `NGC `__. +We run the inference using the following script: + +.. code-block:: bash + + python ${NEMO_ROOT}/examples/asr/transcribe_speech.py \ + model_path=.nemo \ + dataset_manifest=./test_decoded_processed.json \ + output_filename=./test_with_predictions.json \ + batch_size=8 \ + cuda=1 \ + amp=True + +To run inference with NVIDIA's Kinyarwanda checkpoints `STT Rw Conformer-CTC Large `_ or `STT Rw Conformer-Transducer Large `_ use: + +.. code-block:: bash + + python ${NEMO_ROOT}/examples/asr/transcribe_speech.py \ + pretrained_name="stt_rw_conformer_ctc_large" \ + dataset_manifest=test_decoded_processed.json \ + output_filename=./pred_ctc.json \ + batch_size=8 \ + cuda=1 \ + amp=True + +**Note:** If you want to transcribe new audios, you can pass a folder with audio files using `audio_dir` parameter instead of `dataset_manifest`. + +After the inference is finished the `output_filename` is a `.json` manifest augmented with a new field `pred_text` containing the resulting transcript. Example: + +.. code-block:: + + {"audio_filepath": "test/common_voice_rw_19835615.wav", "text": "kw'ibumoso", "up_votes": 2, "down_votes": 0, "age": NaN, "gender": NaN, "accents": NaN, "client_id": "66675a7003e6baa3e7d4af01bff8324ac3c5f15e7f8918180799dd2928227c791f19e2811f9ec5779a2b06dac1b7a97fa7740dcfe98646ea1b5e106250c260be", "duration": 3.672, "pred_text": "n'ibumoso"} + {"audio_filepath": "test/common_voice_rw_24795878.wav", "text": "ni ryari uheruka kurya urusenda", "up_votes": 2, "down_votes": 0, "age": NaN, "gender": NaN, "accents": NaN, "client_id": "90e0438947a75b6c0cf59a0444aee3b81a76c5f9459c4b22df2e14b4ce257aeacaed8ac6092bfcd75b8e831633d58a84287fd62190c21d70d75efe8d93ed74ed", "duration": 3.312, "pred_text": "ni ryari uheruka kurya urusenda"} + {"audio_filepath": "test/common_voice_rw_24256935.wav", "text": "umunani", "up_votes": 2, "down_votes": 0, "age": NaN, "gender": NaN, "accents": NaN, "client_id": "974d4876e99e7437183c20f9107053acc9e514379d448bcf00aaaabc0927f5380128af86d39650867fa80a82525110dfc40784a5371c989de1a5bdf531f6d943", "duration": 3.24, "pred_text": "umunani"} + +Word Error Rate (WER) and Character Error Rate (CER) +#################################################### + +As soon as we have a manifest file with `text` and `pred_text` we can measure the quality of predictions of our model. + +.. code-block:: bash + + # Calculate WER + python ${NEMO_ROOT}/examples/asr/speech_to_text_eval.py \ + dataset_manifest=test_with_predictions.json \ + use_cer=False \ + only_score_manifest=True + + # Calculate CER + python ${NEMO_ROOT}/examples/asr/speech_to_text_eval.py \ + dataset_manifest=test_with_predictions.json \ + use_cer=True \ + only_score_manifest=True + + +Evaluation of NVIDIA's Kinyarwanda checkpoints +############################################## + +If you run inference and evaluation of NVIDIA's published Kinyarwanda models, you should get metrics like these: + ++----------------------------------+-------+-------+ +| Model | WER % | CER % | ++==================================+=======+=======+ +| stt_rw_conformer_ctc_large | 18.22 | 5.45 | ++----------------------------------+-------+-------+ +| stt_rw_conformer_trasducer_large | 16.19 | 5.7 | ++----------------------------------+-------+-------+ + +Error analysis +############## + +Still, even WER of 16% is not as good as we usually get for other languages trained with NeMo toolkit, so we may want to look at the errors that the model makes to better understand what's the problem. + +We can use :doc:`Speech Data Explorer <../../tools/speech_data_explorer>` to analyze the errors. + +If we run + +.. code-block:: bash + + python ${NEMO_ROOT}/tools/speech_data_explorer/data_explorer.py + +it will start a local server, and provide a http address to open from the browser. +In the UI we can see the model predictions and their diff with the reference, and also we can listen to the corresponding audio. We also can sort the sentences by descending WER and look through the top of them. + +The error analysis showed several problems concerning the Kinyarwanda dataset: + +* Noisy multi-speaker records (e.g. common_voice_rw_19830859.wav) +* Bad quality of record (e.g. common_voice_rw_24452415.wav) +* Orthographic variability related to space/no space/apostrophe + * *kugira ngo / kugirango* + * *nkuko / nk'uko* + * *n iyo / n'iyo* +* Multiple orthographic variants for foreign words + * *telefoni / telephone* + * *film / filime* + * *isiraheli / israel* + * *radio / radiyo* + * *kongo / congo* +* l/r variability + * *abamalayika / abamarayika* + + diff --git a/docs/source/asr/images/citrinet_vertical.png b/docs/source/asr/images/citrinet_vertical.png new file mode 100644 index 0000000000000000000000000000000000000000..ebaa70dcd641cb5ad15b073f72b59f2ef56b5d3e --- /dev/null +++ b/docs/source/asr/images/citrinet_vertical.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c00206399bd01fb8335c81bec735cbabc38c663df87f74c807310931af558b5 +size 138615 diff --git a/docs/source/asr/images/conf-ensembles-overview.png b/docs/source/asr/images/conf-ensembles-overview.png new file mode 100644 index 0000000000000000000000000000000000000000..bcda4568d08fd646e5f6da9bdb05793126b0ba60 --- /dev/null +++ b/docs/source/asr/images/conf-ensembles-overview.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe36df78633a672e6d90089f34e5ff07fd2017d8400d45a9bdc01e0d32277b14 +size 134089 diff --git a/docs/source/asr/images/conformer_ctc.png b/docs/source/asr/images/conformer_ctc.png new file mode 100644 index 0000000000000000000000000000000000000000..eebfd30b461f290b5bad92d8a6fe23df52c148da --- /dev/null +++ b/docs/source/asr/images/conformer_ctc.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:406af0448bdb3d93121a00efbbbca63c3f5fe6c4b7db60870f58ac2fcd3664e3 +size 105304 diff --git a/docs/source/asr/images/ctc_asr.png b/docs/source/asr/images/ctc_asr.png new file mode 100644 index 0000000000000000000000000000000000000000..8051f283ab42d7136d86a3994b986f9d7a789f36 --- /dev/null +++ b/docs/source/asr/images/ctc_asr.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:978976d5959e7bae16bd187aae82501ab4fec04018c4c9db7d087be3fd93a9e9 +size 54705 diff --git a/docs/source/asr/images/hat.png b/docs/source/asr/images/hat.png new file mode 100644 index 0000000000000000000000000000000000000000..37c7c3af650094f8cd3b4728528e4be357dd06e1 --- /dev/null +++ b/docs/source/asr/images/hat.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c727fa4ddee01cd4395987b1e17bcf4d9b72c8a42e7fbec59457532e1f45f3af +size 110874 diff --git a/docs/source/asr/images/hybrid_asr_tts_model.png b/docs/source/asr/images/hybrid_asr_tts_model.png new file mode 100644 index 0000000000000000000000000000000000000000..511d191c913f1f840a81be910e72f2ed5cd54e5a --- /dev/null +++ b/docs/source/asr/images/hybrid_asr_tts_model.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16e0a8e98e6748096c0cf9a55495446713f3136205bdb2a1f21a4eef9e2d2e1c +size 112870 diff --git a/docs/source/asr/images/jasper_layers.png b/docs/source/asr/images/jasper_layers.png new file mode 100644 index 0000000000000000000000000000000000000000..05f69a3c93788dea96bc1cb8b8813916f6a90f4b --- /dev/null +++ b/docs/source/asr/images/jasper_layers.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb28dbd07465512905fa890fe3b3b887e79fe22cea6e73f6af3f7c7bdc1988fc +size 25461 diff --git a/docs/source/asr/images/jasper_vertical.png b/docs/source/asr/images/jasper_vertical.png new file mode 100644 index 0000000000000000000000000000000000000000..192f603800305b15d2df5e095962b5555b3d2a67 --- /dev/null +++ b/docs/source/asr/images/jasper_vertical.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24e6d58df50927e50caf9948c429da949c69c95948ff6adb935ec631f667322b +size 279466 diff --git a/docs/source/asr/images/kinyarwanda_finetuning.png b/docs/source/asr/images/kinyarwanda_finetuning.png new file mode 100644 index 0000000000000000000000000000000000000000..e026c75f1ba1cde679f9612b4bd89688dacb51fb --- /dev/null +++ b/docs/source/asr/images/kinyarwanda_finetuning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d73d98246e3f09ef8d81b85e85d8d3fe8a0a367b103db632a761368d44110f48 +size 35424 diff --git a/docs/source/asr/images/kinyarwanda_from_scratch.png b/docs/source/asr/images/kinyarwanda_from_scratch.png new file mode 100644 index 0000000000000000000000000000000000000000..f848aa8d6861a027a537f9ff558cc89ba2cf3286 --- /dev/null +++ b/docs/source/asr/images/kinyarwanda_from_scratch.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4e0e67cadc574d43ce6ab68a9bea43f20208577c9f39a68df34ba6d9faeb814 +size 28442 diff --git a/docs/source/asr/images/quartz_vertical.png b/docs/source/asr/images/quartz_vertical.png new file mode 100644 index 0000000000000000000000000000000000000000..103284339fb6e9d1fd1ae01f7dcfc49fe4d6e1b8 --- /dev/null +++ b/docs/source/asr/images/quartz_vertical.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5fc6ecbe45d5737fe4207902c4466b93472726d6fab674a86b229c1f0803b6e1 +size 262776 diff --git a/docs/source/asr/images/squeezeformer.png b/docs/source/asr/images/squeezeformer.png new file mode 100644 index 0000000000000000000000000000000000000000..a4b620ceae969c6164620c34871394273237a4eb --- /dev/null +++ b/docs/source/asr/images/squeezeformer.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f08586afd7d94a3d2fe62375083f2012fb9b64783fb923e2a1af34ff56c9efca +size 582160 diff --git a/docs/source/asr/intro.rst b/docs/source/asr/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..25efcb2a0ced4aab02c6481eebbfa2eb3db2291d --- /dev/null +++ b/docs/source/asr/intro.rst @@ -0,0 +1,272 @@ +Automatic Speech Recognition (ASR) +================================== + +Automatic Speech Recognition (ASR), also known as Speech To Text (STT), refers to the problem of automatically transcribing spoken language. +You can use NeMo to transcribe speech using open-sourced pretrained models in :ref:`14+ languages `, or :doc:`train your own<./examples/kinyarwanda_asr>` ASR models. + + + +Transcribe speech with 3 lines of code +---------------------------------------- +After :ref:`installing NeMo`, you can transcribe an audio file as follows: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + asr_model = nemo_asr.models.ASRModel.from_pretrained("nvidia/parakeet-tdt-0.6b-v2") + transcript = asr_model.transcribe(["path/to/audio_file.wav"])[0].text + +Obtain timestamps +^^^^^^^^^^^^^^^^^ + +Obtaining char(token), word or segment timestamps is also possible with NeMo ASR Models. + +Currently, timestamps are available for Parakeet Models with all types of decoders (CTC/RNNT/TDT). Support for AED models would be added soon. + +There are two ways to obtain timestamps: +1. By using the `timestamps=True` flag in the `transcribe` method. +2. For more control over the timestamps, you can update the decoding config to mention type of timestamps (char, word, segment) and also specify the segment seperators or word seperator for segment and word level timestamps. + +With the `timestamps=True` flag, you can obtain timestamps for each character in the transcription as follows: + +.. code-block:: python + + # import nemo_asr and instantiate asr_model as above + import nemo.collections.asr as nemo_asr + asr_model = nemo_asr.models.ASRModel.from_pretrained("nvidia/parakeet-tdt-0.6b-v2") + + # specify flag `timestamps=True` + hypotheses = asr_model.transcribe(["path/to/audio_file.wav"], timestamps=True) + + # by default, timestamps are enabled for char, word and segment level + word_timestamps = hypotheses[0].timestamp['word'] # word level timestamps for first sample + segment_timestamps = hypotheses[0].timestamp['segment'] # segment level timestamps + char_timestamps = hypotheses[0].timestamp['char'] # char level timestamps + + for stamp in segment_timestamps: + print(f"{stamp['start']}s - {stamp['end']}s : {stamp['segment']}") + + # segment level timestamps (if model supports Punctuation and Capitalization, segment level timestamps are displayed based on punctuation otherwise complete transcription is considered as a single segment) + +For more control over the timestamps, you can update the decoding config to mention type of timestamps (char, word, segment) and also specify the segment seperators or word seperator for segment and word level timestamps as follows: + +.. code-block:: python + + # import nemo_asr and instantiate asr_model as above + import nemo.collections.asr as nemo_asr + asr_model = nemo_asr.models.ASRModel.from_pretrained("nvidia/parakeet-tdt-0.6b-v2") + + # update decoding config to preserve alignments and compute timestamps + # if necessary also update the segment seperators or word seperator for segment and word level timestamps + from omegaconf import OmegaConf, open_dict + decoding_cfg = asr_model.cfg.decoding + with open_dict(decoding_cfg): + decoding_cfg.preserve_alignments = True + decoding_cfg.compute_timestamps = True + decoding_cfg.segment_seperators = [".", "?", "!"] + decoding_cfg.word_seperator = " " + asr_model.change_decoding_strategy(decoding_cfg) + + # specify flag `return_hypotheses=True`` + hypotheses = asr_model.transcribe(["path/to/audio_file.wav"], return_hypotheses=True) + + timestamp_dict = hypotheses[0].timestamp # extract timestamps from hypothesis of first (and only) audio file + print("Hypothesis contains following timestamp information :", list(timestamp_dict.keys())) + + # For a FastConformer model, you can display the word timestamps as follows: + # 80ms is duration of a timestamp at output of the Conformer + time_stride = 8 * asr_model.cfg.preprocessor.window_stride + + word_timestamps = timestamp_dict['word'] + segment_timestamps = timestamp_dict['segment'] + + for stamp in word_timestamps: + start = stamp['start_offset'] * time_stride + end = stamp['end_offset'] * time_stride + word = stamp['char'] if 'char' in stamp else stamp['word'] + + print(f"Time : {start:0.2f} - {end:0.2f} - {word}") + + for stamp in segment_timestamps: + start = stamp['start_offset'] * time_stride + end = stamp['end_offset'] * time_stride + segment = stamp['segment'] + + print(f"Time : {start:0.2f} - {end:0.2f} - {segment}") + +Transcribe speech via command line +---------------------------------- +You can also transcribe speech via the command line using the following `script `_, for example: + +.. code-block:: bash + + python /examples/asr/transcribe_speech.py \ + pretrained_name="stt_en_fastconformer_transducer_large" \ + audio_dir= # path to dir containing audio files to transcribe + +The script will save all transcriptions in a JSONL file where each line corresponds to an audio file in ````. +This file will correspond to a format that NeMo commonly uses for saving model predictions, and also for storing +input data for training and evaluation. You can learn more about the format that NeMo uses for these files +(which we refer to as "manifest files") :ref:`here`. + +You can also specify the files to be transcribed inside a manifest file, and pass that in using the argument +``dataset_manifest=`` instead of ``audio_dir``. + + +Improve ASR transcriptions by incorporating a language model (LM) +----------------------------------------------------------------- + +You can often improve transcription accuracy by incorporating a language model to guide the selection of more probable words in context. +Even a simple n-gram language model can yield a noticeable improvement. + +NeMo supports GPU-accelerated language model fusion for all major ASR model types, including CTC, RNN-T, TDT, and AED. +Customization is available during both greedy and beam decoding. After :ref:`training ` an n-gram LM, you can apply it using the +`speech_to_text_eval.py `_ script. + +**To configure the evaluation:** + +1. Select the pretrained model: + Use the `pretrained_name` option or provide a local path using `model_path`. + +2. Set up the N-gram language model: + Provide the path to the NGPU-LM model with `ngram_lm_model`, and set LM weight with `ngram_lm_alpha`. + +3. Choose the decoding strategy: + + - CTC models: `greedy_batch` or `beam_batch` + - RNN-T models: `greedy_batch`, `malsd_batch`, or `maes_batch` + - TDT models: `greedy_batch` or `malsd_batch` + - AED models: `beam` (set `beam_size=1` for greedy decoding) + +4. Run the evaluation script. + +**Example: CTC Greedy Decoding with NGPU-LM** + +.. code-block:: bash + + python examples/asr/speech_to_text_eval.py \ + pretrained_name=nvidia/parakeet-ctc-1.1b \ + amp=false \ + amp_dtype=bfloat16 \ + matmul_precision=high \ + compute_dtype=bfloat16 \ + presort_manifest=true \ + cuda=0 \ + batch_size=32 \ + dataset_manifest= \ + ctc_decoding.greedy.ngram_lm_model= \ + ctc_decoding.greedy.ngram_lm_alpha=0.2 \ + ctc_decoding.greedy.allow_cuda_graphs=True \ + ctc_decoding.strategy="greedy_batch" + +**Example: RNN-T Beam Search with NGPU-LM** + +.. code-block:: bash + + python examples/asr/speech_to_text_eval.py \ + pretrained_name=nvidia/parakeet-rnnt-1.1b \ + amp=false \ + amp_dtype=bfloat16 \ + matmul_precision=high \ + compute_dtype=bfloat16 \ + presort_manifest=true \ + cuda=0 \ + batch_size=16 \ + dataset_manifest= \ + rnnt_decoding.beam.ngram_lm_model= \ + rnnt_decoding.beam.ngram_lm_alpha=0.3 \ + rnnt_decoding.beam.beam_size=10 \ + rnnt_decoding.strategy="malsd_batch" + +See detailed documentation here: :ref:`asr_language_modeling_and_customization`. + +Use real-time transcription +--------------------------- + +It is possible to use NeMo to transcribe speech in real-time. We provide tutorial notebooks for `Cache Aware Streaming `_ and `Buffered Streaming `_. + +Try different ASR models +------------------------ + +NeMo offers a variety of open-sourced pretrained ASR models that vary by model architecture: + +* **encoder architecture** (FastConformer, Conformer, etc.), +* **decoder architecture** (Transducer, CTC & hybrid of the two), +* **size** of the model (small, medium, large, etc.). + +The pretrained models also vary by: + +* **language** (English, Spanish, etc., including some **multilingual** and **code-switching** models), +* whether the output text contains **punctuation & capitalization** or not. + +The NeMo ASR checkpoints can be found on `HuggingFace `_, or on `NGC `_. All models released by the NeMo team can be found on NGC, and some of those are also available on HuggingFace. + +All NeMo ASR checkpoints open-sourced by the NeMo team follow the following naming convention: +``stt_{language}_{encoder name}_{decoder name}_{model size}{_optional descriptor}``. + +You can load the checkpoints automatically using the ``ASRModel.from_pretrained()`` class method, for example: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + # model will be fetched from NGC + asr_model = nemo_asr.models.ASRModel.from_pretrained("stt_en_fastconformer_transducer_large") + # if model name is prepended with "nvidia/", the model will be fetched from huggingface + asr_model = nemo_asr.models.ASRModel.from_pretrained("nvidia/stt_en_fastconformer_transducer_large") + # you can also load open-sourced NeMo models released by other HF users using: + # asr_model = nemo_asr.models.ASRModel.from_pretrained("/") + +See further documentation about :doc:`loading checkpoints <./results>`, a full :ref:`list ` of models and their :doc:`benchmark scores <./scores>`. + +There is also more information about the ASR model architectures available in NeMo :doc:`here <./models>`. + + +Try out NeMo ASR transcription in your browser +---------------------------------------------- +You can try out transcription with a NeMo ASR model without leaving your browser, by using the HuggingFace Space embedded below. + +This HuggingFace Space uses `Parakeet TDT 0.6B V2 `__, the latest ASR model from NVIDIA NeMo. It sits at the top of the `HuggingFace OpenASR Leaderboard `__ at time of writing (May 2nd 2025). + +.. raw:: html + + + + + + + +ASR tutorial notebooks +---------------------- +Hands-on speech recognition tutorial notebooks can be found under `the ASR tutorials folder `_. +If you are a beginner to NeMo, consider trying out the `ASR with NeMo `_ tutorial. +This and most other tutorials can be run on Google Colab by specifying the link to the notebooks' GitHub pages on Colab. + +ASR model configuration +----------------------- +Documentation regarding the configuration files specific to the ``nemo_asr`` models can be found in the :doc:`Configuration Files <./configs>` section. + +Preparing ASR datasets +---------------------- +NeMo includes preprocessing scripts for several common ASR datasets. The :doc:`Datasets <./datasets>` section contains instructions on +running those scripts. It also includes guidance for creating your own NeMo-compatible dataset, if you have your own data. + +NeMo ASR Documentation +---------------------- +For more information, see additional sections in the ASR docs on the left-hand-side menu or in the list below: + +.. toctree:: + :maxdepth: 1 + + models + datasets + asr_language_modeling_and_customization + results + scores + configs + api + all_chkpt + streaming_decoding/canary_chunked_and_streaming_decoding + examples/kinyarwanda_asr.rst diff --git a/docs/source/asr/models.rst b/docs/source/asr/models.rst new file mode 100644 index 0000000000000000000000000000000000000000..4a6e329435e4ae0bce837fb16f244c2600fa1951 --- /dev/null +++ b/docs/source/asr/models.rst @@ -0,0 +1,524 @@ +Models +====== + +This section gives a brief overview of the models that NeMo's ASR collection currently supports. + +Each of these models can be used with the example ASR scripts (in the ``/examples/asr`` directory) by +specifying the model architecture in the config file used. Examples of config files for each model can be found in +the ``/examples/asr/conf`` directory. + +For more information about the config files and how they should be structured, refer to the :doc:`./configs` section. + +Pretrained checkpoints for all of these models, as well as instructions on how to load them, can be found in the :doc:`./results` +section. You can use the available checkpoints for immediate inference, or fine-tune them on your own datasets. The checkpoints section +also contains benchmark results for the available ASR models. + + +Spotlight Models +---------------- + +Canary +~~~~~~ + +Canary is the latest family of models from NVIDIA NeMo. Canary models are encoder-decoder models with a :ref:`FastConformer Encoder ` and Transformer Decoder :cite:`asr-models-vaswani2017aayn`. +They are multi-lingual, multi-task model, supporting automatic speech-to-text recognition (ASR) in 25 EU languages as well as translation between English and the 24 other supported languages. + +Models: + +* `Canary-1B V2 `__ model card +* `Canary-1B Flash `__ model card +* `Canary-180M Flash `__ model card +* `Canary-1B `__ model card + +Spaces: + +* `Canary-1B V2 `__ +* `Canary-1B Flash `__ +* `Canary-1B `__ + +Canary models support the following decoding methods for chunked and streaming inference: + +* :ref:`Chunked Inference ` +* :ref:`Streaming Inference ` + + +Parakeet +~~~~~~~~ + +Parakeet is the name of a family of ASR models with a :ref:`FastConformer Encoder ` and a CTC, RNN-T, or TDT decoder. + +Model checkpoints: + +* `Parakeet-TDT-0.6B V2 `__ model card + + * this model sits top of the `HuggingFace OpenASR Leaderboard `__ at time of writing (May 2nd 2025) + +* `Parakeet-CTC-0.6B `__ and `Parakeet-CTC-1.1B `__ model cards + +* `Parakeet-RNNT-0.6B `__ and `Parakeet-RNNT-1.1B `__ model cards + +* `Parakeet-TDT-1.1B `__ model card + +HuggingFace Spaces to try out Parakeet models in your browser: + +* `Parakeet-TDT-0.6B V2 `__ space + +.. _Conformer_model: + +Conformer +--------- + +.. _Conformer-CTC_model: + +Conformer-CTC +~~~~~~~~~~~~~ + +Conformer-CTC is a CTC-based variant of the Conformer model introduced in :cite:`asr-models-gulati2020conformer`. Conformer-CTC has a +similar encoder as the original Conformer but uses CTC loss and decoding instead of RNNT/Transducer loss, which makes it a non-autoregressive model. +We also drop the LSTM decoder and instead use a linear decoder on the top of the encoder. This model uses the combination of +self-attention and convolution modules to achieve the best of the two approaches, the self-attention layers can learn the global +interaction while the convolutions efficiently capture the local correlations. The self-attention modules support both regular +self-attention with absolute positional encoding, and also Transformer-XL's self-attention with relative positional encodings. + +Here is the overall architecture of the encoder of Conformer-CTC: + +.. image:: images/conformer_ctc.png + :align: center + :alt: Conformer-CTC Model + :scale: 50% + +This model supports both the sub-word level and character level encodings. You can find more details on the config files for the +Conformer-CTC models in the :ref:`Conformer-CTC configuration documentation `. The variant with sub-word encoding is a BPE-based model +which can be instantiated using the :class:`~nemo.collections.asr.models.EncDecCTCModelBPE` class, while the +character-based variant is based on :class:`~nemo.collections.asr.models.EncDecCTCModel`. + +You may find the example config files of Conformer-CTC model with character-based encoding at +``/examples/asr/conf/conformer/conformer_ctc_char.yaml`` and +with sub-word encoding at ``/examples/asr/conf/conformer/conformer_ctc_bpe.yaml``. + +.. _Conformer-Transducer_model: + +Conformer-Transducer +~~~~~~~~~~~~~~~~~~~~ + +Conformer-Transducer is the Conformer model introduced in :cite:`asr-models-gulati2020conformer` and uses RNNT/Transducer loss/decoder. +It has the same encoder as Conformer-CTC but utilizes RNNT/Transducer loss/decoder which makes it an autoregressive model. + +Most of the config file for Conformer-Transducer models are similar to Conformer-CTC except the sections related to the decoder and loss: decoder, loss, joint, decoding. +You may take a look at our :doc:`tutorials page <../starthere/tutorials>` on Transducer models to become familiar with their configs: +`Introduction to Transducers `_ and +`ASR with Transducers `_ +You can find more details on the config files for the Conformer-Transducer models in the :ref:`Conformer-CTC configuration documentation `. + +This model supports both the sub-word level and character level encodings. The variant with sub-word encoding is a BPE-based model +which can be instantiated using the :class:`~nemo.collections.asr.models.EncDecRNNTBPEModel` class, while the +character-based variant is based on :class:`~nemo.collections.asr.models.EncDecRNNTModel`. + +You may find the example config files of Conformer-Transducer model with character-based encoding at +``/examples/asr/conf/conformer/conformer_transducer_char.yaml`` and +with sub-word encoding at ``/examples/asr/conf/conformer/conformer_transducer_bpe.yaml``. + +.. _Conformer-HAT_model: + +Conformer-HAT +~~~~~~~~~~~~~ + +Conformer HAT (Hybrid Autoregressive Transducer) model (do not confuse it with Hybrid-Transducer-CTC) is a modification of Conformer-Transducer model based on this previous `work `_. +The main idea is to separate labels and blank score predictions, which allows to estimate the internal LM probabilities during decoding. +When external LM is available for inference, the internal LM can be subtracted from HAT model prediction in beamsearch decoding to improve external LM efficiency. +It can be helpful in the case of text-only adaptation for new domains. + +The only difference from the standard Conformer-Transducer model (RNNT) is the use of `"HATJoint" `_ +class (instead of "RNNTJoint") for joint module. The all HAT logic is implemented in the "HATJoint" class. + +.. image:: images/hat.png + :align: center + :alt: HAT Model + :scale: 50% + +You may find the example config files of Conformer-HAT model with character-based encoding at +``/examples/asr/conf/conformer/hat/conformer_hat_char.yaml`` and +with sub-word encoding at ``/examples/asr/conf/conformer/hat/conformer_hat_bpe.yaml``. + +By default, the decoding for HAT model works in the same way as for Conformer-Transducer. +In the case of external ngram LM fusion you can use ``/scripts/asr_language_modeling/ngram_lm/eval_beamsearch_ngram_transducer.py``. +To enable HAT internal LM subtraction set ``hat_subtract_ilm=True`` and find more appropriate couple of ``beam_alpha`` and ``hat_ilm_weight`` values in terms of the best recognition accuracy. + +.. _Fast-Conformer: + +Fast-Conformer +-------------- + +The Fast Conformer (CTC and RNNT) models have a faster version of the Conformer encoder and differ from it as follows: + +* 8x depthwise convolutional subsampling with 256 channels +* Reduced convolutional kernel size of 9 in the conformer blocks + +The Fast Conformer encoder is about 2.4x faster than the regular Conformer encoder without a significant model quality degradation. +128 subsampling channels yield a 2.7x speedup vs baseline but model quality starts to degrade. +With local attention, inference is possible on audios >1 hrs (256 subsampling channels) / >2 hrs (128 channels). + +Fast Conformer models were trained using CosineAnnealing (instead of Noam) as the scheduler. + +You may find the example CTC config at +``/examples/asr/conf/fastconformer/fast-conformer_ctc_bpe.yaml`` and +the transducer config at ``/examples/asr/conf/fastconformer/fast-conformer_transducer_bpe.yaml`` + +Note that both configs are subword-based (BPE). + +You can also train these models with longformer-style attention (https://arxiv.org/abs/2004.05150) using the following configs: CTC config at +``/examples/asr/conf/fastconformer/fast-conformer-long_ctc_bpe.yaml`` and transducer config at ``/examples/asr/conf/fastconformer/fast-conformer-long_transducer_bpe.yaml`` +This allows using the model on longer audio (up to 70 minutes with Fast Conformer). Note that the Fast Conformer checkpoints +can be used with limited context attention even if trained with full context. However, if you also want to use global tokens, +which help aggregate information from outside the limited context, then training is required. + +You may find more examples under ``/examples/asr/conf/fastconformer/``. + +.. _cache-aware streaming conformer: + +Cache-aware Streaming Conformer +------------------------------- + +Try real-time ASR with the `Cache-aware Streaming Conformer tutorial notebook `_. + +Buffered streaming uses overlapping chunks to make an offline ASR model usable for streaming with reasonable accuracy. However, it causes significant amount of duplication in computation due to the overlapping chunks. +Also, there is an accuracy gap between the offline model and the streaming one, as there is inconsistency between how we train the model and how we perform inference for streaming. +The Cache-aware Streaming Conformer models tackle and address these disadvantages. These streaming Conformers are trained with limited right context, making it possible to match how the model is being used in both training and inference. +They also use caching to store intermediate activations to avoid any duplication in compute. +The cache-aware approach is supported for both the Conformer-CTC and Conformer-Transducer and enables the model to be used very efficiently for streaming. + +Three categories of layers in Conformer have access to right tokens: +#. depthwise convolutions +#. self-attention +#. convolutions in the downsampling layers. + +Streaming Conformer models use causal convolutions or convolutions with lower right context and also self-attention with limited right context to limit the effective right context for the input. +The model trained with such limitations can be used in streaming mode and give the exact same outputs and accuracy as when the whole audio is given to the model in offline mode. +These model can use caching mechanism to store and reuse the activations during streaming inference to avoid any duplications in the computations as much as possible. + +We support the following three right context modeling techniques: + +* | Fully causal model with zero look-ahead: tokens do not see any future tokens. Convolution layers are all causal and right tokens are masked for self-attention. + | + | It gives zero latency but with limited accuracy. + | To train such a model, you need to set `model.encoder.att_context_size=[left_context,0]` and `model.encoder.conv_context_size=causal` in the config. + +* | Regular look-ahead: convolutions are able to see few future frames, and self-attention also sees the same number of future tokens. + | + | In this approach the activations for the look-ahead part are not cached, and are recalculated in the next chunks. The right context in each layer should be a small number as multiple layers would increase the effective context size and then increase the look-ahead size and latency. + | For example for a model of 17 layers with 4x downsampling and 10ms window shift, then even 2 right context in each layer means 17*2*10*4=1360ms look-ahead. Each step after the downsampling corresponds to 4*10=40ms. + +* | Chunk-aware look-ahead: input is split into equal chunks. Convolutions are fully causal while self-attention layers are able to see all the tokens in their corresponding chunk. + | + | For example, in a model with chunk size of 20 tokens, tokens at the first position of each chunk would see all the next 19 tokens while the last token would see zero future tokens. + | This approach is more efficient than regular look-ahead in terms of computations as the activations for most of the look-ahead part would be cached and there is close to zero duplications in the calculations. + | In terms of accuracy, this approach gives similar or even better results in term of accuracy than regular look-ahead as each token in each layer have access to more tokens on average. That is why we recommend to use this approach for streaming. Therefore we recommend to use the chunk-aware for cache-aware models. + +.. note:: Latencies are based on the assumption that the forward time of the network is zero and it just estimates the time needed after a frame would be available until it is passed through the model. + +Approaches with non-zero look-ahead can give significantly better accuracy by sacrificing latency. The latency can get controlled by the left context size. Increasing the right context would help the accuracy to a limit but would increase the computation time. + +In all modes, left context can be controlled by the number of tokens visible in self-attention and the kernel size of the convolutions. +For example, if the left context of self-attention in each layer is set to 20 tokens and there are 10 layers of Conformer, then the effective left context is 20*10=200 tokens. +Left context of self-attention for regular look-ahead can be set as any number, while it should be set as a multiple of the right context in chunk-aware look-ahead. +For convolutions, if we use a left context of 30, then there would be 30*10=300 effective left context. +Left context of convolutions is dependent on their kernel size while it can be any number for self-attention layers. Higher left context for self-attention means larger cache and more computations for the self-attention. +A self-attention left context of around 6 secs would give close results to unlimited left context. For a model with 4x downsampling and shift window of 10ms in the preprocessor, each token corresponds to 4*10=40ms. + +If striding approach is used for downsampling, all the convolutions in downsampling would be fully causal and don't see future tokens. + +Multiple Look-aheads +~~~~~~~~~~~~~~~~~~~~ + +We support multiple look-aheads for cahce-aware models. You may specify a list of context sizes for att_context_size. +During the training, different context sizes would be used randomly with the distribution specified by att_context_probs. +For example you may enable multiple look-aheads by setting `model.encoder.att_context_size=[[70,13],[70,6],[70,1],[70,0]]` for the training. +The first item in the list would be the default during test/validation/inference. To switch between different look-aheads, you may use the method `asr_model.encoder.set_default_att_context_size(att_context_size)` or set the att_context_size like the following when using the script `speech_transcribe.py`: + +.. code-block:: bash + + python [NEMO_GIT_FOLDER]/examples/asr/transcribe_speech.py \ + pretrained_name="stt_en_fastconformer_hybrid_large_streaming_multi" \ + audio_dir="" \ + att_context_size=[70,0] + +.. + +You may find the example config files for cache-aware streaming FastConformer models at +``/examples/asr/conf/fastconformer/cache_aware_streaming/conformer_transducer_bpe_streaming.yaml`` for Transducer variant and +at ``/examples/asr/conf/conformer/cache_aware_streaming/conformer_ctc_bpe.yaml`` for CTC variant. It is recommended to use FastConformer as they are more than 2X faster in both training and inference than regular Conformer. +The hybrid versions of FastConformer can be found here: ``/examples/asr/conf/conformer/hybrid_cache_aware_streaming/`` + +Examples for regular Conformer can be found at +``/examples/asr/conf/conformer/cache_aware_streaming/conformer_transducer_bpe_streaming.yaml`` for Transducer variant and +at ``/examples/asr/conf/conformer/cache_aware_streaming/conformer_ctc_bpe.yaml`` for CTC variant. + +To simulate cache-aware streaming, you may use the script at ``/examples/asr/asr_cache_aware_streaming/speech_to_text_cache_aware_streaming_infer.py``. It can simulate streaming in single stream or multi-stream mode (in batches) for an ASR model. +This script can be used for models trained offline with full-context but the accuracy would not be great unless the chunk size is large enough which would result in high latency. +It is recommended to train a model in streaming model with limited context for this script. More info can be found in the script. + +Note cache-aware streaming models are being exported without caching support by default. +To include caching support, `model.set_export_config({'cache_support' : 'True'})` should be called before export. +Or, if ``/scripts/export.py`` is being used: +`python export.py cache_aware_conformer.nemo cache_aware_conformer.onnx --export-config cache_support=True` + + +Multitalker Cache-aware Streaming FastConformer +----------------------------------------------- + +This model is a streaming multitalker ASR model based on the :ref:`Cache-aware Streaming FastConformer ` architecture. The model only takes the speaker diarization outputs as external information and eliminates the need for explicit speaker queries or enrollment audio :cite:`asr-models-wang25y_interspeech`. Unlike conventional target-speaker ASR approaches that require speaker embeddings, this model dynamically adapts to individual speakers through speaker-wise speech activity prediction. + + +Self-Speaker Adaptation Technique +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The key innovation involves injecting learnable speaker kernels into the pre-encode layer of the FastConformer encoder :cite:`asr-models-rekesh2023fastconformer`. These speaker kernels are generated via speaker supervision activations, enabling instantaneous adaptation to target speakers. This approach leverages the inherent tendency of streaming ASR systems to prioritize specific speakers, repurposing this mechanism to achieve robust speaker-focused recognition. + +The model architecture requires deploying one model instance per speaker, meaning the number of model instances matches the number of speakers in the conversation. While this necessitates additional computational resources, it achieves state-of-the-art performance in handling fully overlapped speech in both offline and streaming scenarios. + +This self-speaker adaptation approach offers several advantages over traditional multitalker ASR methods: + +* | No Speaker Enrollment: Unlike target-speaker ASR systems that require pre-enrollment audio or speaker embeddings, this model only needs speaker activity information from diarization +* | Handles Severe Overlap: Each instance focuses on a single speaker, enabling accurate transcription even during fully overlapped speech +* | Streaming Capable: Designed for real-time streaming scenarios with configurable latency-accuracy tradeoffs +* | Leverages Single-Speaker Models: Can be fine-tuned from strong pre-trained single-speaker ASR models, and single speaker ASR performance is also preserved + +Speaker Kernel Injection +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The streaming multitalker Parakeet model employs a speaker kernel injection mechanism at some layers of the FastConformer encoder. The learnable speaker kernels are injected into selected encoder layers, enabling the model to dynamically adapt to specific speakers. + +The speaker kernels are generated through speaker supervision activations that detect speech activity for each target speaker. This enables the encoder states to become more responsive to the targeted speaker's speech characteristics, even during periods of fully overlapped speech. + +Multi-Instance Architecture +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The model is based on the Parakeet architecture and consists of a NeMo Encoder for Speech Tasks (NEST) :cite:`asr-models-huang2025nest` which is based on FastConformer :cite:`asr-models-rekesh2023fastconformer` encoder. The key architectural park2024nestinnovation is the **multi-instance approach**, where one model instance is deployed per speaker. + +Each model instance has the following characteristics: + +* | Receives the identical speaker-mixed audio input. +* | Injects speaker-specific kernels at the pre-encode layer. +* | Produces transcription output specific to its target speaker. +* | Operates independently and can run in parallel with other instances. + +This architecture enables the model to handle severe speech overlap by having each instance focus exclusively on one speaker, eliminating the permutation problem that affects other multitalker ASR approaches. +Find more details in the :cite:`asr-models-wang25y_interspeech` paper. + +The real-time multitalker ASR model is built on RNNT model structure. :class:`~nemo.collections.asr.models.EncDecMultiTalkerRNNTBPEModel` class inherits from :class:`~nemo.collections.asr.models.EncDecRNNTBPEModel` class and speaker kernel :class:`~nemo.collections.asr.parts.mixins.SpeakerKernel` class. + +Try real-time multitalker ASR with the tutorial notebook: `Streaming Multitalker ASR tutorial notebook `_. + +You can simulate the streaming audio stream and streaming multitalker ASR with the script: +``/examples/asr/asr_cache_aware_streaming/speech_to_text_multitalker_streaming_infer.py`` + + +.. note:: + Many ASR pipelines expect **16 kHz, mono-channel WAV** input. + If your audio is mp3/m4a or has a different sample rate/channel count, convert it first: + + .. code-block:: bash + + ffmpeg -i input.mp3 -ac 1 -ar 16000 -y output.wav + +For an individual audio file: + +.. code-block:: bash + + python /examples/asr/asr_cache_aware_streaming/speech_to_text_multitalker_streaming_infer.py \ + asr_model="/path/to/multitalker-parakeet-streaming-0.6b-v1.nemo" \ + diar_model="/path/to/nvidia/diar_streaming_sortformer_4spk-v2.nemo" \ + audio_file="/path/to/your/example.wav" \ + output_path="/path/to/your/example_output.json" + +If you want to simulate the system on multiple files, use NeMo manifest: + +.. code-block:: bash + + python /examples/asr/asr_cache_aware_streaming/speech_to_text_multitalker_streaming_infer.py \ + asr_model="/path/to/multitalker-parakeet-streaming-0.6b-v1.nemo" \ + diar_model="/path/to/nvidia/diar_streaming_sortformer_4spk-v2.nemo" \ + manifest_file="/path/to/your/example_manifest.json" \ + output_path="/path/to/your/example_output.json" + + +Download model checkpoint and more details can be found on Huggingface model card: `Multitalker Parakeet (Cache-aware FastConformer) Streaming `__. + + + +.. _Hybrid-Transducer_CTC_model: + +Hybrid-Transducer-CTC +--------------------- + +Hybrid RNNT-CTC models is a group of models with both the RNNT and CTC decoders. Training a unified model would speedup the convergence for the CTC models and would enable +the user to use a single model which works as both a CTC and RNNT model. This category can be used with any of the ASR models. +Hybrid models uses two decoders of CTC and RNNT on the top of the encoder. The default decoding strategy after the training is done is RNNT. +User may use the ``asr_model.change_decoding_strategy(decoder_type='ctc' or 'rnnt')`` to change the default decoding. + +The variant with sub-word encoding is a BPE-based model +which can be instantiated using the :class:`~nemo.collections.asr.models.EncDecHybridRNNTCTCBPEModel` class, while the +character-based variant is based on :class:`~nemo.collections.asr.models.EncDecHybridRNNTCTCModel`. + +You may use the example scripts under ``/examples/asr/asr_hybrid_transducer_ctc`` for both the char-based encoding and sub-word encoding. +These examples can be used to train any Hybrid ASR model like Conformer. + +You may find the example config files of Conformer variant of such hybrid models with character-based encoding at +``/examples/asr/conf/conformer/hybrid_transducer_ctc/conformer_hybrid_transducer_ctc_char.yaml`` and +with sub-word encoding at ``/examples/asr/conf/conformer/hybrid_transducer_ctc/conformer_hybrid_transducer_ctc_bpe.yaml``. + +Similar example configs for FastConformer variants of Hybrid models can be found here: +``/examples/asr/conf/fastconformer/hybrid_transducer_ctc/`` +``/examples/asr/conf/fastconformer/hybrid_cache_aware_streaming/`` + +Note Hybrid models are being exported as RNNT (encoder and decoder+joint parts) by default. +To export as CTC (single encoder+decoder graph), `model.set_export_config({'decoder_type' : 'ctc'})` should be called before export. +Or, if ``/scripts/export.py`` is being used: +`python export.py hybrid_transducer.nemo hybrid_transducer.onnx --export-config decoder_type=ctc` + +.. _Hybrid-Transducer-CTC-Prompt_model: + +Hybrid-Transducer-CTC with Prompt Conditioning +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Hybrid RNNT-CTC model with prompt conditioning (``EncDecHybridRNNTCTCBPEModelWithPrompt``) extends the base Hybrid-Transducer-CTC model +to support multi-language and multi-domain ASR through prompt conditioning. This model leverages prompts to guide the transcription process, +enabling language-specific or domain-specific transcription from a single unified model. + +Key features of this model include: + +* **Prompt Feature**: Uses learnable prompt embeddings that are concatenated with acoustic features to guide transcription +* **Multi-language Support**: Can transcribe audio in multiple languages based on language prompts +* **Offline and Buffered Streaming Inference Support**: Can be used in offline and buffered streaming mode + +The model can be instantiated using the :class:`~nemo.collections.asr.models.EncDecHybridRNNTCTCBPEModelWithPrompt` class. + +Architecture Overview +^^^^^^^^^^^^^^^^^^^^^ + +The model architecture builds upon the standard Hybrid-Transducer-CTC model by incorporating prompt information directly into the decoder through a concatenation-based approach. This design enables scalable multilingual ASR/AST capabilities. + +**Core Components:** + +1. **Prompt Supervision Source**: Prompt label information extracted from training and inference manifests or provided as an input +2. **Prompt Vector Representation**: One-hot binary vectors where one element is 1 (prompt) and all others are 0 +3. **Concatenation-Based Prompt Encoding**: Direct combination of prompt vectors with acoustic features + +**Detailed Architecture:** + +**Prompt Vector Design:** +- **Dimensionality**: Default to 128-dimensional vectors for scalability (supports current target language and future prompts) without the need to change the architecture +- **Representation**: Binary one-hot encoding where each position represents a prompt ID +- **Expansion**: Prompt vectors are expanded at each time step to match acoustic feature temporal dimensions + +**Concatenation Method Implementation:** +The model adopts a concatenation approach where language vectors and ASR acoustic features are directly combined: + +1. **Feature Stacking**: Language vectors and encoded acoustic features are stacked along the feature dimension +2. **Projection**: The concatenated representation passes through a projection network (``prompt_kernel``) + + +**Inference Capabilities:** + +The model supports both offline and buffered streaming inference modes: + +- **Offline Mode**: Full context processing for maximum accuracy +- **Buffered Streaming**: Real-time multilingual speech-to-text processing with language-aware decoding + + +Configuration +^^^^^^^^^^^^^ + +The model supports several prompt-specific configuration parameters: + +* ``initialize_prompt_feature``: Boolean flag to enable prompt conditioning +* ``num_prompts``: Number of supported prompt categories (default: 128) +* ``prompt_dictionary``: Mapping from language/domain identifiers to prompt indices +* ``prompt_field``: Field name used for prompt extraction from manifest files + +Example config files for this model can be found at: +``/examples/asr/conf/fastconformer/hybrid_transducer_ctc/fastconformer_hybrid_transducer_ctc_bpe_prompt.yaml`` + +Training +^^^^^^^^ + +To train the Hybrid-Transducer-CTC model with prompt feature, use the training script: + +``/examples/asr/asr_hybrid_transducer_ctc/speech_to_text_hybrid_rnnt_ctc_bpe_prompt.py`` + +Example training command: + +.. code-block:: bash + + python /examples/asr/asr_hybrid_transducer_ctc/speech_to_text_hybrid_rnnt_ctc_bpe_prompt.py \ + --config-path=/examples/asr/conf/fastconformer/hybrid_transducer_ctc/ \ + --config-name=fastconformer_hybrid_transducer_ctc_bpe_prompt.yaml \ + model.train_ds.manifest_filepath= \ + model.validation_ds.manifest_filepath= \ + model.tokenizer.dir= \ + model.test_ds.manifest_filepath= + +Usage Examples +^^^^^^^^^^^^^^ + +**Basic Transcription with Language Prompts:** + +.. code-block:: python + + # Load the model + asr_model = nemo_asr.models.EncDecHybridRNNTCTCBPEModelWithPrompt.restore_from("path/to/model.nemo") + + # Transcribe with specific target language + transcriptions = asr_model.transcribe( + paths2audio_files=["audio1.wav", "audio2.wav"], + target_lang="en-US", # Specify target language + ) + + +Training Data Requirements +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The model requires training data with prompt annotations. The recommended dataset format uses Lhotse with the +:class:`~nemo.collections.asr.data.audio_to_text_lhotse_prompt.LhotseSpeechToTextBpeDatasetWithPrompt` dataset class. + +Manifest files should include prompt information: + +.. code-block:: json + + { + "audio_filepath": "path/to/audio.wav", + "text": "transcription text", + "duration": 10.5, + "target_lang": "en-US" + } + + +.. _LSTM-Transducer_model: + +LSTM-Transducer +--------------- + +LSTM-Transducer is a model which uses RNNs (eg. LSTM) in the encoder. The architecture of this model is followed from suggestions in :cite:`asr-models-he2019streaming`. +It uses RNNT/Transducer loss/decoder. The encoder consists of RNN layers (LSTM as default) with lower projection size to increase the efficiency. +Layer norm is added between the layers to stabilize the training. +It can be trained/used in unidirectional or bidirectional mode. The unidirectional mode is fully causal and can be used easily for simple and efficient streaming. However the accuracy of this model is generally lower than other models like Conformer. + +This model supports both the sub-word level and character level encodings. You may find the example config file of RNNT model with wordpiece encoding at ``/examples/asr/conf/lstm/lstm_transducer_bpe.yaml``. +You can find more details on the config files for the RNNT models at :ref:`LSTM-Transducer `. + +.. _LSTM-CTC_model: + +LSTM-CTC +-------- + +LSTM-CTC model is a CTC-variant of the LSTM-Transducer model which uses CTC loss/decoding instead of Transducer. +You may find the example config file of LSTM-CTC model with wordpiece encoding at ``/examples/asr/conf/lstm/lstm_ctc_bpe.yaml``. + + +References +---------- + +.. bibliography:: asr_all.bib + :style: plain + :labelprefix: ASR-MODELS + :keyprefix: asr-models- diff --git a/docs/source/asr/results.rst b/docs/source/asr/results.rst new file mode 100644 index 0000000000000000000000000000000000000000..294d5ea891d01a319cb743ae8e8d6de9a08b529f --- /dev/null +++ b/docs/source/asr/results.rst @@ -0,0 +1,335 @@ +Checkpoints +=========== + +There are two main ways to load pretrained checkpoints in NeMo: + +* Using the :code:`restore_from()` method to load a local checkpoint file (``.nemo``), or +* Using the :code:`from_pretrained()` method to download and set up a checkpoint from NGC. + +Refer to the following sections for instructions and examples for each. + +Note that these instructions are for loading fully trained checkpoints for evaluation or fine-tuning. For resuming an unfinished +training experiment, use the Experiment Manager to do so by setting the ``resume_if_exists`` flag to ``True``. + +Loading Local Checkpoints +------------------------- + +NeMo automatically saves checkpoints of a model that is trained in a ``.nemo`` format. Alternatively, to manually save the model at any +point, issue :code:`model.save_to(.nemo)`. + +If there is a local ``.nemo`` checkpoint that you'd like to load, use the :code:`restore_from()` method: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + model = nemo_asr.models..restore_from(restore_path="") + +Where the model base class is the ASR model class of the original checkpoint, or the general ``ASRModel`` class. + + +Pretrained Checkpoints +-------------------------- + +The ASR collection has checkpoints of several models trained on various datasets for a variety of tasks. These checkpoints are +obtainable via NGC `NeMo Automatic Speech Recognition collection `_ or `Huggingface `_. +The model cards on these websites contain more information about each of the checkpoints available. + +The tables below list the Top ASR models available from the datasources above. The models can be accessed via the :code:`from_pretrained()` method inside +the ASR Model class. In general, you can load any of these models with code in the following format: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + model = nemo_asr.models.ASRModel.from_pretrained(model_name="") + +Where the model name is the value under "Model Name" entry in the tables below. + +For example, to load the Parakeet TDT model for speech recognition, run: + +.. code-block:: python + + model = nemo_asr.models.ASRModel.from_pretrained(model_name="nvidia/parakeet-tdt-0.6b-v2") + +You can also call :code:`from_pretrained()` from the specific model class (such as :code:`EncDecRNNTBPEModel` +for Parakeet) if you need to access a specific model functionality. + +If you would like to programmatically list the models available for a particular base class, you can use the +:code:`list_available_models()` method. + +.. code-block:: python + + nemo_asr.models..list_available_models() + +Transcribing/Inference +^^^^^^^^^^^^^^^^^^^^^^ + +To perform inference and transcribe a sample of speech after loading the model, use the ``transcribe()`` method: + +.. code-block:: python + + model.transcribe(audio=[list of audio files], batch_size=BATCH_SIZE) + +``audio`` can be a string path to a file, a list of string paths to multiple files, a numpy or PyTorch tensor that is an audio file loaded via ``soundfile`` or some other library or even a list of such tensors. This expanded support for inputs to transcription should help users to easily integrate NeMo into their pipelines. + +----- + +You can do inference on a numpy array that represents an audio signal as follows. Note that it is your responsibility to process the audio to be monochannel and 16KHz sample rate before passing it to the model. + +.. code-block:: python + + import torch + import soundfile as sf + + from nemo.collections.asr.models import ASRModel + model = ASRModel.from_pretrained() + model.eval() + + # Load audio files + audio_file = os.path.join(test_data_dir, "asr", "train", "an4", "wav", "an46-mmap-b.wav") + audio, sr = sf.read(audio_file, dtype='float32') + + audio_file_2 = os.path.join(test_data_dir, "asr", "train", "an4", "wav", "an104-mrcb-b.wav") + audio_2, sr = sf.read(audio_file_2, dtype='float32') + + # Mix one numpy array audio segment with torch audio tensor + audio_2 = torch.from_numpy(audio_2) + + # Numpy array + torch tensor mixed tensor input (for batched inference) + outputs = model.transcribe([audio, audio_2], batch_size=2) + +----- + +In order to obtain alignments from CTC or RNNT models (previously called ``logprobs``), you can use the following code: + +.. code-block:: python + + hyps = model.transcribe(audio=[list of audio files], batch_size=BATCH_SIZE, return_hypotheses=True) + logprobs = hyps[0].alignments + +----- + +Often times, we want to transcribe a large number of files at once (maybe from a manifest for example). In this case, using ``transcribe()`` directly may be incorrect because it will delay the return of the result until every single sample in the input is processed. One work around is to call transcribe() multiple times, each time using a small subset of the data. This workflow is now supported via a :meth:`~nemo.collections.asr.parts.mixins.transcription.TranscriptionMixin.transcribe_generator`. + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + model = nemo_asr.models.ASRModel.from_pretrained() + + config = model.get_transcribe_config() + config.batch_size = 32 + generator = model.transcribe_generator(audio, config) + + for processed_outputs in generator: + # process a batch of 32 results (or less if last batch does not contain 32 elements) + .... + +For more information, see :ref:`nemo.collections.asr.modules `. For more information on the general ``Transcription API``, please take a look at :class:`~nemo.collections.asr.parts.mixins.transcription.TranscriptionMixin`. The audio files should be 16KHz mono-channel wav files. + +----- + + +Inference on long audio +^^^^^^^^^^^^^^^^^^^^^^^ + +In some cases the audio is too long for standard inference, especially if you're using a model such as Conformer, where the time and memory costs of the attention layers scale quadratically with the duration. + +There are two main ways of performing inference on long audio files in NeMo: + +The first way is to use buffered inference, where the audio is divided into chunks to run on, and the output is merged afterwards. +The relevant scripts for this are contained in `this folder `_. + +The second way, specifically for models with the Conformer/Fast Conformer encoder, is to use local attention, which changes the costs to be linear. +You can train Fast Conformer models with Longformer-style (https://arxiv.org/abs/2004.05150) local+global attention using one of the following configs: CTC config at +``/examples/asr/conf/fastconformer/fast-conformer-long_ctc_bpe.yaml`` and transducer config at ``/examples/asr/conf/fastconformer/fast-conformer-long_transducer_bpe.yaml``. +You can also convert any model trained with full context attention to local, though this may result in lower WER in some cases. You can switch to local attention when running the +`transcribe `_ or `evaluation `_ +scripts in the following way: + +.. code-block:: python + + python speech_to_text_eval.py \ + (...other parameters...) \ + ++model_change.conformer.self_attention_model="rel_pos_local_attn" \ + ++model_change.conformer.att_context_size=[128, 128] + +Alternatively, you can change the attention model after loading a checkpoint: + +.. code-block:: python + + asr_model = ASRModel.from_pretrained('stt_en_conformer_ctc_large') + asr_model.change_attention_model( + self_attention_model="rel_pos_local_attn", + att_context_size=[128, 128] + ) + +Sometimes, the downsampling module at the earliest stage of the model can take more memory than the actual forward pass since it directly operates on the audio sequence which may not be able to fit in memory for very long audio files. In order to reduce the memory consumption of the subsampling module, you can ask the model to perform auto-chunking of the input sequence and process it piece by piece, taking more time but avoiding an OutOfMemoryError. + +.. code-block:: python + + asr_model = ASRModel.from_pretrained('stt_en_fastconformer_ctc_large') + # Speedup conv subsampling factor to speed up the subsampling module. + asr_model.change_subsampling_conv_chunking_factor(1) # 1 = auto select + + +.. note:: + + Only certain models which use depthwise separable convolutions in the downsampling layer support this operation. Please try it out on your model and see if it is supported. + + + +Inference with Multi-task Models +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Multi-task models that use structured prompts require additionl task tokens as input, in which case it is recommended to use manifest as input. Below is an example of using the `nvidia/canary-1b-v2` model: + +.. code-block:: python + + from nemo.collections.asr.models import EncDecMultiTaskModel + + # load model + canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-1b-v2') + + # update dcode params + decode_cfg = canary_model.cfg.decoding + decode_cfg.beam.beam_size = 1 + canary_model.change_decoding_strategy(decode_cfg) + + # run transcribe + predicted_text = canary_model.transcribe( + "", + batch_size=16, # batch size to run the inference with + )[0].text + +Here the manifest file should be a json file where each line has the following format: + +.. code-block:: bash + + { + "audio_filepath": "/path/to/audio.wav", # path to the audio file + "duration": None, # duration of the audio in seconds, set to `None` to use full audio + "taskname": "asr", # use "ast" for speech-to-text translation + "source_lang": "en", # language of the audio input, set `source_lang`==`target_lang` for ASR + "target_lang": "en", # language of the text output + "pnc": "yes", # whether to have PnC output, choices=['yes', 'no'] + "answer": "na", # set to non-dummy strings to calculate WER/BLEU scores + } + +Note that using manifest allows to specify the task configuration for each audio individually. If we want to use the same task configuration for all the audio files, it can be specified in `transcribe` method directly. + +.. code-block:: python + + canary_model.transcribe( + audio=[list of audio files], + batch_size=4, # batch size to run the inference with + task="asr", # use "ast" for speech-to-text translation + source_lang="en", # language of the audio input, set `source_lang`==`target_lang` for ASR + target_lang="en", # language of the text output + pnc=True, # whether to have PnC output, choices=[True, False] + )[0].text + +Inference on Apple M-Series GPU +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To perform inference on Apple Mac M-Series GPU (``mps`` PyTorch device), use PyTorch 2.0 or higher (see the `mac-installation ` section). Environment variable ``PYTORCH_ENABLE_MPS_FALLBACK=1`` should be set, since not all operations in PyTorch are currently implemented on ``mps`` device. + +If ``allow_mps=true`` flag is passed to ``speech_to_text_eval.py``, the ``mps`` device will be selected automatically. + +.. code-block:: python + + PYTORCH_ENABLE_MPS_FALLBACK=1 python speech_to_text_eval.py \ + (...other parameters...) \ + allow_mps=true + + +Fine-tuning on Different Datasets +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There are multiple ASR tutorials provided in the Tutorials section. Most of these tutorials explain how to instantiate a pre-trained model, prepare the model for fine-tuning on some dataset (in the same language) as a demonstration. + +Inference Execution Flow Diagram +-------------------------------- + +When preparing your own inference scripts, please follow the execution flow diagram order for correct inference, found at the `examples directory for ASR collection `_. + + +Automatic Speech Recognition Models +----------------------------------- + +.. _asr-checkpoint-list-by-language: + +Speech Recognition +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Below is a list of the high quality ASR models available in NeMo for specific languages, all ASR models can be found in :doc:`All checkpoints <./all_chkpt>`. + +Multilingual Multitask +^^^^^^^^^^^^^^^^^^^^^^ + +.. csv-table:: + :file: data/benchmark_canary.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +Parakeet +^^^^^^^^ + +.. csv-table:: + :file: data/benchmark_parakeet.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +Fast Conformer Hybrid +^^^^^^^^^^^^^^^^^^^^^ +.. csv-table:: + :file: data/benchmark_fastconformer_hybrid.csv + :align: left + :widths: 50,50 + :header-rows: 1 + +Fast Conformer Hybrid with Prompt Feature +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The Hybrid-Transducer-CTC model with prompt conditioning (``EncDecHybridRNNTCTCBPEModelWithPrompt``) supports multilingual ASR/AST through prompt-based conditioning. This model enables: + +- **Multi-language transcription** with language-specific prompts +- **Streaming and offline inference** modes +- **Scalable architecture** can support multilingual ASR and AST tasks + +**Key Features:** +- Prompt-based language conditioning using one-hot embeddings +- Concatenation-based feature fusion with learned projection networks +- Compatible with existing FastConformer hybrid architecture +- Support for both offline and buffered streaming inference + +**Usage Example:** + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + + # Load the model + model = nemo_asr.models.EncDecHybridRNNTCTCBPEModelWithPrompt.restore_from("path/to/model.nemo") + + # Transcribe with language prompts + transcriptions = model.transcribe( + paths2audio_files=["audio1.wav", "audio2.wav"], + target_lang="en-US" # Specify target language + ) + +**Configuration and Training:** +- Training script: ``/examples/asr/asr_hybrid_transducer_ctc/speech_to_text_hybrid_rnnt_ctc_bpe_prompt.py`` +- Config file: ``/examples/asr/conf/fastconformer/hybrid_transducer_ctc/fastconformer_hybrid_transducer_ctc_bpe_prompt.yaml`` + +For detailed configuration parameters, see :ref:`Hybrid-Transducer-CTC with Prompt Conditioning Configuration `. + +Code-Switching +^^^^^^^^^^^^^^ + +.. csv-table:: + :file: data/benchmark_code_switching.csv + :align: left + :widths: 50,50 + :header-rows: 1 + + diff --git a/docs/source/asr/scores.rst b/docs/source/asr/scores.rst new file mode 100644 index 0000000000000000000000000000000000000000..a01b24d7a62326afd4ad84e612b5afcecc007e2f --- /dev/null +++ b/docs/source/asr/scores.rst @@ -0,0 +1,312 @@ +.. + AUTOGENERATED DOC: DO NOT EDIT MANUALLY ! + +Scores +------ + +EN +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/en/conformer_en.csv + +-------------------- + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/en/fastconformer_en.csv + +-------------------- + +BE +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/be/conformer_be.csv + +-------------------- + +BY +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/by/fastconformer_by.csv + +-------------------- + +CA +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/ca/conformer_ca.csv + +-------------------- + +DE +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/de/conformer_de.csv + +-------------------- + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/de/fastconformer_de.csv + +-------------------- + +ENES +^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/enes/conformer_enes.csv + +-------------------- + +EO +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/eo/conformer_eo.csv + +-------------------- + +ES +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/es/conformer_es.csv + +-------------------- + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/es/fastconformer_es.csv + +-------------------- + +FR +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/fr/conformer_fr.csv + +-------------------- + +HR +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/hr/conformer_hr.csv + +-------------------- + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/hr/fastconformer_hr.csv + +-------------------- + +IT +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/it/conformer_it.csv + +-------------------- + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/it/fastconformer_it.csv + +-------------------- + +KAB +^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/kab/conformer_kab.csv + +-------------------- + +NL +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/nl/fastconformer_nl.csv + +-------------------- + +PL +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/pl/fastconformer_pl.csv + +-------------------- + +RU +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/ru/conformer_ru.csv + +-------------------- + +RW +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/rw/conformer_rw.csv + +-------------------- + +UA +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/ua/fastconformer_ua.csv + +-------------------- + +ZH +^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores/zh/conformer_zh.csv + +-------------------- + + +Scores with Punctuation and Capitalization +------------------------------------------ + +EN with P&C +^^^^^^^^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores_pc/en/fastconformer_en.csv + +-------------------- + +BY with P&C +^^^^^^^^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores_pc/by/fastconformer_by.csv + +-------------------- + +DE with P&C +^^^^^^^^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores_pc/de/fastconformer_de.csv + +-------------------- + +ES with P&C +^^^^^^^^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores_pc/es/fastconformer_es.csv + +-------------------- + +HR with P&C +^^^^^^^^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores_pc/hr/fastconformer_hr.csv + +-------------------- + +IT with P&C +^^^^^^^^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores_pc/it/fastconformer_it.csv + +-------------------- + +NL with P&C +^^^^^^^^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores_pc/nl/fastconformer_nl.csv + +-------------------- + +PL with P&C +^^^^^^^^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores_pc/pl/fastconformer_pl.csv + +-------------------- + +UA with P&C +^^^^^^^^^^^ + +.. csv-table:: + :header-rows: 1 + :align: left + :file: data/scores_pc/ua/fastconformer_ua.csv diff --git a/docs/source/asr/speaker_diarization/api.rst b/docs/source/asr/speaker_diarization/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..c0366c2bf9a42c32efb8ae58761a170ff4ca3a3e --- /dev/null +++ b/docs/source/asr/speaker_diarization/api.rst @@ -0,0 +1,26 @@ +NeMo Speaker Diarization API +============================= + + +Model Classes +------------- + +.. autoclass:: nemo.collections.asr.models.ClusteringDiarizer + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.models.SortformerEncLabelModel + :show-inheritance: + :members: list_available_models, setup_training_data, setup_validation_data, setup_test_data, process_signal, forward, forward_infer, frontend_encoder, diarize, training_step, validation_step, multi_validation_epoch_end, _get_aux_train_evaluations, _get_aux_validation_evaluations, _init_loss_weights, _init_eval_metrics, _reset_train_metrics, _reset_valid_metrics, _setup_diarize_dataloader, _diarize_forward, _diarize_output_processing, test_batch, _get_aux_test_batch_evaluations, on_validation_epoch_end + +Mixins +------ + +.. autoclass:: nemo.collections.asr.parts.mixins.DiarizationMixin + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.parts.mixins.diarization.SpkDiarizationMixin + :show-inheritance: + :members: diarize, diarize_generator, _diarize_on_begin, _diarize_input_processing, _diarize_input_manifest_processing, _setup_diarize_dataloader, _diarize_forward, _diarize_output_processing, _diarize_on_end, _input_audio_to_rttm_processing, get_value_from_diarization_config + \ No newline at end of file diff --git a/docs/source/asr/speaker_diarization/configs.rst b/docs/source/asr/speaker_diarization/configs.rst new file mode 100644 index 0000000000000000000000000000000000000000..b44330b6630085e072e75dba18aa09e80704ad25 --- /dev/null +++ b/docs/source/asr/speaker_diarization/configs.rst @@ -0,0 +1,593 @@ +Speaker Diarization Configuration Files +======================================== + +Hydra Configurations for Sortformer Diarizer Training +----------------------------------------------------- + +Sortformer Diarizer is an end-to-end speaker diarization model that is solely based on Transformer-encoder type of architecture. +Model name convention for Sortformer Diarizer: sortformer_diarizer__-.yaml + + +* Example `/examples/speaker_tasks/diarization/neural_diarizer/conf/sortformer_diarizer_hybrid_loss_4spk-v1.yaml`. + +.. code-block:: yaml + + name: "SortformerDiarizer" + num_workers: 18 + batch_size: 8 + + model: + sample_rate: 16000 + pil_weight: 0.5 # Weight for Permutation Invariant Loss (PIL) used in training the Sortformer diarizer model + ats_weight: 0.5 # Weight for Arrival Time Sort (ATS) loss in training the Sortformer diarizer model + max_num_of_spks: 4 # Maximum number of speakers per model; currently set to 4 + + model_defaults: + fc_d_model: 512 # Hidden dimension size of the Fast-conformer Encoder + tf_d_model: 192 # Hidden dimension size of the Transformer Encoder + + train_ds: + manifest_filepath: ??? + sample_rate: ${model.sample_rate} + num_spks: ${model.max_num_of_spks} + session_len_sec: 90 # Maximum session length in seconds + soft_label_thres: 0.5 # Threshold for binarizing target values; higher values make the model more conservative in predicting speaker activity. + soft_targets: False # If True, use continuous values as target values when calculating cross-entropy loss + labels: null + batch_size: ${batch_size} + shuffle: True + num_workers: ${num_workers} + validation_mode: False + # lhotse config + use_lhotse: False + use_bucketing: True + num_buckets: 10 + bucket_duration_bins: [10, 20, 30, 40, 50, 60, 70, 80, 90] + pin_memory: True + min_duration: 10 + max_duration: 90 + batch_duration: 400 + quadratic_duration: 1200 + bucket_buffer_size: 20000 + shuffle_buffer_size: 10000 + window_stride: ${model.preprocessor.window_stride} + subsampling_factor: ${model.encoder.subsampling_factor} + + validation_ds: + manifest_filepath: ??? + is_tarred: False + tarred_audio_filepaths: null + sample_rate: ${model.sample_rate} + num_spks: ${model.max_num_of_spks} + session_len_sec: 90 # Maximum session length in seconds + soft_label_thres: 0.5 # A threshold value for setting up the binarized labels. The higher the more conservative the model becomes. + soft_targets: False + labels: null + batch_size: ${batch_size} + shuffle: False + num_workers: ${num_workers} + validation_mode: True + # lhotse config + use_lhotse: False + use_bucketing: False + drop_last: False + pin_memory: True + window_stride: ${model.preprocessor.window_stride} + subsampling_factor: ${model.encoder.subsampling_factor} + + test_ds: + manifest_filepath: null + is_tarred: False + tarred_audio_filepaths: null + sample_rate: 16000 + num_spks: ${model.max_num_of_spks} + session_len_sec: 90 # Maximum session length in seconds + soft_label_thres: 0.5 + soft_targets: False + labels: null + batch_size: ${batch_size} + shuffle: False + seq_eval_mode: True + num_workers: ${num_workers} + validation_mode: True + # lhotse config + use_lhotse: False + use_bucketing: False + drop_last: False + pin_memory: True + window_stride: ${model.preprocessor.window_stride} + subsampling_factor: ${model.encoder.subsampling_factor} + + preprocessor: + _target_: nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor + normalize: "per_feature" + window_size: 0.025 + sample_rate: ${model.sample_rate} + window_stride: 0.01 + window: "hann" + features: 80 + n_fft: 512 + frame_splicing: 1 + dither: 0.00001 + + sortformer_modules: + _target_: nemo.collections.asr.modules.sortformer_modules.SortformerModules + num_spks: ${model.max_num_of_spks} # Number of speakers per model. This is currently fixed at 4. + dropout_rate: 0.5 # Dropout rate + fc_d_model: ${model.model_defaults.fc_d_model} + tf_d_model: ${model.model_defaults.tf_d_model} # Hidden layer size for linear layers in Sortformer Diarizer module + + encoder: + _target_: nemo.collections.asr.modules.ConformerEncoder + feat_in: ${model.preprocessor.features} + feat_out: -1 + n_layers: 18 + d_model: ${model.model_defaults.fc_d_model} + + # Sub-sampling parameters + subsampling: dw_striding # vggnet, striding, stacking or stacking_norm, dw_striding + subsampling_factor: 8 # must be power of 2 for striding and vggnet + subsampling_conv_channels: 256 # set to -1 to make it equal to the d_model + causal_downsampling: false + # Feed forward module's params + ff_expansion_factor: 4 + # Multi-headed Attention Module's params + self_attention_model: rel_pos # rel_pos or abs_pos + n_heads: 8 # may need to be lower for smaller d_models + # [left, right] specifies the number of steps to be seen from left and right of each step in self-attention + att_context_size: [-1, -1] # -1 means unlimited context + att_context_style: regular # regular or chunked_limited + xscaling: true # scales up the input embeddings by sqrt(d_model) + untie_biases: true # unties the biases of the TransformerXL layers + pos_emb_max_len: 5000 + # Convolution module's params + conv_kernel_size: 9 + conv_norm_type: 'batch_norm' # batch_norm or layer_norm or groupnormN (N specifies the number of groups) + conv_context_size: null + # Regularization + dropout: 0.1 # The dropout used in most of the Conformer Modules + dropout_pre_encoder: 0.1 # The dropout used before the encoder + dropout_emb: 0.0 # The dropout used for embeddings + dropout_att: 0.1 # The dropout for multi-headed attention modules + # Set to non-zero to enable stochastic depth + stochastic_depth_drop_prob: 0.0 + stochastic_depth_mode: linear # linear or uniform + stochastic_depth_start_layer: 1 + + transformer_encoder: + _target_: nemo.collections.asr.modules.transformer.transformer_encoders.TransformerEncoder + num_layers: 18 + hidden_size: ${model.model_defaults.tf_d_model} # Needs to be multiple of num_attention_heads + inner_size: 768 + num_attention_heads: 8 + attn_score_dropout: 0.5 + attn_layer_dropout: 0.5 + ffn_dropout: 0.5 + hidden_act: relu + pre_ln: False + pre_ln_final_layer_norm: True + + loss: + _target_: nemo.collections.asr.losses.bce_loss.BCELoss + weight: null # Weight for binary cross-entropy loss. Either `null` or list type input. (e.g. [0.5,0.5]) + reduction: mean + + lr: 0.0001 + optim: + name: adamw + lr: ${model.lr} + # optimizer arguments + betas: [0.9, 0.98] + weight_decay: 1e-3 + + sched: + name: InverseSquareRootAnnealing + warmup_steps: 2500 + warmup_ratio: null + min_lr: 1e-06 + + trainer: + devices: 1 # number of gpus (devices) + accelerator: gpu + max_epochs: 800 + max_steps: -1 # computed at runtime if not set + num_nodes: 1 + strategy: ddp_find_unused_parameters_true # Could be "ddp" + accumulate_grad_batches: 1 + deterministic: True + enable_checkpointing: False + logger: False + log_every_n_steps: 1 # Interval of logging. + val_check_interval: 1.0 # Set to 0.25 to check 4 times per epoch, or an int for number of iterations + + exp_manager: + use_datetime_version: False + exp_dir: null + name: ${name} + resume_if_exists: True + resume_from_checkpoint: null # The path to a checkpoint file to continue the training, restores the whole state including the epoch, step, LR schedulers, apex, etc. + resume_ignore_no_checkpoint: True + create_tensorboard_logger: True + create_checkpoint_callback: True + create_wandb_logger: False + checkpoint_callback_params: + monitor: "val_f1_acc" + mode: "max" + save_top_k: 9 + every_n_epochs: 1 + wandb_logger_kwargs: + resume: True + name: null + project: null + +Hydra Configurations for Streaming Sortformer Diarizer Training +---------------------------------------------------------------- + +Model name convention for Streaming Sortformer Diarizer: streaming_sortformer_diarizer_-.yaml + +* Example `/examples/speaker_tasks/diarization/neural_diarizer/conf/streaming_sortformer_diarizer_4spk-v2.yaml`. + +.. code-block:: yaml + + name: "StreamingSortformerDiarizer" + num_workers: 18 + batch_size: 4 + + model: + sample_rate: 16000 + pil_weight: 0.5 # Weight for Permutation Invariant Loss (PIL) used in training the Sortformer diarizer model + ats_weight: 0.5 # Weight for Arrival Time Sort (ATS) loss in training the Sortformer diarizer model + max_num_of_spks: 4 # Maximum number of speakers per model; currently set to 4 + streaming_mode: True + + model_defaults: + fc_d_model: 512 # Hidden dimension size of the Fast-conformer Encoder + tf_d_model: 192 # Hidden dimension size of the Transformer Encoder + + train_ds: + manifest_filepath: ??? + sample_rate: ${model.sample_rate} + num_spks: ${model.max_num_of_spks} + session_len_sec: 90 # Maximum session length in seconds + soft_label_thres: 0.5 # Threshold for binarizing target values; higher values make the model more conservative in predicting speaker activity. + soft_targets: False # If True, use continuous values as target values when calculating cross-entropy loss + labels: null + batch_size: ${batch_size} + shuffle: True + num_workers: ${num_workers} + validation_mode: False + # lhotse config + use_lhotse: False + use_bucketing: True + num_buckets: 10 + bucket_duration_bins: [10, 20, 30, 40, 50, 60, 70, 80, 90] + pin_memory: True + min_duration: 10 + max_duration: 90 + batch_duration: 400 + quadratic_duration: 1200 + bucket_buffer_size: 20000 + shuffle_buffer_size: 10000 + window_stride: ${model.preprocessor.window_stride} + subsampling_factor: ${model.encoder.subsampling_factor} + + validation_ds: + manifest_filepath: ??? + is_tarred: False + tarred_audio_filepaths: null + sample_rate: ${model.sample_rate} + num_spks: ${model.max_num_of_spks} + session_len_sec: 90 # Maximum session length in seconds + soft_label_thres: 0.5 # A threshold value for setting up the binarized labels. The higher the more conservative the model becomes. + soft_targets: False + labels: null + batch_size: ${batch_size} + shuffle: False + num_workers: ${num_workers} + validation_mode: True + # lhotse config + use_lhotse: False + use_bucketing: False + drop_last: False + pin_memory: True + window_stride: ${model.preprocessor.window_stride} + subsampling_factor: ${model.encoder.subsampling_factor} + + test_ds: + manifest_filepath: null + is_tarred: False + tarred_audio_filepaths: null + sample_rate: 16000 + num_spks: ${model.max_num_of_spks} + session_len_sec: 90 # Maximum session length in seconds + soft_label_thres: 0.5 + soft_targets: False + labels: null + batch_size: ${batch_size} + shuffle: False + seq_eval_mode: True + num_workers: ${num_workers} + validation_mode: True + # lhotse config + use_lhotse: False + use_bucketing: False + drop_last: False + pin_memory: True + window_stride: ${model.preprocessor.window_stride} + subsampling_factor: ${model.encoder.subsampling_factor} + + preprocessor: + _target_: nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor + normalize: "NA" + window_size: 0.025 + sample_rate: ${model.sample_rate} + window_stride: 0.01 + window: "hann" + features: 128 + n_fft: 512 + frame_splicing: 1 + dither: 0.00001 + + sortformer_modules: + _target_: nemo.collections.asr.modules.sortformer_modules.SortformerModules + num_spks: ${model.max_num_of_spks} # Maximum number of speakers the model can handle + dropout_rate: 0.5 # Dropout rate + fc_d_model: ${model.model_defaults.fc_d_model} # Hidden dimension size for Fast Conformer encoder + tf_d_model: ${model.model_defaults.tf_d_model} # Hidden dimension size for Transformer encoder + # Streaming mode parameters + spkcache_len: 188 # Length of speaker cache buffer (total number of frames for all speakers) + fifo_len: 0 # Length of FIFO buffer for streaming processing (0 = disabled) + chunk_len: 188 # Number of frames processed in each streaming chunk + spkcache_update_period: 188 # Speaker cache update period in frames + chunk_left_context: 1 # Number of previous frames for each streaming chunk + chunk_right_context: 1 # Number of future frames for each streaming chunk + # Speaker cache update parameters + spkcache_sil_frames_per_spk: 3 # Number of silence frames allocated per speaker in the speaker cache + scores_add_rnd: 0 # Standard deviation of random noise added to scores in speaker cache update (training only) + pred_score_threshold: 0.25 # Probability threshold for internal scores processing in speaker cache update + max_index: 99999 # Maximum allowed index value for internal processing in speaker cache update + scores_boost_latest: 0.05 # Gain for scores for recently added frames in speaker cache update + sil_threshold: 0.2 # Threshold for determining silence frames to calculate average silence embedding + strong_boost_rate: 0.75 # Rate determining number of frames per speaker that receive strong score boosting + weak_boost_rate: 1.5 # Rate determining number of frames per speaker that receive weak score boosting + min_pos_scores_rate: 0.5 # Rate threshold for dropping overlapping frames when enough non-overlapping exist + # Self-attention parameters (training only) + causal_attn_rate: 0.5 # Proportion of batches that use self-attention with limited right context + causal_attn_rc: 7 # Right context size for self-attention with limited right context + + encoder: + _target_: nemo.collections.asr.modules.ConformerEncoder + feat_in: ${model.preprocessor.features} + feat_out: -1 + n_layers: 17 + d_model: ${model.model_defaults.fc_d_model} + + # Sub-sampling parameters + subsampling: dw_striding # vggnet, striding, stacking or stacking_norm, dw_striding + subsampling_factor: 8 # must be power of 2 for striding and vggnet + subsampling_conv_channels: 256 # set to -1 to make it equal to the d_model + causal_downsampling: false + # Feed forward module's params + ff_expansion_factor: 4 + # Multi-headed Attention Module's params + self_attention_model: rel_pos # rel_pos or abs_pos + n_heads: 8 # may need to be lower for smaller d_models + # [left, right] specifies the number of steps to be seen from left and right of each step in self-attention + att_context_size: [-1, -1] # -1 means unlimited context + att_context_style: regular # regular or chunked_limited + xscaling: true # scales up the input embeddings by sqrt(d_model) + untie_biases: true # unties the biases of the TransformerXL layers + pos_emb_max_len: 5000 + # Convolution module's params + conv_kernel_size: 9 + conv_norm_type: 'batch_norm' # batch_norm or layer_norm or groupnormN (N specifies the number of groups) + conv_context_size: null + # Regularization + dropout: 0.1 # The dropout used in most of the Conformer Modules + dropout_pre_encoder: 0.1 # The dropout used before the encoder + dropout_emb: 0.0 # The dropout used for embeddings + dropout_att: 0.1 # The dropout for multi-headed attention modules + # Set to non-zero to enable stochastic depth + stochastic_depth_drop_prob: 0.0 + stochastic_depth_mode: linear # linear or uniform + stochastic_depth_start_layer: 1 + + transformer_encoder: + _target_: nemo.collections.asr.modules.transformer.transformer_encoders.TransformerEncoder + num_layers: 18 + hidden_size: ${model.model_defaults.tf_d_model} # Needs to be multiple of num_attention_heads + inner_size: 768 + num_attention_heads: 8 + attn_score_dropout: 0.5 + attn_layer_dropout: 0.5 + ffn_dropout: 0.5 + hidden_act: relu + pre_ln: False + pre_ln_final_layer_norm: True + + loss: + _target_: nemo.collections.asr.losses.bce_loss.BCELoss + weight: null # Weight for binary cross-entropy loss. Either `null` or list type input. (e.g. [0.5,0.5]) + reduction: mean + + lr: 0.0001 + optim: + name: adamw + lr: ${model.lr} + # optimizer arguments + betas: [0.9, 0.98] + weight_decay: 1e-3 + + sched: + name: InverseSquareRootAnnealing + warmup_steps: 500 + warmup_ratio: null + min_lr: 1e-06 + + trainer: + devices: 1 # number of gpus (devices) + accelerator: gpu + max_epochs: 800 + max_steps: -1 # computed at runtime if not set + num_nodes: 1 + strategy: ddp_find_unused_parameters_true # Could be "ddp" + accumulate_grad_batches: 1 + deterministic: True + enable_checkpointing: False + logger: False + log_every_n_steps: 1 # Interval of logging. + val_check_interval: 1.0 # Set to 0.25 to check 4 times per epoch, or an int for number of iterations + + exp_manager: + use_datetime_version: False + exp_dir: null + name: ${name} + resume_if_exists: True + resume_from_checkpoint: null # The path to a checkpoint file to continue the training, restores the whole state including the epoch, step, LR schedulers, apex, etc. + resume_ignore_no_checkpoint: True + create_tensorboard_logger: True + create_checkpoint_callback: True + create_wandb_logger: False + checkpoint_callback_params: + monitor: "val_f1_acc" + mode: "max" + save_top_k: 9 + every_n_epochs: 1 + wandb_logger_kwargs: + resume: True + name: null + project: null + + +Hydra Configurations for (Streaming) Sortformer Diarization Post-processing +----------------------------------------------------------------------------- + +Post-processing converts the floating point number based Tensor output to time stamp output. While generating the speaker-homogeneous segments, onset and offset threshold, +paddings can be considered to render the time stamps that can lead to the lowest diarization error rate (DER). This post-processing can be applied to both offline and streaming Sortformer diarizer. + + +By default, post-processing is bypassed, and only binarization is performed. If you want to reproduce DER scores reported on NeMo model cards, you need to apply post-processing steps. Use batch_size = 1 to have the longest inference window and the highest possible accuracy. + +.. code-block:: yaml + + parameters: + onset: 0.64 # Onset threshold for detecting the beginning of a speech segment + offset: 0.74 # Offset threshold for detecting the end of a speech segment + pad_onset: 0.06 # Adds the specified duration at the beginning of each speech segment + pad_offset: 0.0 # Adds the specified duration at the end of each speech segment + min_duration_on: 0.1 # Removes short speech segments if the duration is less than the specified minimum duration + min_duration_off: 0.15 # Removes short silences if the duration is less than the specified minimum duration + + +Hydra Configurations for Diarization Inference +============================================== + +Example configuration files for speaker diarization inference can be found in ``/examples/speaker_tasks/diarization/conf/inference/``. Choose a yaml file that fits your targeted domain. For example, if you want to diarize audio recordings of telephonic speech, choose ``diar_infer_telephonic.yaml``. + +The configurations for all the components of diarization inference are included in a single file named ``diar_infer_.yaml``. Each ``.yaml`` file has a few different sections for the following modules: VAD, Speaker Embedding, Clustering and ASR. + +In speaker diarization inference, the datasets provided in manifest format denote the data that you would like to perform speaker diarization on. + +Diarizer Configurations +----------------------- + +An example ``diarizer`` Hydra configuration could look like: + +.. code-block:: yaml + + diarizer: + manifest_filepath: ??? + out_dir: ??? + oracle_vad: False # If True, uses RTTM files provided in manifest file to get speech activity (VAD) timestamps + collar: 0.25 # Collar value for scoring + ignore_overlap: True # Consider or ignore overlap segments while scoring + +Under ``diarizer`` key, there are ``vad``, ``speaker_embeddings``, ``clustering`` and ``asr`` keys containing configurations for the inference of the corresponding modules. + +Configurations for Voice Activity Detector +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Parameters for VAD model are provided as in the following Hydra config example. + +.. code-block:: yaml + + vad: + model_path: null # .nemo local model path or pretrained model name or none + external_vad_manifest: null # This option is provided to use external vad and provide its speech activity labels for speaker embeddings extraction. Only one of model_path or external_vad_manifest should be set + + parameters: # Tuned parameters for CH109 (using the 11 multi-speaker sessions as dev set) + window_length_in_sec: 0.15 # Window length in sec for VAD context input + shift_length_in_sec: 0.01 # Shift length in sec for generate frame level VAD prediction + smoothing: "median" # False or type of smoothing method (eg: median) + overlap: 0.875 # Overlap ratio for overlapped mean/median smoothing filter + onset: 0.4 # Onset threshold for detecting the beginning and end of a speech + offset: 0.7 # Offset threshold for detecting the end of a speech + pad_onset: 0.05 # Adding durations before each speech segment + pad_offset: -0.1 # Adding durations after each speech segment + min_duration_on: 0.2 # Threshold for short speech segment deletion + min_duration_off: 0.2 # Threshold for small non_speech deletion + filter_speech_first: True + +Configurations for Speaker Embedding in Diarization +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Parameters for speaker embedding model are provided in the following Hydra config example. Note that multiscale parameters either accept list or single floating point number. + +.. code-block:: yaml + + speaker_embeddings: + model_path: ??? # .nemo local model path or pretrained model name (titanet_large, ecapa_tdnn or speakerverification_speakernet) + parameters: + window_length_in_sec: 1.5 # Window length(s) in sec (floating-point number). Either a number or a list. Ex) 1.5 or [1.5,1.25,1.0,0.75,0.5] + shift_length_in_sec: 0.75 # Shift length(s) in sec (floating-point number). Either a number or a list. Ex) 0.75 or [0.75,0.625,0.5,0.375,0.25] + multiscale_weights: null # Weight for each scale. should be null (for single scale) or a list matched with window/shift scale count. Ex) [1,1,1,1,1] + save_embeddings: False # Save embeddings as pickle file for each audio input. + +Configurations for Clustering in Diarization +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Parameters for clustering algorithm are provided in the following Hydra config example. + +.. code-block:: yaml + + clustering: + parameters: + oracle_num_speakers: False # If True, use num of speakers value provided in the manifest file. + max_num_speakers: 20 # Max number of speakers for each recording. If oracle_num_speakers is passed, this value is ignored. + enhanced_count_thres: 80 # If the number of segments is lower than this number, enhanced speaker counting is activated. + max_rp_threshold: 0.25 # Determines the range of p-value search: 0 < p <= max_rp_threshold. + sparse_search_volume: 30 # The higher the number, the more values will be examined with more time. + +Configurations for Diarization with ASR +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following configuration needs to be appended under ``diarizer`` to run ASR with diarization to get a transcription with speaker labels. + +.. code-block:: yaml + + asr: + model_path: ??? # Provide NGC cloud ASR model name. stt_en_conformer_ctc_* models are recommended for diarization purposes. + parameters: + asr_based_vad: False # if True, speech segmentation for diarization is based on word-timestamps from ASR inference. + asr_based_vad_threshold: 50 # threshold (multiple of 10ms) for ignoring the gap between two words when generating VAD timestamps using ASR based VAD. + asr_batch_size: null # Batch size can be dependent on each ASR model. Default batch sizes are applied if set to null. + lenient_overlap_WDER: True # If true, when a word falls into speaker-overlapped regions, consider the word as a correctly diarized word. + decoder_delay_in_sec: null # Native decoder delay. null is recommended to use the default values for each ASR model. + word_ts_anchor_offset: null # Offset to set a reference point from the start of the word. Recommended range of values is [-0.05 0.2]. + word_ts_anchor_pos: "start" # Select which part of the word timestamp we want to use. The options are: 'start', 'end', 'mid'. + fix_word_ts_with_VAD: False # Fix the word timestamp using VAD output. You must provide a VAD model to use this feature. + colored_text: False # If True, use colored text to distinguish speakers in the output transcript. + print_time: True # If True, the start of the end time of each speaker turn is printed in the output transcript. + break_lines: False # If True, the output transcript breaks the line to fix the line width (default is 90 chars) + + ctc_decoder_parameters: # Optional beam search decoder (pyctcdecode) + pretrained_language_model: null # KenLM model file: .arpa model file or .bin binary file. + beam_width: 32 + alpha: 0.5 + beta: 2.5 + + realigning_lm_parameters: # Experimental feature + arpa_language_model: null # Provide a KenLM language model in .arpa format. + min_number_of_words: 3 # Min number of words for the left context. + max_number_of_words: 10 # Max number of words for the right context. + logprob_diff_threshold: 1.2 # The threshold for the difference between two log probability values from two hypotheses. diff --git a/docs/source/asr/speaker_diarization/data/diarization_results.csv b/docs/source/asr/speaker_diarization/data/diarization_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..c71345ac3dc7684318dceebf1ac67b0af53c28c6 --- /dev/null +++ b/docs/source/asr/speaker_diarization/data/diarization_results.csv @@ -0,0 +1,6 @@ +Model Name,Model Base Class,Model Card +vad_multilingual_marblenet,EncDecClassificationModel,"https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/vad_multilingual_marblenet" +vad_marblenet,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:vad_marblenet" +vad_telephony_marblenet,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:vad_telephony_marblenet" +titanet_large,EncDecSpeakerLabelModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:titanet_large" +ecapa_tdnn,EncDecSpeakerLabelModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:ecapa_tdnn" diff --git a/docs/source/asr/speaker_diarization/data/e2e_diar_models.csv b/docs/source/asr/speaker_diarization/data/e2e_diar_models.csv new file mode 100644 index 0000000000000000000000000000000000000000..6de838971ae374f86b88729a0316df6d8fd4883f --- /dev/null +++ b/docs/source/asr/speaker_diarization/data/e2e_diar_models.csv @@ -0,0 +1,4 @@ +Model Name,Model Base Class,Model Card +diar_sortformer_4spk-v1,SortformerEncLabelModel,"https://huggingface.co/nvidia/diar_sortformer_4spk-v1" +diar_streaming_sortformer_4spk-v2,SortformerEncLabelModel,"https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2" +diar_streaming_sortformer_4spk-v2.1,SortformerEncLabelModel,"https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2.1" \ No newline at end of file diff --git a/docs/source/asr/speaker_diarization/datasets.rst b/docs/source/asr/speaker_diarization/datasets.rst new file mode 100644 index 0000000000000000000000000000000000000000..97c5d0f0c37308e57db8f206ee26b0caa32582a1 --- /dev/null +++ b/docs/source/asr/speaker_diarization/datasets.rst @@ -0,0 +1,183 @@ +Datasets +======== + +Data Preparation for Speaker Diarization Training (End-to-End Diarization) +-------------------------------------------------------------------------- + +Overview +~~~~~~~~ + +Speaker diarization training requires a manifest file in JSON-lines format. Each line describes one training segment and points to an audio file together with its corresponding RTTM ground-truth labels. The same manifest format is used for both training and inference. + +Use ``/scripts/speaker_tasks/pathfiles_to_diarize_manifest.py`` to generate a manifest from lists of audio and RTTM file paths: + +.. code-block:: bash + + python /scripts/speaker_tasks/pathfiles_to_diarize_manifest.py \ + --add_duration \ + --paths2audio_files="/path/to/audio_file_path_list.txt" \ + --paths2rttm_files="/path/to/rttm_file_list.txt" \ + --manifest_filepath="/path/to/train_manifest.json" + +All three arguments are required. Audio and RTTM files are matched by their base filename (e.g., ``abcd01.wav`` pairs with ``abcd01.rttm``). + +.. note:: + All provided files (audio, RTTM, text) must share the same base name, and each base name must be unique across the dataset. + +- Example ``audio_file_path_list.txt``: + +.. code-block:: bash + + /path/to/abcd01.wav + /path/to/abcd02.wav + +- Example ``rttm_file_path_list.txt``: + +.. code-block:: bash + + /path/to/abcd01.rttm + /path/to/abcd02.rttm + +The RTTM (Rich Transcription Time Marked) format provides per-speaker speech activity timestamps. Each line follows this structure: + +.. code-block:: bash + + SPEAKER TS3012d.Mix-Headset 1 32.679 0.671 MTD046ID + +The generated ``train_manifest.json`` will contain one JSON line per segment: + +.. code-block:: bash + + {"audio_filepath": "/path/to/abcd01.wav", "offset": 0, "duration": 90, "label": "infer", "text": "-", "num_speakers": 2, "rttm_filepath": "/path/to/rttm/abcd01.rttm"} + +For end-to-end speaker diarization training, this manifest format is sufficient. For cascaded speaker diarization training, the manifest should be further processed to generate pairwise two-speaker session files. + + +Working with Long-Form Audio +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Long audio recordings do **not** need to be physically split into shorter files. The NeMo diarization dataloader reads only the segment specified by the ``offset`` and ``duration`` fields in each manifest entry. The corresponding RTTM file is also windowed to the same time range automatically — there is no need to create separate RTTM files for each segment. + +To segment a long recording, create multiple manifest entries that reference the same audio and RTTM files but with different ``offset`` and ``duration`` values. Each entry must carry a unique ``uniq_id`` so that the dataloader can distinguish segments originating from the same source file. A recommended convention is ``###``. + +Below is an example where a 45-minute recording (``EN2001a.Mix-Headset.wav``) is divided into 90-second windows. The full session contains 4 speakers, but this particular segment has only 3 active speakers: + +.. code-block:: bash + + {"uniq_id": "EN2001a.Mix-Headset#116#932.92#90.0", "offset": 932.92, "duration": 90, "num_speakers": 3, "audio_filepath": "/path/to/wav/EN2001a.Mix-Headset.wav", "rttm_filepath": "/path/to/rttm/EN2001a.Mix-Headset.rttm"} + + +Handling ``num_speakers`` and Partial Speaker Presence +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A training segment may contain only a subset of the speakers present in the full recording. The ``num_speakers`` field should reflect the number of speakers **active in that specific segment**, not the total across the entire session. + +In practice, ``num_speakers`` is optional — the dataloader can infer the speaker count automatically from the RTTM labels within the segment's time window (see the ``DiarizationLabelDataset`` class in ``/nemo/collections/asr/data/audio_to_diar_label.py``). + + +Speaker-Count Coverage in Training Data +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The model will not generalize to speaker counts it has never encountered during training. If the target scenario involves up to *N* speakers, the training set should include segments with every speaker count from 1 through *N*. When natural data is scarce for higher speaker counts, consider: + +- **Oversampling** segments that contain more speakers. +- **Augmenting** with simulated multi-speaker mixtures (e.g., from LibriSpeech). +- **Scaling data volume** with speaker count — for example, 100 hours for 1-speaker segments, 200 hours for 2-speaker, 300 hours for 3-speaker, and so on. + +Matching the speaker-count distribution between training and inference is critical for good diarization performance. + + +Data Preparation for Diarization Inference: for Both End-to-end and Cascaded Systems +------------------------------------------------------------------------------------ + +As in dataset preparation for diarization trainiing, diarization inference is based on Hydra configurations which are fulfilled by ``.yaml`` files. See :doc:`NeMo Speaker Diarization Configuration Files <./configs>` for setting up the input Hydra configuration file for speaker diarization inference. Input data should be provided in line delimited JSON format as below: + +.. code-block:: bash + + {"audio_filepath": "/path/to/abcd.wav", "offset": 0, "duration": null, "label": "infer", "text": "-", "num_speakers": null, "rttm_filepath": "/path/to/rttm/abcd.rttm", "uem_filepath": "/path/to/uem/abcd.uem"} + +In each line of the input manifest file, ``audio_filepath`` item is mandatory while the rest of the items are optional and can be passed for desired diarization setting. We refer to this file as a manifest file. This manifest file can be created by using the script in ``/scripts/speaker_tasks/pathfiles_to_diarize_manifest.py``. The following example shows how to run ``pathfiles_to_diarize_manifest.py`` by providing path list files. + +.. code-block:: bash + + python pathfiles_to_diarize_manifest.py --paths2audio_files /path/to/audio_file_path_list.txt \ + --paths2txt_files /path/to/transcript_file_path_list.txt \ + --paths2rttm_files /path/to/rttm_file_path_list.txt \ + --paths2uem_files /path/to/uem_file_path_list.txt \ + --paths2ctm_files /path/to/ctm_file_path_list.txt \ + --manifest_filepath /path/to/manifest_output/input_manifest.json + +The ``--paths2audio_files`` and ``--manifest_filepath`` are required arguments. Note that we need to maintain consistency on unique filenames for every field (key) by only changing the filename extensions. For example, if there is an audio file named ``abcd.wav``, the rttm file should be named as ``abcd.rttm`` and the transcription file should be named as ``abcd.txt``. + +- Example audio file path list ``audio_file_path_list.txt`` + +.. code-block:: bash + + /path/to/abcd01.wav + /path/to/abcd02.wav + +- Example RTTM file path list ``rttm_file_path_list.txt`` + +.. code-block:: bash + + /path/to/abcd01.rttm + /path/to/abcd02.rttm + + +The path list files containing the absolute paths to these WAV, RTTM, TXT, CTM and UEM files should be provided as in the above example. ``pathsfiles_to_diarize_manifest.py`` script will match each file using the unique filename (e.g. ``abcd``). Finally, the absolute path of the created manifest file should be provided through Hydra configuration as shown below: + +.. code-block:: yaml + + diarizer.manifest_filepath="path/to/manifest/input_manifest.json" + +The following are descriptions about each field in an input manifest JSON file. + +.. note:: + We expect all the provided files (e.g. audio, rttm, text) to have the same base name and the name should be unique (uniq-id). + +``audio_filepath`` (Required): + + a string containing absolute path to the audio file. + +``num_speakers`` (Optional): + + If the number of speakers is known, provide the integer number or assign null if not known. + +``rttm_filepath`` (Optional): + + To evaluate a diarization system with known rttm files, one needs to provide Rich Transcription Time Marked (RTTM) files as ground truth label files. If RTTM files are provided, the diarization evaluation will be initiated. Here is one line from a RTTM file as an example: + +.. code-block:: bash + + SPEAKER TS3012d.Mix-Headset 1 331.573 0.671 MTD046ID + +``text`` (Optional): + + Ground truth transcription for diarization with ASR inference. Provide the ground truth transcription of the given audio file in string format + +.. code-block:: bash + + {"text": "this is an example transcript"} + +``uem_filepath`` (Optional): + + The UEM file is used for specifying the scoring regions to be evaluated in the given audio file. + UEMfile follows the following convention: `` ``. ```` is set to 1. + + Example lines of UEM file: + +.. code-block:: bash + + TS3012d.Mix-Headset 1 12.31 108.98 + TS3012d.Mix-Headset 1 214.00 857.09 + +``ctm_filepath`` (Optional): + + The CTM file is used for the evaluation of word-level diarization results and word-timestamp alignment. The CTM file follows this convention: `` ``. Note that the ```` should exactly match speaker IDs in RTTM. Since confidence is not required for evaluating diarization results, we assign ```` the value ``NA``. If the type of token is words, we assign ```` as ``lex``. + + Example lines of CTM file: + +.. code-block:: bash + + TS3012d.Mix-Headset 1 12.879 0.32 okay NA lex MTD046ID + TS3012d.Mix-Headset 1 13.203 0.24 yeah NA lex MTD046ID diff --git a/docs/source/asr/speaker_diarization/images/aosc_3spk_example.gif b/docs/source/asr/speaker_diarization/images/aosc_3spk_example.gif new file mode 100644 index 0000000000000000000000000000000000000000..ab3a2bb2d75b0b5d4fca34c1e73606159ffc8aed --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/aosc_3spk_example.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69abf595343af0678eb5ba834b6de83572b1ebed78a523dc508c8b3c9ab0d8ea +size 5491128 diff --git a/docs/source/asr/speaker_diarization/images/asr_sd_diagram.png b/docs/source/asr/speaker_diarization/images/asr_sd_diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..cfbd85cb410ea93d96b227a2c89932d7492b63a4 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/asr_sd_diagram.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8ff98b1fed0f7988f7806c7957ce54f507c8423ef7e4d3f004b656cfb92501d +size 607032 diff --git a/docs/source/asr/speaker_diarization/images/ats.png b/docs/source/asr/speaker_diarization/images/ats.png new file mode 100644 index 0000000000000000000000000000000000000000..93aecff9882a54e3e7b390df65afeb49bd45eb40 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/ats.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce0ee834d924bf19f9cd25f3ac2cec7d76dfc0557919f9e201bbd09f4a577b01 +size 334373 diff --git a/docs/source/asr/speaker_diarization/images/cache_fifo_chunk.png b/docs/source/asr/speaker_diarization/images/cache_fifo_chunk.png new file mode 100644 index 0000000000000000000000000000000000000000..f996e2e17c1907e5e06ad8e5109127c3ebc1a05c --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/cache_fifo_chunk.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b912ae42d03f22bb19c5bdf29c5966cf0fd11ebf86a16bc4263a4501349a39f4 +size 122833 diff --git a/docs/source/asr/speaker_diarization/images/data_flow.png b/docs/source/asr/speaker_diarization/images/data_flow.png new file mode 100644 index 0000000000000000000000000000000000000000..22db1d03de71f97f4a070505f315fbddbf6ee158 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/data_flow.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ca6dfd9c1843041aecc202aa3a8f3599fee05ad64cdeb352cb4787dec052126 +size 212743 diff --git a/docs/source/asr/speaker_diarization/images/e2e_and_cascaded_diar_systems.png b/docs/source/asr/speaker_diarization/images/e2e_and_cascaded_diar_systems.png new file mode 100644 index 0000000000000000000000000000000000000000..edfd01db09fa95f6c628667c32f706824caf2bc0 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/e2e_and_cascaded_diar_systems.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a27f90ee933a2b5ae7224f3c95ec32f062cbb1f72c3300c7250c559e3d110866 +size 240231 diff --git a/docs/source/asr/speaker_diarization/images/e2e_diar_diagram.png b/docs/source/asr/speaker_diarization/images/e2e_diar_diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..126096e6249312d50b349e7a07a5baf991e69fb9 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/e2e_diar_diagram.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e101ab8db39ad068849acd43c05972cd75feca3b95f24c45407292f80f011c6f +size 89889 diff --git a/docs/source/asr/speaker_diarization/images/intro_comparison.png b/docs/source/asr/speaker_diarization/images/intro_comparison.png new file mode 100644 index 0000000000000000000000000000000000000000..6b32e8d5ee743bfde13bca01e8e7fff0575b313d --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/intro_comparison.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3a68d66641791001318e43dd1aa51349fd55c7f0fd12da1c496e64020157741 +size 325066 diff --git a/docs/source/asr/speaker_diarization/images/loss_types.png b/docs/source/asr/speaker_diarization/images/loss_types.png new file mode 100644 index 0000000000000000000000000000000000000000..f82fe3627f40691a77bc75a8eaa27c142e93fd0f --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/loss_types.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:473f06930d780d7e3d96ad14db11e51dcbebe53b753da3d0236c9efc837a9efe +size 221589 diff --git a/docs/source/asr/speaker_diarization/images/main_dataflow.png b/docs/source/asr/speaker_diarization/images/main_dataflow.png new file mode 100644 index 0000000000000000000000000000000000000000..7fe49f27af7f8c9457c9a6b71164fb159cb1aa94 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/main_dataflow.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69f6403ff68d40c58e6f88387e1b91a8907f0f3c46b0f1281a71b3b85ce9643c +size 460168 diff --git a/docs/source/asr/speaker_diarization/images/ms_trade_off.png b/docs/source/asr/speaker_diarization/images/ms_trade_off.png new file mode 100644 index 0000000000000000000000000000000000000000..d54294ad73c8ac3e2b7cffe16e5bad1be760dbd3 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/ms_trade_off.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c6730fd47ebc1c42c8c6fb47a031db6066e1ad28b0eef1944d94598124301b4 +size 609415 diff --git a/docs/source/asr/speaker_diarization/images/msdd_train_and_infer.png b/docs/source/asr/speaker_diarization/images/msdd_train_and_infer.png new file mode 100644 index 0000000000000000000000000000000000000000..be3964b2b0bcd4fa86114f1d26c2e2d7c477f97a --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/msdd_train_and_infer.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d3d1e2e4b9563a9910ce284c909fa2e74b33c218ffd8df91391e35f35f7a753 +size 123505 diff --git a/docs/source/asr/speaker_diarization/images/scale_weight_cnn.png b/docs/source/asr/speaker_diarization/images/scale_weight_cnn.png new file mode 100644 index 0000000000000000000000000000000000000000..e1f7fe0c9c1ebeec4f257f383a5babe26cf6c5a3 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/scale_weight_cnn.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6da420b34c24723410c242b109de9fded71914ea9bc934119d51f5a6b89b1760 +size 676196 diff --git a/docs/source/asr/speaker_diarization/images/sd_pipeline.png b/docs/source/asr/speaker_diarization/images/sd_pipeline.png new file mode 100644 index 0000000000000000000000000000000000000000..1c5593d2e444c0646e92797609fc56b369a4dbc5 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/sd_pipeline.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:156963d5fc656bd389a9f631c943a06c9c2d7c73ef68ed092f486765cff76df4 +size 65688 diff --git a/docs/source/asr/speaker_diarization/images/sequence_model.png b/docs/source/asr/speaker_diarization/images/sequence_model.png new file mode 100644 index 0000000000000000000000000000000000000000..0840393de5f2985ab605faf651f640004b7d7142 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/sequence_model.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b71c7d157c6addd5871385049773d988e60dc6460df947d7e32b8d88445b22c +size 76738 diff --git a/docs/source/asr/speaker_diarization/images/sortformer.png b/docs/source/asr/speaker_diarization/images/sortformer.png new file mode 100644 index 0000000000000000000000000000000000000000..1d5140b3a7c80fe29e2ca83e99c61d35c70a0be3 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/sortformer.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37826da2bece82f590c7b70d76800618764f3dfdd389e1fbb2ca688db01a4edd +size 449944 diff --git a/docs/source/asr/speaker_diarization/images/streaming_steps.png b/docs/source/asr/speaker_diarization/images/streaming_steps.png new file mode 100644 index 0000000000000000000000000000000000000000..3deb8c1046694f7bdecde8cda109ef8272d160b6 --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/streaming_steps.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aba47ea9ce01db2cc35331faf93140235b5ea3348401cc6072658b82b0dbefcb +size 637178 diff --git a/docs/source/asr/speaker_diarization/images/weighted_sum.png b/docs/source/asr/speaker_diarization/images/weighted_sum.png new file mode 100644 index 0000000000000000000000000000000000000000..31d44abdbee5f5d4594176a33a3f3dd2f4e8dbfc --- /dev/null +++ b/docs/source/asr/speaker_diarization/images/weighted_sum.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:365dcd8f10ed55514471a9c06cfed1aec51d30f7a82d5cd48d9f6edf4339986a +size 434698 diff --git a/docs/source/asr/speaker_diarization/intro.rst b/docs/source/asr/speaker_diarization/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..e91c865b00c5ef0798a08d532fb9f32527e4394f --- /dev/null +++ b/docs/source/asr/speaker_diarization/intro.rst @@ -0,0 +1,60 @@ +Speaker Diarization +=================== + +Speaker Diarization Overview +---------------------------- +Speaker diarization is the process of segmenting audio recordings by speaker labels and aims to answer the question “who spoke when?”. Speaker diarization makes a clear distinction when it is compared with speech recognition. As shown in the figure below, before we perform speaker diarization, we know “what is spoken” yet we do not know “who spoke it”. Therefore, speaker diarization is an essential feature for a speech recognition system to enrich the transcription with speaker labels. + +.. image:: images/asr_sd_diagram.png + :align: center + :width: 800px + :alt: Speaker diarization pipeline- VAD, segmentation, speaker embedding extraction, clustering + +To figure out "who spoke when", speaker diarization systems need to capture the characteristics of unseen speakers and tell apart which regions in the audio recording belong to which speaker. To achieve this, speaker diarization systems extract voice characteristics, count the number of speakers, then assign the audio segments to the corresponding speaker index. + +Types of Speaker Diarization Systems +------------------------------------ + +.. image:: images/e2e_and_cascaded_diar_systems.png + :align: center + :width: 800px + :alt: End-to-End and Cascaded Diar Systems + +1. End-to-End Speaker Diarization System: + +End-to-end speaker diarization systems pursue a much more simplified version of a system where a single neural network model accepts raw audio signals and outputs speaker activity for each audio frame. Therefore, end-to-end diarization models have an advantage in ease of optimization and depoloyments. + +Curently, NeMo Speech AI provides the following end-to-end speaker diarization models: + +- **Sortformer Diarizer** : A transformer-based model that estimates speaker labels from the given audio input giving the speaker indexes in arrival-time order. + +2. Cascaded Speaker Diarization System: + +Traditional cascaded (also referred to as modular or pipelined) speaker diarization systems consist of multiple modules such as a speaker activity detection (SAD) module and a speaker embedding extractor module. +On top of the clustering diarizer, target-speaker voice activity detection (VAD) is performed to generate the final speaker labels. Cascaded speaker diarization systems are more challenging to optimize all together and deploy but still has advantage of having less restriction on the number of speakers and session length. + +Cascaded NeMo Speech AI speaker diarization system consists of the following modules: + +- **Voice Activity Detector (VAD)**: A trainable model which detects the presence or absence of speech to generate timestamps for speech activity from the given audio recording. + +- **Speaker Embedding Extractor**: A trainable model that extracts speaker embedding vectors containing voice characteristics from raw audio signal. + +- **Clustering Module**: A non-trainable module that groups speaker embedding vectors into a number of clusters. + +- **Neural Diarizer (TS-VAD)**: A trainable model that estimates speaker labels from the given features. In general, this module is performing target-speaker VAD task to generate the final speaker labels. + + + +The full documentation tree is as follows: + +.. toctree:: + :maxdepth: 8 + + models + datasets + results + configs + api + resources + +.. include:: resources.rst diff --git a/docs/source/asr/speaker_diarization/models.rst b/docs/source/asr/speaker_diarization/models.rst new file mode 100644 index 0000000000000000000000000000000000000000..3717a551a568c4859355e1facf3cb2ea6704ce5b --- /dev/null +++ b/docs/source/asr/speaker_diarization/models.rst @@ -0,0 +1,112 @@ +Models +====== + +This section gives a brief overview of the supported speaker diarization models in NeMo's ASR collection. + +Currently NeMo Speech AI supports two types of speaker diarization systems: + +1. **End-to-end Speaker Diarization:** Sortformer Diarizer + +Sortformer is a Transformer encoder-based end-to-end speaker diarization model that generates predicted speaker labels directly from input audio clips. +We offer offline and online versions of Sortformer Diarizer. Online version of Sortformer diarizer can also be used for offline diarization by setting a long enough chunk size. + +2. **Cascaded (Pipelined) Speaker Diarization:** Clustering diarizer + +The clustering-based speaker diarization pipeline in NeMo Speech AI involves the use of the :doc:`MarbleNet <../speech_classification/models>` model for Voice Activity Detection (VAD) and the :doc:`TitaNet <../speaker_recognition/models>` model for speaker embedding extraction, followed by spectral clustering. + +.. _Sortformer Diarizer: + +Sortformer Diarizer +------------------- +Speaker diarization is all about figuring out who's speaking when in an audio recording. In the world of automatic speech recognition (ASR), this becomes even more important for handling conversations with multiple speakers. Multispeaker ASR (also known as speaker-attributed or multitalker ASR) uses this process to not just transcribe what's being said, but also to label each part of the transcript with the right speaker. + +As ASR technology continues to advance, speaker diarization is increasingly becoming part of the ASR workflow itself. Some systems now handle speaker labeling and transcription at the same time during decoding. This means you not only get accurate text—you're also getting insights into who said what, making it more useful for conversational analysis. + +However, despite significant advancements, integrating speaker diarization and ASR into a unified, seamless system remains a considerable challenge. A key obstacle lies in the need for extensive high-quality, annotated audio data featuring multiple speakers. Acquiring such data is far more complex than collecting monaural-speaker datasets. This challenge is particularly pronounced for low-resource languages and domains like healthcare, where strict privacy regulations further constrain data availability. + +On top of that, many real-world use cases need these models to handle really long audio files—sometimes hours of conversation at a time. Training on such lengthy data is even more complicated because it's hard to find or annotate. This creates a big gap between what's needed and what's available, making multispeaker ASR one of the toughest nuts to crack in the field of speech technology. + +.. image:: images/intro_comparison.png + :align: center + :width: 800px + :alt: Intro Comparison + +To tackle the complexities of multispeaker automatic speech recognition (ASR), we introduce `Sortformer `__, a new approach that incorporates *Sort Loss* and techniques to align timestamps with text tokens. Traditional approaches like permutation-invariant loss (PIL) face challenges when applied in batchable and differentiable computational graphs, especially since token-based objectives struggle to incorporate speaker-specific attributes into PIL-based loss functions. + +To address this, we propose an arrival time sorting (ATS) approach. In this method, speaker tokens from ASR outputs and speaker timestamps from diarization outputs are sorted by their arrival times to resolve permutations. This approach allows the multispeaker ASR system to be trained or fine-tuned using token-based cross-entropy loss, eliminating the need for timestamp-based or frame-level objectives with PIL. + +.. image:: images/ats.png + :align: center + :width: 600px + :alt: Arrival Time Sort + +The ATS-based multispeaker ASR system is powered by an end-to-end neural diarizer model, Sortformer, which generates speaker-label timestamps in arrival time order (ATO). To train the neural diarizer to produce sorted outputs, we introduce Sort Loss, a method that creates gradients enabling the Transformer model to learn the ATS mechanism. + +.. image:: images/main_dataflow.png + :align: center + :width: 500px + :alt: Main Dataflow + + +Additionally, as shown in the above figure, our diarization system integrates directly with the ASR encoder. By embedding speaker supervision data as speaker kernels into the ASR encoder states, the system seamlessly combines speaker and transcription information. This unified approach improves performance and simplifies the overall architecture. + +As a result, our end-to-end multispeaker ASR system is fully or partially trainable with token objectives, allowing both the ASR and speaker diarization modules to be trained or fine-tuned using these objectives. Additionally, during the multispeaker ASR training phase, no specialized loss calculation functions are needed when using Sortformer, as frameworks for standard single-speaker ASR models can be employed. These compatibilities greatly simplify and accelerate the training and fine-tuning process of multispeaker ASR systems. + +On top of all these benefits, *Sortformer* can be used as a stand-alone end-to-end speaker diarization model. By training a Sortformer diarizer model especially on high-quality simulated data with accurate time-stamps, you can boost the performance of multi-speaker ASR systems, just by integrating the *Sortformer* model as *Speaker Supervision* model in a computation graph. + +In this tutorial, we will walk you through the process of training a Sortformer diarizer model with toy dataset. Before starting, we will introduce the concepts of Sort-Loss calculation and the Hybrid loss technique. + +.. image:: images/sortformer.png + :align: center + :width: 500px + :alt: Sortformer Model with Hybrid Loss + +.. image:: images/loss_types.png + :align: center + :width: 1000px + :alt: PIL model VS SortLoss model + +*Sort Loss* is designed to compare the predicted outputs with the true labels, typically sorted in arrival-time order or another relevant metric. The key distinction that *Sortformer* introduces compared to previous end-to-end diarization systems such as `EEND-SA `__, `EEND-EDA `__ lies in the organization of class presence :math:`\mathbf{\hat{Y}}`. + +The figure below illustrates the difference between *Sort Loss* and permutation-invariant loss (PIL) or permutation-free loss. + +- PIL is calculated by finding the permutation of the target that minimizes the loss value between the prediction and the target. + +- *Sort Loss* simply compares the arrival-time-sorted version of speaker activity outputs for both the prediction and the target. Note that sometimes the same ground-truth labels lead to different target matrices for *Sort Loss* and PIL. + +For example, the figure below shows two identical source target matrices (the two matrices at the top), but the resulting target matrices for *Sort Loss* and PIL are different. + +.. _Streaming Sortformer Diarizer: + +Streaming Sortformer Diarizer +----------------------------- + +`Streaming Sortformer `__ is a streaming version of Sortformer diarizer. To handle live audio, Streaming Sortformer processes the sound in small, overlapping chunks. It employs an Arrival-Order Speaker Cache (AOSC) that stores frame-level acoustic embeddings for all speakers previously detected in the audio stream. This allows the model to compare speakers in the current chunk with those in the previous ones, ensuring a person is consistently identified with the same label throughout the stream. + +.. image:: images/cache_fifo_chunk.png + :align: center + :width: 800px + :alt: Chunk-wise processing with AOSC and FIFO buffer in Streaming Sortformer inference + +Streaming Sortformer employs a pre-encoder layer in the Fast-Conformer to generate a speaker cache. At each step, speaker cache is filtered to only retain the high-quality speaker cache vectors. Aside from speaker-cache management part, Streaming Sortformer follows the architecture of the offline version of Sortformer. + +.. image:: images/streaming_steps.png + :align: center + :width: 800px + :alt: The dataflow of step-wise Streaming Sortformer inference + +Below is the animated heatmap illustrating real-time speaker diarization for a three-speaker conversation using Streaming Sortformer. The heatmap shows how activities of speakers are detected in the current chunk and updated in the Arrival-Order Speaker Cache and FIFO queue. + +.. image:: images/aosc_3spk_example.gif + :align: center + :width: 800px + :alt: Streaming Sortformer Animated + + +References +----------- + +.. bibliography:: ../asr_all.bib + :style: plain + :labelprefix: SD-MODELS + :keyprefix: sd-models- diff --git a/docs/source/asr/speaker_diarization/resources.rst b/docs/source/asr/speaker_diarization/resources.rst new file mode 100644 index 0000000000000000000000000000000000000000..9082491811baea7c770471e254b87ecc8a8fea87 --- /dev/null +++ b/docs/source/asr/speaker_diarization/resources.rst @@ -0,0 +1,24 @@ + +Resource and Documentation Guide +-------------------------------- + +Hands-on speaker diarization tutorial notebooks for both end-to-end and cascaded systems can be found under ``/tutorials/speaker_tasks``. + +There are also tutorials for performing both end-to-end speaker diarization cascaded speaker diarization. +We also provide tutorials about getting ASR transcriptions combined with speaker labels along with voice activity timestamps with NeMo ASR collections. + +Most of the tutorials can be run on Google Colab by specifying the link to the notebooks' GitHub pages on Colab. + +If you are looking for information about a particular model used for speaker diarization inference, or would like to find out more about the model +architectures available in the `nemo_asr` collection, check out the :doc:`Models <./models>` page. + +Documentation on dataset preprocessing can be found on the :doc:`Datasets <./datasets>` page. +NeMo includes preprocessing scripts for several common ASR datasets, and this page contains instructions on running +those scripts. +It also includes guidance for creating your own NeMo-compatible dataset, if you have your own data. + +Information about how to load model checkpoints (either local files or pretrained ones from NGC), perform inference, as well as a list +of the checkpoints available on NGC are located on the :doc:`Checkpoints <./results>` page. + +Documentation for configuration files specific to the ``nemo_asr`` models can be found on the +:doc:`Configuration Files <./configs>` page. diff --git a/docs/source/asr/speaker_diarization/results.rst b/docs/source/asr/speaker_diarization/results.rst new file mode 100644 index 0000000000000000000000000000000000000000..ee98c505f744076c76845b0ef290ff2a91afba9e --- /dev/null +++ b/docs/source/asr/speaker_diarization/results.rst @@ -0,0 +1,193 @@ +Checkpoints +=========== + +There are two main ways to load pretrained checkpoints in NeMo as introduced in the :doc:`ASR checkpoints <../results>` section. +In speaker diarization, the diarizer loads checkpoints that are passed through the config file. + + +End-to-end Speaker Diarization Models +===================================== + +Sortformer Diarizer Training +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Use the following command to train a Sortformer diarizer model. + +.. code-block:: bash + + # Feed the config for Sortformer diarizer model training + python ${NEMO_ROOT}/examples/speaker_tasks/diarization/neural_diarizer/sortformer_diar_train.py --config-path='../conf/neural_diarizer' \ + --config-name='sortformer_diarizer_hybrid_loss_4spk-v1.yaml' \ + trainer.devices=1 \ + model.train_ds.manifest_filepath="" \ + model.validation_ds.manifest_filepath="" \ + exp_manager.name='sample_train' \ + exp_manager.exp_dir=./sortformer_diar_train + + +Sortformer Diarizer Inference with Post-processing +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Use the following command to run inference on a Sortformer diarizer model. + +.. code-block:: bash + + # Config for post-processing + PP_YAML1=${NEMO_ROOT}/examples/speaker_tasks/diarization/conf/post_processing/sortformer_diar_4spk-v1_dihard3-dev.yaml + PP_YAML2=${NEMO_ROOT}/examples/speaker_tasks/diarization/conf/post_processing/sortformer_diar_4spk-v1_callhome-part1.yaml + python ${NEMO_ROOT}/examples/speaker_tasks/diarization/neural_diarizer/e2e_diarize_speech.py \ + batch_size=1 \ + model_path=/path/to/diar_sortformer_4spk-v1.nemo \ + postprocessing_yaml=${PP_YAML2} \ + dataset_manifest=/path/to/diarization_manifest.json + + +Streaming Sortformer Diarizer Training +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Use the following command to train a Streaming Sortformer diarizer model. + +.. code-block:: bash + + # Feed the config for Sortformer diarizer model training + python ${NEMO_ROOT}/examples/speaker_tasks/diarization/neural_diarizer/sortformer_diar_train.py --config-path='../conf/neural_diarizer' \ + --config-name='streaming_sortformer_diarizer_4spk-v2.yaml' \ + trainer.devices=1 \ + model.streaming_mode=True \ + model.train_ds.manifest_filepath="" \ + model.validation_ds.manifest_filepath="" \ + exp_manager.name='sample_train' \ + exp_manager.exp_dir=./sortformer_diar_train + + +Streaming Sortformer Diarizer Inference with Post-processing +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Use the following command to run inference on a Streaming Sortformer diarizer model. + +.. code-block:: bash + + # Config for post-processing + STREAM_PP_YAML1=${NEMO_ROOT}/examples/speaker_tasks/diarization/conf/post_processing/diar_streaming_sortformer_4spk-v2_dihard3-dev.yaml + STREAM_PP_YAML2=${NEMO_ROOT}/examples/speaker_tasks/diarization/conf/post_processing/diar_streaming_sortformer_4spk-v2_callhome-part1.yaml + python ${NEMO_ROOT}/examples/speaker_tasks/diarization/neural_diarizer/e2e_diarize_speech.py \ + batch_size=1 \ + model_path=/path/to/diar_streaming_sortformer_4spk-v2.nemo \ + postprocessing_yaml=${STREAM_PP_YAML2} \ + dataset_manifest=/path/to/diarization_manifest.json + + +HuggingFace Pretrained Checkpoints +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ASR collection has checkpoints of several models trained on various datasets for a variety of tasks. +These checkpoints are obtainable via NGC `NeMo Automatic Speech Recognition collection `__. +The model cards on NGC contain more information about each of the checkpoints available. + +In general, you can load models with model name in the following format, + +.. code-block:: bash + + pip install -U "huggingface_hub[cli]" + huggingface-cli login + +Load Offline Sortformer Diarizer from HuggingFace + +.. code-block:: python + + from nemo.collections.asr.models import SortformerEncLabelModel + diar_model = SortformerEncLabelModel.from_pretrained("nvidia/diar_sortformer_4spk-v1") + + +Load Streaming Sortformer Diarizer from HuggingFace + +.. code-block:: python + + from nemo.collections.asr.models import SortformerEncLabelModel + diar_model = SortformerEncLabelModel.from_pretrained("nvidia/diar_streaming_sortformer_4spk-v2") + +where the model name is the value under "Model Name" entry in the tables below. + +End-to-end Speaker Diarization Models +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. csv-table:: + :file: /asr/speaker_diarization/data/e2e_diar_models.csv + :align: left + :widths: 30, 30, 40 + :header-rows: 1 + + + +Models for Cascaded Speaker Diarization Pipeline +================================================ + +Loading Local Checkpoints +^^^^^^^^^^^^^^^^^^^^^^^^^ + +Load VAD models + +.. code-block:: bash + + pretrained_vad_model='/path/to/vad_multilingual_marblenet.nemo' # local .nemo or pretrained vad model name + ... + # pass with hydra config + config.diarizer.vad.model_path=pretrained_vad_model + + +Load speaker embedding models + +.. code-block:: bash + + pretrained_speaker_model='/path/to/titanet-l.nemo' # local .nemo or pretrained speaker embedding model name + ... + # pass with hydra config + config.diarizer.speaker_embeddings.model_path=pretrained_speaker_model + +NeMo will automatically save checkpoints of a model you are training in a `.nemo` format. +You can also manually save your models at any point using :code:`model.save_to(.nemo)`. + + +Inference +^^^^^^^^^ + +.. note:: + For details and deep understanding, please refer to ``/tutorials/speaker_tasks/Speaker_Diarization_Inference.ipynb``. + +Check out :doc:`Datasets <./datasets>` for preparing audio files and optional label files. + +Run and evaluate speaker diarizer with below command: + +.. code-block:: bash + + # Have a look at the instruction inside the script and pass the arguments you might need. + python /examples/speaker_tasks/diarization/offline_diarization.py + + +NGC Pretrained Checkpoints +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ASR collection has checkpoints of several models trained on various datasets for a variety of tasks. +These checkpoints are obtainable via NGC `NeMo Automatic Speech Recognition collection `__. +The model cards on NGC contain more information about each of the checkpoints available. + +In general, you can load models with model name in the following format, + +.. code-block:: python + + pretrained_vad_model='vad_multilingual_marblenet' + pretrained_speaker_model='titanet_large' + ... + config.diarizer.vad.model_path=pretrained_vad_model \ + config.diarizer.speaker_embeddings.model_path=pretrained_speaker_model + +where the model name is the value under "Model Name" entry in the tables below. + +Models for Speaker Diarization Pipeline +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. csv-table:: + :file: /asr/speaker_diarization/data/diarization_results.csv + :align: left + :widths: 30, 30, 40 + :header-rows: 1 diff --git a/docs/source/asr/speaker_recognition/api.rst b/docs/source/asr/speaker_recognition/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..cdadc4dd5f1d07310d4d5293e7068fdccc10f8a8 --- /dev/null +++ b/docs/source/asr/speaker_recognition/api.rst @@ -0,0 +1,11 @@ +NeMo Speaker Recognition API +============================= + + +Model Classes +------------- +.. autoclass:: nemo.collections.asr.models.label_models.EncDecSpeakerLabelModel + :show-inheritance: + :members: setup_finetune_model, get_embedding, verify_speakers, verify_speakers_batch + + diff --git a/docs/source/asr/speaker_recognition/configs.rst b/docs/source/asr/speaker_recognition/configs.rst new file mode 100644 index 0000000000000000000000000000000000000000..dd8c27b92b009c556b3c0a70e01636bd4a903679 --- /dev/null +++ b/docs/source/asr/speaker_recognition/configs.rst @@ -0,0 +1,116 @@ +NeMo Speaker Recognition Configuration Files +============================================ + +This page covers NeMo configuration file setup that is specific to speaker recognition models. +For general information about how to set up and run experiments that is common to all NeMo models (e.g. +experiment manager and PyTorch Lightning trainer parameters), see the :doc:`../../core/core` page. + +The model section of NeMo speaker recognition configuration files will generally require information about the dataset(s) being +used, the preprocessor for audio files, parameters for any augmentation being performed, as well as the +model architecture specification. +The sections on this page cover each of these in more detail. + +Example configuration files for all of the Speaker related scripts can be found in the +config directory of the examples ``{NEMO_ROOT/examples/speaker_tasks/recognition/conf}``. + + +Dataset Configuration +--------------------- + +Training, validation, and test parameters are specified using the ``train_ds``, ``validation_ds``, and +``test_ds`` sections of your configuration file, respectively. +Depending on the task, you may have arguments specifying the sample rate of your audio files, max time length to consider for each audio file , whether or not to shuffle the dataset, and so on. +You may also decide to leave fields such as the ``manifest_filepath`` blank, to be specified via the command line +at run time. + +Any initialization parameters that are accepted for the Dataset class used in your experiment +can be set in the config file. + +An example TitaNet train and validation configuration could look like (``{NEMO_ROOT}examples/speaker_tasks/recognition/conf/titanet-large.yaml``): + +.. code-block:: yaml + + model: + train_ds: + manifest_filepath: ??? + sample_rate: 16000 + labels: None # finds labels based on manifest file + batch_size: 32 + trim_silence: False + shuffle: True + + validation_ds: + manifest_filepath: ??? + sample_rate: 16000 + labels: None # Keep None, to match with labels extracted during training + batch_size: 32 + shuffle: False # No need to shuffle the validation data + + +If you would like to use tarred dataset, have a look at the ASR :ref:`Tarred Datasets ` section. + + +Preprocessor Configuration +-------------------------- +Preprocessor helps to compute MFCC or mel spectrogram features that are given as inputs to model. +For details on how to write this section, refer to :ref:`Preprocessor Configuration `. + + +Augmentation Configurations +--------------------------- + +For TitaNet training we use on-the-fly augmentations with MUSAN and RIR impulses using ``noise`` augmentor section + +The following example sets up musan augmentation with audio files taken from manifest path and +minimum and maximum SNR specified with min_snr and max_snr respectively. This section can be added to +``train_ds`` part in model + +.. code-block:: yaml + + model: + ... + train_ds: + ... + augmentor: + noise: + manifest_path: /path/to/musan/manifest_file + prob: 0.2 # probability to augment the incoming batch audio with augmentor data + min_snr_db: 5 + max_snr_db: 15 + + +See the :class:`nemo.collections.asr.parts.preprocessing.perturb.AudioAugmentor` API section for more details. + + +Model Architecture Configurations +--------------------------------- + +Each configuration file should describe the model architecture being used for the experiment. +Models in the NeMo ASR collection need a ``encoder`` section and a ``decoder`` section, with the ``_target_`` field +specifying the module to use for each. + +The following sections go into more detail about the specific configurations of each model architecture. + +For more information about the TitaNet Encoder models, see the :doc:`Models <./models>` page. + +Decoder Configurations +------------------------ + +After features have been computed from TitaNet encoder, we pass these features to the decoder to compute embeddings and then to compute log probabilities +for training models. + +.. code-block:: yaml + + model: + ... + decoder: + _target_: nemo.collections.asr.modules.SpeakerDecoder + feat_in: *enc_feat_out + num_classes: 7205 # Total number of classes in voxceleb1,2 training manifest file + pool_mode: attention # xvector, attention + emb_sizes: 192 # number of intermediate emb layers. can be comma separated for additional layers like 512,512 + angular: true # if true then loss will be changed to angular softmax loss and consider scale and margin from loss section else train with cross-entropy loss + + loss: + scale: 30 + margin 0.2 diff --git a/docs/source/asr/speaker_recognition/data/speaker_results.csv b/docs/source/asr/speaker_recognition/data/speaker_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..656123472d9208c7129c47a6910245afb40aef61 --- /dev/null +++ b/docs/source/asr/speaker_recognition/data/speaker_results.csv @@ -0,0 +1,8 @@ +Model Name,Model Base Class,Model Card +diar_sortformer_4spk-v1,SortformerEncLabelModel,"https://huggingface.co/nvidia/diar_sortformer_4spk-v1" +diar_streaming_sortformer_4spk-v2,SortformerEncLabelModel,"https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2" +diar_streaming_sortformer_4spk-v2.1,SortformerEncLabelModel,"https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2.1" +titanet_large,EncDecSpeakerLabelModel,"https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/titanet_large" +titanet_small,EncDecSpeakerLabelModel,"https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/titanet_small" +speakerverification_speakernet,EncDecSpeakerLabelModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:speakerverification_speakernet" +ecapa_tdnn,EncDecSpeakerLabelModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:ecapa_tdnn" \ No newline at end of file diff --git a/docs/source/asr/speaker_recognition/datasets.rst b/docs/source/asr/speaker_recognition/datasets.rst new file mode 100644 index 0000000000000000000000000000000000000000..b2ae2b3cb0e6b5e744b16e1ec21073078da89f02 --- /dev/null +++ b/docs/source/asr/speaker_recognition/datasets.rst @@ -0,0 +1,62 @@ +Datasets +======== + +.. _HI-MIA: + +HI-MIA +-------- + +Run the script to download and process ``hi-mia`` dataset in order to generate files in the supported format of ``nemo_asr``. You should set the data folder of +hi-mia using ``--data_root``. These scripts are present in ``/scripts`` + +.. code-block:: bash + + python get_hi-mia_data.py --data_root= + +After download and conversion, your `data` folder should contain directories with following set of files as: + +* `data//train.json` +* `data//dev.json` +* `data//{set}_all.json` +* `data//utt2spk` + + +All-other Datasets +------------------ + +These methods can be applied to any dataset to get similar training or inference manifest files. + +`filelist_to_manifest.py` script in `$/scripts/speaker_tasks/` folder generates manifest file from a text file containing paths to audio files. + +sample `filelist.txt` file contents: + +.. code-block:: bash + + /data/datasets/voxceleb/data/dev/aac_wav/id00179/Q3G6nMr1ji0/00086.wav + /data/datasets/voxceleb/data/dev/aac_wav/id00806/VjpQLxHQQe4/00302.wav + /data/datasets/voxceleb/data/dev/aac_wav/id01510/k2tzXQXvNPU/00132.wav + +This list file is used to generate manifest file. This script has optional arguments to split the whole manifest file in to train and dev and also segment audio files to smaller segments for robust training (for testing, we don't need to create segments for each utterance). + +sample usage: + +.. code-block:: bash + + python filelist_to_manifest.py --filelist=filelist.txt --id=-3 --out=speaker_manifest.json + +This would create a manifest containing file contents as shown below: +.. code-block:: json + + {"audio_filepath": "/data/datasets/voxceleb/data/dev/aac_wav/id00179/Q3G6nMr1ji0/00086.wav", "offset": 0, "duration": 4.16, "label": "id00179"} + {"audio_filepath": "/data/datasets/voxceleb/data/dev/aac_wav/id00806/VjpQLxHQQe4/00302.wav", "offset": 0, "duration": 12.288, "label": "id00806"} + {"audio_filepath": "/data/datasets/voxceleb/data/dev/aac_wav/id01510/k2tzXQXvNPU/00132.wav", "offset": 0, "duration": 4.608, "label": "id01510"} + +For other optional arguments like splitting manifest file to train and dev and for creating segements from each utterance refer to the arguments +described in the script. + +Tarred Datasets +--------------- + +Similarly to ASR, you can tar your audio files and use ASR Dataset class ``TarredAudioToSpeechLabelDataset`` (corresponding to the ``AudioToSpeechLabelDataset``) for this case. + +If you want to use tarred dataset, have a look at the ASR :ref:`Tarred Datasets ` section. diff --git a/docs/source/asr/speaker_recognition/images/ICASPP_SpeakerNet.png b/docs/source/asr/speaker_recognition/images/ICASPP_SpeakerNet.png new file mode 100644 index 0000000000000000000000000000000000000000..010619ff1a527966f5df72d3587a8a8953165954 --- /dev/null +++ b/docs/source/asr/speaker_recognition/images/ICASPP_SpeakerNet.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f94865a1893bc25c48fdd083338084cc73081d1f84ced1e57cbdde52016ec6e +size 211990 diff --git a/docs/source/asr/speaker_recognition/images/titanet_network.png b/docs/source/asr/speaker_recognition/images/titanet_network.png new file mode 100644 index 0000000000000000000000000000000000000000..e8af34e6f1f7be7722c2443d537501ac0f3d6547 --- /dev/null +++ b/docs/source/asr/speaker_recognition/images/titanet_network.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5717aca80e75a6edec83e7c3777a8933a93dbef08e5fb2610e8b3ea305816be +size 150019 diff --git a/docs/source/asr/speaker_recognition/intro.rst b/docs/source/asr/speaker_recognition/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..9242fdb1a9b2261870b9aa23f8ab36e35b0eca50 --- /dev/null +++ b/docs/source/asr/speaker_recognition/intro.rst @@ -0,0 +1,23 @@ +Speaker Recognition (SR) +======================== + +Speaker recognition is a broad research area which solves two major tasks: speaker identification (what is the identity of the speaker?) and speaker verification (is the speaker who they claim to be?). We focus on text-independent speaker recognition when the identity of the speaker is based on how the speech is spoken, not necessarily in what is being said. Typically such speaker recognition systems operate on unconstrained speech utterances, which are converted into vectors of fixed length, called speaker embeddings. Speaker embeddings can also be used in automatic speech recognition (ASR) and speech synthesis. + +The goal of most speaker recognition systems is to get good speaker level representations that could help distinguish oneself from other speakers. To achieve this, we first train a neural network model in an end-to-end manner optimizing the encoder using cross-entropy or angular softmax loss. We modify the decoder to get these fixed size embeddings irrespective of the length of the audio input and employ a pooling strategy such as mean and variance based statistics pooling or attention based method to generate these embeddings. + +In speaker identification, we typically train on a larger training set with cross-entropy loss and fine-tune later on preferred set of labels where one would want to classify only known sets of speakers. +On the other hand, in speaker verification, we train an embedding extractor with angular softmax loss and compare the embeddings from one audio file coming from a single speaker with embeddings from an unknown speaker. For quantifying the similarity of the embeddings we use scoring techniques such as cosine similarity. + +The full documentation tree: + +.. toctree:: + :maxdepth: 8 + + models + configs + datasets + results + api + resources + +.. include:: resources.rst \ No newline at end of file diff --git a/docs/source/asr/speaker_recognition/models.rst b/docs/source/asr/speaker_recognition/models.rst new file mode 100644 index 0000000000000000000000000000000000000000..d16015a637801740d93e7e60c166e0a6e2b5cdf0 --- /dev/null +++ b/docs/source/asr/speaker_recognition/models.rst @@ -0,0 +1,72 @@ +Models +====== + +Examples of config files for all the below models can be found in the ``/examples/speaker_recognition/conf`` directory. + +For more information about the config files and how they should be structured, see the :doc:`./configs` page. + +Pretrained checkpoints for all of these models, as well as instructions on how to load them, can be found on the :doc:`./results` page. +You can use the available checkpoints for immediate inference, or fine-tune them on your own datasets. +The Checkpoints page also contains benchmark results for the available speaker recognition models. + +.. _TitaNet_model: + +TitaNet +----------- + +TitaNet model :cite:`sr-models-koluguri2021titanet` is based on the ContextNet architecture :cite:`sr-models-han2020contextnet` for extracting speaker representations. +We employ 1D depth-wise separable convolutions with Squeeze-and-Excitation (SE) layers with global context followed by channel attention based statistics pooling layer to map +variable-length utterances to a fixed-length embedding (tvector). TitaNet is a scalable architecture and achieves state-of-the-art performance on speaker verification and diarization tasks. + + .. image:: images/titanet_network.png + :align: center + :alt: speakernet model + :scale: 50% + +SpeakerNet models can be instantiated using the :class:`~nemo.collections.asr.models.EncDecSpeakerLabelModel` class. + +SpeakerNet +----------- + +The model is based on the QuartzNet ASR architecture :cite:`sr-models-koluguri2020speakernet` +comprising of an encoder and decoder structure. We use the encoder of the QuartzNet model as a top-level feature extractor, and feed the output to the statistics pooling layer, where +we compute the mean and variance across channel dimensions to capture the time-independent utterance-level speaker features. + +The QuartzNet encoder used for speaker embeddings shown in figure below has the following structure: a QuartzNet BxR +model has B blocks, each with R sub-blocks. Each sub-block applies the following operations: a 1D convolution, batch norm, ReLU, and dropout. All sub-blocks in a block have the same number of output channels. These blocks are connected with residual connections. We use QuartzNet with 3 blocks, 2 sub-blocks, and 512 channels, as the Encoder for Speaker Embeddings. All conv layers have stride 1 and dilation 1. + + + .. image:: images/ICASPP_SpeakerNet.png + :align: center + :alt: speakernet model + :scale: 40% + +Top level acoustic Features, obtained from the output of +encoder are used to compute intermediate features that are +then passed to the decoder for getting utterance level speaker +embeddings. The intermediate time-independent features are +computed using a statistics pooling layer, where we compute the mean and standard deviation of features across +time-channels, to get a time-independent feature representation S of size Batch_size × 3000. +The intermediate features, S are passed through the Decoder consisting of two layers each of output size 512 for a +linear transformation from S to the final number of classes +N for the larger (L) model, and a single linear layer of output size 256 to the final number of classes N for the medium +(M) model. We extract q-vectors after the final linear layer +of fixed size 512, 256 for SpeakerNet-L and SpeakerNet-M +models respectively. + +SpeakerNet models can be instantiated using the :class:`~nemo.collections.asr.models.EncDecSpeakerLabelModel` class. + +ECAPA_TDNN +---------- + +The model is based on the paper "ECAPA_TDNN Embeddings for Speaker Diarization" :cite:`sr-models-Dawalatabad_2021` comprising an encoder of time dilation layers which are based on Emphasized Channel Attention, Propagation, and Aggregation. The ECAPA-TDNN model employs a channel and context dependent attention mechanism, Multi layer Feature Aggregation (MFA), as well as Squeeze-Excitation (SE) and residual blocks, due to faster training and inference we replacing residual blocks with group convolution blocks of single dilation. These models has shown good performance over various speaker tasks. + +ecapa_tdnn models can be instantiated using the :class:`~nemo.collections.asr.models.EncDecSpeakerLabelModel` class. + +References +----------- + +.. bibliography:: ../asr_all.bib + :style: plain + :labelprefix: SR-MODELS + :keyprefix: sr-models- diff --git a/docs/source/asr/speaker_recognition/resources.rst b/docs/source/asr/speaker_recognition/resources.rst new file mode 100644 index 0000000000000000000000000000000000000000..55e83bb598b7fcdc7e3f0a62958335bfc50e0362 --- /dev/null +++ b/docs/source/asr/speaker_recognition/resources.rst @@ -0,0 +1,22 @@ + +Resource and Documentation Guide +-------------------------------- + +Hands-on speaker recognition tutorial notebooks can be found under +`the speaker recognition tutorials folder `_. This and most other tutorials can be run on Google Colab by specifying the link to the notebooks' GitHub pages on Colab. + +If you are looking for information about a particular SpeakerNet model, or would like to find out more about the model +architectures available in the ``nemo_asr`` collection, check out the :doc:`Models <./models>` page. + +Documentation on dataset preprocessing can be found on the :doc:`Datasets <./datasets>` page. +NeMo includes preprocessing and other scripts for speaker_recognition in folder, and this page contains instructions on running +those scripts. It also includes guidance for creating your own NeMo-compatible dataset, if you have your own data. + +Information about how to load model checkpoints (either local files or pretrained ones from NGC), perform inference, as well as a list +of the checkpoints available on NGC are located on the :doc:`Checkpoints <./results>` page. + +Documentation for configuration files specific to the ``nemo_asr`` models can be found on the +:doc:`Configuration Files <./configs>` page. + + +For a clear step-by-step tutorial we advise you to refer to the tutorials found in `folder `_. diff --git a/docs/source/asr/speaker_recognition/results.rst b/docs/source/asr/speaker_recognition/results.rst new file mode 100644 index 0000000000000000000000000000000000000000..e607a35a49e68f6aa155a0f7c5a4a7ba9591c7ee --- /dev/null +++ b/docs/source/asr/speaker_recognition/results.rst @@ -0,0 +1,144 @@ +Checkpoints +=========== + +There are two main ways to load pretrained checkpoints in NeMo: + +* Using the :code:`restore_from()` method to load a local checkpoint file (`.nemo`), or +* Using the :code:`from_pretrained()` method to download and set up a checkpoint from NGC. + +See the following sections for instructions and examples for each. + +Note that these instructions are for loading fully trained checkpoints for evaluation or fine-tuning. +For resuming an unfinished training experiment, please use the experiment manager to do so by setting the +``resume_if_exists`` flag to True. + +Loading Local Checkpoints +------------------------- + +NeMo will automatically save checkpoints of a model you are training in a `.nemo` format. +You can also manually save your models at any point using :code:`model.save_to(.nemo)`. + +If you have a local ``.nemo`` checkpoint that you'd like to load, simply use the :code:`restore_from()` method: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + model = nemo_asr.models..restore_from(restore_path="") + +Where the model base class is the ASR model class of the original checkpoint, or the general `ASRModel` class. + +Speaker Label Inference +------------------------ + +The goal of speaker label inference is to infer speaker labels using a speaker model with known speaker labels from enrollment set. We provide `speaker_identification_infer.py` script for this purpose under `/examples/speaker_tasks/recognition` folder. +Currently supported backends are cosine_similarity and neural classifier. + +The audio files should be 16KHz mono channel wav files. + +The script takes two manifest files: + +* enrollment_manifest : This manifest contains enrollment data with known speaker labels. +* test_manifest: This manifest contains test data for which we map speaker labels captured from enrollment manifest using one of provided backend + +sample format for each of these manifests is provided in `/examples/speaker_tasks/recognition/conf/speaker_identification_infer.yaml` config file. + +To infer speaker labels using cosine_similarity backend + +.. code-block:: bash + + python speaker_identification_infer.py data.enrollment_manifest= data.test_manifest= backend.backend_model=cosine_similarity + + +Speaker Embedding Extraction +----------------------------- +Speaker Embedding Extraction, is to extract speaker embeddings for any wav file (from known or unknown speakers). We provide two ways to do this: + +* single Python liner for extracting embeddings from a single file +* Python script for extracting embeddings from a bunch of files provided through manifest file + +For extracting embeddings from a single file: + +.. code-block:: python + + speaker_model = EncDecSpeakerLabelModel.from_pretrained(model_name="") + embs = speaker_model.get_embedding('') + +For extracting embeddings from a bunch of files: + +The audio files should be 16KHz mono channel wav files. + +Write audio files to a ``manifest.json`` file with lines as in format: + +.. code-block:: json + + {"audio_filepath": "/audio_file.wav", "duration": "duration of file in sec", "label": "speaker_id"} + +This python call will download best pretrained model from NGC and writes embeddings pickle file to current working directory + +.. code-block:: bash + + python examples/speaker_tasks/recognition/extract_speaker_embeddings.py --manifest=manifest.json + +or you can run `batch_inference()` to perform inference on the manifest with seleted batch_size to get embeddings + +.. code-block:: python + + speaker_model = nemo_asr.models.EncDecSpeakerLabelModel.from_pretrained(model_name="") + embs, logits, gt_labels, trained_labels = speaker_model.batch_inference(manifest, batch_size=32) + +Speaker Verification Inference +------------------------------ + +Speaker Verification is a task of verifying if two utterances are from the same speaker or not. + +We provide a helper function to verify the audio files (also in a batch) and return True if provided pair of audio files is from the same speaker, False otherwise. + +The audio files should be 16KHz mono channel wav files. + +.. code-block:: python + + speaker_model = EncDecSpeakerLabelModel.from_pretrained(model_name="titanet_large") + decision = speaker_model.verify_speakers('path/to/one/audio_file','path/to/other/audio_file') + decisions = speaker_model.verify_speakers_batch([ + ('/path/to/audio_0_0', '/path/to/audio_0_1'), + ('/path/to/audio_1_0', '/path/to/audio_1_1'), + ('/path/to/audio_2_0', '/path/to/audio_2_1'), + ('/path/to/audio_3_0', '/path/to/audio_3_1') + ], batch_size=4, device='cuda') + + +NGC Pretrained Checkpoints +-------------------------- + +The SpeakerNet-ASR collection has checkpoints of several models trained on various datasets for a variety of tasks. +`TitaNet `_ , `ECAPA_TDNN `_ and `Speaker_Verification `_ model cards on NGC contain more information about each of the checkpoints available. + +The tables below list the speaker embedding extractor models available from NGC, and the models can be accessed via the +:code:`from_pretrained()` method inside the EncDecSpeakerLabelModel Model class. + +In general, you can load any of these models with code in the following format: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + model = nemo_asr.models..from_pretrained(model_name="") + +where the model name is the value under "Model Name" entry in the tables below. + +If you would like to programatically list the models available for a particular base class, you can use the +:code:`list_available_models()` method. + +.. code-block:: python + + nemo_asr.models..list_available_models() + + +Speaker Recognition Models +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. csv-table:: + :file: data/speaker_results.csv + :align: left + :widths: 30, 30, 40 + :header-rows: 1 + diff --git a/docs/source/asr/speech_classification/configs.rst b/docs/source/asr/speech_classification/configs.rst new file mode 100644 index 0000000000000000000000000000000000000000..5223ed4202503f73f2448d02b704b50bc0696544 --- /dev/null +++ b/docs/source/asr/speech_classification/configs.rst @@ -0,0 +1,115 @@ +NeMo Speech Classification Configuration Files +================================================ + +This page covers NeMo configuration file setup that is specific to models in the Speech Classification collection. +For general information about how to set up and run experiments that is common to all NeMo models (e.g. +experiment manager and PyTorch Lightning trainer parameters), see the :doc:`../../core/core` page. + +The model section of NeMo Speech Classification configuration files will generally require information about the dataset(s) being +used, the preprocessor for audio files, parameters for any augmentation being performed, as well as the +model architecture specification. +The sections on this page cover each of these in more detail. + +Example configuration files for all of the NeMo ASR scripts can be found in the +``/examples/asr/conf>``. + + +Dataset Configuration +--------------------- + +Training, validation, and test parameters are specified using the ``train_ds``, ``validation_ds``, and +``test_ds`` sections of your configuration file, respectively. +Depending on the task, you may have arguments specifying the sample rate of your audio files, labels, whether or not to shuffle the dataset, and so on. +You may also decide to leave fields such as the ``manifest_filepath`` blank, to be specified via the command line +at runtime. + +Any initialization parameters that are accepted for the Dataset class used in your experiment +can be set in the config file. +See the :ref:`Datasets ` section of the API for a list of Datasets and their respective parameters. + +An example Speech Classification train and validation configuration could look like: + +.. code-block:: yaml + + model: + sample_rate: 16000 + repeat: 2 # number of convolutional sub-blocks within a block, R in _[BxRxC] + dropout: 0.0 + kernel_size_factor: 1.0 + labels: ['bed', 'bird', 'cat', 'dog', 'down', 'eight', 'five', 'four', 'go', 'happy', 'house', 'left', 'marvin', + 'nine', 'no', 'off', 'on', 'one', 'right', 'seven', 'sheila', 'six', 'stop', 'three', 'tree', 'two', 'up', + 'wow', 'yes', 'zero'] + + train_ds: + manifest_filepath: ??? + sample_rate: ${model.sample_rate} + labels: ${model.labels} # Uses the labels above + batch_size: 128 + shuffle: True + + validation_ds: + manifest_filepath: ??? + sample_rate: ${model.sample_rate} + labels: ${model.labels} # Uses the labels above + batch_size: 128 + shuffle: False # No need to shuffle the validation data + +If you would like to use tarred dataset, have a look at :ref:`Datasets Configuration `. + + +Preprocessor Configuration +-------------------------- +Preprocessor helps to compute MFCC or mel spectrogram features that are given as inputs to model. +For details on how to write this section, refer to :ref:`Preprocessor Configuration ` + +Check config yaml files in ``/examples/asr/conf`` to find the processors been used by speech classification models. + + +Augmentation Configurations +--------------------------- + +There are a few on-the-fly spectrogram augmentation options for NeMo ASR, which can be specified by the +configuration file using the ``augmentor`` and ``spec_augment`` section. +For details on how to write this section, refer to the ASR :ref:`Augmentation Configuration ` section. + +Check config yaml files in ``/tutorials/asr/conf`` to find the processors been used by speech classification models. + + +Model Architecture Configurations +--------------------------------- + +Each configuration file should describe the model architecture being used for the experiment. +Models in the NeMo ASR collection need a ``encoder`` section and a ``decoder`` section, with the ``_target_`` field +specifying the module to use for each. + +The following sections go into more detail about the specific configurations of each model architecture. + +The :ref:`MatchboxNet ` and :ref:`MarbleNet ` models are very similar, and as +such the components in their configs are very similar as well. + +Decoder Configurations +------------------------ + +After features have been computed from ConvASREncoder, we pass the features to decoder to compute embeddings and then to compute log_probs +for training models. + +.. code-block:: yaml + + model: + ... + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoderClassification + feat_in: *enc_final_filters + return_logits: true # return logits if true, else return softmax output + pooling_type: 'avg' # AdaptiveAvgPool1d 'avg' or AdaptiveMaxPool1d 'max' + + +Fine-tuning Execution Flow Diagram +---------------------------------- + +When preparing your own training or fine-tuning scripts, please follow the execution flow diagram order for correct inference. + +Depending on the type of model, there may be extra steps that must be performed - + +* Speech Classification models - `Examples directory for Classification Models `_ + diff --git a/docs/source/asr/speech_classification/data/classification_results.csv b/docs/source/asr/speech_classification/data/classification_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..06de98a2c4330135185b980932b2fe06cfab8321 --- /dev/null +++ b/docs/source/asr/speech_classification/data/classification_results.csv @@ -0,0 +1,11 @@ +Model Name,Model Base Class,Model Card +langid_ambernet,EncDecSpeakerLabelModel,"https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/langid_ambernet" +vad_multilingual_marblenet,EncDecClassificationModel,"https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/vad_multilingual_marblenet" +vad_marblenet,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:vad_marblenet" +vad_telephony_marblenet,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:vad_telephony_marblenet" +commandrecognition_en_matchboxnet3x1x64_v1,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x1x64_v1" +commandrecognition_en_matchboxnet3x2x64_v1,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x2x64_v1" +commandrecognition_en_matchboxnet3x1x64_v2,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x1x64_v2" +commandrecognition_en_matchboxnet3x2x64_v2,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x2x64_v2" +commandrecognition_en_matchboxnet3x1x64_v2_subset_task,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x1x64_v2_subset_task" +commandrecognition_en_matchboxnet3x2x64_v2_subset_task,EncDecClassificationModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x2x64_v2_subset_task" \ No newline at end of file diff --git a/docs/source/asr/speech_classification/datasets.rst b/docs/source/asr/speech_classification/datasets.rst new file mode 100644 index 0000000000000000000000000000000000000000..fc16e114086d6cf101d05ecbc5a8620129deb563 --- /dev/null +++ b/docs/source/asr/speech_classification/datasets.rst @@ -0,0 +1,149 @@ +Datasets +======== + +NeMo has scripts to convert several common ASR datasets into the format expected by the `nemo_asr` collection. +You can get started with those datasets by following the instructions to run those scripts in the section appropriate to each dataset below. + +If you have your own data and want to preprocess it to use with NeMo ASR models, check out the `Preparing Custom Speech Classification Data`_ section at the bottom of the page. + +.. _Freesound-dataset: + +Freesound +----------- + +`Freesound `_ is a website that aims to create a huge open collaborative database of audio snippets, samples, recordings, bleeps. +Most audio samples are released under Creative Commons licenses that allow their reuse. +Researchers and developers can access Freesound content using the Freesound API to retrieve meaningful sound information such as metadata, analysis files, and the sounds themselves. + +**Instructions** + +Go to ``/scripts/freesound_download_resample`` and follow the below steps to download and convert freedsound data into a format expected by the `nemo_asr` collection. + +1. We will need some required libraries including freesound, requests, requests_oauthlib, joblib, librosa and sox. If they are not installed, please run `pip install -r freesound_requirements.txt` +2. Create an API key for freesound.org at https://freesound.org/help/developers/ +3. Create a python file called `freesound_private_apikey.py` and add lined `api_key = and client_id = ` +4. Authorize by run `python freesound_download.py --authorize` and visit the website and paste response code +5. Feel free to change any arguments in `download_resample_freesound.sh` such as max_samples and max_filesize +6. Run `bash download_resample_freesound.sh ` . For example: + +.. code-block:: bash + + bash download_resample_freesound.sh 4000 ./freesound ./freesound_resampled_background + +Note that downloading this dataset may take hours. Change categories in download_resample_freesound.sh to include other (speech) categories audio files. +Then, you should have 16khz mono wav files in ``. + + +.. _Google-Speech-Commands-Dataset: + +Google Speech Commands Dataset +------------------------------ + +Google released two versions of the dataset with the first version containing 65k samples over 30 classes and the second containing 110k samples over 35 classes. +We refer to these datasets as `v1` and `v2` respectively. + +Run the script `process_speech_commands_data.py` to process Google Speech Commands dataset in order to generate files in the supported format of `nemo_asr`, +which can be found in ``/scripts/dataset_processing/``. +You should set the data folder of Speech Commands using :code:`--data_root` and the version of the dataset using :code:`--data_version` as an int. + +You can further rebalance the train set by randomly oversampling files inside the manifest by passing the `--rebalance` flag. + +.. code-block:: bash + + python process_speech_commands_data.py --data_root= --data_version=<1 or 2> {--rebalance} + + +Then, you should have `train_manifest.json`, `validation_manifest.json` and `test_manifest.json` +in the directory `{data_root}/google_speech_recognition_v{1/2}`. + +.. note:: + You should have at least 4GB or 6GB of disk space available if you use v1 or v2 respectively. + Also, it will take some time to download and process, so go grab a coffee. + +Each line is a training example. + +.. code-block:: bash + + {"audio_filepath": "/two/8aa35b0c_nohash_0.wav", "duration": 1.0, "label": "two"} + {"audio_filepath": "/two/ec5ab5d5_nohash_2.wav", "duration": 1.0, "label": "two"} + + + +Speech Command & Freesound for VAD +------------------------------------ +Speech Command & Freesound (SCF) dataset is used to train MarbleNet in the `paper `_. Here we show how to download and process it. +This script assumes that you already have the Freesound dataset, if not, have a look at :ref:`Freesound-dataset`. +We will use the open-source :ref:`Google-Speech-Commands-Dataset` (we will use V2 of the dataset for SCF dataset, but require very minor changes to support V1 dataset) as our speech data. + +These scripts below will download the Google Speech Commands v2 dataset and convert speech and background data to a format suitable for use with nemo_asr. + +.. note:: + You may additionally pass :code:`--test_size` or :code:`--val_size` flag for splitting train val and test data. + + You may additionally pass :code:`--window_length_in_sec` flag for indicating the segment/window length. Default is 0.63s. + + You may additionally pass a :code:`-rebalance_method='fixed|over|under'` at the end of the script to rebalance the class samples in the manifest. + + + +* `'fixed'`: Fixed number of sample for each class. Train 5000, val 1000, and test 1000. (Change number in script if you want) +* `'over'`: Oversampling rebalance method +* `'under'`: Undersampling rebalance method + + +.. code-block:: bash + + mkdir './google_dataset_v2' + python process_vad_data.py --out_dir='./manifest/' --speech_data_root='./google_dataset_v2'--background_data_root= --log --rebalance_method='fixed' + + +After download and conversion, your `manifest` folder should contain a few json manifest files: + +* `(balanced_)background_testing_manifest.json` +* `(balanced_)background_training_manifest.json` +* `(balanced_)background_validation_manifest.json` +* `(balanced_)speech_testing_manifest.json` +* `(balanced_)speech_training_manifest.json` +* `(balanced_)speech_validation_manifest.json` + +Each line is a training example. `audio_filepath` contains path to the wav file, `duration` is duration in seconds, `offset` is offset in seconds, and `label` is label (class): + +.. code-block:: bash + + {"audio_filepath": "/two/8aa35b0c_nohash_0.wav", "duration": 0.63, "label": "speech", "offset": 0.0} + {"audio_filepath": "/Emergency_vehicle/id_58368 simambulance.wav", "duration": 0.63, "label": "background", "offset": 4.0} + + +.. _Voxlingua107: + +Voxlingua107 +------------------------------ + +VoxLingua107 consists of short speech segments automatically extracted from YouTube videos. +It contains 107 languages. The total amount of speech in the training set is 6628 hours, and 62 hours per language on average but it's highly imbalanced. +It also includes separate evaluation set containing 1609 speech segments from 33 languages, validated by at least two volunteers. + +You could download dataset from its `website `__. + +Each line is a training example. + +.. code-block:: bash + + {"audio_filepath": "/ln/lFpWXQYseo4__U__S113---0400.650-0410.420.wav", "offset": 0, "duration": 3.0, "label": "ln"} + {"audio_filepath": "/lt/w0lp3mGUN8s__U__S28---0352.170-0364.770.wav", "offset": 8, "duration": 4.0, "label": "lt"} + + +Preparing Custom Speech Classification Data +-------------------------------------------- + +Preparing Custom Speech Classification Data is almost identical to :ref:`Preparing Custom ASR Data `. + +Instead of a :code:`text` entry in the manifest, you need a :code:`label` to determine the class of this sample. + + +Tarred Datasets +--------------- + +Similarly to ASR, you can tar your audio files and use ASR Dataset class ``TarredAudioToClassificationLabelDataset`` (corresponding to the ``AudioToClassificationLabelDataset``) for this case. + +If you would like to use tarred dataset, have a look at :ref:`ASR Tarred Datasets `. \ No newline at end of file diff --git a/docs/source/asr/speech_classification/images/marblenet_vertical.png b/docs/source/asr/speech_classification/images/marblenet_vertical.png new file mode 100644 index 0000000000000000000000000000000000000000..570d10ed67520d8e722df099bd4b845cad1432bc --- /dev/null +++ b/docs/source/asr/speech_classification/images/marblenet_vertical.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55e6327045b182b462e69cb5a9c73768b90d6270ff8542b33190420961e0c264 +size 393467 diff --git a/docs/source/asr/speech_classification/images/matchboxnet_vertical.png b/docs/source/asr/speech_classification/images/matchboxnet_vertical.png new file mode 100644 index 0000000000000000000000000000000000000000..8807875e54f1dc97e3bce34e30efe7d7be164b94 --- /dev/null +++ b/docs/source/asr/speech_classification/images/matchboxnet_vertical.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00583b576649507cac2eb96dad2c4cfd8803c358fc2764a4af283edc7044178a +size 490256 diff --git a/docs/source/asr/speech_classification/intro.rst b/docs/source/asr/speech_classification/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..6a7126b8e73389a3d83decba494c47f626b389e3 --- /dev/null +++ b/docs/source/asr/speech_classification/intro.rst @@ -0,0 +1,31 @@ +Speech Classification +================================== +Speech Classification refers to a set of tasks or problems of getting a program to automatically classify input utterance or audio segment into categories, +such as Speech Command Recognition (multi-class), Voice Activity Detection (binary or multi-class), and Audio Sentiment Classification (typically multi-class), etc. + +**Speech Command Recognition** is the task of classifying an input audio pattern into a discrete set of classes. +It is a subset of Automatic Speech Recognition (ASR), sometimes referred to as Key Word Spotting, in which a model is constantly analyzing speech patterns to detect certain "command" classes. +Upon detection of these commands, a specific action can be taken by the system. +It is often the objective of command recognition models to be small and efficient so that they can be deployed onto low-power sensors and remain active for long durations of time. + + +**Voice Activity Detection (VAD)** also known as speech activity detection or speech detection, is the task of predicting which parts of input audio contain speech versus background noise. +It is an essential first step for a variety of speech-based applications including Automatic Speech Recognition. +It serves to determine which samples to be sent to the model and when to close the microphone. + +**Spoken Language Identification (Lang ID)** also known as spoken language recognition, is the task of recognizing the language of the spoken utterance automatically. +It typically serves as the prepossessing of ASR, determining which ASR model would be activate based on the language. + + +The full documentation tree is as follows: + +.. toctree:: + :maxdepth: 8 + + models + datasets + results + configs + resources.rst + +.. include:: resources.rst diff --git a/docs/source/asr/speech_classification/models.rst b/docs/source/asr/speech_classification/models.rst new file mode 100644 index 0000000000000000000000000000000000000000..0e8c3636253731559d49478210a9830053da91ab --- /dev/null +++ b/docs/source/asr/speech_classification/models.rst @@ -0,0 +1,84 @@ +Models +====== + +This page gives a brief overview of the models that NeMo's Speech Classification collection currently supports. +For Speech Classification, we support Speech Command (Keyword) Detection and Voice Activity Detection (VAD). + +Each of these models can be used with the example ASR scripts (in the ``/examples/asr`` directory) by +specifying the model architecture in the config file used. +Examples of config files for each model can be found in the ``/examples/asr/conf`` directory. + +For more information about the config files and how they should be structured, see the :doc:`./configs` page. + +Pretrained checkpoints for all of these models, as well as instructions on how to load them, can be found on the :doc:`./results` page. +You can use the available checkpoints for immediate inference, or fine-tune them on your own datasets. +The Checkpoints page also contains benchmark results for the available ASR models. + +.. _MatchboxNet_model: + +MatchboxNet (Speech Commands) +------------------------------ + +MatchboxNet :cite:`sc-models-matchboxnet` is an end-to-end neural network for speech command recognition. + +The MatchboxNet family of models are denoted as MatchBoxNet_[BxRxC] where B is the number of blocks, and R is the number of convolutional sub-blocks within a block, and C is the number of channels. Each sub-block contains a 1-D *separable* convolution, batch normalization, ReLU, and dropout: + + .. image:: images/matchboxnet_vertical.png + :align: center + :alt: MatchboxNet model + :scale: 50% + +It can reach state-of-the art accuracy on the Google Speech Commands dataset while having significantly fewer parameters than similar models. +The `_v1` and `_v2` are denoted for models trained on `v1` (30-way classification) and `v2` (35-way classification) datasets; +And we use _subset_task to represent (10+2)-way subset (10 specific classes + other remaining classes + silence) classification task. + +MatchboxNet models can be instantiated using the :class:`~nemo.collections.asr.models.EncDecClassificationModel` class. + +.. note:: + For model details and deep understanding about Speech Command Detedction training, inference, finetuning and etc., + please refer to ``/tutorials/asr/Speech_Commands.ipynb`` and ``/tutorials/asr/Online_Offline_Speech_Commands_Demo.ipynb``. + + + +.. _MarbleNet_model: + +MarbleNet (VAD) +------------------ + +MarbleNet :cite:`sc-models-marblenet` an end-to-end neural network for speech command recognition based on :ref:`MatchboxNet_model`, + +Similarly to MatchboxNet, the MarbleNet family of models are denoted as MarbleNet_[BxRxC] where B is the number of blocks, and R is the number of convolutional sub-blocks within a block, and C is the number of channels. Each sub-block contains a 1-D *separable* convolution, batch normalization, ReLU, and dropout: + + .. image:: images/marblenet_vertical.png + :align: center + :alt: MarbleNet model + :scale: 30% + +It can reach state-of-the art performance on the difficult `AVA speech dataset `_ while having significantly fewer parameters than similar models even training on simple data. +MarbleNet models can be instantiated using the :class:`~nemo.collections.asr.models.EncDecClassificationModel` class. + +.. note:: + For model details and deep understanding about VAD training, inference, postprocessing, threshold tuning and etc., + please refer to ``/tutorials/asr/06_Voice_Activiy_Detection.ipynb`` and ``/tutorials/asr/Online_Offline_Microphone_VAD_Demo.ipynb``. + + + +.. _AmberNet_model: + +AmberNet (Lang ID) +------------------ + +AmberNet is an end-to-end neural network for language identification model based on :ref:`TitaNet `. + +It can reach state-of-the art performance on the `Voxlingua107 dataset `__ while having significantly fewer parameters than similar models. +AmberNet models can be instantiated using the :class:`~nemo.collections.asr.models.EncDecSpeakerLabelModel` class. + + + +References +---------------- + +.. bibliography:: ../asr_all.bib + :style: plain + :labelprefix: SC-MODELS + :keyprefix: sc-models- diff --git a/docs/source/asr/speech_classification/resources.rst b/docs/source/asr/speech_classification/resources.rst new file mode 100644 index 0000000000000000000000000000000000000000..eea302c1b94b009b9a19c5b2e1baae5c6d5d75f7 --- /dev/null +++ b/docs/source/asr/speech_classification/resources.rst @@ -0,0 +1,20 @@ +Resource and Documentation Guide +-------------------------------- + +Hands-on speech classification tutorial notebooks can be found under ``/tutorials/asr/``. +There are training and offline & online microphone inference tutorials for Speech Command Detection and Voice Activity Detection tasks. +This and most other tutorials can be run on Google Colab by specifying the link to the notebooks' GitHub pages on Colab. + +If you are looking for information about a particular Speech Classification model or would like to find out more about the model +architectures available in the `nemo_asr` collection, check out the :doc:`Models <./models>` page. + +Documentation on dataset preprocessing can be found on the :doc:`Datasets <./datasets>` page. +NeMo includes preprocessing scripts for several common ASR datasets, and this page contains instructions on running +those scripts. +It also includes guidance for creating your own NeMo-compatible dataset, if you have your own data. + +Information about how to load model checkpoints (either local files or pretrained ones from NGC), perform inference, as well as a list +of the checkpoints available on NGC are located on the :doc:`Checkpoints <./results>` page. + +Documentation for configuration files specific to the ``nemo_asr`` models can be found on the +:doc:`Configuration Files <./configs>` page. diff --git a/docs/source/asr/speech_classification/results.rst b/docs/source/asr/speech_classification/results.rst new file mode 100644 index 0000000000000000000000000000000000000000..f021820c415164875083521b51f4cca6c65905f5 --- /dev/null +++ b/docs/source/asr/speech_classification/results.rst @@ -0,0 +1,138 @@ +Checkpoints +=========== + +There are two main ways to load pretrained checkpoints in NeMo: + +* Using the :code:`restore_from()` method to load a local checkpoint file (`.nemo`), or +* Using the :code:`from_pretrained()` method to download and set up a checkpoint from NGC. + +See the following sections for instructions and examples for each. + +Note that these instructions are for loading fully trained checkpoints for evaluation or fine-tuning. +For resuming an unfinished training experiment, please use the experiment manager to do so by setting the +``resume_if_exists`` flag to True. + +Loading Local Checkpoints +------------------------- + +NeMo will automatically save checkpoints of a model you are training in a `.nemo` format. +You can also manually save your models at any point using :code:`model.save_to(.nemo)`. + +If you have a local ``.nemo`` checkpoint that you'd like to load, simply use the :code:`restore_from()` method: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + model = nemo_asr.models..restore_from(restore_path="") + +Where the model base class is the ASR model class of the original checkpoint, or the general `ASRModel` class. + + +Transcribing/Inference +----------------------- + +The audio files should be 16KHz monochannel wav files. + +`Transcribe speech command segment:` + +You may perform inference and transcribe a sample of speech after loading the model by using its 'transcribe()' method: + +.. code-block:: python + + mbn_model = nemo_asr.models.EncDecClassificationModel.from_pretrained(model_name="") + mbn_model.transcribe([list of audio files], batch_size=BATCH_SIZE, logprobs=False) + +Setting argument ``logprobs`` to True would return the log probabilities instead of transcriptions. You may find more details in :ref:`Modules `. + +Learn how to fine tune on your own data or on subset classes in ``/tutorials/asr/Speech_Commands.ipynb`` + + +`Run VAD inference:` + +.. code-block:: bash + + python /examples/asr/speech_classification/vad_infer.py --config-path="../conf/vad" --config-name="vad_inference_postprocessing.yaml" dataset= + + +This script will perform vad frame-level prediction and will help you perform postprocessing and generate speech segments as well if needed. + +Have a look at configuration file ``/examples/asr/conf/vad/vad_inference_postprocessing.yaml`` and scripts under ``/scripts/voice_activity_detection`` for details regarding posterior processing, postprocessing and threshold tuning. + +Posterior processing includes generating predictions with overlapping input segments. Then a smoothing filter is applied to decide the label for a frame spanned by multiple segments. + +For VAD postprocessing we introduce + +Binarization: + - ``onset`` and ``offset`` threshold for detecting the beginning and end of a speech. + - padding durations ``pad_onset`` before and padding duarations ``pad_offset`` after each speech segment; + +Filtering: + - ``min_duration_on`` threshold for short speech segment deletion, + - ``min_duration_on`` threshold for small silence deletion, + - ``filter_speech_first`` to control whether to perform short speech segment deletion first. + + +`Identify language of utterance` + +You may load the model and identify the language of an audio file by using `get_label()` method: + +.. code-block:: python + + langid_model = nemo_asr.models.EncDecSpeakerLabelModel.from_pretrained(model_name="") + lang = langid_model.get_label('') + +or you can run `batch_inference()` to perform inference on a manifest with seleted batch_size to get trained model labels and gt_labels with logits + +.. code-block:: python + + langid_model = nemo_asr.models.EncDecSpeakerLabelModel.from_pretrained(model_name="") + lang_embs, logits, gt_labels, trained_labels = langid_model.batch_inference(manifest_filepath, batch_size=32) + + +NGC Pretrained Checkpoints +-------------------------- + +The Speech Classification collection has checkpoints of several models trained on various datasets for a variety of tasks. +These checkpoints are obtainable via NGC `NeMo Automatic Speech Recognition collection `_. +The model cards on NGC contain more information about each of the checkpoints available. + +The tables below list the Speech Classification models available from NGC, and the models can be accessed via the +:code:`from_pretrained()` method inside the ASR Model class. + +In general, you can load any of these models with code in the following format. + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + model = nemo_asr.models.EncDecClassificationModel.from_pretrained(model_name="") + +Where the model name is the value under "Model Name" entry in the tables below. + +For example, to load the MatchboxNet3x2x64_v1 model for speech command detection, run: + +.. code-block:: python + + model = nemo_asr.models.EncDecClassificationModel.from_pretrained(model_name="commandrecognition_en_matchboxnet3x2x64_v1") + +You can also call :code:`from_pretrained()` from the specific model class (such as :code:`EncDecClassificationModel` +for MatchboxNet and MarbleNet) if you will need to access specific model functionality. + +If you would like to programatically list the models available for a particular base class, you can use the +:code:`list_available_models()` method. + +.. code-block:: python + + nemo_asr.models..list_available_models() + + +Speech Classification Models +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. tabularcolumns:: 30 30 40 + +.. csv-table:: + :file: data/classification_results.csv + :header-rows: 1 + :class: longtable + :widths: 1 1 1 + diff --git a/docs/source/asr/ssl/api.rst b/docs/source/asr/ssl/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..16b21bdfb12ebc0f939ac04c2c4abfc18c252d8d --- /dev/null +++ b/docs/source/asr/ssl/api.rst @@ -0,0 +1,30 @@ +NeMo SSL collection API +============================= + + +Model Classes +------------- +.. autoclass:: nemo.collections.asr.models.EncDecDenoiseMaskedTokenPredModel + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.asr.models.SpeechEncDecSelfSupervisedModel + :show-inheritance: + :members: + + +Mixins +------ + +.. autoclass:: nemo.collections.asr.parts.mixins.mixins.ASRModuleMixin + :show-inheritance: + :members: + :noindex: + +.. autoclass:: nemo.core.classes.mixins.access_mixins.AccessMixin + :show-inheritance: + :members: + :noindex: + + + diff --git a/docs/source/asr/ssl/configs.rst b/docs/source/asr/ssl/configs.rst new file mode 100644 index 0000000000000000000000000000000000000000..8dfc169ee938d442a033ee4779b33fa0092cff57 --- /dev/null +++ b/docs/source/asr/ssl/configs.rst @@ -0,0 +1,413 @@ +NeMo SSL Configuration Files +============================ + +This page covers NeMo configuration file setup that is specific to models in the Speech Self-Supervised Pre-training collection. +For general information about how to set up and run experiments that is common to all NeMo models (e.g. +experiment manager and PyTorch Lightning trainer parameters), see the :doc:`../../core/core` page. + +Dataset Configuration +--------------------- + +Dataset configuration for self-supervised model is mostly the same as for standard ASR training, +covered :ref:`here `. The main difference is that in order to perform contrastive loss, +we will need to mask an equivalent amount of patches for all utterances in a batch. This means that we want to avoid +the durations varying too significantly within a single batch. There are several ways you can achieve this in NeMo: + +1) The simplest way is to use the ``min_duration`` parameter in the dataset config, which will simply +discard all utterances below the specified length. This is a viable option if removing these utterances will not +significantly impact the total amount of hours of your dataset. + +2) If your dataset contains many long utterances (longer than ~16 seconds) with varying length, then you may instead +want to use the ``random_segment`` perturbation, which will sample segments of a certain length from the full sample at +runtime (samples below the provided segment length will be padded). You can enable this by adding the following to your +dataset config: + +.. code-block:: yaml + + augmentor: + random_segment: + prob: 1.0 + duration_sec: 16 # specify the duration you want + +3) You can also use bucketing to ensure similar utterance lengths within batches. +See :ref:`Bucketing documentation `. + +An example of SSL train and validation configuration should look similar to the following: + +.. code-block:: yaml + + model: + train_ds: + manifest_filepath: ??? + sample_rate: ${model.sample_rate} + batch_size: 16 # you may increase batch_size if your memory allows + shuffle: true + num_workers: 8 + pin_memory: false + use_start_end_token: true + trim_silence: false + max_duration: 16.7 + min_duration: 8.0 + # tarred datasets + is_tarred: false + tarred_audio_filepaths: null + shuffle_n: 2048 + # bucketing params + bucketing_strategy: "synced_randomized" + bucketing_batch_size: null + + validation_ds: + manifest_filepath: ??? + sample_rate: ${model.sample_rate} + batch_size: 16 # you may increase batch_size if your memory allows + shuffle: false + num_workers: 8 + pin_memory: true + use_start_end_token: false + min_duration: 8.0 + + +Preprocessor Configuration +-------------------------- + +Preprocessor helps to compute MFCC or mel spectrogram features that are given as inputs to model. +For details on how to write this section, refer to :ref:`Preprocessor Configuration ` + +Augmentation Configurations +--------------------------- + +For self-supervised pre-training, we recommend using the ``MaskedPatchAugmentation`` class for spectrogram masking. +This augmentation divides utterances into fixed size patches, and then masks a fixed amount/fraction of them. You can +also add ``freq_masks`` and ``freq_width`` to apply masking to frequency bands. + +If you are using contrastive loss with negatives sampled from masked steps in same utterance only, +make sure that the total amount of masked steps in each utterance will be big enough for the number of sampled negatives. +For example, if you are using 4x stride and want to sample 100 negatives, then you will need more than 400 masked steps. +If you are using the default ``patch_size`` of 48, then this means you will need to set ``mask_patches`` to at least 9. +When using a fraction of the total amount of patches instead of a fixed amount, you will need to make sure that the +minimum duration of your samples in large enough for the number of negatives to sample. + +.. code-block:: yaml + + spec_augment: + _target_: nemo.collections.asr.modules.MaskedPatchAugmentation + patch_size: 48 # size of a single patch + mask_patches: 0.5 # fraction of patches to mask (can be fixed int amount instead) + freq_masks: 3 # Cut three frequency bands + freq_width: 20 # ... of width 20 at maximum + + +Model Architecture Configurations +--------------------------------- + +Each configuration file should describe the model architecture being used for the experiment. For self-supervised pre-training, +we will typically train the encoder of the model and then re-use it for fine-tuning, so the encoder can be configured in the same way +as you would for an ASR model. Note that any ASR model encoder can be used with any of the available pre-training methods, +though, given the same model sizes, we find the best downstream results when using :ref:`Conformer `. + +Unlike the encoders, the decoders and corresponding losses will be specific to the self-supervised pre-training, and are small enough that +you can discard them when transferring the model to fine-tuning. + +The most basic method of pre-training we can use is to have the model solve a contrastive task +(this is the approach used in wav2vec 2.0 :cite:`ssl-models-wav2vec2`) +We can define the corresponding decoder and loss configs in the following way for an encoder with stride 4x. + +.. code-block:: yaml + + decoder_out: 128 + + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoderReconstruction + feat_in: ${model.encoder.d_model} + feat_hidden: 128 + feat_out: ${model.decoder_out} + stride_layers: 0 + # if loss.combine_time_steps is less than the encoder stride, then a corresponding amount of stride_layers needs to + # be added to the decoder (here stride and combine_time_steps are both 4) + non_stride_layers: 0 + + loss: + _target_: nemo.collections.asr.losses.ContrastiveLoss + in_dim: ${model.preprocessor.features} + proj_dim: ${model.decoder_out} + combine_time_steps: 4 # how many spectrogram time steps are used for one target/representation for contrastive task + quantized_targets: true # should quantizer or linear layer be used + codebook_size: 300 # size of a single codebook for quantizer + num_groups: 2 # number of codebooks to use for quantizer + num_negatives: 100 # number of sampled negatives for each target + sample_from_same_utterance_only: true # should negatives be sampled only from the same utterance + sample_from_non_masked: false # should negatives be sampled from non-masked steps + +Note that in the above example we combine 4 steps from the input spectrogram into a single "token" for the loss, +which corresponds to the encoder stride 4x. We might want to use different values for "combine_time_steps" and encoder stride. +In that case, we will need to add stride layers to decoders to match the strides. We can use the following example config +for a FastConformer encoder with stride 8x. In order to go from stride 8x to 4x, we use a single ``stride_layer`` in the decoder +with ``stride_transpose`` set to True. + +.. code-block:: yaml + + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoderReconstruction + feat_in: ${model.model_defaults.enc_final} + feat_hidden: 128 + feat_out: ${model.model_defaults.decoder_out_channels} + stride_layers: 1 + #if loss.combine_time_steps is less than the encoder stride, then a corresponding amount of stride_layers needs to + #be added to the decoder (here stride is 8 and combine_time_steps is 4, so 1 stride layer is added) + non_stride_layers: 0 + stride_tranpose: true # whether to use transposed convolution for stride layers or not + + loss: + _target_: nemo.collections.asr.losses.ContrastiveLoss + in_dim: *n_mels + proj_dim: ${model.model_defaults.decoder_out_channels} + combine_time_steps: 4 #how many spectrogram time steps are used for one target/representation for contrastive task + quantized_targets: false #should quantizer or linear layer be used + sample_from_same_utterance_only: true #should negatives be sampled only from the same utterance + sample_from_non_masked: false #should negatives be sampled from non-masked steps + + +It can be beneficial to combine contrastive loss with other losses, such as a masked language modeling (mlm) loss +(similar approach to W2V-Bert :cite:`ssl-models-w2v_bert`). +In order to do this, instead of specifying a single ``decoder`` and ``loss`` in the config, we can specify a ``loss_list``, +which can contain any amount of corresponding decoders and losses. For each decoder-loss pair, +we can specify a separate named sub-config, which contains the following fields: + +1. ``decoder`` - The decoder config, specifying a ``target`` class and parameters. +2. ``loss`` - The corresponding loss config, specifying a ``target`` class and parameters. +3. ``loss_alpha`` - A multiplier on this loss (1.0 by default). +4. ``targets_from_loss`` - This parameter specifies which contrastive loss we should extract labels from. It is necessary for any loss which requires labels, if labels aren't present in your manifest. +5. ``transpose_encoded`` - This parameter is used to optionally transpose the encoded features before passing them into this loss. +6. ``start_step`` - The training step at which we should start using this decoder+loss. +7. ``output_from_layer`` - This parameter can be used to specify the name of the layer that we should extract encoded features from to pass into this decoder. If it's not specified or set to null, the final encoder layer is used. + + +The following is an example of a `loss_list` for a combination of contrastive+mlm losses, +where the mlm loss uses targets from the quantization module of the contrastive loss. + + +.. code-block:: yaml + + decoder_out: 128 + + loss_list: + contrastive: + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoderReconstruction + feat_in: ${model.encoder.d_model} + feat_hidden: 128 + # features in hidden layer of decoder + feat_out: ${model.decoder_out} + stride_layers: 0 + # if loss.combine_time_steps is less than the encoder stride, then a corresponding amount of stride_layers needs to + # be added to the decoder (here stride and combine_time_steps are both 4) + non_stride_layers: 0 + loss: + _target_: nemo.collections.asr.losses.ContrastiveLoss + in_dim: ${model.preprocessor.features} + proj_dim: ${model.decoder_out} + combine_time_steps: 4 # how many spectrogram time steps are used for one target/representation for contrastive task + quantized_targets: true # should quantizer or linear layer be used + # (quantizer is required to extract pseudo-labels for other losses) + codebook_size: 300 + num_groups: 2 + sample_from_same_utterance_only: true # should negatives be sampled only from the same utterance + sample_from_non_masked: false # should negatives be sampled from non-masked steps + + mlm: + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoder + feat_in: ${model.encoder.d_model} + num_classes: 90000 + # set this to be equal to codebook_size^groups in the contrastive loss + loss: + _target_: nemo.collections.asr.losses.MLMLoss + combine_time_steps: 4 + targets_from_loss: "contrastive" + # since this loss requires targets, we can either get them from a manifest or from a quantized contrastive loss + loss_alpha: 1000. + # multiplier applied to this loss relative to others + transpose_encoded: false + # transposing input may be necessary depending on which layer is used as input to decoder + start_step: 0 + # determines what global step this loss starts being used at; + # this can be set to a higher number if your training is long enough, + # which may increase early training stability + output_from_layer: null + # if we wanted to use outputs from non-final encoder layer as input to this decoder, + # the layer name should be specified here + + +We can also use other losses which require labels instead of mlm, such as ctc or rnnt loss. Since these losses, unlike mlm, +don't require our targets to have a direct alignment with our steps, we may also want to use set the ``reduce_ids`` parameter of the +contrastive loss to true, to convert any sequence of consecutive equivalent ids to a single occurrence of that id. + +An example of a ``loss_list`` consisting of contrastive+ctc loss can look like this: + +.. code-block:: yaml + + decoder_out: 128 + + loss_list: + contr: + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoderReconstruction + feat_in: ${model.encoder.d_model} + feat_hidden: 128 + feat_out: ${model.decoder_out} + stride_layers: 0 + non_stride_layers: 0 + loss: + _target_: nemo.collections.asr.losses.ContrastiveLoss + in_dim: ${model.preprocessor.features} + proj_dim: ${model.decoder_out} + combine_time_steps: 4 + quantized_targets: true + codebook_size: 300 + num_groups: 2 + sample_from_same_utterance_only: true + sample_from_non_masked: false + reduce_ids: true + + ctc: + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoder + feat_in: ${model.encoder.d_model} + num_classes: 90000 + loss: + _target_: nemo.collections.asr.losses.CTCLossForSSL + num_classes: 90000 + targets_from_loss: "contr" + start_step: 3000 + +An example of contrastive+rnnt can look like this: + +.. code-block:: yaml + + decoder_out: 128 + + loss_list: + contr: + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoderReconstruction + feat_in: ${model.encoder.d_model} + feat_hidden: 128 + feat_out: ${model.decoder_out} + stride_layers: 0 + non_stride_layers: 0 + loss: + _target_: nemo.collections.asr.losses.ContrastiveLoss + in_dim: ${model.preprocessor.features} + proj_dim: ${model.decoder_out} + combine_time_steps: 4 + quantized_targets: true + codebook_size: 24 + sample_from_same_utterance_only: true + sample_from_non_masked: false + reduce_ids: true + + rnnt: + decoder: + _target_: nemo.collections.asr.modules.RNNTDecoderJointSSL + decoder: + _target_: nemo.collections.asr.modules.RNNTDecoder + normalization_mode: null # Currently only null is supported for export. + random_state_sampling: false # Random state sampling: https://arxiv.org/pdf/1910.11455.pdf + blank_as_pad: true # This flag must be set in order to support exporting of RNNT models + efficient inference. + vocab_size: 576 + prednet: + pred_hidden: 640 + pred_rnn_layers: 1 + t_max: null + dropout: 0.1 + joint: + _target_: nemo.collections.asr.modules.RNNTJoint + log_softmax: null # 'null' would set it automatically according to CPU/GPU device + preserve_memory: false # dramatically slows down training, but might preserve some memory + experimental_fuse_loss_wer: false + jointnet: + encoder_hidden: 512 + pred_hidden: 640 + joint_hidden: 640 + activation: "relu" + dropout: 0.1 + num_classes: 576 + loss: + _target_: nemo.collections.asr.losses.RNNTLossForSSL + num_classes: 576 + targets_from_loss: "contr" + start_step: 1000 + + +We can also use multiple losses, which use features from different intermediate layers of the encoder as input :cite:`ssl-models-ssl_inter`. +In the following config example, we use contrastive loss + three different mlm losses, which use encoder outputs +respectively from 6th, 12th and final layer. + +.. code-block:: yaml + + decoder_out: 128 + + loss_list: + contr: + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoderReconstruction + feat_in: ${model.encoder.d_model} + feat_hidden: 128 + feat_out: ${model.decoder_out} + stride_layers: 0 + non_stride_layers: 0 + loss: + _target_: nemo.collections.asr.losses.ContrastiveLoss + in_dim: ${model.preprocessor.features} + proj_dim: ${model.decoder_out} + combine_time_steps: 4 + quantized_targets: true + codebook_size: 300 + sample_from_same_utterance_only: true + sample_from_non_masked: false + loss_alpha: 5. + + mlm: + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoder + feat_in: ${model.encoder.d_model} + num_classes: 90000 + loss: + _target_: nemo.collections.asr.losses.MLMLoss + combine_time_steps: 4 + targets_from_loss: "contr" + loss_alpha: 1000. + + mlm_2: + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoder + feat_in: ${model.encoder.d_model} + num_classes: 90000 + loss: + _target_: nemo.collections.asr.losses.MLMLoss + combine_time_steps: 4 + targets_from_loss: "contr" + loss_alpha: 300. + output_from_layer: "layers.5" + transpose_encoded: true + + mlm_3: + decoder: + _target_: nemo.collections.asr.modules.ConvASRDecoder + feat_in: ${model.encoder.d_model} + num_classes: 90000 + loss: + _target_: nemo.collections.asr.losses.MLMLoss + combine_time_steps: 4 + targets_from_loss: "contr" + loss_alpha: 300. + output_from_layer: "layers.11" + transpose_encoded: true + +References +----------- + +.. bibliography:: ../asr_all.bib + :style: plain + :labelprefix: SSL-MODELS + :keyprefix: ssl-models- \ No newline at end of file diff --git a/docs/source/asr/ssl/data/benchmark_ssl.csv b/docs/source/asr/ssl/data/benchmark_ssl.csv new file mode 100644 index 0000000000000000000000000000000000000000..6085a5f3fd4f51d6bbb8dbfc24830f729e09d06b --- /dev/null +++ b/docs/source/asr/ssl/data/benchmark_ssl.csv @@ -0,0 +1,3 @@ +Model Name,Model Base Class,Model Card +ssl_en_conformer_large,SpeechEncDecSelfSupervisedModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:ssl_en_conformer_large" +ssl_en_conformer_xlarge,SpeechEncDecSelfSupervisedModel,"https://ngc.nvidia.com/catalog/models/nvidia:nemo:ssl_en_conformer_xlarge" \ No newline at end of file diff --git a/docs/source/asr/ssl/datasets.rst b/docs/source/asr/ssl/datasets.rst new file mode 100644 index 0000000000000000000000000000000000000000..fc326e6996879cf46a412498aa210167a1726043 --- /dev/null +++ b/docs/source/asr/ssl/datasets.rst @@ -0,0 +1,8 @@ +Datasets +======== + +Any dataset available in NeMo for ASR (:doc:`ASR datasets <../datasets>`) can be used for SSL. +To create your own NeMo compatible datasets, refer to +:ref:`Preparing Custom ASR Data ` +section. Note that explicit labels (transcriptions) are not utilized in SSL and hence are optional +when creating datasets for SSL. \ No newline at end of file diff --git a/docs/source/asr/ssl/intro.rst b/docs/source/asr/ssl/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..89002711be97e406f3290010b092aab40b0f7930 --- /dev/null +++ b/docs/source/asr/ssl/intro.rst @@ -0,0 +1,38 @@ +Speech Self-Supervised Learning +=============================== + +Self-Supervised Learning (SSL) refers to the problem of learning without explicit labels. As +any learning process require feedback, without explit labels, SSL derives supervisory signals from +the data itself. The general ideal of SSL is to predict any hidden part (or property) of the input +from observed part of the input (e.g., filling in the blanks in a sentence or predicting whether +an image is upright or inverted). + +SSL for speech/audio understanding broadly falls into either contrastive or reconstruction +based approaches. In contrastive methods, models learn by distinguishing between true and distractor +tokens (or latents). Examples of contrastive approaches are Contrastive Predictive Coding (CPC), +Masked Language Modeling (MLM) etc. In reconstruction methods, models learn by directly estimating +the missing (intentionally leftout) portions of the input. Masked Reconstruction, Autoregressive +Predictive Coding (APC) are few examples. + +In the recent past, SSL has been a major benefactor in improving Acoustic Modeling (AM), i.e., the +encoder module of neural ASR models. Here too, majority of SSL effort is focused on improving AM. +While it is common that AM is the focus of SSL in ASR, it can also be utilized in improving other parts of +ASR models (e.g., predictor module in transducer based ASR models). + +In NeMo, we provide two types of SSL models, `Wav2Vec-BERT `_ and `NEST `_. +The training script for them can be found in `https://github.com/NVIDIA/NeMo/tree/main/examples/asr/speech_pretraining`. + + +The full documentation tree is as follows: + +.. toctree:: + :maxdepth: 8 + + models + datasets + results + configs + api + resources + +.. include:: resources.rst diff --git a/docs/source/asr/ssl/models.rst b/docs/source/asr/ssl/models.rst new file mode 100644 index 0000000000000000000000000000000000000000..69450b89e3f709c23ad63bf65754ce90b0473615 --- /dev/null +++ b/docs/source/asr/ssl/models.rst @@ -0,0 +1,12 @@ +Models +====== + +End-to-End ASR models are typically of encoder-decoder style, where the encoder does acoustic +modeling i.e., converting speech wavform into features, and the decoder converts those features into +text. Encoder contains the bulk of trainable parameters and is usually the focus of SSL in ASR. +Thus, any architecture that can be used as encoder in ASR models can be pre-trained using SSL. For an +overview of model architectures that are currently supported in NeMo's ASR's collection, refer +to :doc:`ASR Models <../models>`. Note that SSL also uses encoder-decoder style of models. During +down-stream fine-tuning, the encoder is retained where as the decoder (used during SSL) is replaced +with down-stream task specific module. Refer to :doc:`checkpoints <./results>` to see how this is +accomplished in NeMo. diff --git a/docs/source/asr/ssl/resources.rst b/docs/source/asr/ssl/resources.rst new file mode 100644 index 0000000000000000000000000000000000000000..19fd63da84ed2d0d2bdea4029f0d7ead2f061a4e --- /dev/null +++ b/docs/source/asr/ssl/resources.rst @@ -0,0 +1,23 @@ +Resources and Documentation +--------------------------- + +Refer to `SSL-for-ASR notebook `_ +for a hands-on tutorial. If you are a beginner to NeMo, consider trying out the +`ASR with NeMo `_ +tutorial. This and most other tutorials can be run on Google Colab by specifying the link to the +notebooks' GitHub pages on Colab. + +If you are looking for information about a particular ASR model, or would like to find out more +about the model architectures available in the ``nemo_asr`` collection, refer to the +:doc:`ASR Models <../models>` page. + +NeMo includes preprocessing scripts for several common ASR datasets. The :doc:`ASR Datasets <../datasets>` +page contains instructions on running those scripts. It also includes guidance for creating your +own NeMo-compatible dataset, if you have your own data. + +Information about how to load model checkpoints (either local files or pretrained ones from NGC), +as well as a list of the checkpoints available on NGC are located on the :doc:`Checkpoints <./results>` +page. + +Documentation regarding the configuration files specific to the SSL can be found in the +:doc:`Configuration Files <./configs>` page. diff --git a/docs/source/asr/ssl/results.rst b/docs/source/asr/ssl/results.rst new file mode 100644 index 0000000000000000000000000000000000000000..11095b7bd1e3473a2479f82d3243e895586a32c7 --- /dev/null +++ b/docs/source/asr/ssl/results.rst @@ -0,0 +1,106 @@ +Checkpoints +=========== + +Pre-trained SSL checkpoints available in NeMo need to be further fine-tuned on down-stream task. +There are two main ways to load pretrained checkpoints in NeMo: + +* Using the :code:`restore_from()` method to load a local checkpoint file (``.nemo``), or +* Using the :code:`from_pretrained()` method to download and set up a checkpoint from NGC. + +Refer to the following sections for instructions and examples for each. + +Note that these instructions are for fine-tuning. To resume an unfinished training experiment, +use the Experiment Manager to do so by setting the ``resume_if_exists`` flag to ``True``. + +Loading Local Checkpoints +------------------------- + +NeMo automatically saves checkpoints of a model that is trained in a ``.nemo`` format. Alternatively, to manually save the model at any +point, issue :code:`model.save_to(.nemo)`. + +If there is a local ``.nemo`` checkpoint that you'd like to load, use the :code:`restore_from()` method: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + ssl_model = nemo_asr.models..restore_from(restore_path="") + +Where the model base class is the ASR model class of the original checkpoint, or the general ``ASRModel`` class. + +Loading NGC Pretrained Checkpoints +---------------------------------- + +The SSL collection has checkpoints of several models trained on various datasets. These checkpoints are +obtainable via NGC `NeMo Automatic Speech Recognition collection `_. +The model cards on NGC contain more information about each of the checkpoints available. + +The table at the end of this page lists the SSL models available from NGC. The models can be accessed via the :code:`from_pretrained()` method inside +the ASR Model class. In general, you can load any of these models with code in the following format: + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + ssl_model = nemo_asr.models.ASRModel.from_pretrained(model_name="") + +Where the ``model_name`` is the value under "Model Name" entry in the tables below. + +For example, to load the conformer Large SSL checkpoint, run: + +.. code-block:: python + + ssl_model = nemo_asr.models.ASRModel.from_pretrained(model_name="ssl_en_conformer_large") + +You can also call :code:`from_pretrained()` from the specific model class (such as :code:`SpeechEncDecSelfSupervisedModel` +for Conformer) if you need to access a specific model functionality. + +If you would like to programatically list the models available for a particular base class, you can use the +:code:`list_available_models()` method. + +.. code-block:: python + + nemo_asr.models..list_available_models() + + +Loading SSL checkpoint into Down-stream Model +--------------------------------------------- +After loading an SSL checkpoint as shown above, it's ``state_dict`` needs to be copied to a +down-stream model for fine-tuning. + +For example, to load a SSL checkpoint for ASR down-stream task using ``EncDecRNNTBPEModel``, run: + +.. code-block:: python + + # define down-stream model + asr_model = nemo_asr.models.EncDecRNNTBPEModel(cfg=cfg.model, trainer=trainer) + + # load ssl checkpoint + asr_model.load_state_dict(ssl_model.state_dict(), strict=False) + + # discard ssl model + del ssl model + +Refer to :doc:`SSL configs <./configs>` to do this automatically via config files. + + +Fine-tuning on Downstream Datasets +----------------------------------- + +After loading SSL checkpoint into down-stream model, refer to multiple ASR tutorials provided in the :ref:`Tutorials ` section. +Most of these tutorials explain how to fine-tune on some dataset as a demonstration. + +Inference Execution Flow Diagram +-------------------------------- + +When preparing your own inference scripts after downstream fine-tuning, please follow the execution flow diagram order for correct inference, found at the `examples directory for ASR collection `_. + +SSL Models +----------------------------------- + +Below is a list of all the SSL models that are available in NeMo. + + +.. csv-table:: + :file: data/benchmark_ssl.csv + :align: left + :widths: 40, 10, 50 + :header-rows: 1 diff --git a/docs/source/asr/streaming_decoding/canary_chunked_and_streaming_decoding.rst b/docs/source/asr/streaming_decoding/canary_chunked_and_streaming_decoding.rst new file mode 100644 index 0000000000000000000000000000000000000000..f0805203cb6805ada0d07715d86e1c42677d3c01 --- /dev/null +++ b/docs/source/asr/streaming_decoding/canary_chunked_and_streaming_decoding.rst @@ -0,0 +1,110 @@ +.. _canary_streaming: + +Canary Chunked and Streaming Decoding +************************************* + +Canary models support chunked and streaming inference for real-time speech recognition and translation. NeMo provides two approaches: + +.. _canary_chunked_inference: + +Chunked Inference +================= + +This script chunks long audios into non-overlapping segments of ``chunk_len_in_secs`` +seconds and performs inference on each segment individually. The results are then concatenated to form the final output. + +**Key Parameters:** + +* ``chunk_len_in_secs`` - Chunk duration (default: 40.0) +* ``timestamps`` - Enable timestamps (default: False) + +.. code-block:: bash + + python examples/asr/asr_chunked_inference/aed/speech_to_text_aed_chunked_infer.py \ + model_path=null \ + pretrained_name="nvidia/canary-1b-flash" \ + audio_dir="<(optional) path to folder of audio files>" \ + dataset_manifest="<(optional) path to manifest>" \ + output_filename="<(optional) specify output filename>" \ + chunk_len_in_secs=40.0 \ + batch_size=16 \ + decoding.beam.beam_size=1 + +To return word and segment level timestamps, add ``timestamps=True`` to the above command. + +Note: Canary-1b-v2 supports long-form inference via the ``.transcribe()`` method. +It will use dynamic chunking with overlapping windows for better performance. +This behavior is enabled automatically for long-form inference when transcribing a single +audio file or when ``batch_size`` is set to 1. + + +.. _canary_streaming_inference: + +Streaming Inference +=================== + +Real-time decoding with configurable latency using **Wait-k** or **AlignAtt** streaming policies: + +**Wait-K** policy predicts only one token per each new speech chunk that increases the overall latency - `original paper `__. +In this case, it is unclear at what point you can forget part of the left context when recognizing with a limited window. +It is recommended to set the left context to the maximum possible value (infinite left context) for the waitk policy. + +**AlignAtt** policy predicts tokens according to the cross-attention condition - `original paper `__. +If the condition is met, then the audio size does not need to be increased, and the prediction of the next token continues. +Otherwise, the audio buffer size needs to be increased. This policy shows lower latency in comparison with waitk. +This policy is also suitable for window recognition (left context is fixed and not infinite), but you can lose accuracy in this case. + +Usage +----- +Decoding policy is controlled by ``AEDStreamingDecodingConfig``. You can choose ``waitk`` or ``alignatt`` policy. +The remaining parameters (such as ``alignatt_thr`` or ``waitk_lagging``) need to be selected depending on the data and the task (for example, for AST, you can increase ``waitk_lagging``, which works for both policies). + +Remember to manage prompt parameters using ``+prompt`` (for example, ``+prompt.pnc=yes/no``, ``+prompt.task=asr/ast``, ``+prompt.source_lang=en``, ``+prompt.target_lang=de``, and so on). This is especially important for AST task. + + +Key Parameters +-------------- + +* ``chunk_secs`` - Streaming chunk duration (default: 2.0) +* ``left_context_secs`` - Left context for quality (default: 10.0) +* ``right_context_secs`` - Right context, affects latency (default: 2.0) +* ``decoding.streaming_policy`` - "waitk" or "alignatt" +* ``decoding.alignatt_thr`` - Cross-attention threshold for AlignAtt policy (default: 8), alignatt only +* ``decoding.waitk_lagging`` - Number of chunks to wait in the beginning (default: 2), works for both policies +* ``decoding.exclude_sink_frames`` - Number of frames to exclude from the xatt scores calculation (default: 8), alignatt only +* ``decoding.xatt_scores_layer`` - Layer to get cross-attention (xatt) scores from (default: -2), alignatt only +* ``decoding.hallucinations_detector`` - Detect hallucinations in the predicted tokens (default: True), works for both policies +* ``+prompt.pnc`` - set punctuation and capitalization prompt (yes/no) +* ``+prompt.task`` - set task prompt (asr/ast) +* ``+prompt.source_lang`` - set source language prompt +* ``+prompt.target_lang`` - set target language prompt + +.. code-block:: bash + + python3 examples/asr/asr_chunked_inference/aed/speech_to_text_aed_streaming_infer.py \ + pretrained_name=nvidia/canary-1b-v2 \ + dataset_manifest="" \ + output_filename="<(optional) specify output filename>" \ + left_context_secs=10 \ + chunk_secs=1 \ + right_context_secs=0.5 \ + batch_size=32 \ + decoding.streaming_policy=waitk \ # [waitk or alignatt] + decoding.alignatt_thr=8 \ + decoding.waitk_lagging=2 \ + decoding.exclude_sink_frames=8 \ + decoding.xatt_scores_layer=-2 \ + decoding.hallucinations_detector=True \ + +prompt.pnc=yes \ + +prompt.task=asr \ + +prompt.source_lang=en \ + +prompt.target_lang=en + + +The script supports latency calculation based on `Length-Adaptive Average Lagging metric (LAAL) `_ for both streaming policies. + +Brief comparison of the two streaming policies: +------------------------------------------------ + +* **Wait-k**: Higher accuracy, requires larger left context, higher latency +* **AlignAtt**: Lower latency, suitable for production, predicts multiple tokens per chunk diff --git a/docs/source/audio/api.rst b/docs/source/audio/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..9629a75e73c79d539ca4c002016c848bb37cb595 --- /dev/null +++ b/docs/source/audio/api.rst @@ -0,0 +1,322 @@ +NeMo Audio API +============== + +Model Classes +------------- +Base Classes +~~~~~~~~~~~~ +.. autoclass:: nemo.collections.audio.models.AudioToAudioModel + :show-inheritance: + :members: + :exclude-members: setup_training_data, setup_validation_data, training_step, on_validation_epoch_end, validation_step, setup_test_data, on_train_epoch_start + + +Processing Models +~~~~~~~~~~~~~~~~~ +.. autoclass:: nemo.collections.audio.models.EncMaskDecAudioToAudioModel + :show-inheritance: + :members: + :exclude-members: setup_training_data, setup_validation_data, training_step, on_validation_epoch_end, validation_step, setup_test_data, on_train_epoch_start + +.. autoclass:: nemo.collections.audio.models.FlowMatchingAudioToAudioModel + :show-inheritance: + :members: + :exclude-members: setup_training_data, setup_validation_data, training_step, on_validation_epoch_end, validation_step, setup_test_data, on_train_epoch_start + +.. autoclass:: nemo.collections.audio.models.PredictiveAudioToAudioModel + :show-inheritance: + :members: + :exclude-members: setup_training_data, setup_validation_data, training_step, on_validation_epoch_end, validation_step, setup_test_data, on_train_epoch_start + +.. autoclass:: nemo.collections.audio.models.ScoreBasedGenerativeAudioToAudioModel + :show-inheritance: + :members: + :exclude-members: setup_training_data, setup_validation_data, training_step, on_validation_epoch_end, validation_step, setup_test_data, on_train_epoch_start + +.. autoclass:: nemo.collections.audio.models.SchroedingerBridgeAudioToAudioModel + :show-inheritance: + :members: + :exclude-members: setup_training_data, setup_validation_data, training_step, on_validation_epoch_end, validation_step, setup_test_data, on_train_epoch_start + + +Modules +------- + +Features +~~~~~~~~ +.. autoclass:: nemo.collections.audio.modules.features.SpectrogramToMultichannelFeatures + :show-inheritance: + :members: + + +Masking +~~~~~~~ +.. autoclass:: nemo.collections.audio.modules.masking.MaskEstimatorRNN + :show-inheritance: + :members: + +.. _audio-api-masking-multi-channel-mask-estimator: +.. autoclass:: nemo.collections.audio.modules.masking.MaskEstimatorFlexChannels + :show-inheritance: + :members: + +.. _audio-api-masking-guided-source-separation: +.. autoclass:: nemo.collections.audio.modules.masking.MaskEstimatorGSS + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.modules.masking.MaskReferenceChannel + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.modules.masking.MaskBasedBeamformer + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.modules.masking.MaskBasedDereverbWPE + :show-inheritance: + :members: + + +Projections +~~~~~~~~~~~ + +.. autoclass:: nemo.collections.audio.modules.projections.MixtureConsistencyProjection + :show-inheritance: + :members: + + +SSL Pretraining +~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.audio.modules.ssl_pretrain_masking.SSLPretrainWithMaskedPatch + :show-inheritance: + :members: + + +Transforms +~~~~~~~~~~ + +.. _audio-api-audio-to-spectrogram: +.. autoclass:: nemo.collections.audio.modules.transforms.AudioToSpectrogram + :show-inheritance: + :members: + +.. _audio-api-spectrogram-to-audio: +.. autoclass:: nemo.collections.audio.modules.transforms.SpectrogramToAudio + :show-inheritance: + :members: + + +Parts +----- + +Submodules: Diffusion +~~~~~~~~~~~~~~~~~~~~~ +.. autoclass:: nemo.collections.audio.parts.submodules.diffusion.StochasticDifferentialEquation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.diffusion.OrnsteinUhlenbeckVarianceExplodingSDE + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.diffusion.ReverseStochasticDifferentialEquation + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.diffusion.PredictorCorrectorSampler + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.diffusion.Predictor + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.diffusion.ReverseDiffusionPredictor + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.diffusion.Corrector + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.diffusion.AnnealedLangevinDynamics + :show-inheritance: + :members: + + +Submodules: Flow +~~~~~~~~~~~~~~~~ +.. autoclass:: nemo.collections.audio.parts.submodules.flow.ConditionalFlow + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.flow.OptimalTransportFlow + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.flow.ConditionalFlowMatchingSampler + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.flow.ConditionalFlowMatchingEulerSampler + :show-inheritance: + :members: + +Submodules: Multichannel +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.audio.parts.submodules.multichannel.ChannelAugment + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.multichannel.TransformAverageConcatenate + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.multichannel.TransformAttendConcatenate + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.multichannel.ChannelAveragePool + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.multichannel.ChannelAttentionPool + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.multichannel.ParametricMultichannelWienerFilter + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.multichannel.ReferenceChannelEstimatorSNR + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.multichannel.WPEFilter + :show-inheritance: + :members: + + +Submodules: NCSN++ +~~~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.audio.parts.submodules.ncsnpp.SpectrogramNoiseConditionalScoreNetworkPlusPlus + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.ncsnpp.NoiseConditionalScoreNetworkPlusPlus + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.ncsnpp.GaussianFourierProjection + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.ncsnpp.ResnetBlockBigGANPlusPlus + :show-inheritance: + :members: + + +Submodules: Schrödinger Bridge +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.audio.parts.submodules.schroedinger_bridge.SBNoiseSchedule + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.schroedinger_bridge.SBNoiseScheduleVE + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.schroedinger_bridge.SBNoiseScheduleVP + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.schroedinger_bridge.SBSampler + :show-inheritance: + :members: + + +Submodules: TransformerUNet +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.audio.parts.submodules.transformerunet.LearnedSinusoidalPosEmb + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.transformerunet.ConvPositionEmbed + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.transformerunet.RMSNorm + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.transformerunet.AdaptiveRMSNorm + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.transformerunet.GEGLU + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.transformerunet.TransformerUNet + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.parts.submodules.transformerunet.SpectrogramTransformerUNet + :show-inheritance: + :members: + + +Losses +------ + +.. autoclass:: nemo.collections.audio.losses.MAELoss + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.losses.MSELoss + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.losses.SDRLoss + :show-inheritance: + :members: + + +Datasets +-------- + +NeMo Format +~~~~~~~~~~~ + +.. autoclass:: nemo.collections.audio.data.audio_to_audio.BaseAudioDataset + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.data.audio_to_audio.AudioToTargetDataset + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.data.audio_to_audio.AudioToTargetWithReferenceDataset + :show-inheritance: + :members: + +.. autoclass:: nemo.collections.audio.data.audio_to_audio.AudioToTargetWithEmbeddingDataset + :show-inheritance: + :members: + + +Lhotse Format +~~~~~~~~~~~~~ + +.. autoclass:: nemo.collections.audio.data.audio_to_audio_lhotse.LhotseAudioToTargetDataset + :show-inheritance: + :members: + + + diff --git a/docs/source/audio/audio_all.bib b/docs/source/audio/audio_all.bib new file mode 100644 index 0000000000000000000000000000000000000000..c24c8f41a076eee8caeacfd485ffe1bff40c5248 --- /dev/null +++ b/docs/source/audio/audio_all.bib @@ -0,0 +1,64 @@ +@inproceedings{jukic2023flexible, + title={Flexible multichannel speech enhancement for noise-robust frontend}, + author={Jukić, Ante and Balam, Jagadeesh and Ginsburg, Boris}, + booktitle={Proc. WASPAA}, + year={2023} +} + +@inproceedings{ito2016directional, + title={Complex angular central Gaussian mixture model for directional statistics in mask-based microphone array signal processing}, + author={Ito, Nobutaka and Araki, Shoko and Nakatani, Tomohiro}, + booktitle={Proc. EUSIPCO}, + year={2016} +} + +@inproceedings{jukic2024sb, + title={Schrödinger Bridge for Generative Speech Enhancement}, + author={Ante Juki\'{c} and Roman Korostik and Jagadeesh Balam and Boris Ginsburg}, + year={2024}, + pages={1175-1179}, + booktitle={Proc. Interspeech} +} + +@inproceedings{welker2022speech, + author={Simon Welker and Julius Richter and Timo Gerkmann}, + title={Speech Enhancement with Score-Based Generative Models in the Complex {STFT} Domain}, + year={2022}, + pages={2928-2932}, + booktitle={Proc. Interspeech} +} + +@article{richter2023sgmse, + author = {Richter, Julius and Welker, Simon and Lemercier, Jean-Marie and Lay, Bunlong and Gerkmann, Timo}, + title = {{Speech Enhancement and Dereverberation with Diffusion-Based Generative Models}}, + journal = {IEEE/ACM Trans. on Audio, Speech, and Language Process.}, + volume = {31}, + pages = {2351-2364}, + year = {2023} +} + +@article{ku2024generative, + title={Generative Speech Foundation Model Pretraining for High-Quality Speech Extraction and Restoration}, + author={Pin-Jui Ku and Alexander H. Liu and Roman Korostik and Sung-Feng Huang and Szu-Wei Fu and Ante Jukić}, + journal={arXiv preprint arXiv:2409.16117}, + year={2024}, +} + +@souden{souden2010, + author={Souden, Mehrez and Benesty, Jacob and Affes, SofiÈne}, + journal={IEEE Transactions on Audio, Speech, and Language Processing}, + title={On Optimal Frequency-Domain Multichannel Linear Filtering for Noise Reduction}, + year={2010}, + volume={18}, + number={2}, + pages={260-276} +} + +@inproceedings{ +lipman2023flow, +title={Flow Matching for Generative Modeling}, +author={Yaron Lipman and Ricky T. Q. Chen and Heli Ben-Hamu and Maximilian Nickel and Matthew Le}, +booktitle={Proc. ICLR}, +year={2023}, +url={https://openreview.net/forum?id=PqvMRDCJT9t} +} diff --git a/docs/source/audio/checkpoints.rst b/docs/source/audio/checkpoints.rst new file mode 100644 index 0000000000000000000000000000000000000000..321a9efaf50f2380eaec73db078f80c25353aadd --- /dev/null +++ b/docs/source/audio/checkpoints.rst @@ -0,0 +1,59 @@ +Checkpoints +=========== + +There are two main ways to load pretrained checkpoints in NeMo: + +* Using the :code:`restore_from()` method to load a local checkpoint file (``.nemo``), or +* Using the :code:`from_pretrained()` method to download and set up a checkpoint from the cloud. + +Note that these instructions are for loading fully trained checkpoints for evaluation or fine-tuning. For resuming an unfinished +training experiment, use the Experiment Manager to do so by setting the ``resume_if_exists`` flag to ``True``. + +Local Checkpoints +------------------------- + +* **Save Model Checkpoints**: NeMo automatically saves final model checkpoints with ``.nemo`` suffix. You could also manually save any model checkpoint using :code:`model.save_to(.nemo)`. +* **Load Model Checkpoints**: if you'd like to load a checkpoint saved at ````, use the :code:`restore_from()` method below, where ```` is the model class of the original checkpoint. + +.. code-block:: python + + import nemo.collections.audio as nemo_audio + model = nemo_audio.models..restore_from(restore_path="") + +Pretrained Checkpoints +---------------------- + +The table below in :ref:`checkpoints_audio_models` list part of available pre-trained audio processing models including speech processing, restoration and extraction. + +Load Model Checkpoints +^^^^^^^^^^^^^^^^^^^^^^ +The models can be accessed via the :code:`from_pretrained()` method inside the audio model class. In general, you can load any of these models with code in the following format, + +.. code-block:: python + + import nemo.collections.audio as nemo_audio + model = nemo_audio.models..from_pretrained(model_name="") + +where ```` is the value in ``Model Name`` column in the tables in :ref:`checkpoints_audio_models`. These names are predefined in the each model's member function ``self.list_available_models()``. + + +.. _checkpoints_audio_models: + +Audio Models +------------ + +Speech Enhancement Models +^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. csv-table:: + :file: data/checkpoints_se.csv + :align: left + :header-rows: 1 + +SSL Models +^^^^^^^^^^ + +.. csv-table:: + :file: data/checkpoints_ssl.csv + :align: left + :header-rows: 1 diff --git a/docs/source/audio/configs.rst b/docs/source/audio/configs.rst new file mode 100644 index 0000000000000000000000000000000000000000..218e52a8afb90505b0c0eab16c6c82986807d6ce --- /dev/null +++ b/docs/source/audio/configs.rst @@ -0,0 +1,405 @@ +NeMo Audio Configuration Files +============================== +This section describes the NeMo configuration file setup that is specific to models in the audio collection. +For general information about how to set up and run experiments that is common to all NeMo models (e.g. Experiment Manager and PyTorch Lightning trainer parameters), see the :doc:`../core/core` section. + +The model section of the NeMo audio configuration files generally requires information about the dataset(s) being used, parameters for any augmentation being performed, as well as the model architecture specification. + +Example configuration files for all of the NeMo audio models can be found in the +`config directory of the examples `_. + + +.. _audio-configs-nemo-dataset-configuration: + +NeMo Dataset Configuration +-------------------------- + +Training, validation, and test parameters are specified using the ``model.train_ds``, ``model.validation_ds``, and ``model.test_ds`` sections in the configuration file, respectively. +Depending on the task, there may be arguments specifying the sample rate or duration of the loaded audio examples. Some fields can be left out and specified via the command-line at runtime. +Refer to the `Dataset Processing Classes <./api.html#datasets>`__ section of the API for a list of datasets classes and their respective parameters. +An example train, validation and test datasets can be configured as follows: + +.. code-block:: yaml + + model: + sample_rate: 16000 + skip_nan_grad: false + + train_ds: + manifest_filepath: ??? + input_key: audio_filepath # key of the input signal path in the manifest + target_key: target_filepath # key of the target signal path in the manifest + target_channel_selector: 0 # target signal is the first channel from files in target_key + audio_duration: 4.0 # in seconds, audio segment duration for training + random_offset: true # if the file is longer than audio_duration, use random offset to select a subsegment + min_duration: ${model.train_ds.audio_duration} + batch_size: 64 # batch size may be increased based on the available memory + shuffle: true + num_workers: 8 + pin_memory: true + + validation_ds: + manifest_filepath: ??? + input_key: audio_filepath # key of the input signal path in the manifest + target_key: target_filepath # key of the target signal path in the manifest + target_channel_selector: 0 # target signal is the first channel from files in target_key + batch_size: 64 # batch size may be increased based on the available memory + shuffle: false + num_workers: 4 + pin_memory: true + + test_ds: + manifest_filepath: ??? + input_key: audio_filepath # key of the input signal path in the manifest + target_key: target_filepath # key of the target signal path in the manifest + target_channel_selector: 0 # target signal is the first channel from files in target_key + batch_size: 1 # batch size may be increased based on the available memory + shuffle: false + num_workers: 4 + pin_memory: true + +More information about online augmentation can found in the `masking example configuration `_ + + +.. _audio-configs-lhotse-dataset-configuration: + +Lhotse Dataset Configuration +---------------------------- + +Lhotse CutSet +~~~~~~~~~~~~~ + +An example train dataset in Lhotse CutSet format can be configured as follows: + +.. code-block:: yaml + + train_ds: + use_lhotse: true # enable Lhotse data loader + cuts_path: ??? # path to Lhotse cuts manifest with input signals and the corresponding target signals (target signals should be in the custom "target_recording" field) + truncate_duration: 4.00 # truncate audio to 4 seconds + truncate_offset_type: random # if the file is longer than truncate_duration, use random offset to select a subsegment + batch_size: 64 # batch size may be increased based on the available memory + shuffle: true + num_workers: 8 + pin_memory: true + +Lhotse CutSet with Online Augmentation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +An example train dataset in Lhotse CutSet format using online augmentation with room impulse response (RIR) convolution and additive noise can be configured as follows: + +.. code-block:: yaml + + train_ds: + use_lhotse: true # enable Lhotse data loader + cuts_path: ??? # path to Lhotse cuts manifest with speech signals for augmentation (including custom "target_recording" field with the same signals) + truncate_duration: 4.00 # truncate audio to 4 seconds + truncate_offset_type: random # if the file is longer than truncate_duration, use random offset to select a subsegment + batch_size: 64 # batch size may be increased based on the available memory + shuffle: true + num_workers: 8 + pin_memory: true + rir_enabled: true # enable room impulse response augmentation + rir_path: ??? # path to Lhotse recordings manifest with room impulse response signals + noise_path: ??? # path to Lhotse cuts manifest with noise signals + +A configuration file with Lhotse online augmentation can found in the `online augmentation example configuration `_. +More information about the online augmentation can be found in the `tutorial notebook `_. + + +Lhotse Shar +~~~~~~~~~~~ + +An example train dataset in Lhotse shar format can be configured as follows: + +.. code-block:: yaml + + train_ds: + shar_path: ??? + use_lhotse: true + truncate_duration: 4.00 # truncate audio to 4 seconds + truncate_offset_type: random + batch_size: 8 # batch size may be increased based on the available memory + shuffle: true + num_workers: 8 + pin_memory: true + + +A configuration file with Lhotse shar format can found in the `SSL pretraining example configuration `_. + + +Dataset Reweighting with Temperature +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When combining multiple datasets using nested ``input_cfg`` groups, you can control the sampling distribution using the ``reweight_temperature`` parameter. This feature allows you to balance dataset sampling without manually recalculating weights **when adding or removing datasets**. + +The temperature scaling formula is: + +.. math:: + + \hat{w}_i = \frac{w_i^{\tau}}{\sum_{j} w_j^{\tau}} + +where :math:`w_i` is the original weight of dataset :math:`i`, :math:`\tau` is the temperature, and :math:`\hat{w}_i` is the normalized sampling probability. + +**How Temperature Works:** + +- ``temperature = 1.0``: Preserves original weight ratios (neutral, no reweighting) +- ``temperature = 0.0``: Equalizes all datasets (each gets equal probability regardless of original weights) +- ``0 < temperature < 1.0``: Over-samples smaller datasets relative to larger ones +- ``temperature > 1.0``: Amplifies differences between dataset weights + +**Configuration Options:** + +The ``reweight_temperature`` parameter accepts two formats: + +1. **Scalar value** (applied to all nesting levels, warning logged): + +.. code-block:: yaml + + train_ds: + use_lhotse: true + reweight_temperature: 0.5 # Applied to all levels, warning logged + input_cfg: + - type: group + input_cfg: + - type: lhotse_shar + shar_path: /path/to/dataset1 + weight: 900 + - type: lhotse_shar + shar_path: /path/to/dataset2 + weight: 100 + - type: lhotse_shar + shar_path: /path/to/dataset3 + weight: 200 + - type: nemo_tarred + manifest_filepath: /path/to/dataset4/manifest.json + tarred_audio_filepath: /path/to/dataset4/audio.tar + weight: 300 + +2. **List matching maximum nesting depth** (one temperature per level): + +.. code-block:: yaml + + train_ds: + use_lhotse: true + reweight_temperature: [1.0, 0.0] # Level 1: preserve ratios, Level 2: equalize + input_cfg: + - type: group + weight: 0.7 + input_cfg: + - type: lhotse_shar + shar_path: /path/to/dataset1 + weight: 600 + - type: lhotse_shar + shar_path: /path/to/dataset2 + weight: 400 + - type: group + weight: 0.3 + input_cfg: + - type: lhotse_shar + shar_path: /path/to/dataset3 + weight: 100 + +.. note:: + + If ``reweight_temperature`` is provided as a list, its length **must** exactly match the maximum nesting depth of ``input_cfg``. + A mismatch (too few or too many values) raises a ``ValueError``. + Use a scalar value instead if you want the same temperature applied uniformly to all levels. + +**Maximum Nesting Depth Calculation:** + +The maximum nesting depth is calculated as the maximum depth of ``input_cfg`` keys in the configuration. Sibling groups at the same level share the same temperature value. + +.. code-block:: yaml + + # This has maximum nesting depth = 2 + input_cfg: # Level 1 + - type: group + input_cfg: # Level 2 + - type: lhotse_shar + - type: group # Same level as above (sibling) + input_cfg: # Level 2 (same as above) + - type: lhotse_shar + +**Example: Balancing Multiple Task Groups** + +.. code-block:: yaml + + train_ds: + use_lhotse: true + reweight_temperature: [1.0, 0.0] # Level 1: Preserve task ratios, Level 2: Equalize within tasks + input_cfg: + - type: group + weight: 0.7 + tags: + task: asr + input_cfg: + - type: nemo_tarred + manifest_filepath: /path/to/asr1/manifest.json + tarred_audio_filepath: /path/to/asr1/audio.tar + weight: 600 # Large dataset + - type: nemo_tarred + manifest_filepath: /path/to/asr2/manifest.json + tarred_audio_filepath: /path/to/asr2/audio.tar + weight: 100 # Small dataset (will be upsampled with temp=0.0) + - type: group + weight: 0.3 + tags: + task: ast + input_cfg: + - type: nemo_tarred + manifest_filepath: /path/to/ast1/manifest.json + tarred_audio_filepath: /path/to/ast1/audio.tar + weight: 50 + - type: nemo_tarred + manifest_filepath: /path/to/ast2/manifest.json + tarred_audio_filepath: /path/to/ast2/audio.tar + weight: 200 + +In this example: + +- Level 1 temperature is ``1.0``: The 70/30 split between ASR and AST groups is preserved +- Level 2 temperature is ``0.0``: Within each group, all datasets are sampled equally regardless of their original weights + + +Model Architecture Configuration +-------------------------------- +Each configuration file should describe the model architecture being used for the experiment. +An example of a simple predictive model configuration is shown below: + +.. code-block:: yaml + + model: + type: predictive + sample_rate: 16000 + skip_nan_grad: false + num_outputs: 1 + normalize_input: true # normalize the input signal to 0dBFS + + train_ds: + manifest_filepath: ??? + input_key: noisy_filepath + target_key: clean_filepath + audio_duration: 2.00 # trim audio to 2 seconds + random_offset: true + normalization_signal: input_signal + batch_size: 8 # batch size may be increased based on the available memory + shuffle: true + num_workers: 8 + pin_memory: true + + validation_ds: + manifest_filepath: ??? + input_key: noisy_filepath + target_key: clean_filepath + batch_size: 8 + shuffle: false + num_workers: 4 + pin_memory: true + + encoder: + _target_: nemo.collections.audio.modules.transforms.AudioToSpectrogram + fft_length: 510 # Number of subbands in the STFT = fft_length // 2 + 1 = 256 + hop_length: 128 + magnitude_power: 0.5 + scale: 0.33 + + decoder: + _target_: nemo.collections.audio.modules.transforms.SpectrogramToAudio + fft_length: ${model.encoder.fft_length} + hop_length: ${model.encoder.hop_length} + magnitude_power: ${model.encoder.magnitude_power} + scale: ${model.encoder.scale} + + estimator: + _target_: nemo.collections.audio.parts.submodules.ncsnpp.SpectrogramNoiseConditionalScoreNetworkPlusPlus + in_channels: 1 # single-channel noisy input + out_channels: 1 # single-channel estimate + num_res_blocks: 3 # increased number of res blocks + pad_time_to: 64 # pad to 64 frames for the time dimension + pad_dimension_to: 0 # no padding in the frequency dimension + + loss: + _target_: nemo.collections.audio.losses.MSELoss # computed in the time domain + + metrics: + val: + sisdr: # output SI-SDR + _target_: torchmetrics.audio.ScaleInvariantSignalDistortionRatio + + optim: + name: adam + lr: 1e-4 + # optimizer arguments + betas: [0.9, 0.999] + weight_decay: 0.0 + + +Complete configuration file can found in the `example configuration `_. + + +Finetuning Configuration +-------------------------- + +All scripts support easy finetuning by partially/fully loading the pretrained weights from a checkpoint into the currently instantiated model. +Note that the currently instantiated model should have parameters that match the pre-trained checkpoint so the weights may load properly. + +Pre-trained weights can be provided by: + +* Providing a path to a NeMo model (via ``init_from_nemo_model``) +* Providing a name of a pretrained NeMo model (which will be downloaded via the cloud) (via ``init_from_pretrained_model``) + + +Training from scratch +~~~~~~~~~~~~~~~~~~~~~ + +A model can be trained from scratch using the following command: + +.. code-block:: shell + + python examples/audio/audio_to_audio_train.py \ + --config-path= + --config-name=) \ + model.train_ds.manifest_filepath="" \ + model.validation_ds.manifest_filepath="" \ + trainer.devices=1 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 + +Fine-tuning via a NeMo model +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A model can be finetuned from an existing NeMo model using the following command: + +.. code-block:: shell + :emphasize-lines: 9 + + python examples/audio/audio_to_audio_train.py \ + --config-path= + --config-name=) \ + model.train_ds.manifest_filepath="" \ + model.validation_ds.manifest_filepath="" \ + trainer.devices=1 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 \ + +init_from_nemo_model="" + + +Fine-tuning via a NeMo pretrained model name +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A model can be finetuned from an pre-trained NeMo model using the following command: + +.. code-block:: shell + :emphasize-lines: 9 + + python examples/audio/audio_to_audio_train.py \ + --config-path= + --config-name=) \ + model.train_ds.manifest_filepath="" \ + model.validation_ds.manifest_filepath="" \ + trainer.devices=1 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 \ + +init_from_pretrained_model="" + diff --git a/docs/source/audio/data/checkpoints_se.csv b/docs/source/audio/data/checkpoints_se.csv new file mode 100644 index 0000000000000000000000000000000000000000..34b9cae4e1c2546c918168bced725d4b1a96654d --- /dev/null +++ b/docs/source/audio/data/checkpoints_se.csv @@ -0,0 +1,3 @@ +Model Name,Dataset,Sampling Rate,Model Class,Model Card +nvidia/se_den_sb_16k_small,WSJ0+CHiME,16000Hz,nemo.collections.audio.models.SchroedingerBridgeAudioToAudioModel,`se_den_sb_16k_small `_ +nvidia/se_der_sb_16k_small,WSJ0+Reverb,16000Hz,nemo.collections.audio.models.SchroedingerBridgeAudioToAudioModel,`se_der_sb_16k_small `_ diff --git a/docs/source/audio/data/checkpoints_ssl.csv b/docs/source/audio/data/checkpoints_ssl.csv new file mode 100644 index 0000000000000000000000000000000000000000..125ccf1f39bb2059cee6daa1c83d8077e605b515 --- /dev/null +++ b/docs/source/audio/data/checkpoints_ssl.csv @@ -0,0 +1,2 @@ +Model Name,Dataset,Sampling Rate,Model Class,Model Card +nvidia/sr_ssl_flowmatching_16k_430m,Libri-Light,16000Hz,nemo.collections.audio.models.FlowMatchingAudioToAudioModel,`sr_ssl_flowmatching_16k_430m `_ diff --git a/docs/source/audio/datasets.rst b/docs/source/audio/datasets.rst new file mode 100644 index 0000000000000000000000000000000000000000..4c023961a29e98254c71f0269c296e642a0f696f --- /dev/null +++ b/docs/source/audio/datasets.rst @@ -0,0 +1,91 @@ +Datasets +======== + +The `audio` collection expect the training, validation and tests datasets in either NeMo format or Lhotse format. + +NeMo Format +----------- + +Each dataset consists of a set of utterances in individual audio files plus a manifest that describes the dataset, with information about one utterance per line (``.json``). +There should be one manifest file per dataset that will be passed in, therefore, if the user wants separate training and validation datasets, they should also have separate manifests. Otherwise, they will be loading validation data with their training data and vice versa. + + +In most applications, such as speech restoration or enhancement, the model aims to transform the input audio signal into the target audio signal. In this case, each line of the manifest should have the following structure: + +.. code-block:: json + + {"input_filepath": "/path/to/input_audio.wav", "target_filepath": "/path/to/target_audio.wav", "duration": 3.147} + +The :code:`input_filepath` field should provide either an absolute path to the audio file corresponding to the utterance, or a relative path with respect to the directory containing the manifest. +The :code:`target_filepath` field should provide either an absolute path to the audio file corresponding to the utterance, or a relative path with respect to the directory containing the manifest. +Note that keys for input and target audio can be custom, and can be configured in the model configuration file, as described in :ref:`Configs `. + +Each entry in the manifest (describing one audio file) should be bordered by ``"{"`` and ``"}"`` and must be placed on one line. The ``"key": value`` pairs should be separated by a commas as shown above. NeMo enforces no blank lines in the manifest so that the total number of lines indicates the total number of audio files in the dataset. + +Once there is a manifest that describes each audio file in the dataset, assign the ``JSON`` manifest file path in the experiment config file, for example, ``training_ds.manifest_filepath=``. + +For more information about the individual tarred datasets and the parameters available, including shuffling options, see the corresponding class APIs in the `Datasets <./api.html#datasets>`_ section. + + +Lhotse Format +------------- + +NeMo supports using `Lhotse`_, a speech data handling library, as a dataloading option. +Lhotse can be easily enabled using `use_lhotse=True` in the dataset configuration file, as described in :ref:`Lhotse dataset configuration `. + +Lhotse dataloading supports the following types of inputs: + +* Lhotse CutSet manifests + Regular Lhotse CutSet manifests (typically gzipped JSONL). + See `Lhotse Cuts documentation`_ to learn more about Lhotse data formats. +* Lhotse Shar data + Lhotse Shar is a data format that also uses tar files for sequential data loading, + but is designed to be modular (i.e., easily extensible with new data sources and with new feature fields). + More details can be found in the tutorial notebook: |tutorial_shar|. + + +.. _Lhotse: https://github.com/lhotse-speech/lhotse +.. _Lhotse Cuts documentation: https://lhotse.readthedocs.io/en/latest/cuts.html +.. |tutorial_shar| image:: https://colab.research.google.com/assets/colab-badge.svg + :target: https://colab.research.google.com/github/lhotse-speech/lhotse/blob/master/examples/04-lhotse-shar.ipynb + + + +Converting NeMo manifest to Lhotse +---------------------------------- + +A dataset with a manifest in NeMo format can be converted to Lhotse format using the provided `conversion script `_. + +.. code:: shell + + CONVERT_SCRIPT=scripts/audio_to_audio/convert_nemo_to_lhotse.py + INPUT_MANIFEST=/path/to/data/nemo_manifest.json + OUTPUT_MANIFEST=/path/to/data/lhotse_manifest.jsonl + + python ${CONVERT_SCRIPT} ${INPUT_MANIFEST} ${OUTPUT_MANIFEST} -i input_filepath -t target_filepath + + +Creating Lhotse shar dataset +---------------------------- + +First, convert the NeMo manifest to Lhotse format with absolute paths. + +.. code:: shell + + CONVERT_SCRIPT=scripts/audio_to_audio/convert_nemo_to_lhotse.py + INPUT_MANIFEST=/path/to/data/nemo_manifest.json + OUTPUT_MANIFEST=/path/to/data/lhotse_manifest_absolute_paths.jsonl + + # convert + python ${CONVERT_SCRIPT} ${INPUT_MANIFEST} ${OUTPUT_MANIFEST} -i input_filepath -t target_filepath --force_absolute_paths + + +Then, create the Lhotse shar dataset. + +.. code:: shell + + LHOTSE_MANIFEST=/path/to/data/lhotse_manifest_absolute_paths.jsonl + OUTPUT_DIR=/path/to/data/shar + + # create shars, each with 2084 examples, flac audio format + lhotse shar export --num-jobs 16 --verbose --shard-size 2084 --audio flac ${LHOTSE_MANIFEST} ${OUTPUT_DIR} diff --git a/docs/source/audio/intro.rst b/docs/source/audio/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..16876afd31c94d4dff8cf4718b089ba99dbb2912 --- /dev/null +++ b/docs/source/audio/intro.rst @@ -0,0 +1,17 @@ +Speech and Audio Processing +=========================== + +Speech and audio processing refers to a system that processes audio signals, such as speech, music, and environmental sounds. This collection includes models for speech enhancement, restoration and extraction. + +We will illustrate details in the following sections. + +.. toctree:: + :maxdepth: 2 + + models + datasets + checkpoints + configs + api + +.. include:: resources.rst diff --git a/docs/source/audio/models.rst b/docs/source/audio/models.rst new file mode 100644 index 0000000000000000000000000000000000000000..51c4bbf634ed7b51ccc463a4e925dce013b91098 --- /dev/null +++ b/docs/source/audio/models.rst @@ -0,0 +1,46 @@ +Models +======= +This section provides a brief overview of models that NeMo's audio collection currently supports. + +* **Model Recipes** can be accessed through `examples/audio `_. +* **Configuration Files** can be found in the directory of `examples/audio/conf `_. For detailed information about configuration files and how they + should be structured, please refer to the section :doc:`./configs`. +* **Pretrained Model Checkpoints** are available for any users for immediately synthesizing speech or fine-tuning models on + your custom datasets. Please follow the section :doc:`./checkpoints` for instructions on how to use those pretrained models. + + +Encoder-Mask-Decoder Model +~~~~~~~~~~~~~~~~~~~~~~~~~~ +Encoder-Mask-Decoder model is a general model consisting of an encoder, a mask estimator, a mask processor and a decoder. The encoder processes the input audio signal and produces a latent representation. The mask estimator estimates the mask from the latent representation. The mask processor processes the mask and the latent representation to produce a processed latent representation. The decoder processes the processed latent representation to produce the output audio signal. The model can be used for various tasks such as speech enhancement or speech separation. +The encoder and decoder can be learned or fixed, such as the :ref:`short-time Fourier transform (STFT) ` and :ref:`inverse STFT ` modules, respectively. +The mask estimator can be a neural model, such as :ref:`multi-channel mask estimator ` :cite:`audio-models-jukic2023flexible` or a non-neural model, such as :ref:`guided source separation (GSS) ` :cite:`audio-models-ito2016directional`. +The mask processor can be either simple masking, or a parametric multichannel Wiener filter :cite:`audio-models-jukic2023flexible`. + + +Predictive Model +~~~~~~~~~~~~~~~~ +Predictive model is similar to the encoder-mask-decoder model, but the mask estimator and mask processor are replaced by a neural estimator. The predictive model estimates the latent representation of the target output signal from the input audio signal :cite:`audio-models-richter2023sgmse,audio-models-jukic2024sb`. The model can be used for various tasks such as speech enhancement or speech separation. + + +Score-Based Generative Model +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Score-based generative model is a diffusion-based generative model that estimates the score function of the data distribution :cite:`audio-models-welker2022speech,audio-models-richter2023sgmse`. The model consists of an encoder and decoder, a neural score estimator, a stochastic differential equation (SDE) model and a sampler. + + +Schrödinger Bridge Model +~~~~~~~~~~~~~~~~~~~~~~~~ +Schrödinger bridge model is a generative model using a data-to-data process to transform the input (degraded) audio signal into the target (clean) audio signal :cite:`audio-models-jukic2024sb`. The model consists of an encoder and decoder, a neural estimator, noise schedule and a sampler. + + +Flow Matching Model +~~~~~~~~~~~~~~~~~~~ +Flow matching model is a generative model using a noise-to-data process to transform the input (degraded) audio signal into the target (clean) audio signal :cite:`audio-models-ku2024generative`. The model consists of an encoder and decoder, a neural estimator, a flow model and a sampler. + + +References +---------- + +.. bibliography:: audio_all.bib + :style: plain + :labelprefix: AUDIO- + :keyprefix: audio-models- \ No newline at end of file diff --git a/docs/source/audio/resources.rst b/docs/source/audio/resources.rst new file mode 100644 index 0000000000000000000000000000000000000000..404e29f4de82a09556e81a632007f862c70d59d4 --- /dev/null +++ b/docs/source/audio/resources.rst @@ -0,0 +1,10 @@ +Resources and Documentation +=========================== + +Tutorial notebooks can be found under `the audio tutorials folder `_. If you are just starting with NeMo, consider trying out the tutorials of `NeMo Primer `_ and `NeMo Model `_. These tutorials can be run on Google Colab by specifying the link to the notebooks' GitHub pages on Colab. + +If you are looking for information about a particular model, or would like to find out more about the model architectures available in the directory of `nemo.collections.audio `_, refer to the :doc:`Models <./models>` section. + +Information about how to load model checkpoints (either local files or pretrained ones from NGC), as well as a list of the checkpoints available on NGC are located on the :doc:`Checkpoints <./checkpoints>` section. + +Documentation regarding the configuration files specific to the NeMo audio models can be found on the :doc:`Configuration Files <./configs>` section. diff --git a/docs/source/broken_links_false_positives.json b/docs/source/broken_links_false_positives.json new file mode 100644 index 0000000000000000000000000000000000000000..493a65fe2740097ceeda89083a79551bc955f470 --- /dev/null +++ b/docs/source/broken_links_false_positives.json @@ -0,0 +1,77 @@ +{ + "filename": "asr/api.rst", + "lineno": 7, + "status": "broken", + "code": 0, + "uri": "http://www.ee.columbia.edu/~dpwe/resources/matlab/pvoc/", + "info": "403 Client Error: Forbidden for url: https://www.ee.columbia.edu/~dpwe/resources/matlab/pvoc/" +} +{ + "filename": "asr/models.rst", + "lineno": 113, + "status": "broken", + "code": 0, + "uri": "https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/asr/modules/hybrid_autoregressive_transducer.py#L39", + "info": "Anchor 'L39' not found" +} +{ + "filename": "features/optimizations/activation_recomputation.rst", + "lineno": 12, + "status": "broken", + "code": 0, + "uri": "https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/transformer/transformer_config.py#L25", + "info": "Anchor 'L25' not found" +} +{ + "filename": "features/optimizations/communication_overlap.rst", + "lineno": 52, + "status": "broken", + "code": 0, + "uri": "https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/llm/recipes/tp_overlap_configs/userbuffers.py#L64", + "info": "Anchor 'L64' not found" +} +{ + "filename": "features/optimizations/communication_overlap.rst", + "lineno": 52, + "status": "broken", + "code": 0, + "uri": "https://github.com/NVIDIA/NeMo/blob/main/nemo/lightning/pytorch/callbacks/megatron_comm_overlap.py#L61", + "info": "Anchor 'L61' not found" +} +{ + "filename": "features/optimizations/attention_optimizations.rst", + "lineno": 96, + "status": "broken", + "code": 0, + "uri": "https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/transformer/attention.py#L89", + "info": "Anchor 'L89' not found" +} +{ + "filename": "features/parallelisms.rst", + "lineno": 319, + "status": "broken", + "code": 0, + "uri": "https://github.com/NVIDIA/Megatron-LM/blob/e2ec14ab5690fead7e33760b0f8fb20c83b4fd1f/megatron/core/transformer/moe/moe_layer.py#L29", + "info": "Anchor 'L29' not found" +} +{ + "filename": "tools/nemo_forced_aligner.rst", + "lineno": 16, + "status": "broken", + "code": 0, + "uri": "https://github.com/NVIDIA/NeMo/blob/stable/tutorials/nlp/GLUE_Benchmark.ipynb", + "info": "404 Client Error: Not Found for url: https://github.com/NVIDIA/NeMo/blob/stable/tutorials/nlp/GLUE_Benchmark.ipynb" +} +{ + "filename": "tools/nemo_forced_aligner.rst", + "lineno": 16, + "status": "broken", + "code": 0, + "uri": "https://nvidia.github.io/NeMo/blogs/2023/2023-08-forced-alignment/", + "info": "404 Client Error: Not Found for url: https://nvidia.github.io/NeMo/blogs/2023/2023-08-forced-alignment/" +} +{ "filename": "audio/datasets.rst", "lineno": 27, "status": "broken", "code": 0, "uri": "./api.html#datasets", "info": "" } +{ "filename": "audio/configs.rst", "lineno": 17, "status": "broken", "code": 0, "uri": "./api.html#datasets", "info": "" } +{ "filename": "tts/configs.rst", "lineno": 19, "status": "broken", "code": 0, "uri": "./api.html#datasets", "info": "" } +{ "filename": "tts/datasets.rst", "lineno": 1, "status": "broken", "code": 0, "uri": "https://zenodo.org/record/7265581/files/ThorstenVoice-Dataset_2022.10.zip?download=1", "info": "403 Client Error: Forbidden for url: https://zenodo.org/record/7265581/files/ThorstenVoice-Dataset_2022.10.zip?download=1" } +{ "filename": "tts/datasets.rst", "lineno": 1, "status": "broken", "code": 0, "uri": "https://zenodo.org/record/5525342/files/thorsten-neutral_v03.tgz?download=1", "info": "403 Client Error: Forbidden for url: https://zenodo.org/record/5525342/files/thorsten-neutral_v03.tgz?download=1" } diff --git a/docs/source/broken_links_needing_review..json b/docs/source/broken_links_needing_review..json new file mode 100644 index 0000000000000000000000000000000000000000..a7cbd050b36fe764cd418f0bc12087e72d349926 --- /dev/null +++ b/docs/source/broken_links_needing_review..json @@ -0,0 +1,24 @@ +{ + "filename": "checkpoints/dist_ckpt.rst", + "lineno": 428, + "status": "broken", + "code": 0, + "uri": "https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/optimizer/optimizer.py#L793", + "info": "Anchor 'L793' not found" +} +{ + "filename": "tools/nemo_forced_aligner.rst", + "lineno": 22, + "status": "broken", + "code": 0, + "uri": "https://github.com/NVIDIA/NeMo#installation", + "info": "Anchor 'installation' not found" +} +{ + "filename": "checkpoints/intro.rst", + "lineno": 28, + "status": "broken", + "code": 0, + "uri": "https://nvidia.github.io/TensorRT-LLM/architecture/checkpoint.html", + "info": "404 Client Error: Not Found for url: https://nvidia.github.io/TensorRT-LLM/architecture/checkpoint.html" +} diff --git a/docs/source/checkpoints/intro.rst b/docs/source/checkpoints/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..a3804458abedb05c1d96004b4d57e13c644b565a --- /dev/null +++ b/docs/source/checkpoints/intro.rst @@ -0,0 +1,76 @@ +Checkpoints +=========== + +In this section, we present the checkpoint formats supported by NVIDIA NeMo. + +NeMo Checkpoints (.nemo) +------------------------- + +A ``.nemo`` checkpoint is a tar archive that bundles model configurations (YAML), model weights (``.ckpt``), +and other artifacts like tokenizer models or vocabulary files. This consolidated design streamlines +sharing, loading, tuning, evaluating, and inference. + +Because ``.nemo`` files are standard tar archives, you can unpack them, inspect or modify their contents, +and repack them: + +.. code-block:: bash + + # Unpack + mkdir model_contents && tar xf model.nemo -C model_contents/ + + # Inspect / edit files inside + ls model_contents/ + + # Repack + cd model_contents && tar cf ../model_modified.nemo * && cd .. + +This is useful for inspecting model configs, swapping tokenizer files, or modifying configuration +without reloading the model in Python. + +``.nemo`` checkpoints are the primary format for ASR, TTS, and Audio pretrained models. + +PyTorch Lightning Checkpoints (.ckpt) +-------------------------------------- + +During training, PyTorch Lightning saves ``.ckpt`` files that contain model weights, optimizer +states, and training metadata (epoch, step, scheduler state). These are used to resume training +from where it left off. + +SafeTensors (.safetensors) +-------------------------- + +`SafeTensors `_ is a format for storing tensors that is +safe (no arbitrary code execution, unlike pickle-based formats), fast (supports zero-copy and +lazy loading of individual tensors), and widely adopted across the HuggingFace ecosystem. + +SpeechLM2 models use ``.safetensors`` as their primary checkpoint format, following the HuggingFace +model conventions. SpeechLM2 models are saved and loaded via HuggingFace Hub integration +(``save_pretrained`` / ``from_pretrained``), and their weights are stored in ``.safetensors`` files. + +.. note:: + + SpeechLM2 models do not use the ``.nemo`` format for their own checkpoints. The ``.nemo`` format + is only used in the SpeechLM2 collection to load pretrained ASR checkpoints that initialize + the speech encoder component. + +Distributed Checkpoints +----------------------- + +When training with ``ModelParallelStrategy`` (FSDP2 / Tensor Parallelism), PyTorch Lightning +automatically saves **distributed checkpoints**. Instead of gathering all shards onto a single +process, each process saves its own shard to a directory. This is significantly faster and uses +less memory than consolidating into a single file. + +Distributed checkpoints are saved as a directory containing: + +- A ``.metadata`` file describing the tensor layout across shards +- Numbered ``.distcp`` files with per-rank weight shards + +PyTorch Lightning handles loading distributed checkpoints transparently -- you resume training +with the same ``ckpt_path`` argument regardless of whether the checkpoint is a single file or a +sharded directory. + +.. code-block:: python + + # Resuming from a distributed checkpoint works the same as a regular checkpoint + trainer.fit(model, ckpt_path="path/to/distributed_checkpoint_dir") diff --git a/docs/source/collections.rst b/docs/source/collections.rst new file mode 100644 index 0000000000000000000000000000000000000000..31e5b9b64ac19b7ef21f3468b891c46f78b57e10 --- /dev/null +++ b/docs/source/collections.rst @@ -0,0 +1,18 @@ +================ +NeMo Collections +================ + +Documentation for the individual collections + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + asr/intro + asr/speech_classification/intro + asr/speaker_recognition/intro + asr/speaker_diarization/intro + asr/ssl/intro + tts/intro + audio/intro + speechlm2/intro diff --git a/docs/source/common/callbacks.rst b/docs/source/common/callbacks.rst new file mode 100644 index 0000000000000000000000000000000000000000..a627e0dd2ca25032cbedece07a2eaf8e4ed3ecc3 --- /dev/null +++ b/docs/source/common/callbacks.rst @@ -0,0 +1,51 @@ +********* +Callbacks +********* + +Exponential Moving Average (EMA) +================================ + +During training, EMA maintains a moving average of the trained parameters. +EMA parameters can produce significantly better results and faster convergence for a variety of different domains and models. + +EMA is a simple calculation. EMA Weights are pre-initialized with the model weights at the start of training. + +Every training update, the EMA weights are updated based on the new model weights. + +.. math:: + ema_w = ema_w * decay + model_w * (1-decay) + +Enabling EMA is straightforward. We can pass the additional argument to the experiment manager at runtime. + +.. code-block:: bash + + python examples/asr/asr_ctc/speech_to_text_ctc.py \ + model.train_ds.manifest_filepath=/path/to/my/train/manifest.json \ + model.validation_ds.manifest_filepath=/path/to/my/validation/manifest.json \ + trainer.devices=2 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 \ + exp_manager.ema.enable=True # pass this additional argument to enable EMA + +To change the decay rate, pass the additional argument. + +.. code-block:: bash + + python examples/asr/asr_ctc/speech_to_text_ctc.py \ + ... + exp_manager.ema.enable=True \ + exp_manager.ema.decay=0.999 + +We also offer other helpful arguments. + +.. list-table:: + :header-rows: 1 + + * - Argument + - Description + * - `exp_manager.ema.validate_original_weights=True` + - Validate the original weights instead of EMA weights. + * - `exp_manager.ema.every_n_steps=2` + - Apply EMA every N steps instead of every step. + * - `exp_manager.ema.cpu_offload=True` + - Offload EMA weights to CPU. May introduce significant slow-downs. diff --git a/docs/source/common/data.rst b/docs/source/common/data.rst new file mode 100644 index 0000000000000000000000000000000000000000..4c2f38cbba833f01caf0000d0f3d12277349a0f8 --- /dev/null +++ b/docs/source/common/data.rst @@ -0,0 +1,13 @@ +Data +---- + +.. autoclass:: nemo.collections.common.data.dataset.ConcatDataset + :show-inheritance: + :members: + :undoc-members: + + +.. autoclass:: nemo.collections.common.data.dataset.ConcatMapDataset + :show-inheritance: + :members: + :undoc-members: diff --git a/docs/source/common/intro.rst b/docs/source/common/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..813783fc720b5a4fe7edc4be867b980ff5d5c673 --- /dev/null +++ b/docs/source/common/intro.rst @@ -0,0 +1,14 @@ +NeMo Common Collection API +========================== + +The common collection contains things that could be used across all collections. + +.. toctree:: + :maxdepth: 8 + + callbacks + losses + metrics + tokenizers + data + s3_checkpointing diff --git a/docs/source/common/losses.rst b/docs/source/common/losses.rst new file mode 100644 index 0000000000000000000000000000000000000000..006746face297a696099a3b1151c30096debb92d --- /dev/null +++ b/docs/source/common/losses.rst @@ -0,0 +1,16 @@ +Losses +------ +.. autoclass:: nemo.collections.common.losses.AggregatorLoss + :special-members: __init__ + +.. autoclass:: nemo.collections.common.losses.CrossEntropyLoss + :special-members: __init__ + +.. autoclass:: nemo.collections.common.losses.MSELoss + :special-members: __init__ + +.. autoclass:: nemo.collections.common.losses.SmoothedCrossEntropyLoss + :special-members: __init__ + +.. autoclass:: nemo.collections.common.losses.SpanningLoss + :special-members: __init__ diff --git a/docs/source/common/metrics.rst b/docs/source/common/metrics.rst new file mode 100644 index 0000000000000000000000000000000000000000..a47bd9f6f09b7e66751bcad60453586157d61134 --- /dev/null +++ b/docs/source/common/metrics.rst @@ -0,0 +1,7 @@ +Metrics +------- + +.. autoclass:: nemo.collections.common.metrics.Perplexity + :show-inheritance: + :members: + :undoc-members: diff --git a/docs/source/common/s3_checkpointing.rst b/docs/source/common/s3_checkpointing.rst new file mode 100644 index 0000000000000000000000000000000000000000..7a5c0bb09661fd59832da4a2c989931f85552fc5 --- /dev/null +++ b/docs/source/common/s3_checkpointing.rst @@ -0,0 +1,96 @@ +**************** +S3 Checkpointing +**************** + +S3CheckpointIO +============== + +This checkpoint_io is used for saving and loading files to and from S3. +Initializing this checkpoint_io requires the dirpath be an S3 dirpath. + +**Example Usage:** + +.. code-block:: bash + + async_checkpointing = self.cfg.s3_checkpointing.get('enable_async_checkpointing', False) + chunk_size_MB = self.cfg.s3_checkpointing.get('chunk_size_MB') + max_read_concurrency = self.cfg.s3_checkpointing.get('max_read_concurrency') + max_write_concurrency = self.cfg.s3_checkpointing.get('max_write_concurrency') + dirpath = self.cfg.exp_manager.checkpoint_callback_params.get('dirpath') + + s3_checkpoint_io = S3CheckpointIO(dirpath=dirpath, chunk_size_MB=chunk_size_MB, max_read_concurrency=max_read_concurrency, max_write_concurrency=max_write_concurrency, async_checkpointing=async_checkpointing) + + strategy = NLPDDPStrategy( + no_ddp_communication_hook=True, + checkpoint_io=s3_checkpoint_io, + gradient_as_bucket_view=self.cfg.model.gradient_as_bucket_view, + find_unused_parameters=False, + nccl_communicator_config_path=self.cfg.model.get('nccl_communicator_config_path', None), + sharp=self.cfg.model.get('sharp', False), + ) + + +**Config changes:** + +.. code-block:: bash + + checkpoint_callback_params: + dirpath: s3://mstar-eks-dev-us-east-2/alxzhang/nemo123/1n/checkpoints + + ... + + s3_checkpointing: + # write_concurrency * tp * pp * 1.15 (buffer) should be within 3500 S3 TPS limit per partition + max_write_concurrency: 10 + # read_concurrency * tp * pp * 1.15 (buffer) should be within 5500 S3 TPS limit per partition + max_read_concurrency: 15 + chunk_size_MB: 64 + # enables asynchronous checkpoint writing to S3 + enable_async_checkpointing: False + +**Asynchronous** +By default, the S3CheckpointIO class acts synchronously. +The async feature currently does not check if the previous async save is completed, so it is possible +that an old checkpoint is removed even when the current save fails. +To prevent this, this feature is meant to be used in conjunction with saving top k checkpoints. + + +S3Utils and Dependencies +======================== + +This utility class is used by the S3CheckpoinIO and the exp_manager to do S3-related operations. +It has dependencies on + +1. boto3[crt] + +2. s3fs==0.4.2 + +3. tenacity + +If any of these are missing, this class can't be used. + + + +s3_dirpath_utils +================ + +Used to operate on strings by checking if they are S3 dirpaths, or convert a bucket and key into an s3 dirpath. +This has no reliance on the S3Utils utility class, and can be used without any new dependencies. + + +S3 Demands and ExpManager Details When Running at Scale +======================================================= + +Typically, in the ExpManager, every rank looks for the checkpoint file to load from. At large scale, there can be thousands of ranks querying S3 for dirpaths which can cause slowdown or throttling errors. + +To avoid overloading S3 when resuming from a checkpoint only rank 0 needs to identify the checkpoint path and find the correct resumption file. Rank 0 will broadcast the checkpoint path to the other ranks. + +.. code-block:: bash + + trainer._checkpoint_connector = NeMoCheckpointConnector(trainer) + +The NeMoModelCheckpoint setup() method will automatically broadcast the checkpoint path. + +The NeMoCheckpointConnector is defined in the exp_manager.py file, and uses the broadcasted checkpoint path founds by rank 0 on all ranks when resuming training from an existing checkpoint. + +The setting of the trainer._checkpoint_connector needs to happen before the ExpManager call as the ExpManager updates the trainer's checkpoint connector. diff --git a/docs/source/common/tokenizers.rst b/docs/source/common/tokenizers.rst new file mode 100644 index 0000000000000000000000000000000000000000..5c7336e8d603bd31202223fb1f8479f3b4f58186 --- /dev/null +++ b/docs/source/common/tokenizers.rst @@ -0,0 +1,8 @@ +Tokenizers +---------- +.. autoclass:: nemo.collections.common.tokenizers.AutoTokenizer + :special-members: __init__ +.. autoclass:: nemo.collections.common.tokenizers.SentencePieceTokenizer + :special-members: __init__ +.. autoclass:: nemo.collections.common.tokenizers.TokenizerSpec + :special-members: __init__ diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..54d112cfed366fcde24ad90b088912da6ef3c582 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import re +import sys +import glob + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. + +sys.path.insert(0, os.path.abspath("../..")) +# Append (not prepend) the nemo/ subdir so package_info is importable, +# but real third-party packages like `lightning` are found first. +sys.path.append(os.path.abspath("../../nemo")) + +from package_info import __version__ + +templates_path = ["_templates"] + +autodoc_mock_imports = [ + 'torch', + 'torch.nn', + 'torch.utils', + 'torch.optim', + 'torch.utils.data', + 'torch.utils.data.sampler', + 'torchtext', + 'torchvision', + 'ruamel.yaml', # ruamel.yaml has ., which is troublesome for this regex + 'hydra', # hydra-core in requirements, hydra during import + 'dateutil', # part of core python + 'transformers.tokenization_bert', # has ., troublesome for this regex + 'sklearn', # scikit_learn in requirements, sklearn in import + 'nemo_text_processing.inverse_text_normalization', # Not installed automatically + 'nemo_text_processing.text_normalization', # Not installed automatically + 'attr', # attrdict in requirements, attr in import + 'torchmetrics', # inherited from PTL + 'lightning_utilities', # inherited from PTL + 'lightning_fabric', + 'apex', + 'megatron.core', + 'transformer_engine', + 'joblib', # inherited from optional code + 'IPython', + 'ipadic', + 'psutil', + 'pytorch_lightning', + 'regex', + 'PIL', + 'boto3', + 'taming', + 'cytoolz', # for adapters + 'megatron', # for nlp + "open_clip", +] + +_skipped_autodoc_mock_imports = ['wrapt', 'numpy'] + +for req_path in sorted(list(glob.glob("../../requirements/*.txt"))): + if "docs.txt" in req_path: + continue + + req_file = os.path.abspath(os.path.expanduser(req_path)) + with open(req_file, 'r') as f: + for line in f: + line = line.replace("\n", "") + req = re.search(r"([a-zA-Z0-9-_]*)", line) + if req: + req = req.group(1) + req = req.replace("-", "_") + + if req not in autodoc_mock_imports: + if req in _skipped_autodoc_mock_imports: + print(f"Skipping req : `{req}` (lib {line})") + continue + + autodoc_mock_imports.append(req) + print(f"Adding req : `{req}` to autodoc mock requirements (lib {line})") + else: + print(f"`{req}` already added to autodoc mock requirements (lib {line})") + +# Filter out packages that are actually installed and importable. +# autodoc_mock_imports is designed for packages missing from the build env; +# mocking installed packages causes issues (e.g., issubclass() fails on mocks). +import importlib.util + +_final_mock_imports = [] +for _mod in autodoc_mock_imports: + _top_level = _mod.split('.')[0] + if importlib.util.find_spec(_top_level) is not None: + print(f"Skipping mock for installed package: `{_mod}` (found `{_top_level}`)") + else: + _final_mock_imports.append(_mod) +autodoc_mock_imports = _final_mock_imports + +# +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. + +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.todo", + "sphinx.ext.coverage", + "sphinx.ext.mathjax", + "sphinx.ext.ifconfig", + "sphinx.ext.viewcode", + "sphinx.ext.napoleon", + "sphinx.ext.githubpages", + "sphinx.ext.inheritance_diagram", + "sphinx.ext.intersphinx", + # "sphinx.ext.autosectionlabel", + "sphinxcontrib.bibtex", + "sphinx_copybutton", + "sphinxext.opengraph", +] + +bibtex_bibfiles = [ + 'asr/asr_all.bib', + 'tools/tools_all.bib', + 'tts/tts_all.bib', + 'core/adapters/adapter_bib.bib', + 'audio/audio_all.bib', +] + +intersphinx_mapping = { + 'pytorch': ('https://pytorch.org/docs/stable', None), + 'pytorch-lightning': ('https://pytorch-lightning.readthedocs.io/en/latest/', None), +} + +# Set default flags for all classes. +autodoc_default_options = {'members': None, 'undoc-members': None, 'show-inheritance': True} + +locale_dirs = ['locale/'] # path is example but recommended. +gettext_compact = False # optional. + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = ".rst" + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = "NeMo-Speech" +copyright = "2026, NVIDIA Corporation" +author = "NVIDIA CORPORATION" +release = "nightly" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. + + +# The short X.Y version. +# version = "0.10.0" +version = __version__ + + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = [] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "default" + +# Ignore Github links and downloading a large file +# Github links are now getting rate limited from the Github Actions +linkcheck_ignore = [ + "https://zenodo.org/record/5525342/files/thorsten-neutral_v03.tgz?download=1", + ".*github\\.com.*", + ".*githubusercontent\\.com.*", +] +linkcheck_retries = 10 +linkcheck_rate_limit_timeout = 600 + +### Previous NeMo theme +# # NVIDIA theme settings. +# html_theme = 'nvidia_theme' + +# html_theme_path = ["."] + +# html_theme_options = { +# 'display_version': True, +# 'project_version': version, +# 'project_name': project, +# 'logo_path': None, +# 'logo_only': True, +# } +# html_title = 'Introduction' + +# html_logo = html_theme_options["logo_path"] + +# html_sidebars = { +# "**": ["navbar-logo.html", "search-field.html", "sbt-sidebar-nav.html"] +# } + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = "nemodoc" + +### from TLT conf.py +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# + +# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +html_theme = "nvidia_sphinx_theme" +html_theme_options = { + "switcher": {"json_url": "../versions1.json", "version_match": release}, + "public_docs_features": True, + "icon_links": [ + { + "name": "GitHub", + "url": "https://github.com/NVIDIA-NeMo/NeMo", + "icon": "fa-brands fa-github", + } + ], + "extra_head": { + """ + + """ + }, + "extra_footer": { + """ + + """ + }, +} +html_extra_path = ["project.json", "versions1.json"] + +# OpenGraph settings +ogp_site_url = 'https://nvidia.github.io/NeMo/' +ogp_image = 'https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/_static/nv_logo.png' + +# MathJax CDN +# follow recommendation here https://www.sphinx-doc.org/en/master/usage/extensions/math.html#module-sphinx.ext.mathjax +mathjax_path = "https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=TeX-AMS-MML_HTMLorMML" diff --git a/docs/source/core/adapters/adapter_bib.bib b/docs/source/core/adapters/adapter_bib.bib new file mode 100644 index 0000000000000000000000000000000000000000..9a04d876f162657f83cda03a228672efd08a323e --- /dev/null +++ b/docs/source/core/adapters/adapter_bib.bib @@ -0,0 +1,21 @@ + + +@inproceedings{houlsby2019adapter, + title={Parameter-efficient transfer learning for NLP}, + author={Houlsby, Neil and Giurgiu, Andrei and Jastrzebski, Stanislaw and Morrone, Bruna and De Laroussilhe, Quentin and Gesmundo, Andrea and Attariyan, Mona and Gelly, Sylvain}, + booktitle={International Conference on Machine Learning}, + pages={2790--2799}, + year={2019}, + organization={PMLR} +} + +@misc{Junxian2021unified, + doi = {10.48550/ARXIV.2110.04366}, + url = {https://arxiv.org/abs/2110.04366}, + author = {He, Junxian and Zhou, Chunting and Ma, Xuezhe and Berg-Kirkpatrick, Taylor and Neubig, Graham}, + keywords = {Computation and Language (cs.CL), Machine Learning (cs.LG), FOS: Computer and information sciences, FOS: Computer and information sciences}, + title = {Towards a Unified View of Parameter-Efficient Transfer Learning}, + publisher = {arXiv}, + year = {2021}, + copyright = {arXiv.org perpetual, non-exclusive license} +} diff --git a/docs/source/core/adapters/api.rst b/docs/source/core/adapters/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..5625802944be6402bedb553822670469da2c0d5e --- /dev/null +++ b/docs/source/core/adapters/api.rst @@ -0,0 +1,66 @@ +Adapters API +============ + +Core +---- + +.. autoclass:: nemo.core.adapter_mixins.AdapterModuleMixin + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + :noindex: + + +.. autoclass:: nemo.core.adapter_mixins.AdapterModelPTMixin + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + :noindex: + + +Adapter Networks +---------------- + + +.. autoclass:: nemo.collections.common.parts.adapter_modules.AdapterModuleUtil + :show-inheritance: + :members: + :member-order: bysource + :noindex: + + +.. autoclass:: nemo.collections.common.parts.adapter_modules.LinearAdapter + :show-inheritance: + :members: + :member-order: bysource + :noindex: + + +Adapter Strategies +------------------ + + +.. autoclass:: nemo.core.classes.mixins.adapter_mixin_strategies.AbstractAdapterStrategy + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + :noindex: + + +.. autoclass:: nemo.core.classes.mixins.adapter_mixin_strategies.ReturnResultAdapterStrategy + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + :noindex: + + +.. autoclass:: nemo.core.classes.mixins.adapter_mixin_strategies.ResidualAddAdapterStrategy + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + :noindex: diff --git a/docs/source/core/adapters/components.rst b/docs/source/core/adapters/components.rst new file mode 100644 index 0000000000000000000000000000000000000000..d4b38bc147b2907c117c14f4c84bee930d990074 --- /dev/null +++ b/docs/source/core/adapters/components.rst @@ -0,0 +1,94 @@ +Adapter Components +================== + +Adapters can be considered as any set of parameters that are added to a pre-existing module/model. In our case, we currently support the standard adapter in literature, more advanced adapter modules are being researched and can potentially be supported by NeMo. + +An adapter module can be any pytorch module, but it must follow certain straightforward requirements - + +1) The model accepts an input of some input dimension, and its output must match this dimension. +2) Ideally, the module is initialized such that the output of the adapter when initialized is such that it does not modify the original input. This allows the model to produce the same output results, even when additional parameters have been added. + +According to Junxian et al :cite:`adapters-components-Junxian2021unified`, we can consider an adapter being represented as three components - + +1) Functional form - the trainable parameters that will modify the input +2) Insertion form - Where the adapter outputs are integrated with the original input. The input to the adapters can be the last output of the layer, the input to some attention layer, or even the original input to the module itself (before even the modules forward pass). +3) Composition function - How the adapters outputs are integrated with the inputs. It can be as simple as residual addition connection, or concatenation, or point-wise multiplication etc. + +Functional Form - Adapter Networks +================================== + +Adapter modules represent the functional form of the adapter. We discuss an example of a most commonly used adapter module found in literature, titled the ``LinearAdapter`` (or Houlsby Adapter) :cite:`adapters-components-houlsby2019adapter`. + +.. note:: + + All adapter modules must extend :class:`~nemo.collections.common.parts.adapter_modules.AdapterModuleUtil` and should ideally have an equivalent DataClass config for easy instantiation ! + + +.. autoclass:: nemo.collections.common.parts.adapter_modules.AdapterModuleUtil + :show-inheritance: + :members: + :member-order: bysource + :noindex: + +----- + +.. autoclass:: nemo.collections.common.parts.adapter_modules.LinearAdapter + :show-inheritance: + :members: + :member-order: bysource + :noindex: + + +Insertion Form - Module Adapters +-------------------------------- + +Adapter modules can be integrated into many different locations of a given module. For example, it is possible to have an adapter that affects only the outputs of the final layer in each module. We can also have a ``Parallel Adapter`` :cite:`adapters-components-Junxian2021unified` that operates at the input of the module itself, in parallel to the forward pass of the module. Yet another insertion location is inside the Multi Head Attention Layers. + +On top of this, while adapters are commonly used only in the layers containing the most parameters (say the Encoder of a network), some models can support adapters in multiple locations (Encoder-Decoder architecture for Language Models, Machine Translation, or even Encoder-Decoder-Joint for ASR with Transducer Loss). As such, NeMo utilizes the concept of ``Module Adapters``. + +``Module Adapters`` are very simply defined when adding an adapter - by specifying the module that the adapter should be inserted into. + +.. code-block:: python + + # Get the list of supported modules / locations in a adapter compatible Model + print(model.adapter_module_names) # assume ['', 'encoder', 'decoder'] + + # When calling add_adapter, specify the module name in the left of the colon symbol, and the adapter name afterwords. + # The adapter is then directed to the decoder module instead of the default / encoder module. + model.add_adapter("decoder:first_adapter", cfg=...) + +You might note that ``model.adapter_module_names`` can sometimes return ``''`` as one of the supported module names - this refers to the "default module". Generally we try to provide the default as the most commonly used adapter in literature - for example, Encoder adapters in NLP/NMT/ASR. + +Composition Function - Adapter Strategies +----------------------------------------- + +Finally, we discuss how to compose the input and output of adapter modules. In order to generalize this step, we construct ``Adapter Strategies``. +A strategy is any class (not torch.nn.Module!) that extends :class:`~nemo.core.classes.mixins.adapter_mixin_strategies.AbstractAdapterStrategy`, and provides a ``forward()`` method that accepts a specific signature of the inputs and produces an output tensor which combines the input and output with some specific method. + +We discuss a simple residual additional connection strategy below - that accepts an input to the adapter and an adapters output and simply adds them together. It also supports ``stochastic_depth`` which enables adapters to be dynamically switched off during training, making training more robust. + +.. autoclass:: nemo.core.classes.mixins.adapter_mixin_strategies.AbstractAdapterStrategy + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + :noindex: + +----- + +.. autoclass:: nemo.core.classes.mixins.adapter_mixin_strategies.ResidualAddAdapterStrategy + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + :noindex: + +----- + + +References +---------- + +.. bibliography:: ./adapter_bib.bib + :style: plain + :keyprefix: adapters-components- diff --git a/docs/source/core/adapters/intro.rst b/docs/source/core/adapters/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..6fb2bc3176255d8ca3b62f93a7ef43c137c3e764 --- /dev/null +++ b/docs/source/core/adapters/intro.rst @@ -0,0 +1,149 @@ +Adapters +======== + +In NeMo, we often train models and fine-tune them for a specific task. This is a reasonable approach when the models are just a few million parameters. However, this approach quickly becomes infeasible when approaching hundreds of millions or even billions of parameters. As a potential solution to such a scenario, where fine-tuning a massive model is no longer feasible, we look to `Adapters `_ :cite:`adapters-houlsby2019adapter` to specialize our model on a specific domain or task. Adapters require a fraction of the total number of parameters as the original model and are much more efficient to fine-tune. + +.. note:: + + For a detailed tutorial on adding ``Adapter`` support to any PyTorch module, please refer to the NeMo Adapter :doc:`Tutorials <../../starthere/tutorials>`. + + +What are Adapters? +------------------ + +Adapters are a straightforward concept - one formulation can be shown by the diagram below. At their simplest, they are residual Feedforward layers that compress the input dimension (:math:`D`) to a small bottleneck dimension (:math:`H`), such that :math:`R^D \text{->} R^H`, compute an activation (such as ReLU), finally mapping :math:`R^H \text{->} R^D` with another Feedforward layer. This output is then added to the input via a simple residual connection. + +.. raw:: html + +
+ +
+ +Adapter modules such as this are usually initialized such that the initial output of the adapter will always be zeros so as to prevent degradation of the original model's performance due to addition of such modules. + +``torch.nn.Module`` with Adapters +--------------------------------- + +In NeMo, Adapters are supported via a ``Mixin`` class that can be attached to any ``torch.nn.Module``. Such a module will +have multiple additional methods which will enable adapter capabilities in that module. + +.. code-block:: python + + # Import the adapter mixin from NeMo + from nemo.core import adapter_mixins + + # NOTE: See the *two* classes being inherited here ! + class MyModule(torch.nn.Module, adapter_mixins.AdapterModuleMixin): + pass + + +AdapterModuleMixin +------------------ +Let's look into what :class:`~nemo.core.adapter_mixins.AdapterModuleMixin` adds to the general PyTorch module. Some of the most important methods that are required are listed below : + +1) ``add_adapter``: Used to add an adapter with a unique name to the module. +2) ``get_enabled_adapters``: Returns a list of names of all enabled adapter modules. +3) ``set_enabled_adapters``: Sets whether a single (or all) adapters are enabled or disabled. +4) ``is_adapter_available``: Check if any adapter is available and enabled or not. + +Modules that extend this mixin usually can directly use these methods without extending them, but we will cover a case below +where you may wish to extend these methods. + +.. autoclass:: nemo.core.adapter_mixins.AdapterModuleMixin + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + + +Using the Adapter Module +------------------------ + +Now that ``MyModule`` supports adapters, we can easily add adapters, set their state, check if they are available and +perform their forward pass. Note that if multiple adapters are enabled, they are called in a chain, the output of the previous adapter is passed as input to the next adapter and so on. + +.. code-block:: python + + # Import the adapter mixin and modules from NeMo + import torch + from nemo.core import adapter_mixins + from nemo.collections.common.parts import adapter_modules + + class MyModule(torch.nn.Module, adapter_mixins.AdapterModuleMixin): + + def forward(self, x: torch.Tensor) -> torch.Tensor: + output = self.layers(x) # assume self.layers is some Sequential() module + + if self.is_adapter_available(): # check if adapters were added or not + output = self.forward_enabled_adapters() # perform the forward of all enabled adapters in a chain + + return output + + # Now let us create a module, add an adapter and do a forward pass with some random inputs + module = MyModule(dim) # assume dim is some input and output dimension of the module. + + # Add an adapter + module.add_adapter("first_adapter", cfg=adapter_modules.LinearAdapter(in_features=dim, dim=5)) + + # Check if adapter is available + module.is_adapter_available() # returns True + + # Check the name(s) of the enabled adapters + module.get_enabled_adapters() # returns ['first_adapter'] + + # Set the state of the adapter (by name) + module.set_enabled_adapters(name="first_adapter", enabled=True) + + # Freeze all the weights of the original module (equivalent to calling module.freeze() for a NeuralModule) + for param in module.parameters(): + param.requires_grad = False + + # Unfreeze only the adapter weights (so that we finetune only the adapters and not the original weights !) + module.unfreeze_enabled_adapters() + + # Now you can train this model's adapters ! + input_data = torch.randn(4, dim) # assume dim is the input-output dim of the module + outputs_with_adapter = module(input_data) + + # Compute loss and backward ... + + +Adapter Compatible Models +------------------------- + +If the goal was to support adapters in a single module, then the goal has been accomplished. In the real world however, we +build large composite models out of multiple modules and combine them to build a final model that we then train. We do this using the +:class:`~nemo.core.adapter_mixins.AdapterModelPTMixin`. + +.. note:: + + For an in-depth guide to supporting hierarchical adapter modules, please refer to the NeMo Adapter :doc:`Tutorials <../../starthere/tutorials>`. + + +.. autoclass:: nemo.core.adapter_mixins.AdapterModelPTMixin + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: adapter_module_names + +Below, we will discuss some useful functionality of Adapter Compatible Models. + +1) ``Save and restore a Model with adapter capability``: Any NeMo model that implements this class correctly can save and restore NeMo models with adapter capabilities, thereby allowing sharing of adapters. +2) ``save_adapters`` and ``load_adapters``: Adapters are usually a very small number of parameters, there is no need for the entire model to be duplicated for each adapter. This method allows storing just the adapter module(s) separately from the Model, so that you can use the same "base" model, and share just the Adapter modules. + + +.. toctree:: + :maxdepth: 8 + :caption: Adapters + + components + api + + +References +---------- + +.. bibliography:: ./adapter_bib.bib + :style: plain + :labelprefix: adapters + :keyprefix: adapters- diff --git a/docs/source/core/api.rst b/docs/source/core/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..f72e5ba76453e97e4a836d066dfb45341c2639a9 --- /dev/null +++ b/docs/source/core/api.rst @@ -0,0 +1,130 @@ + +NeMo Core APIs +============== + +Base class for all NeMo models +------------------------------ + +.. autoclass:: nemo.core.ModelPT + :show-inheritance: + :members: + :member-order: bysource + :undoc-members: cfg, num_weights + :exclude-members: set_eff_save, use_eff_save, teardown + +Base Neural Module class +------------------------ + +.. autoclass:: nemo.core.NeuralModule + :show-inheritance: + :members: + :member-order: bysource + +Base Mixin classes +------------------ + +.. autoclass:: nemo.core.Typing + :show-inheritance: + :members: + :member-order: bysource + :private-members: + :exclude-members: _abc_impl + :noindex: + + +.. autoclass:: nemo.core.Serialization + :show-inheritance: + :members: + :member-order: bysource + :noindex: + + +.. autoclass:: nemo.core.FileIO + :show-inheritance: + :members: + :member-order: bysource + :noindex: + + +Base Connector classes +---------------------- + +.. autoclass:: nemo.core.connectors.save_restore_connector.SaveRestoreConnector + :show-inheritance: + :members: + :member-order: bysource + + +Base Mixin Classes +------------------ + +.. autoclass:: nemo.core.classes.mixins.access_mixins.AccessMixin + :show-inheritance: + :members: + :member-order: bysource + + +.. autoclass:: nemo.core.classes.mixins.hf_io_mixin.HuggingFaceFileIO + :show-inheritance: + :members: + :member-order: bysource + + +Neural Type checking +-------------------- + +.. autoclass:: nemo.core.classes.common.typecheck + :show-inheritance: + :members: + :member-order: bysource + + .. automethod:: __call__ + +Neural Type classes +------------------- + +.. autoclass:: nemo.core.neural_types.NeuralType + :show-inheritance: + :members: + :member-order: bysource + + +.. autoclass:: nemo.core.neural_types.axes.AxisType + :show-inheritance: + :members: + :member-order: bysource + + +.. autoclass:: nemo.core.neural_types.elements.ElementType + :show-inheritance: + :members: + :member-order: bysource + + +.. autoclass:: nemo.core.neural_types.comparison.NeuralTypeComparisonResult + :show-inheritance: + :members: + :member-order: bysource + +Experiment manager +------------------ + +.. autoclass:: nemo.utils.exp_manager.exp_manager + :show-inheritance: + :members: + :member-order: bysource + +.. autoclass:: nemo.utils.exp_manager.ExpManagerConfig + :show-inheritance: + :members: + :member-order: bysource + + +Exportable +---------- + +.. autoclass:: nemo.core.classes.exportable.Exportable + :show-inheritance: + :members: + :member-order: bysource + diff --git a/docs/source/core/core.rst b/docs/source/core/core.rst new file mode 100644 index 0000000000000000000000000000000000000000..c3351c281ba6d19a8a0392a5fa7d0c87b1090fdf --- /dev/null +++ b/docs/source/core/core.rst @@ -0,0 +1,777 @@ +NeMo Models +=========== + +Basics +------ + +NeMo models contain everything needed to train and reproduce conversational AI models: + +- neural network architectures +- datasets/data loaders +- data preprocessing/postprocessing +- data augmentors +- optimizers and schedulers +- tokenizers +- language models + +NeMo uses `Hydra `_ for configuring both NeMo models and the PyTorch Lightning Trainer. + +.. note:: + Every NeMo model has an example configuration file and training script that can be found `here `__. + +The end result of using NeMo, `Pytorch Lightning `__, and Hydra is that NeMo models all have the same look and feel and are also fully compatible with the PyTorch ecosystem. + +Pretrained +---------- + +NeMo comes with many pretrained models for each of our collections: ASR, TTS, Audio, and SpeechLM2. Every pretrained NeMo model can be downloaded +and used with the ``from_pretrained()`` method. + +As an example, we can instantiate a Parakeet model with the following: + +.. code-block:: Python + + import nemo.collections.asr as nemo_asr + + model = nemo_asr.models.ASRModel.from_pretrained(model_name="nvidia/parakeet-tdt-0.6b-v2") + +To see all available pretrained models for a specific NeMo model, use the ``list_available_models()`` method: + +.. code-block:: Python + + nemo_asr.models.EncDecCTCModel.list_available_models() + +For detailed information on the available pretrained models, refer to the collections documentation: + +- :doc:`Automatic Speech Recognition (ASR) <../asr/intro>` +- :doc:`Text-to-Speech Synthesis (TTS) <../tts/intro>` + +Training +-------- + +NeMo leverages `PyTorch Lightning `__ for model training. PyTorch Lightning lets NeMo decouple the +conversational AI code from the PyTorch training code. This means that NeMo users can focus on their domain (ASR, NLP, TTS) and +build complex AI applications without having to rewrite boilerplate code for PyTorch training. + +When using PyTorch Lightning, NeMo users can automatically train with: + +- multi-GPU/multi-node +- mixed precision +- model checkpointing +- logging +- early stopping +- and more + +The two main aspects of the Lightning API are the `LightningModule `_ +and the `Trainer `_. + +PyTorch Lightning ``LightningModule`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Every NeMo model is a ``LightningModule`` which is an ``nn.module``. This means that NeMo models are compatible with the PyTorch +ecosystem and can be plugged into existing PyTorch workflows. + +Creating a NeMo model is similar to any other PyTorch workflow. We start by initializing our model architecture, then define the forward pass: + +.. code-block:: python + + class TextClassificationModel(NLPModel, Exportable): + ... + def __init__(self, cfg: DictConfig, trainer: Trainer = None): + """Initializes the BERTTextClassifier model.""" + ... + super().__init__(cfg=cfg, trainer=trainer) + + # instantiate a BERT based encoder + self.bert_model = get_lm_model( + config_file=cfg.language_model.config_file, + config_dict=cfg.language_model.config, + vocab_file=cfg.tokenizer.vocab_file, + trainer=trainer, + cfg=cfg, + ) + + # instantiate the FFN for classification + self.classifier = SequenceClassifier( + hidden_size=self.bert_model.config.hidden_size, + num_classes=cfg.dataset.num_classes, + num_layers=cfg.classifier_head.num_output_layers, + activation='relu', + log_softmax=False, + dropout=cfg.classifier_head.fc_dropout, + use_transformer_init=True, + idx_conditioned_on=0, + ) + +.. code-block:: python + + def forward(self, input_ids, token_type_ids, attention_mask): + """ + No special modification required for Lightning, define it as you normally would + in the `nn.Module` in vanilla PyTorch. + """ + hidden_states = self.bert_model( + input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask + ) + logits = self.classifier(hidden_states=hidden_states) + return logits + +The ``LightningModule`` organizes PyTorch code so that across all NeMo models we have a similar look and feel. +For example, the training logic can be found in ``training_step``: + +.. code-block:: python + + def training_step(self, batch, batch_idx): + """ + Lightning calls this inside the training loop with the data from the training dataloader + passed in as `batch`. + """ + # forward pass + input_ids, input_type_ids, input_mask, labels = batch + logits = self.forward(input_ids=input_ids, token_type_ids=input_type_ids, attention_mask=input_mask) + + train_loss = self.loss(logits=logits, labels=labels) + + lr = self._optimizer.param_groups[0]['lr'] + + self.log('train_loss', train_loss) + self.log('lr', lr, prog_bar=True) + + return { + 'loss': train_loss, + 'lr': lr, + } + +While validation logic can be found in ``validation_step``: + +.. code-block:: python + + def validation_step(self, batch, batch_idx): + """ + Lightning calls this inside the validation loop with the data from the validation dataloader + passed in as `batch`. + """ + if self.testing: + prefix = 'test' + else: + prefix = 'val' + + input_ids, input_type_ids, input_mask, labels = batch + logits = self.forward(input_ids=input_ids, token_type_ids=input_type_ids, attention_mask=input_mask) + + val_loss = self.loss(logits=logits, labels=labels) + + preds = torch.argmax(logits, axis=-1) + + tp, fn, fp, _ = self.classification_report(preds, labels) + + return {'val_loss': val_loss, 'tp': tp, 'fn': fn, 'fp': fp} + +PyTorch Lightning then handles all of the boilerplate code needed for training. Virtually any aspect of training can be customized +via PyTorch Lightning `hooks `_, +`Plugins `_, +`callbacks `_, or by overriding `methods `_. + +For more domain-specific information, see: + +- :doc:`Automatic Speech Recognition (ASR) <../asr/intro>` +- :doc:`Text-to-Speech Synthesis (TTS) <../tts/intro>` + +PyTorch Lightning Trainer +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since every NeMo model is a ``LightningModule``, we can automatically take advantage of the PyTorch Lightning ``Trainer``. Every NeMo +`example `_ training script uses the ``Trainer`` object to fit the model. + +First, instantiate the model and trainer, then call ``.fit``: + +.. code-block:: python + + # We first instantiate the trainer based on the model configuration. + # See the model configuration documentation for details. + trainer = pl.Trainer(**cfg.trainer) + + # Then pass the model configuration and trainer object into the NeMo model + model = TextClassificationModel(cfg.model, trainer=trainer) + + # Now we can train with by calling .fit + trainer.fit(model) + + # Or we can run the test loop on test data by calling + trainer.test(model=model) + +All `trainer flags `_ can be set from from the NeMo configuration. + + +Configuration +------------- + +Hydra is an open-source Python framework that simplifies configuration for complex applications that must bring together many different +software libraries. Conversational AI model training is a great example of such an application. To train a conversational AI model, we +must be able to configure: + +- neural network architectures +- training and optimization algorithms +- data pre/post processing +- data augmentation +- experiment logging/visualization +- model checkpointing + +For an introduction to using Hydra, refer to the `Hydra Tutorials `_. + +With Hydra, we can configure everything needed for NeMo with three interfaces: + +- Command Line (CLI) +- Configuration Files (YAML) +- Dataclasses (Python) + +YAML +~~~~ + +NeMo provides YAML configuration files for all of our `example `_ training scripts. +YAML files make it easy to experiment with different model and training configurations. + +Every NeMo example YAML has the same underlying configuration structure: + +- trainer +- exp_manager +- model + +The model configuration always contains ``train_ds``, ``validation_ds``, ``test_ds``, and ``optim``. Model architectures, however, can vary across domains. +Refer to the documentation of specific collections (LLM, ASR etc.) for detailed information on model architecture configuration. + +A NeMo configuration file should look similar to the following: + +.. code-block:: yaml + + # PyTorch Lightning Trainer configuration + # any argument of the Trainer object can be set here + trainer: + devices: 1 # number of gpus per node + accelerator: gpu + num_nodes: 1 # number of nodes + max_epochs: 10 # how many training epochs to run + val_check_interval: 1.0 # run validation after every epoch + + # Experiment logging configuration + exp_manager: + exp_dir: /path/to/my/nemo/experiments + name: name_of_my_experiment + create_tensorboard_logger: True + create_wandb_logger: True + + # Model configuration + # model network architecture, train/val/test datasets, data augmentation, and optimization + model: + train_ds: + manifest_filepath: /path/to/my/train/manifest.json + batch_size: 256 + shuffle: True + validation_ds: + manifest_filepath: /path/to/my/validation/manifest.json + batch_size: 32 + shuffle: False + test_ds: + manifest_filepath: /path/to/my/test/manifest.json + batch_size: 32 + shuffle: False + optim: + name: novograd + lr: .01 + betas: [0.8, 0.5] + weight_decay: 0.001 + # network architecture can vary greatly depending on the domain + encoder: + ... + decoder: + ... + +CLI +~~~ + +With NeMo and Hydra, every aspect of model training can be modified from the command-line. This is extremely helpful for running lots +of experiments on compute clusters or for quickly testing parameters during development. + +All NeMo `examples `_ come with instructions on how to +run the training/inference script from the command-line (e.g. see `here `__ +for an example). + +With Hydra, arguments are set using the ``=`` operator: + +.. code-block:: bash + + python examples/asr/asr_ctc/speech_to_text_ctc.py \ + model.train_ds.manifest_filepath=/path/to/my/train/manifest.json \ + model.validation_ds.manifest_filepath=/path/to/my/validation/manifest.json \ + trainer.devices=2 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 + +We can use the ``+`` operator to add arguments from the CLI: + +.. code-block:: bash + + python examples/asr/asr_ctc/speech_to_text_ctc.py \ + model.train_ds.manifest_filepath=/path/to/my/train/manifest.json \ + model.validation_ds.manifest_filepath=/path/to/my/validation/manifest.json \ + trainer.devices=2 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 \ + +trainer.fast_dev_run=true + +We can use the ``~`` operator to remove configurations: + +.. code-block:: bash + + python examples/asr/asr_ctc/speech_to_text_ctc.py \ + model.train_ds.manifest_filepath=/path/to/my/train/manifest.json \ + model.validation_ds.manifest_filepath=/path/to/my/validation/manifest.json \ + ~model.test_ds \ + trainer.devices=2 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 \ + +trainer.fast_dev_run=true + +We can specify configuration files using the ``--config-path`` and ``--config-name`` flags: + +.. code-block:: bash + + python examples/asr/asr_ctc/speech_to_text_ctc.py \ + --config-path=conf/conformer \ + --config-name=conformer_ctc_bpe \ + model.train_ds.manifest_filepath=/path/to/my/train/manifest.json \ + model.validation_ds.manifest_filepath=/path/to/my/validation/manifest.json \ + ~model.test_ds \ + trainer.devices=2 \ + trainer.accelerator='gpu' \ + trainer.max_epochs=50 \ + +trainer.fast_dev_run=true + +Dataclasses +~~~~~~~~~~~ + +Dataclasses allow NeMo to ship model configurations as part of the NeMo library and also enables pure Python configuration of NeMo models. +With Hydra, dataclasses can be used to create `structured configs `_ for the conversational AI application. + +As an example, refer to the code block below for an *Attenion is All You Need* machine translation model. The model configuration can +be instantiated and modified like any Python `Dataclass `_. + +.. code-block:: Python + + from nemo.collections.nlp.models.machine_translation.mt_enc_dec_config import AAYNBaseConfig + + cfg = AAYNBaseConfig() + + # modify the number of layers in the encoder + cfg.encoder.num_layers = 8 + + # modify the training batch size + cfg.train_ds.tokens_in_batch = 8192 + +.. note:: Configuration with Hydra always has the following precedence CLI > YAML > Dataclass. + +.. _optimization-label: + +Optimization +------------ + +Optimizers and learning rate schedules are configurable across all NeMo models and have their own namespace. Here is a sample YAML +configuration for a Novograd optimizer with a Cosine Annealing learning rate schedule. + +.. code-block:: yaml + + optim: + name: novograd + lr: 0.01 + + # optimizer arguments + betas: [0.8, 0.25] + weight_decay: 0.001 + + # scheduler setup + sched: + name: CosineAnnealing + + # Optional arguments + max_steps: -1 # computed at runtime or explicitly set here + monitor: val_loss + reduce_on_plateau: false + + # scheduler config override + warmup_steps: 1000 + warmup_ratio: null + min_lr: 1e-9: + +.. note:: `NeMo Examples `_ has optimizer and scheduler configurations for every NeMo model. + +Optimizers can be configured from the CLI as well: + +.. code-block:: bash + + python examples/asr/asr_ctc/speech_to_text_ctc.py \ + --config-path=conf/conformer \ + --config-name=conformer_ctc_bpe \ + ... + # train with the adam optimizer + model.optim=adam \ + # change the learning rate + model.optim.lr=.0004 \ + # modify betas + model.optim.betas=[.8, .5] + +.. _optimizers-label: + +Optimizers +~~~~~~~~~~ + +``name`` corresponds to the lowercase name of the optimizer. To view a list of available optimizers, run: + +.. code-block:: Python + + from nemo.core.optim.optimizers import AVAILABLE_OPTIMIZERS + + for name, opt in AVAILABLE_OPTIMIZERS.items(): + print(f'name: {name}, opt: {opt}') + +.. code-block:: bash + + name: sgd opt: + name: adam opt: + name: adamw opt: + name: adadelta opt: + name: adamax opt: + name: adagrad opt: + name: rmsprop opt: + name: rprop opt: + name: novograd opt: + +Optimizer Params +~~~~~~~~~~~~~~~~ + +Optimizer params can vary between optimizers but the ``lr`` param is required for all optimizers. To see the available params for an +optimizer, we can look at its corresponding dataclass. + +.. code-block:: python + + from nemo.core.config.optimizers import NovogradParams + + print(NovogradParams()) + +.. code-block:: bash + + NovogradParams(lr='???', betas=(0.95, 0.98), eps=1e-08, weight_decay=0, grad_averaging=False, amsgrad=False, luc=False, luc_trust=0.001, luc_eps=1e-08) + +``'???'`` indicates that the lr argument is required. + +Register Optimizer +~~~~~~~~~~~~~~~~~~ + +To register a new optimizer to be used with NeMo, run: + +.. autofunction:: nemo.core.optim.optimizers.register_optimizer + +.. _learning-rate-schedulers-label: + +Learning Rate Schedulers +~~~~~~~~~~~~~~~~~~~~~~~~ + +Learning rate schedulers can be optionally configured under the ``optim.sched`` namespace. + +``name`` corresponds to the name of the learning rate schedule. To view a list of available schedulers, run: + +.. code-block:: Python + + from nemo.core.optim.lr_scheduler import AVAILABLE_SCHEDULERS + + for name, opt in AVAILABLE_SCHEDULERS.items(): + print(f'name: {name}, schedule: {opt}') + +.. code-block:: bash + + name: WarmupPolicy, schedule: + name: WarmupHoldPolicy, schedule: + name: SquareAnnealing, schedule: + name: CosineAnnealing, schedule: + name: NoamAnnealing, schedule: + name: WarmupAnnealing, schedule: + name: InverseSquareRootAnnealing, schedule: + name: SquareRootAnnealing, schedule: + name: PolynomialDecayAnnealing, schedule: + name: PolynomialHoldDecayAnnealing, schedule: + name: StepLR, schedule: + name: ExponentialLR, schedule: + name: ReduceLROnPlateau, schedule: + name: CyclicLR, schedule: + +Scheduler Params +~~~~~~~~~~~~~~~~ + +To see the available params for a scheduler, we can look at its corresponding dataclass: + +.. code-block:: Python + + from nemo.core.config.schedulers import CosineAnnealingParams + + print(CosineAnnealingParams()) + +.. code-block:: bash + + CosineAnnealingParams(last_epoch=-1, warmup_steps=None, warmup_ratio=None, min_lr=0.0) + +Register scheduler +~~~~~~~~~~~~~~~~~~ + +To register a new scheduler to be used with NeMo, run: + +.. autofunction:: nemo.core.optim.lr_scheduler.register_scheduler + +Save and Restore +---------------- + +NeMo models all come with ``.save_to`` and ``.restore_from`` methods. + +Save +~~~~ + +To save a NeMo model, run: + +.. code-block:: Python + + model.save_to('/path/to/model.nemo') + +Everything needed to use the trained model is packaged and saved in the ``.nemo`` file. For example, in the NLP domain, ``.nemo`` files +include the necessary tokenizer models and/or vocabulary files, etc. + +.. note:: A ``.nemo`` file is simply an archive like any other ``.tar`` file. + +Restore +~~~~~~~ + +To restore a NeMo model, run: + +.. code-block:: Python + + # Here, you should usually use the class of the model, or simply use ModelPT.restore_from() for simplicity. + model.restore_from('/path/to/model.nemo') + +When using the PyTorch Lightning Trainer, a PyTorch Lightning checkpoint is created. These are mainly used within NeMo to auto-resume +training. Since NeMo models are ``LightningModules``, the PyTorch Lightning method ``load_from_checkpoint`` is available. Note that +``load_from_checkpoint`` won't necessarily work out-of-the-box for all models as some models require more artifacts than just the +checkpoint to be restored. For these models, the user will have to override ``load_from_checkpoint`` if they want to use it. + +It's highly recommended to use ``restore_from`` to load NeMo models. + +Restore with Modified Config +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Sometimes, there may be a need to modify the model (or it's sub-components) prior to restoring a model. A common case is when +the model's internal config must be updated due to various reasons (such as deprecation, newer versioning, support a new feature). +As long as the model has the same parameters as compared to the original config, the parameters can once again be restored safely. + +In NeMo, as part of the .nemo file, the model's internal config will be preserved. This config is used during restoration, and +as shown below we can update this config prior to restoring the model. + +.. code-block:: + + # When restoring a model, you should generally use the class of the model + # Obtain the config (as an OmegaConf object) + config = model_class.restore_from('/path/to/model.nemo', return_config=True) + # OR + config = model_class.from_pretrained('name_of_the_model', return_config=True) + + # Modify the config as needed + config.x.y = z + + # Restore the model from the updated config + model = model_class.restore_from('/path/to/model.nemo', override_config_path=config) + # OR + model = model_class.from_pretrained('name_of_the_model', override_config_path=config) + +Register Artifacts +------------------ + +Restoring conversational AI models can be complicated because it requires more than just the checkpoint weights; additional information is also needed to use the model. +NeMo models can save additional artifacts in the .nemo file by calling ``.register_artifact``. +When restoring NeMo models using ``.restore_from`` or ``.from_pretrained``, any artifacts that were registered will be available automatically. + +As an example, consider an NLP model that requires a trained tokenizer model. +The tokenizer model file can be automatically added to the .nemo file with the following: + +.. code-block:: python + + self.encoder_tokenizer = get_nmt_tokenizer( + ... + tokenizer_model=self.register_artifact(config_path='encoder_tokenizer.tokenizer_model', + src='/path/to/tokenizer.model', + verify_src_exists=True), + ) + +By default, ``.register_artifact`` will always return a path. If the model is being restored from a .nemo file, +then that path will be to the artifact in the .nemo file. Otherwise, ``.register_artifact`` will return the local path specified by the user. + +``config_path`` is the artifact key. It usually corresponds to a model configuration but does not have to. +The model config that is packaged with the .nemo file will be updated according to the ``config_path`` key. +In the above example, the model config will have + +.. code-block:: YAML + + encoder_tokenizer: + ... + tokenizer_model: nemo:4978b28103264263a03439aaa6560e5e_tokenizer.model + +``src`` is the path to the artifact and the base-name of the path will be used when packaging the artifact in the .nemo file. +Each artifact will have a hash prepended to the basename of ``src`` in the .nemo file. This is to prevent collisions with basenames +base-names that are identical (say when there are two or more tokenizers, both called `tokenizer.model`). +The resulting .nemo file will then have the following file: + +.. code-block:: bash + + 4978b28103264263a03439aaa6560e5e_tokenizer.model + +If ``verify_src_exists`` is set to ``False``, then the artifact is optional. This means that ``.register_artifact`` will return ``None`` +if the ``src`` cannot be found. + +Push to Hugging Face Hub +------------------------ + +NeMo models can be pushed to the `Hugging Face Hub `_ with the :meth:`~nemo.core.classes.mixins.hf_io_mixin.HuggingFaceFileIO.push_to_hf_hub` method. This method performs the same actions as ``save_to()`` and then uploads the model to the HuggingFace Hub. It offers an additional ``pack_nemo_file`` argument that allows the user to upload the entire NeMo file or just the ``.nemo`` file. This is useful for large language models that have a massive number of parameters, and a single NeMo file could exceed the max upload size of Hugging Face Hub. + + +Upload a model to the Hub +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: python + + token = "" or None + pack_nemo_file = True # False will upload multiple files that comprise the NeMo file onto HF Hub; Generally useful for LLMs + + model.push_to_hf_hub( + repo_id=repo_id, pack_nemo_file=pack_nemo_file, token=token, + ) + +Use a Custom Model Card Template for the Hub +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: python + + # Override the default model card + template = """ + # {model_name} + """ + kwargs = {"model_name": "ABC", "repo_id": "nvidia/ABC_XYZ"} + model_card = model.generate_model_card(template=template, template_kwargs=kwargs, type="hf") + + model.push_to_hf_hub( + repo_id=repo_id, token=token, model_card=model_card + ) + + # Write your own model card class + class MyModelCard: + def __init__(self, model_name): + self.model_name = model_name + + def __repr__(self): + template = """This is the {model_name} model""".format(model_name=self.model_name) + return template + + model.push_to_hf_hub( + repo_id=repo_id, token=token, model_card=MyModelCard("ABC") + ) + + +Nested NeMo Models +------------------ + +In some cases, it may be helpful to use NeMo models inside other NeMo models. For example, we can incorporate language models into ASR models to use in a decoding process to improve accuracy. + +There are three ways to instantiate child models inside parent models: + +- use subconfig directly +- use the ``.nemo`` checkpoint path to load the child model +- use a pretrained NeMo model + +To register a child model, use the ``register_nemo_submodule`` method of the parent model. This method will add the child model to a specified model attribute. During serialization, it will correctly handle child artifacts and store the child model’s configuration in the parent model’s ``config_field``. + +.. code-block:: python + + from nemo.core.classes import ModelPT + + class ChildModel(ModelPT): + ... # implement necessary methods + + class ParentModel(ModelPT): + def __init__(self, cfg, trainer=None): + super().__init__(cfg=cfg, trainer=trainer) + + # optionally annotate type for IDE autocompletion and type checking + self.child_model: Optional[ChildModel] + if cfg.get("child_model") is not None: + # load directly from config + # either if config provided initially, or automatically + # after model restoration + self.register_nemo_submodule( + name="child_model", + config_field="child_model", + model=ChildModel(self.cfg.child_model, trainer=trainer), + ) + elif cfg.get('child_model_path') is not None: + # load from .nemo model checkpoint + # while saving, config will be automatically assigned/updated + # in cfg.child_model + self.register_nemo_submodule( + name="child_model", + config_field="child_model", + model=ChildModel.restore_from(self.cfg.child_model_path, trainer=trainer), + ) + elif cfg.get('child_model_name') is not None: + # load from pretrained model + # while saving, config will be automatically assigned/updated + # in cfg.child_model + self.register_nemo_submodule( + name="child_model", + config_field="child_model", + model=ChildModel.from_pretrained(self.cfg.child_model_name, trainer=trainer), + ) + else: + self.child_model = None + + + +Profiling +--------- + +NeMo offers users two options for profiling: Nsys and CUDA memory profiling. These two options allow users +to debug performance issues as well as memory issues such as memory leaks. + +To enable Nsys profiling, add the following options to the model config: + +.. code-block:: yaml + + nsys_profile: False + start_step: 10 # Global batch to start profiling + end_step: 10 # Global batch to end profiling + ranks: [0] # Global rank IDs to profile + gen_shape: False # Generate model and kernel details including input shapes + +Finally, run the model training script with: + +.. code-block:: bash + + nsys profile -s none -o -t cuda,nvtx --force-overwrite true --capture-range=cudaProfilerApi --capture-range-end=stop python ./examples/... + +See more options at `nsight user guide `_. + + + +To enable CUDA memory profiling, add the following options to the model config: + +.. code-block:: yaml + + memory_profile: + enabled: True + start_step: 10 # Global batch to start profiling + end_step: 10 # Global batch to end profiling + rank: 0 # Global rank ID to profile + output_path: None # Path to store the profile output file + +Then invoke your NeMo script without any changes in the invocation command. diff --git a/docs/source/core/exp_manager.rst b/docs/source/core/exp_manager.rst new file mode 100644 index 0000000000000000000000000000000000000000..5d9e8a858c9a84697f8c667be9120c5222d80892 --- /dev/null +++ b/docs/source/core/exp_manager.rst @@ -0,0 +1,502 @@ + +.. _exp-manager-label: + +Experiment Manager +================== + +The NeMo Toolkit Experiment Manager leverages PyTorch Lightning for model checkpointing, TensorBoard Logging, Weights and Biases, DLLogger and MLFlow logging. The +Experiment Manager is included by default in all NeMo example scripts. + +To use the Experiment Manager, call :class:`~nemo.utils.exp_manager.exp_manager` and pass in the PyTorch Lightning ``Trainer``. + +.. code-block:: python + + exp_dir = exp_manager(trainer, cfg.get("exp_manager", None)) + +The Experiment Manager is configurable using YAML with Hydra. + +.. code-block:: bash + + exp_manager: + exp_dir: /path/to/my/experiments + name: my_experiment_name + create_tensorboard_logger: True + create_checkpoint_callback: True + +Optionally, launch TensorBoard to view the training results in ``exp_dir``, which by default is set to ``./nemo_experiments``. + +.. code-block:: bash + + tensorboard --bind_all --logdir nemo_experiments + +.. + +If ``create_checkpoint_callback`` is set to ``True``, then NeMo automatically creates checkpoints during training +using PyTorch Lightning's `ModelCheckpoint `_. +We can configure the ``ModelCheckpoint`` via YAML or CLI: + +.. code-block:: yaml + + exp_manager: + ... + # configure the PyTorch Lightning ModelCheckpoint using checkpoint_call_back_params + # any ModelCheckpoint argument can be set here + + # save the best checkpoints based on this metric + checkpoint_callback_params.monitor=val_loss + + # choose how many total checkpoints to save + checkpoint_callback_params.save_top_k=5 + +Resume Training +--------------- + +To auto-resume training, configure the ``exp_manager``. This feature is important for long training runs that might be interrupted or +shut down before the procedure has completed. To auto-resume training, set the following parameters via YAML or CLI: + +.. code-block:: yaml + + exp_manager: + ... + # resume training if checkpoints already exist + resume_if_exists: True + + # to start training with no existing checkpoints + resume_ignore_no_checkpoint: True + + # by default experiments will be versioned by datetime + # we can set our own version with + exp_manager.version: my_experiment_version + + +Experiment Loggers +------------------ + +Alongside Tensorboard, NeMo also supports Weights and Biases, MLFlow, DLLogger, ClearML and NeptuneLogger. To use these loggers, set the following +via YAML or :class:`~nemo.utils.exp_manager.ExpManagerConfig`. + + +Weights and Biases (WandB) +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _exp_manager_weights_biases-label: + +.. code-block:: yaml + + exp_manager: + ... + create_checkpoint_callback: True + create_wandb_logger: True + wandb_logger_kwargs: + name: ${name} + project: ${project} + entity: ${entity} + + + +MLFlow +~~~~~~ + +.. _exp_manager_mlflow-label: + +.. code-block:: yaml + + exp_manager: + ... + create_checkpoint_callback: True + create_mlflow_logger: True + mlflow_logger_kwargs: + experiment_name: ${name} + tags: + + save_dir: './mlruns' + prefix: '' + artifact_location: None + # provide run_id if resuming a previously started run + run_id: Optional[str] = None + +DLLogger +~~~~~~~~ + +.. _exp_manager_dllogger-label: + +.. code-block:: yaml + + exp_manager: + ... + create_checkpoint_callback: True + create_dllogger_logger: True + dllogger_logger_kwargs: + verbose: False + stdout: False + json_file: "./dllogger.json" + +ClearML +~~~~~~~ + +.. _exp_manager_clearml-label: + +.. code-block:: yaml + + exp_manager: + ... + create_checkpoint_callback: True + create_clearml_logger: True + clearml_logger_kwargs: + project: None # name of the project + task: None # optional name of task + connect_pytorch: False + model_name: None # optional name of model + tags: None # Should be a list of str + log_model: False # log model to clearml server + log_cfg: False # log config to clearml server + log_metrics: False # log metrics to clearml server + +Neptune +~~~~~~~ + +.. _exp_manager_neptune-label: + +.. code-block:: yaml + + exp_manager: + ... + create_checkpoint_callback: True + create_neptune_logger: false + neptune_logger_kwargs: + project: ${project} + name: ${name} + prefix: train + log_model_checkpoints: false # set to True if checkpoints need to be pushed to Neptune + tags: null # can specify as an array of strings in yaml array format + description: null + + +Exponential Moving Average +-------------------------- + +.. _exp_manager_ema-label: + +NeMo supports using exponential moving average (EMA) for model parameters. This can be useful for improving model generalization +and stability. To use EMA, set the following parameters via YAML or :class:`~nemo.utils.exp_manager.ExpManagerConfig`. + +.. code-block:: yaml + + exp_manager: + ... + # use exponential moving average for model parameters + ema: + enabled: True # False by default + decay: 0.999 # decay rate + cpu_offload: False # If EMA parameters should be offloaded to CPU to save GPU memory + every_n_steps: 1 # How often to update EMA weights + validate_original_weights: False # Whether to use original weights for validation calculation or EMA weights + +.. Support for Preemption + ---------------------- + + .. _exp_manager_preemption_support-label: + + NeMo adds support for a callback upon preemption while running the models on clusters. The callback takes care of saving the current state of training via the ``.ckpt`` + file followed by a graceful exit from the run. The checkpoint saved upon preemption has the ``*last.ckpt`` suffix and replaces the previously saved last checkpoints. + This feature is useful to increase utilization on clusters. + The ``PreemptionCallback`` is enabled by default. To disable it, add ``create_preemption_callback: False`` under exp_manager in the config YAML file. + + Stragglers Detection + ---------------------- + + .. _exp_manager_straggler_det_support-label: + + .. note:: + Stragglers Detection feature is included in the optional NeMo resiliency package. + + Distributed training can be affected by stragglers, which are workers that slow down the overall training process. + NeMo provides a straggler detection feature that can identify slower GPUs. + + This feature is implemented in the ``StragglerDetectionCallback``, which is disabled by default. + + The callback computes normalized GPU performance scores, which are scalar values ranging from 0.0 (worst) to 1.0 (best). + A performance score can be interpreted as the ratio of current performance to reference performance. + + There are two types of performance scores provided by the callback: + * Relative GPU performance score: The best-performing GPU in the workload is used as a reference. + * Individual GPU performance score: The best historical performance of the GPU is used as a reference. + + Examples: + * If the relative performance score is 0.5, it means that a GPU is twice slower than the fastest GPU. + * If the individual performance score is 0.5, it means that a GPU is twice slower than its best observed performance. + + If a GPU performance score drops below the specified threshold, it is identified as a straggler. + + To enable straggler detection, add ``create_straggler_detection_callback: True`` under exp_manager in the config YAML file. + You might also want to adjust the callback parameters: + + .. code-block:: yaml + + exp_manager: + ... + create_straggler_detection_callback: True + straggler_detection_callback_params: + report_time_interval: 300 # Interval [seconds] of the straggler check + calc_relative_gpu_perf: True # Calculate relative GPU performance + calc_individual_gpu_perf: True # Calculate individual GPU performance + num_gpu_perf_scores_to_log: 5 # Log 5 best and 5 worst GPU performance scores, even if no stragglers are detected + gpu_relative_perf_threshold: 0.7 # Threshold for relative GPU performance scores + gpu_individual_perf_threshold: 0.7 # Threshold for individual GPU performance scores + stop_if_detected: True # Terminate the workload if stragglers are detected + + Straggler detection may require inter-rank synchronization and should be performed at regular intervals, such as every few minutes. + + +.. Fault Tolerance + --------------- + + .. _exp_manager_fault_tolerance_support-label: + + .. note:: + Fault Tolerance feature is included in the optional NeMo resiliency package. + + When training Deep Neural Network (DNN models), faults may occur, hindering the progress of the entire training process. + This is particularly common in distributed, multi-node training scenarios, with many nodes and GPUs involved. + + NeMo incorporates a fault tolerance mechanism to detect training halts. + In response, it can terminate a hung workload and, if requested, restart it from the last checkpoint. + + Fault tolerance ("FT") relies on a special launcher (``ft_launcher``), which is a modified ``torchrun``. + The FT launcher runs background processes called rank monitors. **You need to use ft_launcher to start + your workload if you are using FT**. I.e., `NeMo-Framework-Launcher `_ + can be used to generate SLURM batch scripts with FT support. + + Each training process (rank) sends `heartbeats` to its monitor during training and validation steps. + If a rank monitor stops receiving `heartbeats`, a training failure is detected. + + Fault detection is implemented in the ``FaultToleranceCallback`` and is disabled by default. + To enable it, add a ``create_fault_tolerance_callback: True`` option under ``exp_manager`` in the + config YAML file. Additionally, you can customize FT parameters by adding ``fault_tolerance`` section: + + .. code-block:: yaml + + exp_manager: + ... + create_fault_tolerance_callback: True + fault_tolerance: + initial_rank_heartbeat_timeout: 600 # wait for 10 minutes for the initial heartbeat + rank_heartbeat_timeout: 300 # wait for 5 minutes for subsequent heartbeats + calculate_timeouts: True # estimate more accurate timeouts based on observed intervals + + Timeouts for fault detection need to be adjusted for a given workload: + * ``initial_rank_heartbeat_timeout`` should be long enough to allow for workload initialization. + * ``rank_heartbeat_timeout`` should be at least as long as the longest possible interval between steps. + + **Importantly, `heartbeats` are not sent during checkpoint loading and saving**, so time for + checkpointing related operations should be taken into account. + + If ``calculate_timeouts: True``, timeouts will be automatically estimated based on observed intervals. + Estimated timeouts take precedence over timeouts defined in the config file. **Timeouts are estimated + at the end of a training run when checkpoint loading and saving were observed.** Hence, in a multi-part + training started from scratch, estimated timeouts won't be available during the initial two runs. + Estimated timeouts are stored in a separate JSON file. + + ``max_subsequent_job_failures`` allows for the automatic continuation of training on a SLURM cluster. + This feature requires SLURM job to be scheduled with ``NeMo-Framework-Launcher``. If ``max_subsequent_job_failures`` + value is `>0` continuation job is prescheduled. It will continue the work until ``max_subsequent_job_failures`` + subsequent jobs failed (SLURM job exit code is `!= 0`) or the training is completed successfully + ("end of training" marker file is produced by the ``FaultToleranceCallback``, i.e. due to iters or time limit reached). + + All FT configuration items summary: + * ``workload_check_interval`` (float, default=5.0) Periodic workload check interval [seconds] in the workload monitor. + * ``initial_rank_heartbeat_timeout`` (Optional[float], default=60.0 * 60.0) Timeout [seconds] for the first heartbeat from a rank. + * ``rank_heartbeat_timeout`` (Optional[float], default=45.0 * 60.0) Timeout [seconds] for subsequent heartbeats from a rank. + * ``calculate_timeouts`` (bool, default=True) Try to calculate ``rank_heartbeat_timeout`` and ``initial_rank_heartbeat_timeout`` + based on the observed heartbeat intervals. + * ``safety_factor``: (float, default=5.0) When calculating the timeouts, multiply the maximum observed heartbeat interval + by this factor to obtain the timeout estimate. Can be made smaller for stable environments and larger for unstable ones. + * ``rank_termination_signal`` (signal.Signals, default=signal.SIGKILL) Signal used to terminate the rank when failure is detected. + * ``log_level`` (str, default='INFO') Log level for the FT client and server(rank monitor). + * ``max_rank_restarts`` (int, default=0) Used by FT launcher. Max number of restarts for a rank. + If ``>0`` ranks will be restarted on existing nodes in case of a failure. + * ``max_subsequent_job_failures`` (int, default=0) Used by FT launcher. How many subsequent job failures are allowed until stopping autoresuming. + ``0`` means do not auto-resume. + * ``additional_ft_launcher_args`` (str, default='') Additional FT launcher params (for advanced use). + + +.. _nemo_multirun-label: + +Hydra Multi-Run with NeMo +------------------------- + +When training neural networks, it is common to perform a hyperparameter search to improve the model’s performance on validation data. +However, manually preparing a grid of experiments and managing all checkpoints and their metrics can be tedious. +To simplify these tasks, NeMo integrates with `Hydra Multi-Run support `_, +providing a unified way to run a set of experiments directly from the configuration. + +There are certain limitations to this framework, which we list below: + +* All experiments are assumed to be run on a single GPU, and multi GPU for single run (model parallel models are not supported as of now). +* NeMo Multi-Run currently supports only grid search over a set of hyperparameters. Support for advanced hyperparameter search strategies will be added in the future. +* **NeMo Multi-Run requires one or more GPUs** to function and will not work without GPU devices. + +Config Setup +~~~~~~~~~~~~ + +In order to enable NeMo Multi-Run, we first update our YAML configs with some information to let Hydra know we expect to run multiple experiments from this one config - + +.. code-block:: yaml + + # Required for Hydra launch of hyperparameter search via multirun + defaults: + - override hydra/launcher: nemo_launcher + + # Hydra arguments necessary for hyperparameter optimization + hydra: + # Helper arguments to ensure all hyper parameter runs are from the directory that launches the script. + sweep: + dir: "." + subdir: "." + + # Define all the hyper parameters here + sweeper: + params: + # Place all the parameters you wish to search over here (corresponding to the rest of the config) + # NOTE: Make sure that there are no spaces between the commas that separate the config params ! + model.optim.lr: 0.001,0.0001 + model.encoder.dim: 32,64,96,128 + model.decoder.dropout: 0.0,0.1,0.2 + + # Arguments to the process launcher + launcher: + num_gpus: -1 # Number of gpus to use. Each run works on a single GPU. + jobs_per_gpu: 1 # If each GPU has large memory, you can run multiple jobs on the same GPU for faster results (until OOM). + + +Next, we will setup the config for ``Experiment Manager``. When we perform hyper parameter search, each run may take some time to complete. +We want to therefore avoid the case where a run ends (say due to OOM or timeout on the machine) and we need to redo all experiments. +We therefore setup the experiment manager config such that every experiment has a unique "key", whose value corresponds to a single +resumable experiment. + +Let us see how to setup such a unique "key" via the experiment name. Simply attach all the hyper parameter arguments to the experiment +name as shown below - + +.. code-block:: yaml + + exp_manager: + exp_dir: null # Can be set by the user. + + # Add a unique name for all hyper parameter arguments to allow continued training. + # NOTE: It is necessary to add all hyperparameter arguments to the name ! + # This ensures successful restoration of model runs in case HP search crashes. + name: ${name}-lr-${model.optim.lr}-adim-${model.adapter.dim}-sd-${model.adapter.adapter_strategy.stochastic_depth} + + ... + checkpoint_callback_params: + ... + save_top_k: 1 # Dont save too many .ckpt files during HP search + always_save_nemo: True # saves the checkpoints as nemo files for fast checking of results later + ... + + # We highly recommend use of any experiment tracking took to gather all the experiments in one location + create_wandb_logger: True + wandb_logger_kwargs: + project: "" + + # HP Search may crash due to various reasons, best to attempt continuation in order to + # resume from where the last failure case occurred. + resume_if_exists: true + resume_ignore_no_checkpoint: true + + +Run a NeMo Multi-Run Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Once the config has been updated, we can now run it just like any normal Hydra script, with one special flag (``-m``). + +.. code-block:: bash + + python script.py --config-path=ABC --config-name=XYZ -m \ + trainer.max_steps=5000 \ # Any additional arg after -m will be passed to all the runs generated from the config ! + ... + +Tips and Tricks +--------------- + +This section provides recommendations for using the Experiment Manager. + +Preserving disk space for a large number of experiments +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Some models may have a large number of parameters, making it very expensive to save numerous checkpoints on physical storage drives. +For example, if you use the Adam optimizer, each PyTorch Lightning ".ckpt" file will be three times the size of just the model +parameters. This can become exorbitant if you have multiple runs. + +In the above configuration, we explicitly set ``save_top_k: 1`` and ``always_save_nemo: True``. This limits the number of ".ckpt" +files to just one and also saves a NeMo file, which contains only the model parameters without the optimizer state. +This NeMo file can be restored immediately for further work. + +We can further save storage space by using NeMo's utility functions to automatically delete either ".ckpt" or NeMo files +after a training run has finished. This is sufficient if you are collecting results in an experiment tracking tool and can +simply rerun the best configuration after the search is completed. + +.. code-block:: python + + # Import `clean_exp_ckpt` along with exp_manager + from nemo.utils.exp_manager import clean_exp_ckpt, exp_manager + + @hydra_runner(...) + def main(cfg): + ... + + # Keep track of the experiment directory + exp_log_dir = exp_manager(trainer, cfg.get("exp_manager", None)) + + ... add any training code here as needed ... + + # Add following line to end of the training script + # Remove PTL ckpt file, and potentially also remove .nemo file to conserve storage space. + clean_exp_ckpt(exp_log_dir, remove_ckpt=True, remove_nemo=False) + + +Debugging Multi-Run Scripts +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When running Hydra scripts, you may encounter configuration issues that crash the program. In NeMo Multi-Run, a crash in +any single run will not crash the entire program. Instead, we will note the error and proceed to the next job. Once all +jobs are completed, we will raise the errors in the order they occurred, crashing the program with the first error’s stack trace. + + +To debug NeMo Multi-Run, we recommend commenting out the entire hyperparameter configuration set inside ``sweep.params``. +Instead, run a single experiment with the configuration, which will immediately raise the error. + + +Experiment name cannot be parsed by Hydra +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Sometimes our hyperparameters include PyTorch Lightning ``trainer`` arguments, such as the number of steps, number of epochs, +and whether to use gradient accumulation. When we attempt to add these as keys to the experiment manager's ``name``, +Hydra may complain that ``trainer.xyz`` cannot be resolved. + +A simple solution is to finalize the Hydra config before you call ``exp_manager()`` as follows: + +.. code-block:: python + + @hydra_runner(...) + def main(cfg): + # Make any changes as necessary to the config + cfg.xyz.abc = uvw + + # Finalize the config + cfg = OmegaConf.resolve(cfg) + + # Carry on as normal by calling trainer and exp_manager + trainer = pl.Trainer(**cfg.trainer) + exp_log_dir = exp_manager(trainer, cfg.get("exp_manager", None)) + ... + + +ExpManagerConfig +---------------- + +.. autoclass:: nemo.utils.exp_manager.ExpManagerConfig + :show-inheritance: + :members: + :member-order: bysource + :noindex: diff --git a/docs/source/core/neural_modules.rst b/docs/source/core/neural_modules.rst new file mode 100644 index 0000000000000000000000000000000000000000..fbeec5440d013277453f8b239321edb0d56d1f61 --- /dev/null +++ b/docs/source/core/neural_modules.rst @@ -0,0 +1,88 @@ +Neural Modules +============== + +NeMo is built around Neural Modules, conceptual blocks of neural networks that take typed inputs and produce typed outputs. Such +modules typically represent data layers, encoders, decoders, language models, loss functions, or methods of combining activations. +NeMo makes it easy to combine and re-use these building blocks while providing a level of semantic correctness checking via its neural +type system. + +.. note:: *All Neural Modules inherit from ``torch.nn.Module`` and are therefore compatible with the PyTorch ecosystem.* + +There are 3 types on Neural Modules: + + - Regular modules + - Dataset/IterableDataset + - Losses + +Every Neural Module in NeMo must inherit from `nemo.core.classes.module.NeuralModule` class. + +.. autoclass:: nemo.core.classes.module.NeuralModule + +Every Neural Modules inherits the ``nemo.core.classes.common.Typing`` interface and needs to define neural types for its inputs and outputs. +This is done by defining two properties: ``input_types`` and ``output_types``. Each property should return an ordered dictionary of +"port name"->"port neural type" pairs. Here is the example from :class:`~nemo.collections.asr.modules.ConvASREncoder` class: + +.. code-block:: python + + @property + def input_types(self): + return OrderedDict( + { + "audio_signal": NeuralType(('B', 'D', 'T'), SpectrogramType()), + "length": NeuralType(tuple('B'), LengthsType()), + } + ) + + @property + def output_types(self): + return OrderedDict( + { + "outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), + "encoded_lengths": NeuralType(tuple('B'), LengthsType()), + } + ) + + @typecheck() + def forward(self, audio_signal, length=None): + ... + +The code snippet above means that ``nemo.collections.asr.modules.conv_asr.ConvASREncoder`` expects two arguments: + * First one, named ``audio_signal`` of shape ``[batch, dimension, time]`` with elements representing spectrogram values. + * Second one, named ``length`` of shape ``[batch]`` with elements representing lengths of corresponding signals. + +It also means that ``.forward(...)`` and ``__call__(...)`` methods each produce two outputs: + * First one, of shape ``[batch, dimension, time]`` but with elements representing encoded representation (``AcousticEncodedRepresentation`` class). + * Second one, of shape ``[batch]``, corresponding to their lengths. + +.. tip:: It is a good practice to define types and add ``@typecheck()`` decorator to your ``.forward()`` method after your module is ready for use by others. + +.. note:: The outputs of ``.forward(...)`` method will always be of type ``torch.Tensor`` or container of tensors and will work with any other Pytorch code. The type information is attached to every output tensor. If tensors without types is passed to your module, it will not fail, however the types will not be checked. Thus, it is recommended to define input/output types for all your modules, starting with data layers and add ``@typecheck()`` decorator to them. + +.. note:: To temporarily disable typechecking, you can enclose your code in ```with typecheck.disable_checks():``` statement. + + +Dynamic Layer Freezing +---------------------- + +You can selectively freeze any modules inside a Nemo model by specifying a freezing schedule in the config yaml. Freezing stops any gradient updates +to that module, so that its weights are not changed for that step. This can be useful for combatting catastrophic forgetting, for example +when finetuning a large pretrained model on a small dataset. + +The default approach is to freeze a module for the first N training steps, but you can also enable freezing for a specific range of steps, +for example, from step 20 - 100, or even activate freezing from some N until the end of training. You can also freeze a module for the entire training run. +Dynamic freezing is specified in training steps, not epochs. + +To enable freezing, add the following to your config: + +.. code-block:: yaml + + model: + ... + freeze_updates: + enabled: true # set to false if you want to disable freezing + + modules: # list all of the modules you want to have freezing logic for + encoder: 200 # module will be frozen for the first 200 training steps + decoder: [50, -1] # module will be frozen at step 50 and will remain frozen until training ends + joint: [10, 100] # module will be frozen between step 10 and step 100 (step >= 10 and step <= 100) + transcoder: -1 # module will be frozen for the entire training run diff --git a/docs/source/core/neural_types.rst b/docs/source/core/neural_types.rst new file mode 100644 index 0000000000000000000000000000000000000000..989cc8d998f4d789f77a3e26058baa2ca819c7b8 --- /dev/null +++ b/docs/source/core/neural_types.rst @@ -0,0 +1,181 @@ + +Neural Types +============ + +Motivation +---------- + +Neural Types describe the semantics, axis order, and dimensions of a tensor. The purpose of this type system is to catch semantic and +dimensionality errors during model creation and facilitate module re-use. + +.. image:: whyntypes.gif + :width: 900 + :alt: Neural Types Motivation + +``NeuralType`` class +-------------------- + +Neural Types perform semantic checks for modules and models inputs/outputs. They contain information about: + + - Semantics of what is stored in the tensors. For example, logits, logprobs, audiosignal, embeddings, etc. + - Axes layout, semantic and (optionally) dimensionality. For example: ``[Batch, Time, Channel]`` + +Types are implemented in ``nemo.core.neural_types.NeuralType`` class. When you instantiate an instance of this class, you +are expected to include both *axes* information and *element type* information. + +.. autoclass:: nemo.core.neural_types.NeuralType + :noindex: + +Type Comparison Results +----------------------- + +When comparing two neural types, the following comparison results are generated. + +.. autoclass:: nemo.core.neural_types.NeuralTypeComparisonResult + :noindex: + +Examples +-------- + +Long vs short notation +~~~~~~~~~~~~~~~~~~~~~~ + +NeMo's ``NeuralType`` class allows you to express axis semantics information in long and short form. Consider these two equivalent types. Both encoder 3 dimensional tensors and both contain elements of type ``AcousticEncodedRepresentation`` (this type is a typical output of ASR encoders). + +.. code-block:: python + + long_version = NeuralType( + axes=(AxisType(AxisKind.Batch, None), AxisType(AxisKind.Dimension, None), AxisType(AxisKind.Time, None)), + elements_type=AcousticEncodedRepresentation(), + ) + short_version = NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()) + assert long_version.compare(short_version) == NeuralTypeComparisonResult.SAME + +Transpose same +~~~~~~~~~~~~~~ + +Often it is useful to know if a simple transposition will solve type incompatibility. This is the case if the comparison result of two types equals ``nemo.core.neural_types.NeuralTypeComparisonResult.TRANSPOSE_SAME``. + +.. code-block:: python + + type1 = NeuralType(axes=('B', 'T', 'C')) + type2 = NeuralType(axes=('T', 'B', 'C')) + assert type1.compare(type2) == NeuralTypeComparisonResult.TRANSPOSE_SAME + assert type2.compare(type1) == NeuralTypeComparisonResult.TRANSPOSE_SAME + +Note that in this example, we dropped ``elements_type`` argument of ``NeuralType`` constructor. If not supplied, the element type is ``VoidType``. + +``VoidType`` for elements +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Sometimes it is useful to express that elements' types don't matter but axes layout do. ``VoidType`` for elements can be used to express this. + +.. note:: ``VoidType`` is compatible with every other elements' type but not the other way around. See the following code snippet below for details. + +.. code-block:: python + + btc_spctr = NeuralType(('B', 'T', 'C'), SpectrogramType()) + btc_spct_bad = NeuralType(('B', 'T'), SpectrogramType()) + # Note the VoidType for elements here + btc_void = NeuralType(('B', 'T', 'C'), VoidType()) + + # This is true because VoidType is compatible with every other element type (SpectrogramType in this case) + # And axes layout between btc_void and btc_spctr is the same + assert btc_void.compare(btc_spctr) == NeuralTypeComparisonResult.SAME + # These two types are incompatible because even though VoidType is used for elements on one side, + # the axes layout is different + assert btc_void.compare(btc_spct_bad) == NeuralTypeComparisonResult.INCOMPATIBLE + # Note that even though VoidType is compatible with every other type, other types are not compatible with VoidType! + # It is one-way compatibility + assert btc_spctr.compare(btc_void) == NeuralTypeComparisonResult.INCOMPATIBLE + +Element type inheritance +~~~~~~~~~~~~~~~~~~~~~~~~ + +Neural types in NeMo support Python inheritance between element types. Consider an example where you want to develop a Neural Module which performs data augmentation for all kinds of spectrograms. +In ASR, two types of spectrograms are frequently used: mel and mfcc. To express this, we will create 3 classes to express +element's types: ``SpectrogramType``, ``MelSpectrogramType(SpectrogramType)``, ``MFCCSpectrogramType(SpectrogramType)``. + +.. code-block:: python + + input = NeuralType(('B', 'D', 'T'), SpectrogramType()) + out1 = NeuralType(('B', 'D', 'T'), MelSpectrogramType()) + out2 = NeuralType(('B', 'D', 'T'), MFCCSpectrogramType()) + + # MelSpectrogram and MFCCSpectrogram are not interchangeable. + assert out1.compare(out2) == NeuralTypeComparisonResult.INCOMPATIBLE + assert out2.compare(out1) == NeuralTypeComparisonResult.INCOMPATIBLE + # Type comparison detects that MFCC/MelSpectrogramType is a kind of SpectrogramType and can be accepted. + assert input.compare(out1) == NeuralTypeComparisonResult.GREATER + assert input.compare(out2) == NeuralTypeComparisonResult.GREATER + +Custom element types +~~~~~~~~~~~~~~~~~~~~ + +It is possible to create user-defined element types to express the semantics of elements in your tensors. To do so, the user will need to inherit and implement abstract methods of the ``nemo.core.neural_types.elements.ElementType`` class + +.. autoclass:: nemo.core.neural_types.elements.ElementType + :noindex: + +Note that element types can be parametrized. Consider this example where it distinguishes between audio sampled at 8Khz and 16Khz. + +.. code-block:: python + + audio16K = NeuralType(axes=('B', 'T'), elements_type=AudioSignal(16000)) + audio8K = NeuralType(axes=('B', 'T'), elements_type=AudioSignal(8000)) + + assert audio8K.compare(audio16K) == NeuralTypeComparisonResult.SAME_TYPE_INCOMPATIBLE_PARAMS + assert audio16K.compare(audio8K) == NeuralTypeComparisonResult.SAME_TYPE_INCOMPATIBLE_PARAMS + +Enforcing dimensions +~~~~~~~~~~~~~~~~~~~~ + +In addition to specifying tensor layout and elements' semantics, neural types also allow you to enforce tensor dimensions. +The user will have to use long notations to specify dimensions. Short notations only allows you to specify axes semantics and assumes +arbitrary dimensions. + +.. code-block:: python + + type1 = NeuralType( + (AxisType(AxisKind.Batch, 64), AxisType(AxisKind.Time, 10), AxisType(AxisKind.Dimension, 128)), + SpectrogramType(), + ) + type2 = NeuralType(('B', 'T', 'C'), SpectrogramType()) + + # type2 will accept elements of type1 because their axes semantics match and type2 does not care about dimensions + assert type2.compare(type1), NeuralTypeComparisonResult.SAME + # type1 will not accept elements of type2 because it need dimensions to match strictly. + assert type1.compare(type2), NeuralTypeComparisonResult.DIM_INCOMPATIBLE + +Generic Axis kind +~~~~~~~~~~~~~~~~~ + +Sometimes (especially in the case of loss modules) it is useful to be able to specify a "generic" axis kind which will make it +compatible with any other kind of axis. This is easy to express with Neural Types by using ``nemo.core.neural_types.axes.AxisKind.Any`` for axes. + +.. code-block:: python + + type1 = NeuralType(('B', 'Any', 'Any'), SpectrogramType()) + type2 = NeuralType(('B', 'T', 'C'), SpectrogramType()) + type3 = NeuralType(('B', 'C', 'T'), SpectrogramType()) + + # type1 will accept elements of type2 and type3 because it only cares about element kind (SpectrogramType) + # number of axes (3) and that first one corresponds to batch + assert type1.compare(type2) == NeuralTypeComparisonResult.SAME + assert type1.compare(type3) == NeuralTypeComparisonResult.INCOMPATIBLE + +Container types +~~~~~~~~~~~~~~~ + +The NeMo-type system understands Python containers (lists). If your module returns a nested list of typed tensors, the way to express it is by +using Python list notation and Neural Types together when defining your input/output types. + +The example below shows how to express that your module returns single output ("out") which is list of lists of two dimensional tensors of shape ``[batch, dimension]`` containing logits. + +.. code-block:: python + + @property + def output_types(self): + return { + "out": [[NeuralType(('B', 'D'), LogitsType())]], + } diff --git a/docs/source/core/whyntypes.gif b/docs/source/core/whyntypes.gif new file mode 100644 index 0000000000000000000000000000000000000000..9d3f4c2f48b859dc8c2dbc2282be36adc3aad428 --- /dev/null +++ b/docs/source/core/whyntypes.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8270599f9b83b0bba0ada1ffb43cf6946bbde86979b514c017cd2a2b0eb9b938 +size 309073 diff --git a/docs/source/favicon.ico b/docs/source/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..424df87200c706460f9ad1c7722ef0d35f286f2b Binary files /dev/null and b/docs/source/favicon.ico differ diff --git a/docs/source/features/mixed_precision.rst b/docs/source/features/mixed_precision.rst new file mode 100644 index 0000000000000000000000000000000000000000..0d2c7be8bb9a51d41bc900dc316df38e927bdd28 --- /dev/null +++ b/docs/source/features/mixed_precision.rst @@ -0,0 +1,96 @@ +.. _mix_precision: + +Mixed Precision Training +======================== + +Mixed precision training enhances computational efficiency by conducting operations in low-precision +format while selectively maintaining critical data in single-precision. NeMo supports FP16 and BF16 +precision via PyTorch Lightning, in both mixed and true half-precision modes. + +Precision Modes +--------------- + +PyTorch Lightning provides two categories of half-precision training: + +**Mixed Precision** (``"bf16-mixed"`` / ``"16-mixed"``): + Operations run in half-precision where safe, but model weights are kept in FP32. + Gradients are computed in half-precision and accumulated in FP32. This is the safest + option and generally a good default for ASR and TTS training. + +**True Half Precision** (``"bf16-true"`` / ``"fp16-true"``): + The entire model -- weights, activations, and gradients -- runs in half-precision. + This uses less memory than mixed precision (no FP32 weight copy) and is faster, + but requires the model to be numerically stable in half-precision. + SpeechLM2 models use ``"bf16-true"`` by default for training. + +Configuration +------------- + +Set precision through the PyTorch Lightning trainer's ``precision`` argument. + +In YAML (with Hydra): + +.. code-block:: yaml + + trainer: + precision: "bf16-mixed" # BF16 mixed precision + # precision: "16-mixed" # FP16 mixed precision + # precision: "bf16-true" # True BF16 half precision + # precision: "fp16-true" # True FP16 half precision + +In Python: + +.. code-block:: python + + import lightning.pytorch as pl + + trainer = pl.Trainer( + precision="bf16-mixed", + devices=2, + accelerator="gpu", + ) + +Choosing a Precision Format +---------------------------- + +- **BF16** has the same dynamic range as FP32, which makes it more numerically stable and generally + easier to use. It is the recommended choice for most Speech AI training workloads. +- **FP16** offers slightly higher throughput on some hardware but has a reduced dynamic range. + In mixed precision mode, PyTorch Lightning handles loss scaling automatically. + +HalfPrecisionForAudio +---------------------- + +Audio waveform tensors are sensitive to precision loss -- downcasting raw audio samples to half-precision +can degrade signal quality and hurt model accuracy. NeMo provides the ``HalfPrecisionForAudio`` plugin +(in ``nemo.utils.trainer_utils``) that extends Lightning's ``HalfPrecision`` plugin to preserve +full-precision for audio tensors while still casting all other inputs to half-precision. + +Specifically, when the training mini-batch is a dictionary, any tensor whose key contains +the substring ``"audio"`` is kept in its original precision (typically FP32). All other floating-point +tensors are cast to the target half-precision dtype. + +This plugin is used automatically when you launch training with NeMo's ``resolve_trainer_cfg`` +utility (used by all NeMo example training scripts). When the trainer config specifies +``precision: "bf16-true"`` or ``precision: "fp16-true"``, ``resolve_trainer_cfg`` replaces +the precision setting with the ``HalfPrecisionForAudio`` plugin: + +.. code-block:: python + + from nemo.utils.trainer_utils import resolve_trainer_cfg + + # In YAML: trainer.precision = "bf16-true" + # resolve_trainer_cfg automatically installs HalfPrecisionForAudio + trainer = pl.Trainer(**resolve_trainer_cfg(cfg.trainer)) + +If you construct the trainer manually, you can install the plugin directly: + +.. code-block:: python + + from nemo.utils.trainer_utils import HalfPrecisionForAudio + + trainer = pl.Trainer( + plugins=[HalfPrecisionForAudio("bf16-true")], + devices=2, + accelerator="gpu", + ) diff --git a/docs/source/features/parallelisms.rst b/docs/source/features/parallelisms.rst new file mode 100644 index 0000000000000000000000000000000000000000..013e56141ab74bd995fb87bdf0f06485f070430a --- /dev/null +++ b/docs/source/features/parallelisms.rst @@ -0,0 +1,150 @@ +.. _parallelisms: + +Parallelisms +============ + +NeMo uses native PyTorch parallelism primitives for distributed training, enabling efficient multi-GPU and multi-node +model training for Speech AI workloads. + +DDP (all collections) +--------------------- + +Distributed Data Parallelism (DDP) is the default strategy for all NeMo collections (ASR, TTS, Audio, SpeechLM2). +It replicates the entire model on every GPU, runs each GPU on a different data shard, and synchronizes +parameter gradients via all-reduce after each backward pass. + +**When to use:** DDP works well when the full model fits in a single GPU's memory. +This covers the vast majority of ASR, TTS, and Audio training workloads. + +DDP is enabled by default in NeMo. You can configure it explicitly in YAML: + +.. code-block:: yaml + + trainer: + strategy: + _target_: lightning.pytorch.strategies.DDPStrategy + gradient_as_bucket_view: true + find_unused_parameters: true + +Or in Python: + +.. code-block:: python + + from lightning.pytorch.strategies import DDPStrategy + + trainer = pl.Trainer( + strategy=DDPStrategy(gradient_as_bucket_view=True, find_unused_parameters=True), + devices=8, + accelerator="gpu", + ) + +ModelParallelStrategy (SpeechLM2) +--------------------------------- + +For SpeechLM2 models (e.g. SALM / Canary-Qwen), the backbone LLM can be too large for a single GPU. +PyTorch Lightning's ``ModelParallelStrategy`` enables FSDP2, Tensor Parallelism (TP), and +Sequence Parallelism (SP) using PyTorch-native DTensor. + +**When to use:** When training or fine-tuning SpeechLM2 models whose LLM backbone does not fit +in a single GPU's memory, or when you want to scale training to many GPUs more efficiently +than DDP allows. + +**Requirements:** Each model must implement a ``configure_model()`` method that defines how its +layers are sharded (FSDP2) and parallelized (TP / SP). The SpeechLM2 models (SALM, DuplexEARTTS) +already implement this. You cannot simply switch an arbitrary model from DDP to +``ModelParallelStrategy`` without providing this implementation. + +Concepts +^^^^^^^^ + +**FSDP2 (Fully Sharded Data Parallelism):** + Shards model parameters, gradients, and optimizer states across GPUs in the data-parallel + dimension. Dramatically reduces per-GPU memory -- enabling training of models that would not + fit with DDP. Controlled via the ``data_parallel_size`` argument. + +**Tensor Parallelism (TP):** + Splits individual weight matrices across GPUs. For example, a large linear layer's weight + is partitioned column-wise or row-wise so each GPU holds only a slice. Controlled via the + ``tensor_parallel_size`` argument. The model must define a TP sharding plan (which layers + are split and how). SpeechLM2 models automatically use the HuggingFace TP plan for the + backbone LLM when available. + +**Sequence Parallelism (SP):** + Distributes activation memory along the sequence dimension across the TP group. + SP is typically enabled alongside TP and reduces activation memory further. + +Configuration +^^^^^^^^^^^^^ + +To enable ``ModelParallelStrategy`` for SpeechLM2, replace the DDP strategy block in the +trainer config. The product of ``data_parallel_size`` and ``tensor_parallel_size`` must equal +the total number of GPUs (``devices * num_nodes``). + +In YAML (with Hydra): + +.. code-block:: yaml + + trainer: + devices: 8 + num_nodes: 1 + accelerator: gpu + precision: bf16-true + strategy: + _target_: lightning.pytorch.strategies.ModelParallelStrategy + data_parallel_size: 4 # FSDP2: shard across 4 GPUs + tensor_parallel_size: 2 # TP: split layers across 2 GPUs + +In Python: + +.. code-block:: python + + from lightning.pytorch.strategies import ModelParallelStrategy + + trainer = pl.Trainer( + strategy=ModelParallelStrategy( + data_parallel_size=4, + tensor_parallel_size=2, + ), + devices=8, + accelerator="gpu", + precision="bf16-true", + use_distributed_sampler=False, + ) + +.. note:: + + When using ``ModelParallelStrategy``, set ``use_distributed_sampler=False`` in the trainer. + NeMo's data modules handle distributed sampling internally. + +Example: SALM with FSDP2 only (no TP) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The simplest ``ModelParallelStrategy`` setup uses FSDP2 alone. This requires no TP plan +and works when individual layers fit in GPU memory: + +.. code-block:: yaml + + trainer: + devices: 8 + strategy: + _target_: lightning.pytorch.strategies.ModelParallelStrategy + data_parallel_size: 8 + tensor_parallel_size: 1 + +Example: SALM with TP + FSDP2 +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For larger LLM backbones, combine TP with FSDP2. Here, 2-way TP splits each layer across +2 GPUs within a node, and 4-way FSDP2 shards the model across 4 such groups: + +.. code-block:: yaml + + trainer: + devices: 8 + strategy: + _target_: lightning.pytorch.strategies.ModelParallelStrategy + data_parallel_size: 4 + tensor_parallel_size: 2 + +See the SpeechLM2 example configs in ``examples/speechlm2/conf/`` for complete training +configurations including data and optimizer settings. diff --git a/docs/source/index.rst b/docs/source/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..235fea0ee4b701b969650dc6c880ddd40e777a8d --- /dev/null +++ b/docs/source/index.rst @@ -0,0 +1,122 @@ +NVIDIA NeMo Speech Developer Docs +================================= + +`NVIDIA NeMo Speech `_ is an open-source toolkit for speech, audio, and multimodal language model research, with a clear path from experimentation to production deployment. + +.. raw:: html + + + + + + +What is NeMo? +-------------- + +`NVIDIA NeMo `_ is an open-source toolkit for building, customizing, and deploying speech, audio, and multimodal language models. It provides: + +- **Pretrained models** — production-ready checkpoints on `NGC `__ and `HuggingFace Hub `__ +- **Modular architecture** — neural modules you can mix, match, and extend +- **Scalable training** — multi-GPU/multi-node via PyTorch Lightning with mixed-precision support +- **Simple configuration** — YAML-based experiment configs with `Hydra `__ + +Get started in 30 seconds: + +.. code-block:: bash + + pip install nemo_toolkit[asr,tts] + +.. code-block:: python + + import nemo.collections.asr as nemo_asr + model = nemo_asr.models.ASRModel.from_pretrained("nvidia/parakeet-tdt-0.6b-v2") + print(model.transcribe(["audio.wav"])[0].text) + + +.. toctree:: + :maxdepth: 1 + :caption: Getting Started + :name: starthere + + starthere/install + starthere/ten_minutes + starthere/key_concepts + starthere/choosing_a_model + starthere/tutorials + + +.. toctree:: + :maxdepth: 1 + :caption: Training + :name: Training + + features/parallelisms + features/mixed_precision + +.. toctree:: + :maxdepth: 1 + :caption: Model Checkpoints + :name: Checkpoints + + checkpoints/intro + +.. toctree:: + :maxdepth: 1 + :caption: APIs + :name: APIs + :titlesonly: + + apis + +.. toctree:: + :maxdepth: 1 + :caption: Collections + :name: Collections + :titlesonly: + + collections + +.. toctree:: + :maxdepth: 1 + :caption: Speech AI Tools + :name: Speech AI Tools + :titlesonly: + + tools/intro diff --git a/docs/source/nv_logo.png b/docs/source/nv_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..5546c1b57d8e3f0ba39fc988fceaa12541af5020 --- /dev/null +++ b/docs/source/nv_logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17a25111e145aa52b77ec5a89eb3b0c7d9a2a90dea25a0bb867a937514fc783c +size 63541 diff --git a/docs/source/project.json b/docs/source/project.json new file mode 100644 index 0000000000000000000000000000000000000000..d6625d68a54c12eef408ec566c3640ab4644aeea --- /dev/null +++ b/docs/source/project.json @@ -0,0 +1,4 @@ +{ + "name": "NeMo-Speech", + "version": "nightly" +} diff --git a/docs/source/speechlm2/configs.rst b/docs/source/speechlm2/configs.rst new file mode 100644 index 0000000000000000000000000000000000000000..56b6e4ac3327a826358d0d17db92240b9fe45c9d --- /dev/null +++ b/docs/source/speechlm2/configs.rst @@ -0,0 +1,319 @@ +Configuration Files +=================== + +The SpeechLM2 models use YAML configuration files to define model architecture, training parameters, and data settings. +This page describes the configuration structure and important parameters for each model type in the collection. + +Configuration Structure +----------------------- + +SpeechLM2 configuration files typically have the following high-level structure: + +.. code-block:: yaml + + model: + # Model architecture settings + ... + + trainer: + # PyTorch Lightning trainer settings + ... + + exp_manager: + # Experiment logging settings + ... + + data: + # Dataset settings + ... + +SALM Configuration +------------------ + +The SALM (Speech-Augmented Language Model) configuration includes settings for the pretrained LLM, audio perception module, and training parameters. +See the `SALM paper `_ for more details. + +.. code-block:: yaml + + model: + # Pretrained model paths + pretrained_llm: "TinyLlama/TinyLlama_v1.1" # HF model path + pretrained_asr: "stt_en_fastconformer_hybrid_large_streaming_80ms" # NeMo checkpoint name + pretrained_weights: True # Whether to load weights or just architecture + + # Special token settings + audio_locator_tag: "