{"record":{"id":"86a484c0ca930907","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"illegal-stride-value-86a484","errorCode":null,"errorMessage":"illegal stride value.","messagePattern":"illegal stride value\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_classification/Test7_shufflenet/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/Test7_shufflenet/model.py#L12-L48","documentation":"ShuffleNetV2's InvertedResidual block validates that stride is 1 or 2 and raises ValueError otherwise. Only these strides are implemented: stride 2 uses the split/concat with downsampling branch; stride 1 relies on channel-split residual connections.","triggerScenarios":"Instantiating InvertedResidual(input_c, output_c, stride) with stride = 3, 0, -1, etc., usually via a custom stages_repeats/stages_out_channels architecture or a hand-modified layer list passed to ShuffleNetV2.","commonSituations":"Users editing the model to add stronger downsampling; adapting code from other networks (e.g. ResNet which supports stride 4 in deeper blocks) and reusing stride values not supported here.","solutions":["Use stride=1 or stride=2 for every InvertedResidual in the network.","Chain multiple stride-2 stages instead of a single larger-stride layer.","Keep the standard presets (0.5x/1.0x/1.5x/2.0x) that hard-code legal strides in _stage."],"exampleFix":"// before\nlayers += [InvertedResidual(24, 116, stride=3)]\n// after\nlayers += [InvertedResidual(24, 116, stride=2)]","handlingStrategy":"validation","validationCode":"for layer in my_layers:\n    if isinstance(layer, InvertedResidual) and layer.stride not in (1, 2):\n        raise ValueError(f\"bad stride {layer.stride} for ShuffleNetV2 block\")","typeGuard":"def legal_shufflenet_stride(s: int) -> bool:\n    return s in (1, 2)","tryCatchPattern":"try:\n    block = InvertedResidual(input_c, output_c, stride)\nexcept ValueError as e:\n    if \"illegal stride\" in str(e):\n        block = InvertedResidual(input_c, output_c, 2 if stride > 1 else 1)\n    else:\n        raise","preventionTips":["Hard-code stride as 1 or 2 in any custom stage builder.","Reuse the preset _stage construction instead of hand-writing blocks.","Test custom architectures with a single forward pass of dummy input."],"tags":["pytorch","shufflenetv2","valueerror","stride"],"backgroundTag":"illegal-stride-value","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}