d2l-ai/d2l-zh · error · NotImplementedError

NotImplementedError

Error message

NotImplementedError

What it means

NotImplementedError raised by Encoder.forward in d2l.mxnet (the base encoder interface for the encoder-decoder architecture, sec_encoder-decoder). Encoder is an abstract nn.Block subclass: instantiating it directly and calling it (or a subclass that fails to override forward) hits the guard. Every concrete encoder (Seq2SeqEncoder, etc.) must supply its own forward.

Source

Thrown at d2l/mxnet.py:860

    text = preprocess_nmt(read_data_nmt())
    source, target = tokenize_nmt(text, num_examples)
    src_vocab = d2l.Vocab(source, min_freq=2,
                          reserved_tokens=['<pad>', '<bos>', '<eos>'])
    tgt_vocab = d2l.Vocab(target, min_freq=2,
                          reserved_tokens=['<pad>', '<bos>', '<eos>'])
    src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)
    tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)
    data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)
    data_iter = d2l.load_array(data_arrays, batch_size)
    return data_iter, src_vocab, tgt_vocab

class Encoder(nn.Block):
    """编码器-解码器架构的基本编码器接口"""
    def __init__(self, **kwargs):
        super(Encoder, self).__init__(**kwargs)

    def forward(self, X, *args):
        raise NotImplementedError

class Decoder(nn.Block):
    """编码器-解码器架构的基本解码器接口

    Defined in :numref:`sec_encoder-decoder`"""
    def __init__(self, **kwargs):
        super(Decoder, self).__init__(**kwargs)

    def init_state(self, enc_outputs, *args):
        raise NotImplementedError

    def forward(self, X, state):
        raise NotImplementedError

class EncoderDecoder(nn.Block):
    """编码器-解码器架构的基类

    Defined in :numref:`sec_encoder-decoder`"""

View on GitHub (pinned to e6b18ccea7)

Solutions

  1. Instantiate a concrete implementation, e.g. d2l.Seq2SeqEncoder(vocab_size, embed_size, num_hiddens, num_layers)
  2. If subclassing, define forward(self, X, *args) with the exact name and correct indentation inside the class
  3. Check the object you pass as encoder to EncoderDecoder is the concrete class, not d2l.Encoder
  4. Add `import inspect; assert 'forward' in MyEncoder.__dict__` style checks in tests to catch un-overridden abstract methods early

Example fix

# before
enc = d2l.Encoder()
enc(X)  # NotImplementedError
# after
enc = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2)
enc.initialize()
enc(X)  # returns output, state
# or subclass correctly
class MyEncoder(d2l.Encoder):
    def forward(self, X, *args):
        return X, None
Defensive patterns

Strategy: type-guard

Validate before calling

import d2l
enc = d2l.Encoder
assert 'forward' in vars(enc) and getattr(enc, 'forward', None) is not d2l.Encoder.forward or enc is not d2l.Encoder, 'use a concrete Encoder subclass'

Type guard

def is_concrete_encoder(obj) -> bool:
    return isinstance(obj, d2l.Encoder) and type(obj).forward is not d2l.Encoder.forward

Prevention

When it happens

Trigger: e = d2l.Encoder(); e(X); or defining class MyEncoder(d2l.Encoder) with a typo in the method name (e.g. forward(self, x) lowercase mismatch is fine but hyphenated names like my_forward, or forgetting forward entirely) so the base implementation runs; also calling encoder(...) on an EncoderDecoder whose encoder member was accidentally set to the base class.

Common situations: Learners experimenting with the encoder-decoder chapter instantiate the interface to 'see what happens'; subclass method named `forwad` or defined outside the class body due to indentation mistakes; refactoring that replaces the concrete encoder with the base class during testing.

Related errors


AI-assisted analysis of d2l-ai/d2l-zh@e6b18ccea7 (2026-08-14). Data as JSON: /api/errors/4e4fd7703730d1aa. Report an issue: GitHub.