{"record":{"id":"7934fbb665988db8","repo":"open-mmlab/mmdetection","slug":"the-last-dim-of-cls-scores-should-equal-to-num","errorCode":null,"errorMessage":"The last dim of `cls_scores` should equal to `num_classes` or `num_classes + 1`,but got {}.","messagePattern":"The last dim of `cls_scores` should equal to `num_classes` or `num_classes \\+ 1`,but got (.+?)\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"mmdet/models/roi_heads/bbox_heads/bbox_head.py","lineNumber":648,"sourceCode":"            ...                                  batch_img_metas)\n            >>> print(bboxes_list)\n        \"\"\"\n        pos_is_gts = [res.pos_is_gt for res in sampling_results]\n        # bbox_targets is a tuple\n        labels = bbox_results['bbox_targets'][0]\n        cls_scores = bbox_results['cls_score']\n        rois = bbox_results['rois']\n        bbox_preds = bbox_results['bbox_pred']\n        if self.custom_activation:\n            # TODO: Create a SeasawBBoxHead to simplified logic in BBoxHead\n            cls_scores = self.loss_cls.get_activation(cls_scores)\n        if cls_scores.numel() == 0:\n            return None\n        if cls_scores.shape[-1] == self.num_classes + 1:\n            # remove background class\n            cls_scores = cls_scores[:, :-1]\n        elif cls_scores.shape[-1] != self.num_classes:\n            raise ValueError('The last dim of `cls_scores` should equal to '\n                             '`num_classes` or `num_classes + 1`,'\n                             f'but got {cls_scores.shape[-1]}.')\n        labels = torch.where(labels == self.num_classes, cls_scores.argmax(1),\n                             labels)\n\n        img_ids = rois[:, 0].long().unique(sorted=True)\n        assert img_ids.numel() <= len(batch_img_metas)\n\n        results_list = []\n        for i in range(len(batch_img_metas)):\n            inds = torch.nonzero(\n                rois[:, 0] == i, as_tuple=False).squeeze(dim=1)\n            num_rois = inds.numel()\n\n            bboxes_ = rois[inds, 1:]\n            label_ = labels[inds]\n            bbox_pred_ = bbox_preds[inds]\n            img_meta_ = batch_img_metas[i]","sourceCodeStart":630,"sourceCodeEnd":666,"githubUrl":"https://github.com/open-mmlab/mmdetection/blob/cfd5d3a985b0249de009b67d04f37263e11cdf3d/mmdet/models/roi_heads/bbox_heads/bbox_head.py#L630-L666","documentation":"BBoxHead.refine_bboxes strips the background column from cls_scores when the last dim equals num_classes+1 and expects exactly num_classes otherwise. Any other last-dimension (e.g. a mismatched head num_classes vs bbox_head) raises this ValueError.","triggerScenarios":"Calling refine_bboxes during two-stage refinement (e.g. Cascade R-CNN, ConvFCBBoxHead with reg_with_fc / refine stages) when the cls_score tensor width is neither num_classes nor num_classes+1 — typically the shared head/roi head num_classes differs from the producing head.","commonSituations":"Changing num_classes in one config component (bbox_head) but not another (shared head or next-stage head); checkpoint loading from a model with a different class count.","solutions":["Make num_classes identical across all bbox heads and the model config","Check that the loaded checkpoint's classifier shape matches config num_classes","Verify custom heads output cls_scores with last dim num_classes (+1 for softmax background)"],"exampleFix":"# before\nroi_head.bbox_head.num_classes=80, shared_head outputs 20-class scores\n# after\nroi_head=dict(bbox_head=dict(num_classes=80)), shared_head aligned to 80","handlingStrategy":"validation","validationCode":"assert cls_scores.shape[-1] in (model.num_classes, model.num_classes + 1)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Keep num_classes consistent across every bbox_head/shared_head in the config","After loading checkpoints, verify classifier layer shapes match config"],"tags":["mmdetection","bbox-head","shape-mismatch","config"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"cfd5d3a985b0249de009b67d04f37263e11cdf3d","analyzedAt":"2026-08-27T20:54:20.183Z","schemaVersion":2},"datasetVersion":"2026-08-28T00:17:15.603Z"}