thingsvision

repository·master·Indexed 41 days ago

https://github.com/vicco-group/thingsvision

A Python library for extracting high-level image representations from state-of-the-art computer vision models. It supports a wide range of sources including torchvision, Keras, timm, OpenCLIP, and specialized architectures like DreamSim, Harmonization, and CORnet. The library provides a CLI and Python API for feature extraction and includes tools to align extracted features with human object similarity using the gLocal method.

Tokens
13.4K
Snippets
39
Records
45
Agent score
51%

What's inside thingsvision

  1. Overview of thingsvision

    master

    thingsvision is a Python package designed for extracting image representations (features) from various state-of-the-art deep neural networks.

    Core Workflow:

    1. Provide a directory containing images.
    2. Specify a neural network model and its source.
    3. thingsvision processes the images and returns a feature vector for each image.

    These feature vectors can then be used for downstream computer vision analyses.

    For interactive exploration, you can use the provided Colab notebooks for PyTorch or Tensorflow.

  2. Select a model and source in thingsvision

    master

    To extract features, you must specify both the model name (as a str) and its source using the source parameter. Note that model names are case-sensitive depending on the source (e.g., vgg16 for torchvision vs VGG16 for keras).

    Supported Sources and Model Examples:

    • torchvision: e.g., vgg16
    • Keras: e.g., VGG16
    • timm: (PyTorch Image Models)
    • ssl (Self-Supervised Learning):
      • simclr-rn50, mocov2-rn50, barlowtwins-rn50, pirl-rn50
      • jigsaw-rn50, rotnet-rn50, swav-rn50, vicreg-rn50
      • dino-rn50, dino-xcit-{small/medium}-{12/24}-p{8/16}
      • dino-vit-{tiny/small/base}-p{8/16}, dinov2-vit-{small/base/large/giant}-p14
      • mae-vit-{base/large}-p16, mae-vit-huge-p14
    • OpenCLIP: CLIP models trained on LAION-{400M/2B/5B}
    • CLIP: CLIP models trained on WiT
    • CORnet: Various versions available
    • Harmonization: Default is ViT_B16. Others include ResNet50, VGG16, EfficientNetB0, tiny_ConvNeXT, tiny_MaxViT, and LeViT_small.
    • DreamSim: Default is open_clip_vitb32. Others include clip_vitb32, dino_vitb16, and ensemble.

    Refer to the Available Models page for a complete list.

  3. Available model sources in thingsvision

    master

    You can extract features from a wide variety of model architectures and sources, including:

    • Standard Libraries: torchvision, Keras, timm.
    • Self-Supervised Learning (SSL): Models like simclr-rn50, mocov2-rn50, dino-vit-{tiny/small/base}-p{8/16}, dinov2-vit-{small/base/large/giant}-p14, and mae-vit variants.
    • CLIP-based Models: OpenCLIP (LAION-400M/2B/5B) and CLIP (WiT).
    • Specialized Architectures: CORnet (recurrent vision models), Segment Anything (SAM), and ALIGN.
    • Pre-trained on Ecoset: Alexnet, VGG-16, Resnet50, and Inception_v3.
    • Harmonization Models: Default is ViT_B16; also supports ResNet50, VGG16, EfficientNetB0, tiny_ConvNeXT, tiny_MaxViT, and LeViT_small.
    • DreamSim Models: Default is open_clip_vitb32; also supports clip_vitb32, dino_vitb16, and an ensemble.
  4. Reduce GPU memory usage

    master

    If you encounter GPU memory issues during feature extraction, you can use one of two strategies:

    1. Reduce Batch Size: Decrease the batch_size parameter in your DataLoader instance.
    2. Switch to CPU: Run extraction on the CPU instead of the GPU. This is slower but allows for larger batch sizes. Set the device parameter to 'cpu' in the get_extractor function.
  5. Handle `MemoryError` when saving activations using `split_activations`

    master

    Even if activations fit in RAM, you may encounter MemoryError when attempting to save them to disk. To resolve this, use the split_activations helper function to split the activation matrix into multiple files.

    • Splitting: Call split_activations to divide the matrix into batches. The split parameter controls the number of files created (default is 10).
    • Merging: To reconstruct the full activation matrix after loading, use the merge_activations function.

    Example workflow:

    # To save split files
    split_activations(activations, PATH, split=10)
    
    # To load and merge them back
    activations = merge_activations(PATH)
  6. Perform Centered Kernel Alignment (CKA)

    master

    Use CKA to compare image features from two different model architectures (at the same layer) or two different layers within the same architecture.

    To use CKA, initialize a CKA object using get_cka and then call the .compare() method with your feature sets.

    from thingsvision.core.cka import get_cka
    
    backend = "torch" # 'torch' or 'numpy'
    m = # number of images (e.g., features_i.shape[0])
    kernel = 'linear' # 'linear' or 'rbf'
    unbiased = True # whether to compute an unbiased version
    device = "cuda" # only for 'torch' backend; NumPy runs on CPU
    sigma = None # required if kernel='rbf'
    
    cka = get_cka(backend=backend, m=m, kernel=kernel, unbiased=unbiased, device=device, sigma=sigma)
    rho = cka.compare(X=features_i, Y=features_j)
  7. Reduce RAM usage by writing features to disk

    master

    By default, thingsvision stores all extracted features in RAM. For large datasets, this may cause your system to run out of memory. To prevent this, write features directly to disk as they are extracted:

    • Set the output_dir parameter in the extract_features function to your desired directory.
    • When output_dir is provided, extract_features returns None instead of the feature matrix.
    • Use the step_size parameter to control how many batches are processed before writing to disk (the default is tuned to use approximately 8GB of RAM).
    # get extractor and dataloader 
    extractor = ...
    batches = ...
    
    output_dir = '/path/to/output/directory'
    extractor.extract_features(
        batches=batches,
        module_name=...,
        flatten_acts=True,
        output_dir=output_dir
    ) # returns None if output_dir is set
  8. Use DreamSim models

    master

    To use DreamSim, you must first install the dreamsim package:

    $ pip install dreamsim==0.1.2

    Set model_name='DreamSim' and source='custom'. Use model_parameters={'variant': '...'} to select one of the four available models.

    Available variants:

    • clip_vitb32
    • open_clip_vitb32
    • dino_vitb16 (Note: requires module_name='model.mlp')
    • ensemble (Note: requires module_name='model.mlp')

    Caution: For dino_vitb16 and ensemble, features can only be extracted from the model.mlp module, not the model block.

    import torch
    from thingsvision import get_extractor
    
    extractor = get_extractor(
      model_name='DreamSim',
      module_name='model.mlp',
      source='custom',
      device='cuda' if torch.cuda.is_available() else 'cpu',
      pretrained=True,
      model_parameters={'variant': 'open_clip_vitb32'}
    )
  9. Load HDF5 datasets using the HDF5Dataset class

    master

    Use the HDF5Dataset class to load image datasets stored in HDF5 files (such as NSD stimuli).

    Parameters:

    • hdf5_fp: Path to the HDF5 file.
    • img_ds_key: The key identifying the image dataset within the HDF5 file.
    • out_path: Directory where extracted features will be saved.
    • backend: The backend used by the extractor (obtained via extractor.get_backend()).
    • transforms: The image transformations required by the extractor (obtained via extractor.get_transformations()).
    • img_indices (optional): A list of indices specifying which images in the HDF5 file should be loaded. Use this to load a subset of the data.

    Features are extracted in the order they appear in the HDF5 file.

    from thingsvision.utils.data import HDF5Dataset
    
    # load extractor beforehand
    extractor = ...
    
    dataset = HDF5Dataset(
        hdf5_fp='path/to/hdf5/file' # (e.g., './nsd_stimuli.hdf5')
        img_ds_key='imgBrick',
        out_path='path/to/features',
        backend=extractor.get_backend(),
        transforms=extractor.get_transformations()
    )
  10. Use Harmonization models

    master

    To extract features from Harmonization models, install the required dependencies (works best on Ubuntu; macOS support is currently limited):

    $ pip install git+https://github.com/serre-lab/Harmonization.git
    $ pip install keras-cv-attention-models>=1.3.5

    Set model_name='Harmonization' and source='custom'. Specify the architecture via model_parameters={'variant': '...'}.

    Available variants:

    • ViT_B16
    • ResNet50
    • VGG16
    • EfficientNetB0
    • tiny_ConvNeXT
    • tiny_MaxViT
    • LeViT_small
    import torch
    from thingsvision import get_extractor
    
    extractor = get_extractor(
      model_name='Harmonization',
      source='custom',
      device='cuda' if torch.cuda.is_available() else 'cpu',
      pretrained=True,
      model_parameters={'variant': 'ViT_B16'}
    )
  11. Load image datasets using the ImageDataset class

    master

    Use the ImageDataset class to load images stored in a directory structure. Labels are automatically inferred from the subfolder names. For example, images in root/class1/ will be assigned the label class1.

    Requirements:

    • You must provide an extractor (or its backend and transformations) because images are loaded and then passed to the extractor, which requires specific preprocessing.
    • The out_path directory will contain a file_names.txt file that maps extracted features to their original image filenames in order.

    Parameters:

    • root: Path to the directory containing the image folders.
    • out_path: Directory where extracted features and the file_names.txt mapping will be saved.
    • backend: The backend used by the extractor (obtained via extractor.get_backend()).
    • transforms: The image transformations required by the extractor (obtained via extractor.get_transformations()).
    from thingsvision.utils.data import ImageDataset
    
    # load extractor beforehand
    extractor = ...
    
    dataset = ImageDataset(
        root='path/to/root/img/directory' # (e.g., './root/')
        out_path='path/to/features',
        backend=extractor.get_backend(),
        transforms=extractor.get_transformations()
    )
  12. Prepare the THINGS dataset for thingsvision

    master

    If you are using the THINGS image database, you must organize your files in a specific directory structure for thingsvision to work correctly.

    Directory Structure Requirements:

    • All object directories must be stored in a parent directory named ./images/ (e.g., ./images/object_xy/).
    • The things_concepts.tsv file must be stored in the ./data/ folder.

    Setup Steps:

    1. Download the Main folder from the THINGS database (approx. 5GB).
    2. Unzip the object_images_*.zip files. These files are password protected; check description.txt for the password.
    3. Use the provided script bash get_files.sh to automatically move the .tsv file to the ./data/ folder.

    Unzipping Example: If the password is provided in description.txt, you can unzip all object image archives using a loop:

    for fn in object_images_*.zip; do unzip -P the_password $fn; done