{"record":{"id":"ab8d40889becef8d","repo":"hankcs/HanLP","slug":"the-mask-name-should-be-specified-for-len-sel","errorCode":null,"errorMessage":"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}.","messagePattern":"The `(.+?)` should be specified for (.+?) layers, but it is for (.+?)\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"hanlp/components/amr/amrbart/model_interface/modeling_bart.py","lineNumber":1056,"sourceCode":"        # embed positions\n        positions = self.embed_positions(input_shape, past_key_values_length)\n\n        hidden_states = inputs_embeds + positions\n        hidden_states = self.layernorm_embedding(hidden_states)\n\n        hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n\n        # decoder layers\n        all_hidden_states = () if output_hidden_states else None\n        all_self_attns = () if output_attentions else None\n        all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None\n        next_decoder_cache = () if use_cache else None\n\n        # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired\n        for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], [\"head_mask\", \"cross_attn_head_mask\"]):\n            if attn_mask is not None:\n                if attn_mask.size()[0] != (len(self.layers)):\n                    raise ValueError(\n                        f\"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for\"\n                        f\" {head_mask.size()[0]}.\"\n                    )\n\n        for idx, decoder_layer in enumerate(self.layers):\n            # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n            if output_hidden_states:\n                all_hidden_states += (hidden_states,)\n            dropout_probability = random.uniform(0, 1)\n            if self.training and (dropout_probability < self.layerdrop):\n                continue\n\n            past_key_value = past_key_values[idx] if past_key_values is not None else None\n\n            if self.gradient_checkpointing and self.training:\n\n                if use_cache:\n                    logger.warning(","sourceCodeStart":1038,"sourceCodeEnd":1074,"githubUrl":"https://github.com/hankcs/HanLP/blob/ddb1299bddff079e447af52ec12549c50636bfa8/hanlp/components/amr/amrbart/model_interface/modeling_bart.py#L1038-L1074","documentation":"When a mask is supplied to the elementwise accuracy call, it must match predictions.shape exactly so the metric knows which cells to count. A mask with different shape (e.g. (B,) for (B, C) predictions) raises ValueError.","triggerScenarios":"Passing mask of shape (B,) or (B, T) alongside (B, C) / (B, T, C) predictions to the same-shape __call__ variant.","commonSituations":"Reusing a length-based 1-D mask from seq labeling in a multi-label metric; mask computed before a view/reshape of predictions; padding mask broadcasting assumptions.","solutions":["Expand the mask to predictions' shape: mask.unsqueeze(-1).expand_as(predictions) or a Boolean multi-hot mask","Recompute the mask after any reshape of predictions","Validate mask.shape == predictions.shape before the call"],"exampleFix":"# before\nmetric(predictions, gold, mask)  # mask (B,)\n# after\nmetric(predictions, gold, mask.unsqueeze(-1).expand_as(predictions))","handlingStrategy":"validation","validationCode":"assert mask is None or mask.size() == predictions.size(), (mask.shape if mask is not None else None, predictions.shape)","typeGuard":"import torch\ndef mask_matches(mask: torch.Tensor, predictions: torch.Tensor) -> bool:\n    return mask.size() == predictions.size()","tryCatchPattern":"try:\n    metric(predictions, gold, mask)\nexcept ValueError as e:\n    if 'mask' in str(e) and mask is not None:\n        metric(predictions, gold, mask.unsqueeze(-1).expand_as(predictions))\n    else:\n        raise","preventionTips":["Expand 1-D length masks to prediction shape before passing","Recompute masks after reshaping predictions","Standardize mask conventions (bool, prediction-shaped) across the codebase"],"tags":["hanlp","metrics","mask","shape-mismatch"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"ddb1299bddff079e447af52ec12549c50636bfa8","analyzedAt":"2026-08-27T03:36:54.287Z","schemaVersion":2},"datasetVersion":"2026-08-27T08:17:20.692Z"}