code: def instance_retrieval_test(args, cfg):
      if (
          cfg.IMG_RETRIEVAL.USE_FEATURE_EXTRACTION_ENGINE
          and not cfg.IMG_RETRIEVAL.FEATURE_EXTRACTION_DIR
      ):
          # We require 1-gpu for feature extraction. Hence check CUDA is available.
          # If we provide FEATURE_EXTRACTION_DIR, we have already extracted the features
          # and do not require GPU.
          assert torch.cuda.is_available(), "CUDA not available, Exit!"
  
      train_dataset_name = cfg.IMG_RETRIEVAL.TRAIN_DATASET_NAME
      eval_dataset_name = cfg.IMG_RETRIEVAL.EVAL_DATASET_NAME
      spatial_levels = cfg.IMG_RETRIEVAL.SPATIAL_LEVELS
      resize_img = cfg.IMG_RETRIEVAL.RESIZE_IMG
      eval_binary_path = cfg.IMG_RETRIEVAL.EVAL_BINARY_PATH
      root_dataset_path = cfg.IMG_RETRIEVAL.DATASET_PATH
      save_features = cfg.IMG_RETRIEVAL.SAVE_FEATURES
      use_feature_extractor = (
          cfg.IMG_RETRIEVAL.USE_FEATURE_EXTRACTION_ENGINE
      )
  
      temp_dir = None
  
      if save_features:
          temp_dir = os.path.join(
              get_checkpoint_folder(cfg), "features"
          )
          logging.info(f"Temp directory: {temp_dir}")
  
      ############################################################################
      # Step 1: Prepare the train/eval datasets, create model and load weights
      # We only create the train dataset if we need PCA/whitening otherwise
      # train_dataset is None
      train_dataset = get_train_dataset(
          cfg, root_dataset_path, train_dataset_name, eval_binary_path
      )
  
      # create the eval dataset. INSTRE data evaluation requires whitening.
      eval_dataset = get_eval_dataset(
          cfg, root_dataset_path, eval_dataset_name, eval_binary_path
      )
  
      # Setup the data transforms (basic) that we apply on the train/eval dataset.
      transforms = get_transforms(cfg, eval_dataset_name)
  
      # Create the image helper
      image_helper = InstanceRetrievalImageLoader(
          S=resize_img,
          transforms=transforms,
          center_crop=cfg.IMG_RETRIEVAL.CENTER_CROP,
      )
  
      model = None
      if not use_feature_extractor:
          # Build the model on gpu and set in the eval mode
          model = build_retrieval_model(cfg)
          model = copy_model_to_gpu(model)
  
          logging.info("Freezing the model.....")
          model.eval()
          model.freeze_head_and_trunk()
  
      ############################################################################
      # Step 2: Extract the features for the train dataset, calculate PCA or
      # whitening and save
      if cfg.IMG_RETRIEVAL.TRAIN_PCA_WHITENING:
          logging.info("Extracting training features...")
          # the features are already processed based on type: rmac | GeM | l2 norm
          with PerfTimer("get_train_features", PERF_STATS):
              # TODO: encapsulate the approach "WithFeatureExtractor" from the other one.
              if use_feature_extractor:
                  input_dir = (
                      cfg.IMG_RETRIEVAL.FEATURE_EXTRACTION_DIR
                      or get_checkpoint_folder(cfg)
                  )
                  input_dir = os.path.join(input_dir, "train_database")
                  train_features = load_and_process_features(
                      cfg, input_dir, "train"
                  )
  
              else:
                  train_features = extract_train_features(
                      cfg,
                      temp_dir,
                      train_dataset_name,
                      resize_img,
                      spatial_levels,
                      image_helper,
                      train_dataset,
                      model,
                  )
  
              train_features = np.vstack(
                  [x.reshape(-1, x.shape[-1]) for x in train_features]
              )
  
          ########################################################################
          # Train PCA on the train features
          pca_out_fname = None
          if temp_dir:
              pca_out_fname = f"{temp_dir}/{train_dataset_name}_S{resize_img}_PCA.pickle"
          if pca_out_fname and g_pathmgr.exists(pca_out_fname):
              logging.info("Loading PCA...")
              pca = load_pca(pca_out_fname)
          else:
              logging.info("Training and saving PCA...")
              pca = train_and_save_pca(
                  train_features, cfg.IMG_RETRIEVAL.N_PCA, pca_out_fname
              )
      else:
          pca = None
  
      ############################################################################
      # Step 4: Extract db_features and q_features for the eval dataset
      with PerfTimer("get_query_features", PERF_STATS):
          logging.info("Extracting Queries features...")
          # TODO: encapsulate the approach "WithFeatureExtractor" from the other one.
          if use_feature_extractor:
              input_dir = (
                  cfg.IMG_RETRIEVAL.FEATURE_EXTRACTION_DIR
                  or get_checkpoint_folder(cfg)
              )
              input_dir = os.path.join(input_dir, "query")
              features_queries = load_and_process_features(
                  cfg, input_dir, "test", pca
              )
  
          else:
              features_queries = get_queries_features(
                  cfg,
                  temp_dir,
                  eval_dataset_name,
                  resize_img,
                  spatial_levels,
                  image_helper,
                  eval_dataset,
                  model,
                  pca,
              )
  
          features_queries = np.vstack(features_queries)
  
      with PerfTimer("get_dataset_features", PERF_STATS):
          logging.info("Extracting Dataset features...")
          # TODO: encapsulate the approach "WithFeatureExtractor" from the other one.
          if use_feature_extractor:
              input_dir = (
                  cfg.IMG_RETRIEVAL.FEATURE_EXTRACTION_DIR
                  or get_checkpoint_folder(cfg)
              )
              input_dir = os.path.join(input_dir, "train_database")
              features_dataset = load_and_process_features(
                  cfg, input_dir, "test", pca
              )
          else:
              features_dataset = get_dataset_features(
                  cfg,
                  temp_dir,
                  eval_dataset_name,
                  resize_img,
                  spatial_levels,
                  image_helper,
                  eval_dataset,
                  model,
                  pca,
              )
  
          features_dataset = np.vstack(features_dataset)
  
      ############################################################################
      # Step 5: Compute similarity, score, and save results
      with PerfTimer("scoring_results", PERF_STATS):
          logging.info("Calculating similarity and score...")
  
          if (
              cfg.IMG_RETRIEVAL.SIMILARITY_MEASURE
              == "cosine_similarity"
          ):
              sim = features_queries.dot(features_dataset.T)
          elif cfg.IMG_RETRIEVAL.SIMILARITY_MEASURE == "l2":
              sim = -compute_l2_distance_matrix(
                  features_queries, features_dataset
              )
          else:
              raise ValueError(
                  f"{ cfg.IMG_RETRIEVAL.SIMILARITY_MEASURE } not supported."
              )
  
          logging.info(f"Similarity tensor: {sim.shape}")
          results = eval_dataset.score(sim, temp_dir)
  
      ############################################################################
      # Step 6: save results and cleanup the temp directory
      if cfg.IMG_RETRIEVAL.SAVE_RETRIEVAL_RANKINGS_SCORES:
          checkpoint_folder = get_checkpoint_folder(cfg)
  
          # Save the rankings
          sim = sim.T
          ranks = np.argsort(-sim, axis=0)
          save_file(
              ranks.T.tolist(),
              os.path.join(checkpoint_folder, "rankings.json"),
          )
  
          # Save the similarity scores
          save_file(
              sim.tolist(),
              os.path.join(checkpoint_folder, "similarity_scores.json"),
          )
          # Save the result metrics
          save_file(
              results,
              os.path.join(checkpoint_folder, "metrics.json"),
              append_to_json=False,
          )
  
      logging.info("All done!!")
  
imports: import logging
  import os
  import sys
  from argparse import Namespace
  from typing import Any, List
  import numpy
  import torch
  import torchvision
  from classy_vision.generic.util import copy_model_to_gpu, load_checkpoint
  from iopath.common.file_io import g_pathmgr
  from vissl.config import AttrDict
  from vissl.hooks import default_hook_generator
  from vissl.models import build_model
  from vissl.utils.checkpoint import get_checkpoint_folder, init_model_from_consolidated_weights
  from vissl.utils.distributed_launcher import launch_distributed
  from vissl.utils.env import set_env_vars, setup_path_manager
  from vissl.utils.extract_features_utils import ExtractedFeaturesLoader
  from vissl.utils.hydra_config import compose_hydra_configuration, convert_to_attrdict, print_cfg
  from vissl.utils.instance_retrieval_utils.data_util import CopyDaysDataset, GenericInstanceRetrievalDataset, get_average_gem, InstanceRetrievalDataset, InstanceRetrievalImageLoader, InstreDataset, is_copdays_dataset, is_instre_dataset, is_oxford_paris_dataset, is_revisited_dataset, is_whiten_dataset, l2n, MultigrainResize, RevisitedInstanceRetrievalDataset, WhiteningTrainingImageDataset
  from vissl.utils.instance_retrieval_utils.rmac import get_rmac_descriptors
  from vissl.utils.io import load_file, makedir, save_file
  from vissl.utils.logger import setup_logging, shutdown_logging
  from vissl.utils.pca import load_pca, train_and_save_pca
  from vissl.utils.perf_stats import PerfStats, PerfTimer
label_desc: Use image node_id 13 for calling a global function with example usage: instance_retrieval_test(args, cfg) without return types