{"record":{"id":"60202a3d32286479","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"illegal-stride-value-60202a","errorCode":null,"errorMessage":"illegal stride value.","messagePattern":"illegal stride value\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_classification/mini_imagenet/model.py","lineNumber":30,"sourceCode":"\n    # reshape\n    # [batch_size, num_channels, height, width] -> [batch_size, groups, channels_per_group, height, width]\n    x = x.view(batch_size, groups, channels_per_group, height, width)\n\n    x = torch.transpose(x, 1, 2).contiguous()\n\n    # flatten\n    x = x.view(batch_size, -1, height, width)\n\n    return x\n\n\nclass InvertedResidual(nn.Module):\n    def __init__(self, input_c: int, output_c: int, stride: int):\n        super(InvertedResidual, self).__init__()\n\n        if stride not in [1, 2]:\n            raise ValueError(\"illegal stride value.\")\n        self.stride = stride\n\n        assert output_c % 2 == 0\n        branch_features = output_c // 2\n        # 当stride为1时，input_channel应该是branch_features的两倍\n        # python中 '<<' 是位运算，可理解为计算×2的快速方法\n        assert (self.stride != 1) or (input_c == branch_features << 1)\n\n        if self.stride == 2:\n            self.branch1 = nn.Sequential(\n                self.depthwise_conv(input_c, input_c, kernel_s=3, stride=self.stride, padding=1),\n                nn.BatchNorm2d(input_c),\n                nn.Conv2d(input_c, branch_features, kernel_size=1, stride=1, padding=0, bias=False),\n                nn.BatchNorm2d(branch_features),\n                nn.ReLU(inplace=True)\n            )\n        else:\n            self.branch1 = nn.Sequential()","sourceCodeStart":12,"sourceCodeEnd":48,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_classification/mini_imagenet/model.py#L12-L48","documentation":"The MiniResNet-style InvertedResidual in mini_imagenet/model.py supports only stride 1 and 2, since a stride-1 branch requires doubled input channels (branch_features doubling) and stride 2 implements downsampling. Any other stride passed to __init__ raises ValueError immediately when building the model.","triggerScenarios":"Constructing the backbone with a per-stage config (like ResNet's layer list) where a stride value of 3, 4, or 0 is passed as InvertedResidual(input_c, output_c, stride=...), e.g. from a mis-edited cfg list or copied ResNet config using [1,2,4,8].","commonSituations":"Adapting MobileNetV2 definitions with custom strides; typos in the stride list; reusing ResNet50 cfg arrays where later stages use larger strides in the config not meant for this block.","solutions":["Restrict every InvertedResidual stride to 1 or 2 (use 2 for the first block of each downsampling stage)","Clamp/validate the config before instantiation, e.g. stride = 2 if s > 1 else 1","If larger downsampling is needed, stack multiple stride-2 blocks or add explicit MaxPool/conv-stride layers"],"exampleFix":"// before\nlayers.append(InvertedResidual(input_c, output_c, stride=4))\n// after\nlayers.append(InvertedResidual(input_c, output_c, stride=2))  # repeat twice for 4x downsample","handlingStrategy":"validation","validationCode":"cfg = [(input_c, output_c, s) for (input_c, output_c, s) in cfg if s in (1, 2)]\nassert all(s in (1, 2) for _, _, s in cfg), 'stride must be 1 or 2'","typeGuard":"def valid_cfg(cfg) -> bool:\n    return all(s in (1, 2) for (_, _, s) in cfg)","tryCatchPattern":"try:\n    model = MobileNetV2(num_classes=100)\nexcept ValueError as e:\n    if 'illegal stride' in str(e):\n        print('Sanitize your stride config:', e)\n    raise","preventionTips":["Keep stride configuration separate from ResNet-style config arrays that use larger strides","Use stride 2 only at stage boundaries; rely on 1x1 convs elsewhere","Add a construction unit test with the default cfg before edits"],"tags":["pytorch","mobilenet","valueerror","stride"],"backgroundTag":"illegal-stride-value","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}