# Buggy code
def make_base_model(model_opt, fields, gpu, checkpoint=None):
    """
    Args:
        model_opt: the option loaded from checkpoint.
        fields: `Field` objects for the model.
        gpu(bool): whether to use gpu.
        checkpoint: the model gnerated by train phase, or a resumed snapshot
                    model from a stopped training.
    Returns:
        the NMTModel.
    """
    assert model_opt.model_type in ["text", "img"], "Unsupported model type %s" % (
        model_opt.model_type
    )

    # Make encoder.
    if model_opt.model_type == "text":
        src_dict = fields["src"].vocab
        feature_dicts = onmt.IO.collect_feature_dicts(fields, "src")
        src_embeddings = make_embeddings(model_opt, src_dict, feature_dicts)
        encoder = make_encoder(model_opt, src_embeddings)
    else:
        encoder = ImageEncoder(
            model_opt.layers, model_opt.brnn, model_opt.rnn_size, model_opt.dropout
        )

    # Make decoder.
    tgt_dict = fields["tgt"].vocab
    # TODO: prepare for a future where tgt features are possible.
    feature_dicts = onmt.IO.collect_feature_dicts(fields, "tgt")
    tgt_embeddings = make_embeddings(
        model_opt, tgt_dict, feature_dicts, for_encoder=False
    )

    # Share the embedding matrix - preprocess with share_vocab required
    if model_opt.share_embeddings:
        tgt_embeddings.word_lut.weight = src_embeddings.word_lut.weight

    decoder = make_decoder(model_opt, tgt_embeddings)

    # Make NMTModel(= encoder + decoder).
    model = NMTModel(encoder, decoder)

    # Make Generator.
    if not model_opt.copy_attn:
        generator = nn.Sequential(
            nn.Linear(model_opt.rnn_size, len(fields["tgt"].vocab)), nn.LogSoftmax()
        )
        if model_opt.share_decoder_embeddings:
            generator[0].weight = decoder.embeddings.word_lut.weight
    else:
        generator = CopyGenerator(model_opt, fields["src"].vocab, fields["tgt"].vocab)

    # Load the model states from checkpoint or initialize them.
    if checkpoint is not None:
        print("Loading model parameters.")
        model.load_state_dict(checkpoint["model"])
        generator.load_state_dict(checkpoint["generator"])
    else:
        if model_opt.param_init != 0.0:
            print("Intializing model parameters.")
            for p in model.parameters():
                p.data.uniform_(-model_opt.param_init, model_opt.param_init)
            for p in generator.parameters():
                p.data.uniform_(-model_opt.param_init, model_opt.param_init)
        model.encoder.embeddings.load_pretrained_vectors(
            model_opt.pre_word_vecs_enc, model_opt.fix_word_vecs_enc
        )
        model.decoder.embeddings.load_pretrained_vectors(
            model_opt.pre_word_vecs_dec, model_opt.fix_word_vecs_dec
        )

    # Add generator to model (this registers it as parameter of model).
    model.generator = generator

    # Make the whole model leverage GPU if indicated to do so.
    if gpu:
        model.cuda()
    else:
        model.cpu()

    return model


# Traceback (RuntimeError)
./run.sh translate

[...]
Loading model parameters.
While copying the parameter named encoder.embeddings.make_embedding.emb_luts.0.weight, whose dimensions in the model are torch.Size([22, 500]) and whose dimensions in the checkpoint are torch.Size([22, 100]), ...
Traceback (most recent call last):
File "translate.py", line 133, in <module>
main()
File "translate.py", line 55, in main
translator = onmt.Translator(opt, dummy_opt.__dict__)
File "/home/pltrdy/pytorchwork/OpenNMT-py/onmt/Translator.py", line 29, in __init__
model_opt, self.fields, use_gpu(opt), checkpoint)
File "/home/pltrdy/pytorchwork/OpenNMT-py/onmt/ModelConstructor.py", line 166, in make_base_model
model.load_state_dict(checkpoint['model'])
File "/home/pltrdy/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 360, in load_state_dict
own_state[name].copy_(param)
RuntimeError: inconsistent tensor size, expected tensor [22 x 500] and src [22 x 100] to have the same number of elements, but got 11000 and 2200 elements respectively at /home/pltrdy/pytorch/torch/lib/TH/generic/THTensorCopy.c:86

# Fixed code
def make_base_model(model_opt, fields, gpu, checkpoint=None):
    """
    Args:
        model_opt: the option loaded from checkpoint.
        fields: `Field` objects for the model.
        gpu(bool): whether to use gpu.
        checkpoint: the model gnerated by train phase, or a resumed snapshot
                    model from a stopped training.
    Returns:
        the NMTModel.
    """
    assert model_opt.model_type in ["text", "img"], "Unsupported model type %s" % (
        model_opt.model_type
    )

    # Make encoder.
    if model_opt.model_type == "text":
        src_dict = fields["src"].vocab
        feature_dicts = onmt.IO.collect_feature_dicts(fields, "src")
        src_embeddings = make_embeddings(model_opt, src_dict, feature_dicts)
        encoder = make_encoder(model_opt, src_embeddings)
    else:
        encoder = ImageEncoder(
            model_opt.layers, model_opt.brnn, model_opt.rnn_size, model_opt.dropout
        )

    # Make decoder.
    tgt_dict = fields["tgt"].vocab
    # TODO: prepare for a future where tgt features are possible.
    feature_dicts = onmt.IO.collect_feature_dicts(fields, "tgt")
    tgt_embeddings = make_embeddings(
        model_opt, tgt_dict, feature_dicts, for_encoder=False
    )

    # Share the embedding matrix - preprocess with share_vocab required
    if model_opt.share_embeddings:
        tgt_embeddings.word_lut.weight = src_embeddings.word_lut.weight

    decoder = make_decoder(model_opt, tgt_embeddings)

    # Make NMTModel(= encoder + decoder).
    model = NMTModel(encoder, decoder)
    model.opt = model_opt

    # Make Generator.
    if not model_opt.copy_attn:
        generator = nn.Sequential(
            nn.Linear(model_opt.rnn_size, len(fields["tgt"].vocab)), nn.LogSoftmax()
        )
        if model_opt.share_decoder_embeddings:
            generator[0].weight = decoder.embeddings.word_lut.weight
    else:
        generator = CopyGenerator(model_opt, fields["src"].vocab, fields["tgt"].vocab)

    # Load the model states from checkpoint or initialize them.
    if checkpoint is not None:
        print("Loading model parameters.")
        model.load_state_dict(checkpoint["model"])
        generator.load_state_dict(checkpoint["generator"])
    else:
        if model_opt.param_init != 0.0:
            print("Intializing model parameters.")
            for p in model.parameters():
                p.data.uniform_(-model_opt.param_init, model_opt.param_init)
            for p in generator.parameters():
                p.data.uniform_(-model_opt.param_init, model_opt.param_init)
        model.encoder.embeddings.load_pretrained_vectors(
            model_opt.pre_word_vecs_enc, model_opt.fix_word_vecs_enc
        )
        model.decoder.embeddings.load_pretrained_vectors(
            model_opt.pre_word_vecs_dec, model_opt.fix_word_vecs_dec
        )

    # Add generator to model (this registers it as parameter of model).
    model.generator = generator

    # Make the whole model leverage GPU if indicated to do so.
    if gpu:
        model.cuda()
    else:
        model.cpu()

    return model