WZMIAOMIAO/deep-learning-for-image-processing · error · KeyError

no match key '{}'

Error message

no match key '{}'

What it means

trans_weights_to_pytorch.py maps each TensorFlow/official EfficientNet weight tensor name to the matching PyTorch key. If an incoming name (e.g. a TF variable like 'conv2d/kernel:0' variant or a new official checkpoint layout) has no if/elif branch, the script raises KeyError('no match key ...') instead of silently dropping tensors.

Source

Thrown at pytorch_classification/Test9_efficientNet/trans_weights_to_pytorch.py:93

            torch_name = "features.top.1.weight"
            weights_dict[torch_name] = data
        elif "top_bn/beta:0" == name:
            torch_name = "features.top.1.bias"
            weights_dict[torch_name] = data
        elif "top_bn/moving_mean:0" == name:
            torch_name = "features.top.1.running_mean"
            weights_dict[torch_name] = data
        elif "top_bn/moving_variance:0" == name:
            torch_name = "features.top.1.running_var"
            weights_dict[torch_name] = data
        elif "predictions/kernel:0" == name:
            torch_name = "classifier.1.weight"
            weights_dict[torch_name] = np.transpose(data, (1, 0)).astype(np.float32)
        elif "predictions/bias:0" == name:
            torch_name = "classifier.1.bias"
            weights_dict[torch_name] = data
        else:
            raise KeyError("no match key '{}'".format(name))

    for k, v in weights_dict.items():
        weights_dict[k] = torch.as_tensor(v)

    torch.save(weights_dict, save_path)
    print("Conversion complete.")


if __name__ == '__main__':
    main()

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Add an elif branch mapping the reported name to the correct PyTorch key (with proper transpose like (1, 0) or (3, 2, 1, 0) for conv kernels)
  2. Print/inspect all unmatched names first and extend the mapping table for the variant you are converting
  3. Use a checkpoint from the same model version the script was written for (official EfficientNet B0 naming)

Example fix

// before
else:
    raise KeyError("no match key '{}'".format(name))
// after
elif name.startswith("conv2d_") and name.endswith("kernel:0"):
    torch_name = "features.{}.weight".format(...)  # map per matched index
    weights_dict[torch_name] = np.transpose(data, (3, 2, 0, 1)).astype(np.float32)
else:
    raise KeyError("no match key '{}'".format(name))
Defensive patterns

Strategy: try-catch

Validate before calling

# pre-check all TF names against the mapping before converting
for name in tf_weights:
    if not any(pattern matches name for pattern in known_patterns):
        print('unmapped key:', name)

Type guard

def is_known_tf_key(name: str) -> bool:
    return name.endswith((':0',)) and any(p in name for p in KNOWN_PATTERNS)

Try / catch

try:
    main()
except KeyError as e:
    print('Add an elif branch for this TF variable name:', e)
    sys.exit(1)

Prevention

When it happens

Trigger: Converting a TF checkpoint whose layer names don't match the expected official EfficientNet naming scheme, e.g. different prefix, numbered conv names (conv2d_5), or added head variables like 'predictions/proliferation' not handled above.

Common situations: Using a different EfficientNet release (B1-B7 vs B0, or EfficientNetV2) whose TF names differ; Keras auto-renamed duplicate layers with _N suffixes; checking checkpoints from tensorflow hub models with altered naming.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/2382e09e8f009b76. Report an issue: GitHub.