hankcs/HanLP · error · ValueError
Unrecognized type for {embed}
Error message
Unrecognized type for {embed} What it means
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.
Source
Thrown at hanlp/layers/embeddings/char_cnn.py:67
ngrams of size 2 to 5 with some number of filters.
conv_layer_activation: `Activation`, optional (default=`torch.nn.ReLU`)
Activation to use after the convolution layers.
output_dim: After doing convolutions and pooling, we'll project the collected features into a vector of
this size. If this value is `None`, we will just return the result of the max pooling,
giving an output of shape `len(ngram_filter_sizes) * num_filters`.
vocab_size: The size of character vocab.
Returns:
A tensor of shape `(batch_size, output_dim)`.
"""
super().__init__()
EmbeddingDim.__init__(self)
# the embedding layer
if isinstance(embed, int):
embed = nn.Embedding(num_embeddings=vocab_size,
embedding_dim=embed)
else:
raise ValueError(f'Unrecognized type for {embed}')
self.field = field
self.embed = TimeDistributed(embed)
self.encoder = TimeDistributed(
CnnEncoder(embed.embedding_dim, num_filters, ngram_filter_sizes, conv_layer_activation, output_dim))
self.embedding_dim = output_dim or num_filters * len(ngram_filter_sizes)
def forward(self, batch: dict, **kwargs):
tokens: torch.Tensor = batch[f'{self.field}_char_id']
mask = tokens.ge(0)
x = self.embed(tokens)
return self.encoder(x, mask)
def get_output_dim(self) -> int:
return self.embedding_dim
class CharCNNEmbedding(Embedding, AutoConfigurable):
def __init__(self,View on GitHub (pinned to ddb1299bdd)
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
Example fix
# before embed = CharCNNEmbedding(vocab, embed='50') # str -> error # after embed = CharCNNEmbedding(vocab, embed=50)
Defensive patterns
Strategy: type-guard
Validate before calling
embed = int(embed) if isinstance(embed, (str, float)) else embed assert isinstance(embed, int)
Type guard
def is_valid_embed_arg(embed) -> bool:
return isinstance(embed, int) and not isinstance(embed, bool) Prevention
- Keep embedding dim config as int
- Validate config values right after parsing YAML/JSON
When it happens
Trigger: Calling CharCNN(vocab_size, embed='100') or embed=nn.Embedding(...) or a config string parsed as non-int; also passing a float dimension.
Common situations: 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.
Related errors
- Unrecognized type for {embed}
- Unsupported parameter type: {embed}
- error
- output ({}) must be of type bool or str
- Call fit or load before evaluate.
AI-assisted analysis of hankcs/HanLP@ddb1299bdd (2026-08-27).
Data as JSON: /api/errors/09d5faa5ea0b2ce8.
Report an issue: GitHub.