{"record":{"id":"f1a3b2399adab939","repo":"hankcs/HanLP","slug":"the-head-mask-should-be-specified-for-len-self-la","errorCode":null,"errorMessage":"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}.","messagePattern":"The head_mask 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":818,"sourceCode":"\n        embed_pos = self.embed_positions(input_shape)\n\n        hidden_states = inputs_embeds + embed_pos\n        hidden_states = self.layernorm_embedding(hidden_states)\n        hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n\n        # expand attention_mask\n        if attention_mask is not None:\n            # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n            attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)\n\n        encoder_states = () if output_hidden_states else None\n        all_attentions = () if output_attentions else None\n\n        # check if head_mask has a correct number of layers specified if desired\n        if head_mask is not None:\n            if head_mask.size()[0] != (len(self.layers)):\n                raise ValueError(\n                    f\"The head_mask should be specified for {len(self.layers)} layers, but it is for\"\n                    f\" {head_mask.size()[0]}.\"\n                )\n\n        for idx, encoder_layer in enumerate(self.layers):\n            if output_hidden_states:\n                encoder_states = encoder_states + (hidden_states,)\n            # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n            dropout_probability = random.uniform(0, 1)\n            if self.training and (dropout_probability < self.layerdrop):  # skip the layer\n                layer_outputs = (None, None)\n            else:\n                if self.gradient_checkpointing and self.training:\n\n                    def create_custom_forward(module):\n                        def custom_forward(*inputs):\n                            return module(*inputs, output_attentions)\n","sourceCodeStart":800,"sourceCodeEnd":836,"githubUrl":"https://github.com/hankcs/HanLP/blob/ddb1299bddff079e447af52ec12549c50636bfa8/hanlp/components/amr/amrbart/model_interface/modeling_bart.py#L800-L836","documentation":"For classification accuracy, predictions are (..., num_classes) scores while gold labels are class indices with one fewer dimension. If gold_labels.dim() != predictions.dim()-1 (e.g. one-hot gold labels, or score-shaped targets), __call__ raises ValueError.","triggerScenarios":"Calling metric(predictions=[B, C], gold_labels=[B, C]) (one-hot gold) or passing logits/gold with equal dims; also 3-D token-level predictions with 3-D gold.","commonSituations":"Feeding one-hot encoded targets instead of class indices; datasets returning gold as probabilities; a mask arg mistakenly passed as gold_labels positionally.","solutions":["Convert gold labels to integer class indices (argmax if one-hot): gold.argmax(-1)","Check shapes: gold.shape == predictions.shape[:-1]","Reorder positional args if mask was passed in the gold slot"],"exampleFix":"# before\nmetric(predictions, gold_onehot)  # gold is (B, C)\n# after\nmetric(predictions, gold_onehot.argmax(dim=-1))  # gold is (B,)","handlingStrategy":"validation","validationCode":"assert gold_labels.dim() == predictions.dim() - 1, (gold_labels.shape, predictions.shape)","typeGuard":"import torch\ndef valid_gold(predictions: torch.Tensor, gold: torch.Tensor) -> bool:\n    return gold.dim() == predictions.dim() - 1 and gold.dtype in (torch.long, torch.int)","tryCatchPattern":"try:\n    metric(predictions, gold_labels)\nexcept ValueError:\n    if gold_labels.dim() == predictions.dim():\n        metric(predictions, gold_labels.argmax(-1))\n    else:\n        raise","preventionTips":["Keep gold labels as integer class indices","Add shape asserts in debug builds of training loops","Write small unit checks for dataloader output shapes"],"tags":["hanlp","metrics","shape-mismatch","gold-labels"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"ddb1299bddff079e447af52ec12549c50636bfa8","analyzedAt":"2026-08-27T03:36:54.287Z","schemaVersion":2},"datasetVersion":"2026-08-27T08:17:20.692Z"}