OSCR

MIRAGE: Robust multi-modal architectures translate fMRI-to-image models from vision to mental imagery.

Code ↔ Paper

6 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 6 matches
  1. [1] § 2. Results ↔ src/final_evaluations_mi_multi.ipynb, lines 500–559 · score 0.77 · AlexNet, EffNet, InceptionV3, PixCorr, SwAV, brain correlation
  2. [2] § 2. Results ↔ src/plots_across_methods.sh, lines 1–47 · score 0.75 · AlexNet, EffNet, InceptionV3, PixCorr, SwAV, brain correlation
  3. [3] § 4. Methods › 4.2. MIRAGE › 4.2.6 Reconstruction. ↔ src/Train.ipynb, lines 214–238 · score 0.52 · Stable Cascade, text embeddings, image embeddings, latent, train, CLIP
  4. [4] § 4. Methods › 4.2. MIRAGE › 4.2.2. Methodology. ↔ src/Train.ipynb, lines 214–238 · score 0.51 · Stable Cascade, text embedding, image embedding, VDVAE, retrieval, GiT
  5. [5] § 4. Methods › 4.2. MIRAGE › 4.2.2. Methodology. ↔ src/recon_inference_mi.ipynb, lines 192–223 · score 0.51 · Stable Cascade, text embedding, image embedding, VDVAE, retrieval, GiT
  6. [6] § 4. Methods › 4.2. MIRAGE › 4.2.1. Datasets. ↔ src/utils.py, lines 766–850 · score 0.51 · visual cortex, NSD subjects, voxel, mask, stimuli, trained

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 439 lines · 17 KB · MIT · 2 matches

  1. # %% [markdown]
  2. # # Import packages & functions
  3. # %%
  4. import os
  5. import sys
  6. import json
  7. import argparse
  8. import numpy as np
  9. import math
  10. from einops import rearrange
  11. import time
  12. import random
  13. import string
  14. import h5py
  15. from tqdm import tqdm
  16. import webdataset as wds
  17. import gc
  18. from PIL import Image
  19. import matplotlib.pyplot as plt
  20. import torch
  21. import torch.nn as nn
  22. from torchvision import transforms
  23. from sklearn.linear_model import SGDRegressor
  24. from sklearn.preprocessing import StandardScaler
  25. from sklearn.utils import shuffle
  26. # tf32 data type is faster than standard float32
  27. torch.backends.cuda.matmul.allow_tf32 = True
  28. from sklearn.linear_model import Ridge
  29. import pickle
  30. # custom functions #
  31. import utils
  32. from sc_reconstructor import SC_Reconstructor
  33. from vdvae import VDVAE
  34. # %% [markdown]
  35. # # Configurations
  36. # %%
  37. # if running this interactively, can specify jupyter_args here for argparser to use
  38. if utils.is_interactive():
  39. model_name = "subj01_40sess_hypatia_ridge_scsubj01_40sess_hypatia_ridge_sc_medium_captions"
  40. print("model_name:", model_name)
  41. # global_batch_size and batch_size should already be defined in the 2nd cell block
  42. jupyter_args = f"--data_path=../dataset/ \
  43. --cache_dir=../cache/ \
  44. --model_name={model_name} \
  45. --batch_size=64 \
  46. --no-multi_subject --subj=1 --num_sessions=40 \
  47. --dual_guidance --prompt_recon --caption_type medium"
  48. print(jupyter_args)
  49. jupyter_args = jupyter_args.split()
  50. from IPython.display import clear_output # function to clear print outputs in cell
  51. %load_ext autoreload
  52. # this allows you to change functions in models.py or utils.py and have this notebook automatically update with your revisions
  53. %autoreload 2
  54. # %%
  55. parser = argparse.ArgumentParser(description="Model Training Configuration")
  56. parser.add_argument(
  57. "--model_name", type=str, default="testing",
  58. help="name of model, used for ckpt saving and wandb logging (if enabled)",
  59. )
  60. parser.add_argument(
  61. "--data_path", type=str, default=os.getcwd(),
  62. help="Path to where NSD data is stored / where to download it to",
  63. )
  64. parser.add_argument(
  65. "--cache_dir", type=str, default=os.getcwd(),
  66. help="Path to where misc. files downloaded from huggingface are stored. Defaults to current src directory.",
  67. )
  68. parser.add_argument(
  69. "--subj",type=int, default=1, choices=[1,2,3,4,5,6,7,8],
  70. help="Validate on which subject?",
  71. )
  72. parser.add_argument(
  73. "--num_sessions", type=float, default=40,
  74. help="Number of training sessions to include",
  75. )
  76. parser.add_argument(
  77. "--prompt_recon",action=argparse.BooleanOptionalAction, default=True,
  78. help="Use for prompt generating",
  79. )
  80. parser.add_argument(
  81. "--blurry_recon",action=argparse.BooleanOptionalAction,default=True,
  82. help="whether to output blurry reconstructions",
  83. )
  84. parser.add_argument(
  85. "--seed",type=int,default=42,
  86. )
  87. parser.add_argument(
  88. "--weight_decay",type=int,default=100000,
  89. )
  90. parser.add_argument(
  91. "--max_iter",type=int,default=50000,
  92. )
  93. parser.add_argument(
  94. "--dual_guidance",action=argparse.BooleanOptionalAction,default=True,
  95. help="Use the decoded captions for dual guidance",
  96. )
  97. parser.add_argument(
  98. "--caption_type",type=str,default='medium',choices=['coco','short', 'medium', 'schmedium'],
  99. )
  100. parser.add_argument(
  101. "--retrieval",action=argparse.BooleanOptionalAction,default=True,
  102. help="Use the decoded captions for dual guidance",
  103. )
  104. if utils.is_interactive():
  105. args = parser.parse_args(jupyter_args)
  106. else:
  107. args = parser.parse_args()
  108. print(f"args: {args}")
  109. # create global variables without the args prefix
  110. for attribute_name in vars(args).keys():
  111. globals()[attribute_name] = getattr(args, attribute_name)
  112. # seed all random functions
  113. utils.seed_everything(seed)
  114. outdir = os.path.abspath(f'../train_logs/{model_name}')
  115. os.makedirs(outdir,exist_ok=True)
  116. device = "cuda"
  117. # %% [markdown]
  118. # # Prep data, models, and dataloaders
  119. # %%
  120. x_train, valid_nsd_ids_train, x_test, test_nsd_ids = utils.load_nsd(subject=subj, num_sessions=num_sessions, data_path=data_path)
  121. print(x_train.shape, valid_nsd_ids_train.shape)
  122. print(f"Loaded subj {subj} betas!\n")
  123. # %% [markdown]
  124. # ## Prepare git feature
  125. # %%
  126. if not os.path.exists(f'{data_path}/git_image_features.hdf5'):
  127. print("Creating Git Feature...")
  128. from PIL import Image
  129. import requests
  130. from transformers import AutoProcessor, GitVisionModel, AutoModelForCausalLM, GitModel
  131. from modeling_git import GitForCausalLMClipEmb
  132. # Load 73k NSD images
  133. f = h5py.File(f'{data_path}/coco_images_224_float16.hdf5', 'r')
  134. beta_images = f['images']
  135. print("Loaded all 73k possible NSD images to cpu!", beta_images.shape)
  136. git_images = []
  137. processor = AutoProcessor.from_pretrained("microsoft/git-large-coco")
  138. git_text_model = GitForCausalLMClipEmb.from_pretrained("microsoft/git-large-coco")
  139. git_text_model.to(device)
  140. git_text_model.eval().requires_grad_(False)
  141. print("success load Git model")
  142. for i, image in enumerate(tqdm(beta_images)):
  143. pil_image = (image.transpose((1, 2, 0))*255).astype(np.uint8)
  144. inputs = processor(images=pil_image, return_tensors="pt").pixel_values.to(device)
  145. outputs = git_text_model.git.image_encoder(inputs).last_hidden_state
  146. # valid the captions
  147. if i <= 5:
  148. generated_ids = git_text_model.generate(pixel_values=outputs, max_length=50)
  149. generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)
  150. print(generated_caption)
  151. git_images.append(outputs.detach().cpu().numpy())
  152. with h5py.File(f'{data_path}/git_image_features.hdf5', 'w') as f:
  153. f.create_dataset('features', data=np.array(git_images))
  154. print("Finished!")
  155. del beta_images, git_images
  156. else:
  157. print("git_image_features.hdf5 already exist!")
  158. # %%
  159. # Load 73k NSD images
  160. f = h5py.File(f'{data_path}/coco_images_224_float16.hdf5', 'r')
  161. images = f['images'] # if you go OOM you can remove the [:] so it isnt preloaded to cpu! (will require a few edits elsewhere tho)
  162. # images = torch.Tensor(images).to("cpu").to(data_type)
  163. print("Loaded all 73k possible NSD images to cpu!", images.shape)
  164. # Load 73k NSD captions
  165. if caption_type == "schmedium":
  166. captions_small = np.load(f'{data_path}/preprocessed_data/short_length_captions.npy')
  167. captions_medium = np.load(f'{data_path}/preprocessed_data/mid_length_captions_73K.npy')
  168. # Create a mask to randomly select elements from both arrays
  169. mask = np.random.rand(len(captions_small)) > 0.5
  170. # Mix the arrays based on the mask
  171. captions = np.where(mask, captions_small, captions_medium)
  172. else:
  173. if caption_type == "coco":
  174. caption_file = "annots_73k.npy"
  175. elif caption_type == "short":
  176. caption_file = "short_length_captions.npy"
  177. elif caption_type == "medium":
  178. caption_file = "mid_length_captions_73K.npy"
  179. else:
  180. raise ValueError("Invalid caption type")
  181. captions = np.load(f'{data_path}/preprocessed_data/{caption_file}')
  182. print("Loaded all 73k NSD captions to cpu!", captions.shape)
  183. train_images = torch.zeros((len(valid_nsd_ids_train), 3, 224, 224))
  184. train_captions = np.zeros((len(valid_nsd_ids_train),), dtype=object)
  185. # Load specific training data
  186. for i, idx in enumerate(valid_nsd_ids_train):
  187. train_images[i] = torch.from_numpy(images[idx])
  188. train_captions[i] = captions[idx]
  189. print(f"Filtered down to only the {len(valid_nsd_ids_train)} training images for subject {subj}!")
  190. # %% [markdown]
  191. # ## Load models
  192. # %% [markdown]
  193. # ### Feature extractor model
  194. # %%
  195. clip_extractor = SC_Reconstructor(compile_models=False, embedder_only=True, device=device, cache_dir=cache_dir)
  196. vdvae = VDVAE(device=device, cache_dir=cache_dir)
  197. image_embedding_variant = "stable_cascade"
  198. clip_emb_dim = 768
  199. clip_seq_dim = 1
  200. retrieval_embedding_variant = "stable_cascade_hidden"
  201. retrieval_emb_dim = 1024
  202. retrieval_seq_dim = 257
  203. text_embedding_variant = "stable_cascade"
  204. clip_text_seq_dim=77
  205. clip_text_emb_dim=1280
  206. latent_embedding_variant = "vdvae"
  207. latent_emb_dim = 91168
  208. prompt_embedding_variant = "git"
  209. git_seq_dim = 257
  210. git_emb_dim = 1024
  211. if caption_type != "coco":
  212. text_embedding_variant += f"_{caption_type}"
  213. # %% [markdown]
  214. # # Creating block of CLIP embeddings
  215. # %%
  216. file_path = f"{data_path}/preprocessed_data/subject{subj}/{image_embedding_variant}_image_embeddings_train_{num_sessions}sess.pt"
  217. emb_batch_size = 50
  218. if not os.path.exists(file_path):
  219. # Generate CLIP Image embeddings
  220. print("Generating Image embeddings!")
  221. clip_image_train = torch.zeros((len(train_images), clip_seq_dim, clip_emb_dim)).to("cpu")
  222. for i in tqdm(range(len(train_images) // emb_batch_size), desc="Encoding clip images..."):
  223. batch_list = []
  224. for img in train_images[i * emb_batch_size:i * emb_batch_size + emb_batch_size]:
  225. batch_list.append(transforms.ToPILImage()(img))
  226. clip_image_train[i * emb_batch_size:i * emb_batch_size + emb_batch_size] = clip_extractor.embed_image(batch_list).to("cpu")
  227. torch.save(clip_image_train, file_path)
  228. else:
  229. clip_image_train = torch.load(file_path)
  230. if dual_guidance:
  231. emb_batch_size = 50
  232. file_path_txt = f"{data_path}/preprocessed_data/subject{subj}/{text_embedding_variant}_text_embeddings_train_{num_sessions}sess.pt"
  233. if not os.path.exists(file_path_txt):
  234. # Generate CLIP Text embeddings
  235. print("Generating Text embeddings!")
  236. clip_text_train = torch.zeros((len(train_captions), clip_text_seq_dim, clip_text_emb_dim)).to("cpu")
  237. for i in tqdm(range(len(train_captions) // emb_batch_size), desc="Encoding captions..."):
  238. batch_captions = train_captions[i * emb_batch_size:i * emb_batch_size + emb_batch_size].tolist()
  239. clip_text_train[i * emb_batch_size:i * emb_batch_size + emb_batch_size] = clip_extractor.embed_text(batch_captions).to("cpu")
  240. torch.save(clip_text_train, file_path_txt)
  241. else:
  242. clip_text_train = torch.load(file_path_txt)
  243. if blurry_recon:
  244. emb_batch_size = 1
  245. file_path = f"{data_path}/preprocessed_data/subject{subj}/{latent_embedding_variant}_latent_embeddings_train_{num_sessions}sess.pt"
  246. if not os.path.exists(file_path):
  247. print("Generating Latent Image embeddings!")
  248. vae_image_train = torch.zeros((len(train_images), latent_emb_dim)).to("cpu")
  249. for i in tqdm(range(len(train_images)), desc="Encoding blurry images..."):
  250. img = transforms.ToPILImage()(train_images[i])
  251. vae_image_train[i * emb_batch_size:i * emb_batch_size + emb_batch_size] = vdvae.embed_latent(img).reshape(-1, latent_emb_dim).to("cpu")
  252. torch.save(vae_image_train, file_path)
  253. else:
  254. vae_image_train = torch.load(file_path)
  255. if retrieval:
  256. file_path = f"{data_path}/preprocessed_data/subject{subj}/{retrieval_embedding_variant}_retrieval_embeddings_train_{num_sessions}sess.pt"
  257. emb_batch_size = 50
  258. if not os.path.exists(file_path):
  259. # Generate CLIP Retrieval embeddings
  260. print("Generating Retrieval embeddings!")
  261. retrieval_image_train = torch.zeros((len(train_images), retrieval_seq_dim, retrieval_emb_dim)).to("cpu")
  262. for i in tqdm(range(len(train_images) // emb_batch_size), desc="Encoding images..."):
  263. batch_list = []
  264. for img in train_images[i * emb_batch_size:i * emb_batch_size + emb_batch_size]:
  265. batch_list.append(transforms.ToPILImage()(img))
  266. retrieval_image_train[i * emb_batch_size:i * emb_batch_size + emb_batch_size] = clip_extractor.embed_image(batch_list, hidden=True).to("cpu")
  267. # Normalize for optimal cosine similarity
  268. retrieval_image_train = torch.nn.functional.normalize(retrieval_image_train, p=2, dim=2)
  269. torch.save(retrieval_image_train, file_path)
  270. else:
  271. retrieval_image_train = torch.load(file_path)
  272. # Load 73k GiT NSD features
  273. if prompt_recon:
  274. file_path_git = f"{data_path}/preprocessed_data/subject{subj}/{prompt_embedding_variant}_prompt_embeddings_train_{num_sessions}sess.pt"
  275. if not os.path.exists(file_path_git):
  276. with h5py.File(f'{data_path}/git_image_features.hdf5', 'r') as f:
  277. git_features = f['features'][:]
  278. train_git_images = torch.zeros((len(valid_nsd_ids_train), 257,1024))
  279. for i, idx in enumerate(valid_nsd_ids_train):
  280. train_git_images[i] = torch.from_numpy(git_features[idx])
  281. torch.save(train_git_images, file_path_git)
  282. del git_features
  283. else:
  284. train_git_images = torch.load(file_path_git)
  285. print(f"Loaded vectors for subj{subj}!")
  286. # %% [markdown]
  287. # # Train Ridge regression models
  288. # %%
  289. start = time.time()
  290. ridge_weights = np.zeros((clip_seq_dim * clip_emb_dim, x_train.shape[-1])).astype(np.float32)
  291. ridge_biases = np.zeros((clip_seq_dim * clip_emb_dim)).astype(np.float32)
  292. print(f"Training Ridge Image model with alpha={weight_decay}")
  293. model = Ridge(
  294. alpha=weight_decay,
  295. max_iter=max_iter,
  296. random_state=42,
  297. )
  298. model.fit(x_train, clip_image_train.reshape(len(clip_image_train), -1))
  299. ridge_weights = model.coef_
  300. ridge_biases = model.intercept_
  301. datadict = {"coef" : ridge_weights, "intercept" : ridge_biases}
  302. # Save the regression weights
  303. with open(f'{outdir}/ridge_image_weights.pkl', 'wb') as f:
  304. pickle.dump(datadict, f)
  305. del clip_image_train
  306. del ridge_weights
  307. del ridge_biases
  308. del datadict
  309. if dual_guidance:
  310. ridge_weights_txt = np.zeros((clip_text_seq_dim * clip_text_emb_dim, x_train.shape[-1])).astype(np.float32)
  311. ridge_biases_txt = np.zeros((clip_text_seq_dim * clip_text_emb_dim)).astype(np.float32)
  312. print(f"Training Ridge Text model with alpha={weight_decay}")
  313. model = Ridge(
  314. alpha=weight_decay,
  315. max_iter=max_iter,
  316. random_state=42,
  317. )
  318. model.fit(x_train, clip_text_train.reshape(len(clip_text_train), -1))
  319. ridge_weights_txt = model.coef_
  320. ridge_biases_txt = model.intercept_
  321. datadict = {"coef" : ridge_weights_txt, "intercept" : ridge_biases_txt}
  322. # Save the regression weights
  323. with open(f'{outdir}/ridge_text_weights.pkl', 'wb') as f:
  324. pickle.dump(datadict, f)
  325. del clip_text_train
  326. del ridge_weights_txt
  327. del ridge_biases_txt
  328. del datadict
  329. if blurry_recon:
  330. ridge_weights_blurry = np.zeros((latent_emb_dim, x_train.shape[-1])).astype(np.float32)
  331. ridge_biases_blurry = np.zeros((latent_emb_dim,)).astype(np.float32)
  332. print(f"Training Ridge Blurry recon model with alpha={weight_decay}")
  333. model = Ridge(
  334. alpha=weight_decay,
  335. max_iter=max_iter,
  336. random_state=42,
  337. )
  338. model.fit(x_train, vae_image_train)
  339. ridge_weights_blurry = model.coef_
  340. ridge_biases_blurry = model.intercept_
  341. datadict = {"coef" : ridge_weights_blurry, "intercept" : ridge_biases_blurry}
  342. # Save the regression weights
  343. with open(f'{outdir}/ridge_blurry_weights.pkl', 'wb') as f:
  344. pickle.dump(datadict, f)
  345. del vae_image_train
  346. del ridge_weights_blurry
  347. del ridge_biases_blurry
  348. del datadict
  349. if retrieval:
  350. ridge_weights = np.zeros((retrieval_seq_dim * retrieval_emb_dim, x_train.shape[-1])).astype(np.float32)
  351. ridge_biases = np.zeros((retrieval_seq_dim * retrieval_emb_dim)).astype(np.float32)
  352. print(f"Training Ridge Retrieval model with alpha={weight_decay}")
  353. model = Ridge(
  354. alpha=weight_decay,
  355. max_iter=max_iter,
  356. random_state=42,
  357. )
  358. x_train_norm = torch.nn.functional.normalize(x_train, p=2, dim=1)
  359. model.fit(x_train_norm, retrieval_image_train.reshape(len(retrieval_image_train), -1))
  360. ridge_weights = model.coef_
  361. ridge_biases = model.intercept_
  362. datadict = {"coef" : ridge_weights, "intercept" : ridge_biases}
  363. # Save the regression weights
  364. with open(f'{outdir}/ridge_retrieval_weights.pkl', 'wb') as f:
  365. pickle.dump(datadict, f)
  366. del retrieval_image_train
  367. del ridge_weights
  368. del ridge_biases
  369. del datadict
  370. if prompt_recon:
  371. ridge_weights_prompt = np.zeros((git_seq_dim*git_emb_dim, x_train.shape[-1])).astype(np.float32)
  372. ridge_biases_prompt = np.zeros((git_seq_dim*git_emb_dim)).astype(np.float32)
  373. print(f"Training Ridge prompt recon model with alpha={weight_decay}")
  374. model = Ridge(
  375. alpha=weight_decay,
  376. max_iter=max_iter,
  377. random_state=42,
  378. )
  379. model.fit(x_train, train_git_images.reshape(len(train_git_images), -1))
  380. ridge_weights_prompt = model.coef_
  381. ridge_biases_prompt = model.intercept_
  382. datadict = {"coef" : ridge_weights_prompt, "intercept" : ridge_biases_prompt}
  383. # Save the regression weights
  384. with open(f'{outdir}/ridge_prompt_weights.pkl', 'wb') as f:
  385. pickle.dump(datadict, f)
  386. del train_git_images
  387. del ridge_weights_prompt
  388. del ridge_biases_prompt
  389. del datadict
  390. print(f"Elapsed training time for {model_name}: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start))}")

Train.ipynb at commit 7dbc13f, under MIT · at the source

Overview

Authors: Reese Kneeland1,2, Cesar Kadir Torrico Villanueva2, Tong Chen2,3, Jordyn Ojeda1, Shubh Khanna4, Jonathan Xu2,5, Paul S. Scotti2,6,7, Thomas Naselaris1
ORCID iDs: Reese Kneeland
  1. University of Minnesota, Minneapolis, Minnesota, United States of America
  2. Medical AI Research Center (MedARC), San Francisco, California, United States of America
  3. University of Sydney, Sydney, Australia
  4. Stanford University, Palo Alto, California, United States of America
  5. Alljoined, San Francisco, California, Unites States of America
  6. Sophont, San Francisco, California‌‌, Unites States of America
  7. Princeton Neuroscience Institute, Princeton, New Jersey,‌‌ United States of America
Institutions: University of Minnesota (United States); The University of Sydney (Australia); Stanford University (United States); Princeton University (United States)
Journal: PLoS computational biology, volume 22, issue 5, article e1014263
Dates: received 1 September 2025; accepted 23 April 2026; published online 22 May 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1371/journal.pcbi.1014263 · PMID 42172302 · PMCID PMC13218618 · OpenAlex W7162087174
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: fMRI (modality), human (organism)
Methods: Statistics, Machine learning, fMRI & imaging
MeSH: Brain*, Image Processing, Computer-Assisted*, Imagination*, Magnetic Resonance Imaging*, Algorithms, Brain Mapping, Computational Biology, Humans (* major topic)
Journal subjects: Biology and Life Sciences, Neuroscience, Brain Mapping, Functional Magnetic Resonance Imaging, Medicine and Health Sciences, Diagnostic Medicine, Diagnostic Radiology, Magnetic Resonance Imaging, Research and Analysis Methods, Imaging Techniques, Radiology and Imaging, Neuroimaging, Cognitive Science, Cognitive Psychology, Perception, Sensory Perception, Vision, Psychology, Social Sciences, Anatomy, Brain, Visual Cortex, Engineering and Technology, Electronics Engineering, Electronics, Signal Decoders, Signal Processing, Signal to Noise Ratio
Topic: Face Recognition and Perception (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: National Eye Institute (R01EY023384 and R01EY038606)
Citations: not cited yet (Europe PMC); 72 references in the paper

Abstract

To be useful for downstream applications, vision decoding models that are trained to reconstruct seen images from human brain activity must be able to generalize to internally generated visual representations, i.e., mental images. In an analysis of the recently released NSD-Imagery dataset, we demonstrated that while some modern vision decoders can perform quite well on mental image reconstruction, some fail, and that state-of-the-art (SOTA) performance on seen image reconstruction is no guarantee of SOTA performance on mental image reconstruction. Motivated by these findings, we developed MIRAGE, a method explicitly designed to train on vision datasets and cross-decode mental images from brain activity. MIRAGE employs a linear backbone and multi-modal text and image features as input to a diffusion model. Feature metrics and human raters establish MIRAGE as SOTA for mental image reconstruction on the NSD-Imagery benchmark. With ablation analysis we show that mental image reconstruction works best when decoders use image features with relatively few dimensions and include guidance from text-based and both high- and low-level image-based features. Our work indicates that–given the right architecture–existing large-scale datasets using external stimuli are viable training data for decoding mental images, and warrant optimism about the future success and utility of mental image reconstruction.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 6 matches between paragraphs and lines of code.

naturalscenesdataset.org

License: none: the authors keep all their rights
State: the link answers, verified on 28 September 2026
Evidence: the link answers
Software Heritage: not checked
Found in: “Data Availability”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Availability: 1 check, the latest on 28 September 2026: the link answers (HTTP 200)
  • 28 September 2026: the link answers (HTTP 200)

MedARC-AI/MIRAGE

License: MIT
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Commit: 7dbc13fb888df0845ea40c4a8c7375cf0bce626f, 16 February 2025
Languages: Python (82), Shell (10), Jupyter (6)
Size: 154 files, 98 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README, license file, environment (src/requirements.txt, src/generative_models/pyproject.toml, src/generative_models/requirements/pt2.txt), tests, 6 notebooks
Not found: CITATION.cff, continuous integration, documentation
Tools: PyTorch (61 files), NumPy (35 files), Pillow (15 files), Matplotlib (10 files), PyTorch Lightning (9 files), h5py (7 files), Hugging Face Transformers (6 files), pandas (5 files), scikit-learn (5 files), OpenCV (4 files), SciPy (4 files), imageio (2 files), NiBabel (2 files), scikit-image (2 files), UMAP (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers
  • 28 September 2026: the link answers
100 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 98 scripts, each with its path and the digest of its content;
  • 6 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data Availability

NSD-Imagery data has been released publically, and can be accessed at https://naturalscenesdataset.org/ The code for the MIRAGE method is open source and available at https://github.com/MedARC-AI/MIRAGE.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 28 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 8 authors, 8 MeSH terms, 1 funder, 44 references.

Cite

This paper

Kneeland, R., Villanueva, C. K. T., Chen, T., Ojeda, J., Khanna, S., Xu, J., Scotti, P. S., & Naselaris, T. (2026). MIRAGE: Robust multi-modal architectures translate fMRI-to-image models from vision to mental imagery. PLoS computational biology, 22(5), e1014263. https://doi.org/10.1371/journal.pcbi.1014263

BibTeX

@article{kneeland2026mirage,
author = {Kneeland, Reese and Villanueva, Cesar Kadir Torrico and Chen, Tong and Ojeda, Jordyn and Khanna, Shubh and Xu, Jonathan and Scotti, Paul S. and Naselaris, Thomas},
title = {{MIRAGE: Robust multi-modal architectures translate fMRI-to-image models from vision to mental imagery}},
journal = {PLoS computational biology},
year = {2026},
month = may,
volume = {22},
number = {5},
pages = {e1014263},
publisher = {PLOS},
issn = {1553-734X},
doi = {10.1371/journal.pcbi.1014263},
url = {https://doi.org/10.1371/journal.pcbi.1014263},
pmid = {42172302},
pmcid = {PMC13218618}
}

RIS

TY - JOUR
AU - Kneeland, Reese
AU - Villanueva, Cesar Kadir Torrico
AU - Chen, Tong
AU - Ojeda, Jordyn
AU - Khanna, Shubh
AU - Xu, Jonathan
AU - Scotti, Paul S.
AU - Naselaris, Thomas
TI - MIRAGE: Robust multi-modal architectures translate fMRI-to-image models from vision to mental imagery
T2 - PLoS computational biology
J2 - PLoS Comput Biol
PY - 2026
DA - 2026/05/22
VL - 22
IS - 5
SP - e1014263
SN - 1553-734X
PB - PLOS
DO - 10.1371/journal.pcbi.1014263
UR - https://doi.org/10.1371/journal.pcbi.1014263
LA - en
ER -

CSL-JSON

{
"id": "10.1371/journal.pcbi.1014263",
"type": "article-journal",
"title": "MIRAGE: Robust multi-modal architectures translate fMRI-to-image models from vision to mental imagery",
"container-title": "PLoS computational biology",
"author": [
{
"family": "Kneeland",
"given": "Reese"
},
{
"family": "Villanueva",
"given": "Cesar Kadir Torrico"
},
{
"family": "Chen",
"given": "Tong"
},
{
"family": "Ojeda",
"given": "Jordyn"
},
{
"family": "Khanna",
"given": "Shubh"
},
{
"family": "Xu",
"given": "Jonathan"
},
{
"family": "Scotti",
"given": "Paul S."
},
{
"family": "Naselaris",
"given": "Thomas"
}
],
"container-title-short": "PLoS Comput Biol",
"volume": "22",
"issue": "5",
"page": "e1014263",
"DOI": "10.1371/journal.pcbi.1014263",
"PMID": "42172302",
"PMCID": "PMC13218618",
"ISSN": "1553-734X",
"publisher": "PLOS",
"URL": "https://doi.org/10.1371/journal.pcbi.1014263",
"language": "en",
"issued": {
"date-parts": [
[
2026,
5,
22
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.7554/elife.107933 [code]
Modality-agnostic decoding of vision and language from fMRI.
Journal: eLife
In common: Hugging Face Transformers, OpenCV, scikit-image, 9 other tools, fMRI, 11 references
[2] doi:10.1007/s12021-026-09803-3 [code]
NeuroFusion: A Unified Framework for Generalized Visual Stimulus Decoding from fMRI Across Datasets and Subjects.
Journal: Neuroinformatics
In common: PyTorch Lightning, scikit-image, h5py, 8 other tools, fMRI, 6 references
[3] doi:10.1162/imag.a.1299 [code]
A modular semantic-structural pipeline for visual decoding from primate spiking data via selective temporal integration.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: PyTorch Lightning, Hugging Face Transformers, scikit-image, 8 other tools, 6 references
[4] doi:10.1038/s41597-026-07248-6 [code]
A large-scale fMRI dataset for vision-language semantic association.
Journal: Scientific data
In common: imageio, OpenCV, scikit-image, 9 other tools, fMRI, 3 references
[5] doi:10.1162/imag.a.1326 [code]
RAVEN: Robust, generalizable, multi-resolution structural MRI upsampling using autoencoders.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: PyTorch Lightning, imageio, Hugging Face Transformers, 10 other tools
[6] doi:10.1038/s42003-026-10169-0 [code]
Shared representations in brains and models reveal a two-route cortical organization during scene perception.
Journal: Communications biology
In common: Hugging Face Transformers, h5py, Pillow, 7 other tools, 3 references
[7] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: PyTorch Lightning, Hugging Face Transformers, UMAP, 9 other tools
[8] doi:10.1038/s41467-026-71267-5 [code]
Human-like cognitive generalization for large models via mental representation-guided supervision.
Journal: Nature communications
In common: Hugging Face Transformers, UMAP, scikit-image, 8 other tools, 1 reference
[9] doi:10.1371/journal.pcbi.1013499 [code]
VesiclePy: A machine learning vesicle analysis toolbox for volume electron microscopy.
Journal: PLoS computational biology
In common: imageio, UMAP, OpenCV, 9 other tools
[10] doi:10.1371/journal.pcbi.1014656 [code]
Contrastive learning to fine-tune feature extraction models for the visual cortex.
Journal: PLoS computational biology
In common: Pillow, NiBabel, PyTorch, 5 other tools, fMRI, 4 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.