Download predict_ube.py from Goeschel/sub-005_task-C_ube-inputs: direct link, hf CLI and curl.
- Browser
- Download file 2.76 kB
-
https://huggingface.co/datasets/Goeschel/sub-005_task-C_ube-inputs/resolve/main/predict_ube.py
- Command line
-
hf download hf://datasets/Goeschel/sub-005_task-C_ube-inputs/predict_ube.py
-
curl -L -o predict_ube.py https://huggingface.co/datasets/Goeschel/sub-005_task-C_ube-inputs/resolve/main/predict_ube.py
2.76 kB
| """Predict the 50 test patterns with an encoder trained by the original UBE code. | |
| For checkpoints saved by train_transfer/train_encoder_transfer_custom.py in | |
| https://github.com/WeizmannVision/universal-brain-encoder-code (a whole pickled model). | |
| Run from the root of that repo, which the pickle needs in order to import the model code. | |
| Image preprocessing and the model call follow that repo's inference/predict_fmri_for_images.py. | |
| python predict_ube.py --model results/saved_models/transfer/<name>.pth \ | |
| --images sub-005/test/images.npy --out pred.npy | |
| The output (50, 2792) goes straight into score_retrieval.py. Models that are not UBE only | |
| need to produce the same array: one row per test image, columns in the order of the fMRI. | |
| """ | |
| import argparse | |
| import os | |
| import sys | |
| import numpy as np | |
| import torch | |
| sys.path.append(os.getcwd()) # as in the original repo's scripts, so the pickle finds models/ | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--model", required=True, help="checkpoint from train_encoder_transfer_custom.py") | |
| ap.add_argument("--images", required=True, help="test images .npy, (50, 224, 224, 3) uint8") | |
| ap.add_argument("--out", required=True, help="where to save the predictions .npy") | |
| args = ap.parse_args() | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| # The pickled model contains a DINOv2 backbone whose code comes from torch hub, so it has to | |
| # be loaded once before torch.load can unpickle the model (same two lines as the original repo). | |
| torch.hub.set_dir("data/external_models/torch_hub/") | |
| torch.hub.load("facebookresearch/dinov2", "dinov2_vits14_reg") | |
| model = torch.load(args.model, map_location=device, weights_only=False).eval().to(device) | |
| # A transfer model has one voxel embedding per training voxel; predict all of them, in order, | |
| # so prediction column k is the same voxel as column k of the fMRI arrays. | |
| n_voxels = model.voxel_embed.shape[0] | |
| vox_ind = torch.arange(n_voxels, device=device).unsqueeze(0) | |
| # ImageNet normalisation, as in the original repo: scale to [0, 1], normalise, and reorder | |
| # height x width x RGB to RGB x height x width. No random shift at test time. | |
| MEAN = np.array([0.485, 0.456, 0.406]).reshape([1, 1, 3]) | |
| STD = np.array([0.229, 0.224, 0.225]).reshape([1, 1, 3]) | |
| images = np.load(args.images) | |
| pred = np.zeros((len(images), n_voxels), dtype=np.float32) | |
| with torch.no_grad(): | |
| for i, img in enumerate(images): | |
| x = ((img / 255.0 - MEAN) / STD).transpose([2, 0, 1]) | |
| x = torch.from_numpy(x.astype(np.float32)).unsqueeze(0).to(device) | |
| pred[i] = model(x, vox_ind).cpu().numpy() | |
| np.save(args.out, pred) | |
| print(f"saved {pred.shape} predictions -> {args.out}") | |