Skip to content

Fix StdScaler broadcasting with keepdim disabled - #3370

Draft
linjiaye929 wants to merge 1 commit into
awslabs:devfrom
linjiaye929:fix-stdscaler-reduction-broadcast
Draft

linjiaye929 wants to merge 1 commit into
awslabs:devfrom
linjiaye929:fix-stdscaler-reduction-broadcast

Conversation

@linjiaye929

Copy link
Copy Markdown

Issue #, if available: No existing issue found for this broadcasting defect.

Description of changes:

StdScaler defaults to keepdim=False, but its reduced loc and scale are subtracted/divided directly into unreduced data. For a (2, 3) input this raises a size-mismatch error; square inputs silently broadcast along the wrong axis and compute an incorrect variance.

import torch
from gluonts.torch.scaler import StdScaler
x = torch.tensor([[1., 3., 5.], [10., 14., 18.]])
StdScaler()(x, torch.ones_like(x))

Keep the reduction dimension internally for weighted centering, variance and normalization, then squeeze only returned loc and scale when requested. The keepdim=True behavior used by built-in model callers is preserved, as are float64 variance accumulation, output dtype and minimum scale.

Regression tests cover rectangular and square inputs, partial observations, float32/float64, positive/negative reduction axes and multivariate inputs. The original implementation fails the rectangular/default and silent square cases.

Validation on Python 3.12.14, PyTorch 2.10.0+cpu:

  • scaler tests: 26 passed;
  • entire torch CPU suite: 590 passed (GPU-only test file explicitly excluded);
  • Black, Ruff and git diff whitespace checks passed;
  • an independent AI review checked the change and tests.

CUDA, the full dependency/Python matrix, non-torch tests and upstream CI have not been verified. This is a draft for review, not a claim of CI approval.

AI disclosure: this fix, tests and explanation were prepared and checked with an OpenAI AI coding assistant.

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Requested release label: bug fix

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant