huggingface/pytorch-image-models · error · ValueError

Invalid class map file, expected a dict ({class_map_path}).

Error message

Invalid class map file, expected a dict ({class_map_path}).

What it means

load_class_map unpickles .pkl class-map files with a restricted unpickler and requires the result to be a dict mapping class name to index. If the pickle contains anything else (list, string, arbitrary object), this ValueError is raised, protecting downstream indexing from a malformed class map.

Source

Thrown at timm/data/readers/class_map.py:33


def load_class_map(map_or_filename, root=''):
    if isinstance(map_or_filename, dict):
        assert dict, 'class_map dict must be non-empty'
        return map_or_filename
    class_map_path = map_or_filename
    if not os.path.exists(class_map_path):
        class_map_path = os.path.join(root, class_map_path)
        assert os.path.exists(class_map_path), 'Cannot locate specified class map file (%s)' % map_or_filename
    class_map_ext = os.path.splitext(map_or_filename)[-1].lower()
    if class_map_ext == '.txt':
        with open(class_map_path) as f:
            class_to_idx = {v.strip(): k for k, v in enumerate(f)}
    elif class_map_ext == '.pkl':
        with open(class_map_path, 'rb') as f:
            class_to_idx = _ClassMapUnpickler(f).load()
        if not isinstance(class_to_idx, dict):
            raise ValueError(f'Invalid class map file, expected a dict ({class_map_path}).')
    else:
        assert False, f'Unsupported class map file extension ({class_map_ext}).'
    return class_to_idx

View on GitHub (pinned to 9a5261e31b)

Solutions

  1. Regenerate the class map as a dict: {class_name: int_index} and pickle it.
  2. If your classes are plain text, save the file as .txt (one class name per line) — load_class_map supports that natively.
  3. Verify with python -c "import pickle; print(type(pickle.load(open('map.pkl','rb'))))" and reformat accordingly.

Example fix

# before
import pickle
pickle.dump(['cat','dog'], open('map.pkl','wb'))  # list -> raises

# after
import pickle
pickle.dump({'cat':0,'dog':1}, open('map.pkl','wb'))  # dict -> ok
Defensive patterns

Strategy: validation

Validate before calling

import pickle
m = pickle.load(open('map.pkl','rb'))
assert isinstance(m, dict) and all(isinstance(k,str) and isinstance(v,int) for k,v in m.items()), 'bad class map'

Try / catch

try:
    class_to_idx = load_class_map(path)
except ValueError as e:
    log.error(f'class map {path} invalid: {e}'); raise

Prevention

When it happens

Trigger: Calling load_class_map('classes.pkl') (directly or via a dataset reader's class_map argument) where the pickle holds a non-dict object, e.g. a pickled list of names, a numpy array, or a plain text file renamed to .pkl.

Common situations: User-created class map saved with pickle.dump(['a','b',...]) instead of a dict; a .txt class map mistakenly saved with a .pkl extension; class-map files generated by a different training framework with an incompatible schema.

Related errors


AI-assisted analysis of huggingface/pytorch-image-models@9a5261e31b (2026-08-27). Data as JSON: /api/errors/efb84277ed61b765. Report an issue: GitHub.