Skip to content

Derive Conv*Subsampling masks from per-utterance lengths - #6633

Merged
sw005320 merged 1 commit into
espnet:masterfrom
modelpath-dev:fix/6600-subsampling-mask-olens
Sep 11, 2026
Merged

sw005320 merged 1 commit into
espnet:masterfrom
modelpath-dev:fix/6600-subsampling-mask-olens

Conversation

@modelpath-dev

@modelpath-dev modelpath-dev commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

What did you change?

Conv*Subsampling used to shrink the pad mask by slicing from the end of the padded batch (x_mask[:, :, :-2:1][:, :, :-2:2], and the same pattern in the other seven classes). That makes olens for a given utterance depend on the longest row.

The mask is now rebuilt from each row's own input length using the convolution length formula. All eight classes go through one helper. Encoders already do olens = masks.sum(1), so they pick this up without further changes.

The longest utterance in a batch is unchanged; that path already matched the formula. A shorter one now matches the length it has when decoded alone.

Why did you make this change?

Filed as #6600 after #6599. With batched beam search, --batch_size > 1 cannot reproduce --batch_size 1 because the encoder itself disagrees about how long the output is.

The issue's snippet, input_layer="conv1d2":

feats_lengths olens before olens after
288 alone [142] [142]
[363, 288] [180, 144] [180, 142]
[288, 288] [142, 142] [142, 142]

This will move training and decode for shorter utterances in a mixed-length batch by a frame or two. Length-bucketed recipes (batch_type: sorted / folded) barely see it. Published numbers from --batch_size 1 are unaffected. I think that is the right trade: olens is a function of ilens again.

Fixes #6600.

Is your PR small enough?

Yes. Two files.

Additional Context

test/espnet2/legacy/test_subsampling.py now checks, for every Conv* class, that a 288-frame utterance has the same olens alone, next to a 363-frame one, and next to a copy of itself. The Conv1dSubsampling2 case pins the numbers from the issue. A second test runs the encoder snippet from #6600.

pytest test/espnet2/legacy/test_subsampling.py

Slicing the padded batch mask from the end made a short utterance
report a different length depending on its batch mates (espnet#6600).

Co-authored-by: Cursor <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: QUIET

Plan: Team

Run ID: 5123b058-1143-4ffe-b5ec-a4afc51f5d2c

📥 Commits

Reviewing files that changed from the base of the PR and between 322d199 and f545c8b.

📒 Files selected for processing (2)
  • espnet2/legacy/nets/pytorch_backend/transformer/subsampling.py
  • test/espnet2/legacy/test_subsampling.py

Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The change adds shared helpers for convolution-derived output lengths and per-utterance mask reconstruction. All supported 1D and 2D subsampling classes use these helpers instead of fixed padded-batch slicing. Tests verify batch-independent output lengths, issue 6600 behavior, and convolution-length consistency across subsampling classes.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Merge Risk: ⚪ Minimal · up to f545c

Subsampling output lengths now depend on each utterance’s input length rather than batch padding, making mixed-batch and single-utterance behavior consistent. The affected subsampling variants and encoder regression case are covered, with no remaining merge-blocking risk identified.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address issue #6600 by rebuilding masks from each utterance's convolution-derived length across all eight Conv*Subsampling classes. The tests cover batch independence and the reported Tran…
Out of Scope Changes check ✅ Passed The implementation and regression tests are limited to the linked issue objective. No unrelated code or behavior changes are identified.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 2 files.
Title check ✅ Passed The title clearly and concisely describes the main change: deriving Conv*Subsampling masks from per-utterance input lengths.
Description check ✅ Passed The description accurately explains the batch-dependent length issue, the per-utterance convolution-length fix, the expected behavior changes, and the regression tests.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@codecov

codecov Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 71.61%. Comparing base (2f6c338) to head (f545c8b).
⚠️ Report is 5 commits behind head on master.

Files with missing lines Patch % Lines
...cy/nets/pytorch_backend/transformer/subsampling.py 95.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6633      +/-   ##
==========================================
+ Coverage   71.43%   71.61%   +0.17%     
==========================================
  Files         827      834       +7     
  Lines       78253    78789     +536     
==========================================
+ Hits        55902    56425     +523     
- Misses      22351    22364      +13     
Flag Coverage Δ
test_configuration_espnet2 26.86% <10.00%> (?)
test_integration_espnet2 47.27% <65.00%> (+0.02%) ⬆️
test_integration_espnet3 33.11% <60.00%> (?)
test_python_espnet2 60.12% <95.00%> (+0.01%) ⬆️
test_python_espnet3 20.08% <10.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sw005320 sw005320 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @modelpath-dev — the diagnosis is right and the fix is the correct shape: rebuilding the mask from each row's own length instead of slicing the padded batch makes olens a function of ilens again, and routing all eight classes through one helper is better than eight near-identical edits. The test that checks 288-alone against 288-next-to-363 against 288-next-to-288 is exactly the right assertion. I also agree with the trade-off call in the description — a frame or two of movement for short utterances in mixed-length batches is worth olens being well-defined.

There is a ninth class with the same bug, in a sibling file, and it is live.

espnet2/legacy/nets/pytorch_backend/transformer/subsampling_without_posenc.py:60-61:

for k, s in zip(self.kernels, self.strides):
    x_mask = x_mask[:, :, : -k + 1 : s]

Same construction: the slice bound is relative to the padded batch length, so the surviving count depends on the longest row. For kernels=[3, 3], strides=[2, 2] this expands to x_mask[:, :, :-2:2][:, :, :-2:2] — character-for-character what Conv2dSubsampling does at line 453 of the file you are fixing.

I reproduced it with the three configurations the encoders actually construct:

input_layer kernels / strides 288 alone 288 padded to 363 conv formula
conv2d [3,3] / [2,2] 71 72 71
conv2d6 [3,5] / [2,3] 47 48 47
conv2d8 [3,3,3] / [2,2,2] 35 36 35

Same one-frame overshoot as the conv1d2 case in #6600.

This is not dead code. Conv2dSubsamplingWOPosEnc is the embed layer for both streaming encoders:

  • espnet2/asr/encoder/contextual_block_transformer_encoder.py:108,113,118
  • espnet2/asr/encoder/contextual_block_conformer_encoder.py:113,118,123

and both derive lengths the way your description assumes — olens = masks.squeeze(1).sum(1), at contextual_block_transformer_encoder.py:251,365 and contextual_block_conformer_encoder.py:269,383. So they inherit the bug today and would inherit the fix for free, exactly like the encoders you already covered.

Worth folding into this PR rather than a follow-up, I think. The class takes kernels and strides as constructor arguments rather than hard-coding them, so it should drop straight into the same helper — arguably more cleanly than the eight fixed-geometry classes, since the loop already has (k, s) in hand. A test row for at least the conv2d config would keep it honest.

Also checked and clean: RNNP in espnet2/legacy/nets/pytorch_backend/rnn/encoders.py:85 computes ilens = [int(i + 1) // sub for i in ilens] per row, so it never depended on the batch maximum. A repository-wide search for stride-slicing of masks ([:, :, :-N:M]) turns up only subsampling.py and subsampling_without_posenc.py, so with that second file this should be the complete set.

@sw005320 sw005320 added this to the v.202612 milestone Sep 7, 2026
@sw005320 sw005320 added Bugfix ASR Automatic speech recogntion labels Sep 7, 2026
@sw005320
sw005320 merged commit 0b3b12b into espnet:master Sep 11, 2026
137 checks passed
sw005320 added a commit that referenced this pull request Sep 11, 2026
An utterance encoded next to a longer one did not come out the same as when
encoded alone, even with #6633 fixing the subsampled lengths. The reason is
every convolution that runs along time inside the encoder blocks: the
depthwise convolution of the conformer convolution module, the convolution
of cgMLP's spatial gating unit, the merge convolution of E-Branchformer and
the per-kernel and fusion convolutions of the multi-convolution cgMLP. Their
kernels reach past the last real frame into the padding, and the padding is
not zero there: the pointwise convolution and GLU, or the LayerNorm, that
precede them have already written their biases into it. The last few real
frames therefore change, and one attention layer later so does every frame.

The non-padding mask that every encoder layer already holds is now handed
down to those modules, which zero the padded time steps right before the
convolution (`mask_padded_frames`). Masking the module input instead would
not work, for the reason above. A mask whose time axis does not match, such
as the single-frame query of a cached step, is ignored. A custom convolution
module handed to the conformer `EncoderLayer` without the argument is still
called as before.

With #6633 (on which this is based) the conformer, E-Branchformer,
Branchformer and all four multi-convolution cgMLP variants now encode a
padded utterance identically to the utterance alone, to float rounding. The
legacy relative-position attention remains dependent on the padded length,
which is a property of those models; a test pins that so it is not read as a
regression.

Real data: the AISHELL-1 conformer (legacy rel_pos) decoded with the batched
beam search, 50 test utterances, batch 4 against batch 1 (CER 7.03%): master
7.57% with 43 transcripts identical, #6633 alone unchanged, #6633 with this
change 7.16% and 49 of 50 identical.

Training sees the same change for the padded rows of a mixed-length batch;
the longest utterance of a batch and anything decoded alone are untouched.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@modelpath-dev

Copy link
Copy Markdown
Contributor Author

@sw005320
Shinji, you merged 6633 and asked for the ninth class in subsampling_without_posenc.py. I'll land that next. The 6660 table already showed olens was necessary and not sufficient.

@modelpath-dev

modelpath-dev commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@sw005320 Ninth class is up in https://github.com/espnet/espnet/pull/6670
Same helper, with the conv2d / conv2d6 / conv2d8 rows from your review.

@sw005320 sw005320 modified the milestones: v.202612, v.202610 Sep 19, 2026
mergify Bot pushed a commit that referenced this pull request Sep 19, 2026
The ninth class still reports a different length next to a longer
utterance. Lock the 288/363 numbers from the #6633 review.
mergify Bot pushed a commit that referenced this pull request Sep 19, 2026
Slicing the padded mask from the end made olens depend on batch mates.
Route the class through the same _subsample_mask helper as #6633.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ASR Automatic speech recogntion Bugfix ESPnet2

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Encoder output length depends on the longest utterance in the batch (Conv*Subsampling mask slicing)

2 participants