{"record":{"id":"5a81d6ab76906a65","repo":"hankcs/HanLP","slug":"unrecognized-type-for-embed-5a81d6","errorCode":null,"errorMessage":"Unrecognized type for {embed}","messagePattern":"Unrecognized type for (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"hanlp/layers/embeddings/char_rnn.py","lineNumber":40,"sourceCode":"        \"\"\"Character level RNN embedding module.\n\n        Args:\n            field: The field in samples this encoder will work on.\n            vocab_size: The size of character vocab.\n            embed: An ``Embedding`` object or the feature size to create an ``Embedding`` object.\n            hidden_size: The hidden size of RNNs.\n        \"\"\"\n        super(CharRNN, self).__init__()\n        self.field = field\n        # the embedding layer\n        if isinstance(embed, int):\n            self.embed = nn.Embedding(num_embeddings=vocab_size,\n                                      embedding_dim=embed)\n        elif isinstance(embed, nn.Module):\n            self.embed = embed\n            embed = embed.embedding_dim\n        else:\n            raise ValueError(f'Unrecognized type for {embed}')\n        # the lstm layer\n        self.lstm = nn.LSTM(input_size=embed,\n                            hidden_size=hidden_size,\n                            batch_first=True,\n                            bidirectional=True)\n\n    def forward(self, batch, mask, **kwargs):\n        x = batch[f'{self.field}_char_id']\n        # [batch_size, seq_len, fix_len]\n        mask = x.ne(0)\n        # [batch_size, seq_len]\n        lens = mask.sum(-1)\n        char_mask = lens.gt(0)\n\n        # [n, fix_len, n_embed]\n        x = self.embed(batch) if isinstance(self.embed, EmbeddingDim) else self.embed(x[char_mask])\n        x = pack_padded_sequence(x[char_mask], lens[char_mask].cpu(), True, False)\n        x, (h, _) = self.lstm(x)","sourceCodeStart":22,"sourceCodeEnd":58,"githubUrl":"https://github.com/hankcs/HanLP/blob/ddb1299bddff079e447af52ec12549c50636bfa8/hanlp/layers/embeddings/char_rnn.py#L22-L58","documentation":"CharRNN's constructor accepts embed either as an int (embedding dim, builds nn.Embedding internally) or as an nn.Module with an embedding_dim attribute (reuses it and reads its dim for LSTM input_size). Anything else (str, float, None) raises this error before the LSTM is constructed.","triggerScenarios":"Passing embed='100' (string from config), a float, or an nn.Module lacking embedding_dim (e.g. a raw Linear) to CharRNNEmbedding.","commonSituations":"Config files yielding strings; passing a pretrained embedding wrapper that doesn't expose embedding_dim; passing None due to a missing config key.","solutions":["Pass an int dim or a module exposing .embedding_dim (e.g. nn.Embedding)","Coerce config values: int(embed) when it's a numeric string","Wrap custom embeddings in a small module that defines embedding_dim"],"exampleFix":"# before\nembed = CharRNNEmbedding(vocab, embed='100')  # str\n# after\nembed = CharRNNEmbedding(vocab, embed=int('100'))","handlingStrategy":"type-guard","validationCode":"if isinstance(embed, str) and embed.isdigit():\n    embed = int(embed)\nassert isinstance(embed, int) or (isinstance(embed, nn.Module) and hasattr(embed, 'embedding_dim'))","typeGuard":"def valid_char_rnn_embed(embed) -> bool:\n    return isinstance(embed, int) or (isinstance(embed, nn.Module) and hasattr(embed, 'embedding_dim'))","tryCatchPattern":null,"preventionTips":["Pass nn.Embedding instances or int dims","Coerce stringified numbers from configs"],"tags":["hanlp","embedding","char-rnn","type-validation"],"backgroundTag":"invalid-constructor-argument-type","analyzedSha":"ddb1299bddff079e447af52ec12549c50636bfa8","analyzedAt":"2026-08-27T03:36:54.287Z","schemaVersion":2},"datasetVersion":"2026-08-27T08:17:20.692Z"}