{"record":{"id":"09d5faa5ea0b2ce8","repo":"hankcs/HanLP","slug":"unrecognized-type-for-embed","errorCode":null,"errorMessage":"Unrecognized type for {embed}","messagePattern":"Unrecognized type for (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"hanlp/layers/embeddings/char_cnn.py","lineNumber":67,"sourceCode":"                ngrams of size 2 to 5 with some number of filters.\n            conv_layer_activation: `Activation`, optional (default=`torch.nn.ReLU`)\n                Activation to use after the convolution layers.\n            output_dim: After doing convolutions and pooling, we'll project the collected features into a vector of\n                this size.  If this value is `None`, we will just return the result of the max pooling,\n                giving an output of shape `len(ngram_filter_sizes) * num_filters`.\n            vocab_size: The size of character vocab.\n\n        Returns:\n            A tensor of shape `(batch_size, output_dim)`.\n        \"\"\"\n        super().__init__()\n        EmbeddingDim.__init__(self)\n        # the embedding layer\n        if isinstance(embed, int):\n            embed = nn.Embedding(num_embeddings=vocab_size,\n                                 embedding_dim=embed)\n        else:\n            raise ValueError(f'Unrecognized type for {embed}')\n        self.field = field\n        self.embed = TimeDistributed(embed)\n        self.encoder = TimeDistributed(\n            CnnEncoder(embed.embedding_dim, num_filters, ngram_filter_sizes, conv_layer_activation, output_dim))\n        self.embedding_dim = output_dim or num_filters * len(ngram_filter_sizes)\n\n    def forward(self, batch: dict, **kwargs):\n        tokens: torch.Tensor = batch[f'{self.field}_char_id']\n        mask = tokens.ge(0)\n        x = self.embed(tokens)\n        return self.encoder(x, mask)\n\n    def get_output_dim(self) -> int:\n        return self.embedding_dim\n\n\nclass CharCNNEmbedding(Embedding, AutoConfigurable):\n    def __init__(self,","sourceCodeStart":49,"sourceCodeEnd":85,"githubUrl":"https://github.com/hankcs/HanLP/blob/ddb1299bddff079e447af52ec12549c50636bfa8/hanlp/layers/embeddings/char_cnn.py#L49-L85","documentation":"CharCNN's embedding constructor only accepts embed as an int (vocab size + embedding dim); any other type is rejected. The int is used to build nn.Embedding(num_embeddings=vocab_size, embedding_dim=embed) which is then wrapped in TimeDistributed for character-level encoding. Passing an nn.Module or str bypasses that path and raises.","triggerScenarios":"Calling CharCNN(vocab_size, embed='100') or embed=nn.Embedding(...) or a config string parsed as non-int; also passing a float dimension.","commonSituations":"Loading a config from YAML/JSON where embed comes out as a string; reusing a pattern from char_rnn.py which also accepts nn.Module; typo'd config key yielding None.","solutions":["Pass embed as an int, e.g. CharCNN(vocab, embed=50, ...)","If config-driven, coerce: embed=int(embed) before constructing","If you need a custom module, extend the class instead of passing a module today"],"exampleFix":"# before\nembed = CharCNNEmbedding(vocab, embed='50')  # str -> error\n# after\nembed = CharCNNEmbedding(vocab, embed=50)","handlingStrategy":"type-guard","validationCode":"embed = int(embed) if isinstance(embed, (str, float)) else embed\nassert isinstance(embed, int)","typeGuard":"def is_valid_embed_arg(embed) -> bool:\n    return isinstance(embed, int) and not isinstance(embed, bool)","tryCatchPattern":null,"preventionTips":["Keep embedding dim config as int","Validate config values right after parsing YAML/JSON"],"tags":["hanlp","embedding","char-cnn","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"}