Skip to content

Fix: Resolve KeyError and NameError in TorchGeo backbones weight loading#1200

Open
clementgilli wants to merge 2 commits into
torchgeo:mainfrom
clementgilli:fix-torchgeo-weights-loading
Open

Fix: Resolve KeyError and NameError in TorchGeo backbones weight loading#1200
clementgilli wants to merge 2 commits into
torchgeo:mainfrom
clementgilli:fix-torchgeo-weights-loading

Conversation

@clementgilli

Copy link
Copy Markdown

Description

This PR fixes two bugs that prevent the initialization of several TorchGeo-based backbones when using pretrained=True.

1. Missing TorchGeo Bands (KeyError)

Files modified: terratorch/models/backbones/torchgeo_resnet.py, terratorch/models/backbones/torchgeo_vit.py and terratorch/models/backbones/torchgeo_swin_satlas.py

  • Issue: When loading weights, TorchGeo models often define their Sentinel-2 bands using formats like "B4", "B3", or "B8a". These keys were missing from the look_up_table, causing a KeyError to be raised during get_pretrained_bands().
  • Fix: Added the legacy TorchGeo band formats ("B1" to "B9", specifically including the lowercase "B8a" which was causing silent failures) to the look_up_table. I proactively applied this fix to the Swin Satlas backbone as well to prevent identical crashes.

2. Undefined Function (NameError)

File modified: terratorch/models/backbones/torchgeo_vit.py

  • Issue: In the load_vit_weights function, the elif weights is not None block calls a remove_keys() function. This function is not defined anywhere in the file or imported, resulting in a NameError: name 'remove_keys' is not defined.
  • Fix: Replaced the undefined remove_keys call with the explicit dictionary key deletion logic (for k in ["head.weight", "head.bias"]: del ...) that is already correctly implemented a few lines above in the same file.

Testing

Tested locally. Models such as seco_resnet18_sentinel2_rgb_seco and ssl4eos12_vit_small_patch16_224_sentinel2_all_dino now successfully translate band names, process the checkpoints, and load their pretrained weights without crashing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant