hankcs/HanLP · error · ValueError
Unrecognized type for {embed}
Error message
Unrecognized type for {embed} What it means
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.
Source
Thrown at hanlp/layers/embeddings/char_rnn.py:40
"""Character level RNN embedding module.
Args:
field: The field in samples this encoder will work on.
vocab_size: The size of character vocab.
embed: An ``Embedding`` object or the feature size to create an ``Embedding`` object.
hidden_size: The hidden size of RNNs.
"""
super(CharRNN, self).__init__()
self.field = field
# the embedding layer
if isinstance(embed, int):
self.embed = nn.Embedding(num_embeddings=vocab_size,
embedding_dim=embed)
elif isinstance(embed, nn.Module):
self.embed = embed
embed = embed.embedding_dim
else:
raise ValueError(f'Unrecognized type for {embed}')
# the lstm layer
self.lstm = nn.LSTM(input_size=embed,
hidden_size=hidden_size,
batch_first=True,
bidirectional=True)
def forward(self, batch, mask, **kwargs):
x = batch[f'{self.field}_char_id']
# [batch_size, seq_len, fix_len]
mask = x.ne(0)
# [batch_size, seq_len]
lens = mask.sum(-1)
char_mask = lens.gt(0)
# [n, fix_len, n_embed]
x = self.embed(batch) if isinstance(self.embed, EmbeddingDim) else self.embed(x[char_mask])
x = pack_padded_sequence(x[char_mask], lens[char_mask].cpu(), True, False)
x, (h, _) = self.lstm(x)View on GitHub (pinned to ddb1299bdd)
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
Example fix
# before
embed = CharRNNEmbedding(vocab, embed='100') # str
# after
embed = CharRNNEmbedding(vocab, embed=int('100')) Defensive patterns
Strategy: type-guard
Validate before calling
if isinstance(embed, str) and embed.isdigit():
embed = int(embed)
assert isinstance(embed, int) or (isinstance(embed, nn.Module) and hasattr(embed, 'embedding_dim')) Type guard
def valid_char_rnn_embed(embed) -> bool:
return isinstance(embed, int) or (isinstance(embed, nn.Module) and hasattr(embed, 'embedding_dim')) Prevention
- Pass nn.Embedding instances or int dims
- Coerce stringified numbers from configs
When it happens
Trigger: Passing embed='100' (string from config), a float, or an nn.Module lacking embedding_dim (e.g. a raw Linear) to CharRNNEmbedding.
Common situations: Config files yielding strings; passing a pretrained embedding wrapper that doesn't expose embedding_dim; passing None due to a missing config key.
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/5a81d6ab76906a65.
Report an issue: GitHub.