hankcs/HanLP · error · ValueError

Unsupported dim: {x.dim()}. Only 2d (T,C) or 3d (B,T,C) is s

Error message

Unsupported dim: {x.dim()}. Only 2d (T,C) or 3d (B,T,C) is supported

What it means

HanLP's custom dropout (spatial dropout over feature columns) only supports 2-D (T,C) or 3-D (B,T,C) tensors: for 3-D it samples a per-feature mask broadcast over timesteps, for 2-D a plain elementwise mask. Any other rank is rejected because the masking scheme (masking whole channels) is undefined there.

Source

Thrown at hanlp/layers/dropout.py:158

        return items


class LockedDropout(nn.Module):
    def __init__(self, dropout_rate=0.5):
        super(LockedDropout, self).__init__()
        self.dropout_rate = dropout_rate

    def forward(self, x):
        if not self.training or not self.dropout_rate:
            return x

        if x.dim() == 3:
            mask = x.new(x.size(0), 1, x.size(2)).bernoulli_(1 - self.dropout_rate) / (1 - self.dropout_rate)
            mask = mask.expand_as(x)
        elif x.dim() == 2:
            mask = torch.empty_like(x).bernoulli_(1 - self.dropout_rate) / (1 - self.dropout_rate)
        else:
            raise ValueError(f'Unsupported dim: {x.dim()}. Only 2d (T,C) or 3d (B,T,C) is supported')
        return mask * x

View on GitHub (pinned to ddb1299bdd)

Solutions

  1. Reshape input to (B,T,C) or (T,C) before this dropout
  2. For 4-D conv activations, use nn.Dropout2d / standard Dropout instead
  3. Move the dropout after a view/reshape that yields 2-D or 3-D

Example fix

# before
y = dropout(x)  # x is (B, C, H, W) -> error
# after
B, C, H, W = x.shape
y = dropout(x.permute(0,2,3,1).reshape(B, H*W, C)).reshape(B, H, W, C).permute(0,3,1,2)
Defensive patterns

Strategy: type-guard

Validate before calling

if x.dim() not in (2, 3):
    x = x.reshape(x.shape[0], -1, x.shape[-1])

Type guard

def dropout_supported(x: torch.Tensor) -> bool:
    return x.dim() in (2, 3)

Prevention

When it happens

Trigger: Calling this dropout module's forward on a 1-D vector, a 4-D tensor (e.g. conv feature maps), or a batched 4-D input from a CNN/transformer pipeline.

Common situations: Reusing the layer on image or audio tensors; applying it to flattened logits or scalars; inserting it before an unsqueeze/reshape that was expected but omitted.

Related errors


AI-assisted analysis of hankcs/HanLP@ddb1299bdd (2026-08-27). Data as JSON: /api/errors/0bce53882838db44. Report an issue: GitHub.