WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError

illegal stride value.

Error message

illegal stride value.

What it means

EfficientNetV2's MBConv block only supports strides 1 or 2 (needed for the residual shortcut / downsampling logic). The constructor raises ValueError if a stride outside {1,2} is passed. All block construction in model.py assumes this constraint.

Source

Thrown at tensorflow_classification/Test11_efficientnetV2/model.py:77

        se_tensor = self.se_reduce(se_tensor)
        se_tensor = self.se_expand(se_tensor)
        return se_tensor * inputs


class MBConv(layers.Layer):
    def __init__(self,
                 kernel_size: int,
                 input_c: int,
                 out_c: int,
                 expand_ratio: int,
                 stride: int,
                 se_ratio: float = 0.25,
                 drop_rate: float = 0.,
                 name: str = None):
        super(MBConv, self).__init__(name=name)

        if stride not in [1, 2]:
            raise ValueError("illegal stride value.")

        self.has_shortcut = (stride == 1 and input_c == out_c)
        expanded_c = input_c * expand_ratio

        bid = itertools.count(0)
        get_norm_name = lambda: 'batch_normalization' + ('' if not next(
            bid) else '_' + str(next(bid) // 2))
        cid = itertools.count(0)
        get_conv_name = lambda: 'conv2d' + ('' if not next(cid) else '_' + str(
            next(cid) // 2))

        # 在EfficientNetV2中,MBConv中不存在expansion=1的情况所以conv_pw肯定存在
        assert expand_ratio != 1
        # Point-wise expansion
        self.expand_conv = layers.Conv2D(
            filters=expanded_c,
            kernel_size=1,
            strides=1,

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Use only stride=1 or stride=2 in MBConv definitions
  2. Check positional argument order: (input_c, out_c, kernel_size, stride, expand_ratio, ...)
  3. If larger downsampling is needed, stack multiple stride-2 blocks instead

Example fix

// before
MBConv(24, 24, kernel_size=3, stride=3, expand_ratio=4)
// after
MBConv(24, 24, kernel_size=3, stride=2, expand_ratio=4)
Defensive patterns

Strategy: validation

Validate before calling

def build_mbconv(**cfg):
    assert cfg.get('stride', 1) in (1, 2), f"MBConv stride must be 1 or 2, got {cfg.get('stride')}"
    return MBConv(**cfg)

Type guard

def stride_valid(stride) -> bool:
    return isinstance(stride, int) and stride in (1, 2)

Try / catch

try:
    block = MBConv(input_c, out_c, kernel_size, stride, expand_ratio)
except ValueError as e:
    print(f"bad block config: {e}"); raise

Prevention

When it happens

Trigger: Building MBConv with stride=3, 0, or any non-{1,2} integer, typically from a hand-edited architecture config or wrong parameter order (e.g. passing expand_ratio positionally where stride is expected).

Common situations: Custom EfficientNetV2 configs copied from papers with stride-3 downsampling, positional-arg mistakes when instantiating MBConv, or editing the model variants dict with unsupported strides.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/8f5aa934f80a1e35. Report an issue: GitHub.