メインコンテンツへスキップ

GeneCISをgoogle colabで試してみた。

    GeneCISとは

    GeneCISは、facebookresearchが出したさまざまなテキストプロンプトが与えられた場合に、モデルがさまざまな視覚的「類似性」の概念に適応する能力を測定するためのゼロショット評価ベンチマークです。


    リンク

    Colab
    github

    準備

    Google Colabを開き、メニューから「ランタイム→ランタイムのタイプを変更」でランタイムを「GPU」に変更します。

    環境構築

    インストール手順です。

    !pip install git+https://github.com/openai/CLIP.git
    !git clone https://github.com/facebookresearch/genecis.git
    %cd genecis
    !pip install -r requirements.txt
    !python -m spacy download en

    推論

    MIT statesというデータセットに対して評価を行うところまでを試してみます。
    (1)モデルのダウンロード

    !wget https://dl.fbaipublicfiles.com/genecis/vitb16_backbone.pt -P /content
    !wget https://dl.fbaipublicfiles.com/genecis/vitb16_combiner_head.pt -P /content

    (2)evaluation datasetの準備

    !wget http://wednesday.csail.mit.edu/joseph_result/state_and_transformation/release_dataset.zip -P /content
    !unzip /content/release_dataset.zip

    (3)推論
    (3-1)ライブラリのインポート

    %cd /content/genecis/
    import os
    
    from datasets.cirr_datasets import CIRRImageDataset, CIRRValGlobalDataset
    from datasets.vaw_dataset import VAWValSubset
    from datasets.mit_states_dataset import MITStatesImageOnly, MITStatesGlobalTestSet 
    from datasets.coco_dataset import COCOValSubset
    
    from eval.eval_functions import validate, validate_global
    from models.combiner_model import Combiner
    
    import clip
    import torch
    
    import argparse
    import torch.backends.cudnn as cudnn
    from utils.dist_utils import fix_random_seeds, init_distributed_mode, get_rank
    from utils.gen_utils import bool_flag, strip_state_dict, none_flag
    from functools import partial
    
    from utils.model_utils import FeatureComb
    from utils.dist_utils import CLIPDistDataParallel
    
    from config import genecis_root

    (3-2)パラメータ設定

    # -------------
    # DEFINE MODEL SPECS
    # -------------
    MODEL='ViT-B/16'          # Set to one of the CLIP models
    COMBINER_MODE='combiner_original'           # Either learned combiner head or one of ('image_only' 'text_only' 'image_plus_text')
    
    # -------------
    # DEFINE PRETRAINED PATHS
    # -------------
    COMBINER_PRETRAIN_PATH="/content/vitb16_combiner_head.pt"               # Set to path of model to evaluate (combiner head)  (set to 'None' if using image_only etc.)
    CLIP_PRETRAIN_PATH="/content/vitb16_backbone.pt"                   # Set to path of model to evaluate (backbone)  (set to 'None' to use CLIP pre-trained model, if using image_only etc.)
    
    
    DATASET='mit_states'
    
    use_complete_text_query = False
    
    # --------------
    # INIT
    # --------------
    fix_random_seeds(0)
    cudnn.benchmark = True

    (3-3)評価

    # --------------
    # GET BACKBONE
    # --------------
    print('Loading models...')
    # define clip model and preprocess pipeline, get input_dim and feature_dim
    clip_model, preprocess = clip.load(MODEL)
    clip_model.float().eval()
    input_dim = clip_model.visual.input_resolution
    feature_dim = clip_model.visual.output_dim
    
    # --------------
    # GET COMBINER
    # --------------
    if COMBINER_MODE == 'combiner_original':
        combiner = Combiner(clip_feature_dim=feature_dim, projection_dim=2560, hidden_dim=2 * 2560)
    elif COMBINER_MODE in ('image_only', 'text_only', 'image_plus_text'):
        combiner = FeatureComb(COMBINER_MODE, feature_comb_average=0.5)
    else:
        raise ValueError
    
    # --------------
    # LOAD PRETRAINED WEIGHTS
    # --------------
    if COMBINER_PRETRAIN_PATH is not None:
        state_dict = torch.load(COMBINER_PRETRAIN_PATH, map_location='cpu')
        state_dict = strip_state_dict(state_dict=state_dict, strip_key='module.')
        combiner.load_state_dict(state_dict)
    
    if CLIP_PRETRAIN_PATH is not None:
        state_dict = torch.load(CLIP_PRETRAIN_PATH, map_location='cpu')
        state_dict = strip_state_dict(state_dict=state_dict, strip_key='module.')
        clip_model.load_state_dict(state_dict)    
    
    # --------------
    # To cuda
    # --------------
    clip_model, combiner = clip_model.cuda(), combiner.cuda()
    
    tokenizer = partial(clip.tokenize, truncate=True)
    val_dataset_return_images = MITStatesImageOnly(path="/content/genecis/release_dataset", split='test', transform=preprocess)
    val_dataset_global = MITStatesGlobalTestSet(path="/content/genecis/release_dataset", split='test', transform=preprocess, tokenizer=tokenizer, use_complete_text_query=use_complete_text_query)
    
    batch_size_per_gpu = 8
    num_workers = 8
    pred_save_path = None
    get_dataloader = partial(torch.utils.data.DataLoader, sampler=None,
            batch_size=batch_size_per_gpu,
            num_workers=num_workers,
            pin_memory=True,
            shuffle=False)
    
    valloader_global = get_dataloader(dataset=val_dataset_global)
    valloader_only_images = get_dataloader(dataset=val_dataset_return_images)
    
    # --------------
    # EVALUTE
    # --------------
    # TODO: Adjust eval code for multiple GPUs
    if get_rank() == 0:
        validate_global(clip_model, combiner, valloader_only_images, valloader_global, topk=(1, 5, 10), save_path=None)
    
    # Output
    # Recall @ 1 = 0.1805
    # Recall @ 5 = 0.4106
    # Recall @ 10 = 0.5302

    結果もなかなか良さげ

    最後に

    今回はimage similarityをtext promptから評価するGeneCISというモデルを試してみました。パッとどんな利用用途があるのかは思いつかないのですが、面白いモデルだと思ったので参考までに載せてみました。

    今後ともLLM, Diffusion model, Image Analysis, 3Dに関連する試した記事を投稿していく予定なのでよろしくお願いします。

    あなたへのおすすめ