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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b8e236f1-385a-4d93-bb39-bea3ee384d76",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "outdir /weka/proj-fmri/ckadirt/fMRI-foundation-model/src/checkpoints/HCPflat_large_gsrFalse_\n",
      "Loaded config.yaml from ckpt folder /weka/proj-fmri/ckadirt/fMRI-foundation-model/src/checkpoints/HCPflat_large_gsrFalse_\n",
      "\n",
      "__CONFIG__\n",
      "base_lr = 0.001\n",
      "batch_size = 32\n",
      "ckpt_interval = 5\n",
      "ckpt_saving = True\n",
      "cls_embed = True\n",
      "contrastive_loss_weight = 1.0\n",
      "datasets_to_include = HCP\n",
      "decoder_embed_dim = 512\n",
      "grad_accumulation_steps = 1\n",
      "grad_clip = 1.0\n",
      "gsr = False\n",
      "hcp_flat_path = /weka/proj-medarc/shared/HCP-Flat\n",
      "mask_ratio = 0.75\n",
      "model_name = HCPflat_large_gsrFalse_\n",
      "no_qkv_bias = False\n",
      "norm_pix_loss = False\n",
      "nsd_flat_path = /weka/proj-medarc/shared/NSD-Flat\n",
      "num_epochs = 100\n",
      "num_frames = 16\n",
      "num_samples_per_epoch = 200000\n",
      "num_workers = 10\n",
      "patch_size = 16\n",
      "pct_masks_to_decode = 1\n",
      "plotting = True\n",
      "pred_t_dim = 8\n",
      "print_interval = 20\n",
      "probe_base_lr = 0.0003\n",
      "probe_batch_size = 8\n",
      "probe_num_epochs = 30\n",
      "probe_num_samples_per_epoch = 100000\n",
      "resume_from_ckpt = True\n",
      "seed = 42\n",
      "sep_pos_embed = True\n",
      "t_patch_size = 2\n",
      "test_num_samples_per_epoch = 50000\n",
      "test_set = False\n",
      "trunc_init = False\n",
      "use_contrastive_loss = False\n",
      "wandb_log = True\n",
      "\n",
      "\n",
      "PID of this process = 1830897\n"
     ]
    }
   ],
   "source": [
    "# Import packages and setup gpu configuration.\n",
    "# This code block shouldnt need to be adjusted other than the model_name (if interactive)!\n",
    "import os\n",
    "import sys\n",
    "import json\n",
    "import yaml\n",
    "import numpy as np\n",
    "import math\n",
    "import time\n",
    "import datetime\n",
    "import random\n",
    "from tqdm import tqdm\n",
    "import webdataset as wds\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from torchvision import transforms\n",
    "import utils\n",
    "from mae_utils import flat_models\n",
    "from elbow.sinks import BufferedParquetWriter\n",
    "\n",
    "## MODEL TO LOAD ##\n",
    "if utils.is_interactive():\n",
    "    model_name = \"HCPflat_large_gsrFalse_\"\n",
    "else:\n",
    "    model_name = sys.argv[1]\n",
    "outdir = os.path.abspath(f'checkpoints/{model_name}')\n",
    "print(\"outdir\", outdir)\n",
    "\n",
    "# Load previously saved config.yaml made during main training script\n",
    "assert os.path.exists(f\"{outdir}/config.yaml\")\n",
    "config = yaml.load(open(f\"{outdir}/config.yaml\", 'r'), Loader=yaml.FullLoader)\n",
    "print(f\"Loaded config.yaml from ckpt folder {outdir}\")\n",
    "# create global variables from the config\n",
    "print(\"\\n__CONFIG__\")\n",
    "for attribute_name in config.keys():\n",
    "    print(f\"{attribute_name} = {config[attribute_name]}\")\n",
    "    globals()[attribute_name] = config[f'{attribute_name}']\n",
    "print(\"\\n\")\n",
    "\n",
    "if utils.is_interactive():\n",
    "    # Following allows you to change functions in other files and \n",
    "    # have this notebook automatically update with your revisions\n",
    "    %load_ext autoreload\n",
    "    %autoreload 2\n",
    "\n",
    "device = torch.device('cuda')\n",
    "\n",
    "print(\"PID of this process =\",os.getpid())\n",
    "\n",
    "# seed all random functions\n",
    "utils.seed_everything(seed)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d505c08d-bd96-4b99-b7d9-32af3c50579e",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ['HCP_FLAT_ROOT'] = hcp_flat_path\n",
    "# os.environ['global_pool'] = \"False\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "fb0a4f06-c75b-4255-ab94-ea6206330778",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "global_pool = False\n",
      "gsr = False\n"
     ]
    }
   ],
   "source": [
    "if os.getenv('global_pool') == \"False\":\n",
    "    global_pool = False\n",
    "else:\n",
    "    global_pool = True\n",
    "print(f\"global_pool = {global_pool}\")\n",
    "\n",
    "try:\n",
    "    gsr\n",
    "except:\n",
    "    gsr = True\n",
    "    print(\"set gsr to True\")\n",
    "print(f\"gsr = {gsr}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab15aca0-148e-435f-b8f2-7a708b61a6d9",
   "metadata": {},
   "source": [
    "# hcp_flat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "de1a5b87-fa69-44e1-bdb9-bd9e257485c6",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "img_size (144, 320) patch_size (16, 16) frames 16 t_patch_size 2\n",
      "model initialized\n"
     ]
    }
   ],
   "source": [
    "from mae_utils.flat import load_hcp_flat_mask\n",
    "from mae_utils.flat import create_hcp_flat\n",
    "from mae_utils.flat import batch_unmask\n",
    "import mae_utils.visualize as vis\n",
    "\n",
    "flat_mask = load_hcp_flat_mask(hcp_flat_path)\n",
    "\n",
    "model = flat_models.mae_vit_large_fmri(\n",
    "    patch_size=patch_size,\n",
    "    decoder_embed_dim=decoder_embed_dim,\n",
    "    t_patch_size=t_patch_size,\n",
    "    pred_t_dim=pred_t_dim,\n",
    "    decoder_depth=4,\n",
    "    cls_embed=cls_embed,\n",
    "    norm_pix_loss=norm_pix_loss,\n",
    "    no_qkv_bias=no_qkv_bias,\n",
    "    sep_pos_embed=sep_pos_embed,\n",
    "    trunc_init=trunc_init,\n",
    "    pct_masks_to_decode=pct_masks_to_decode,\n",
    "    img_mask=flat_mask,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b8e6baa-4b1c-4f38-b078-70b2b092d14d",
   "metadata": {},
   "source": [
    "# Load checkpoint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4da73c08-ca61-48ef-9e63-b70db6f07a59",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "latest_checkpoint: epoch99.pth\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_1830897/1892075218.py:12: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  state = torch.load(checkpoint_path)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Loaded checkpoint epoch99.pth from /weka/proj-fmri/ckadirt/fMRI-foundation-model/src/checkpoints/HCPflat_large_gsrFalse_\n",
      "\n"
     ]
    }
   ],
   "source": [
    "checkpoint_files = [f for f in os.listdir(outdir) if f.endswith('.pth')]\n",
    "\n",
    "if utils.is_interactive():\n",
    "    latest_checkpoint = \"epoch99.pth\"\n",
    "else:\n",
    "    latest_checkpoint = sys.argv[2] \n",
    "print(f\"latest_checkpoint: {latest_checkpoint}\")\n",
    "\n",
    "# Load the checkpoint\n",
    "checkpoint_path = os.path.join(outdir, latest_checkpoint)\n",
    "\n",
    "state = torch.load(checkpoint_path)\n",
    "model.load_state_dict(state[\"model_state_dict\"], strict=False)\n",
    "model.to(device)\n",
    "model.eval()\n",
    "\n",
    "print(f\"\\nLoaded checkpoint {latest_checkpoint} from {outdir}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3dd51ddf-fb71-48f4-bdbd-88753b44d2aa",
   "metadata": {},
   "source": [
    "## Create dataset and data loaders"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3e330cd2-8f4f-4ca7-ae68-16698e90060f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "changed batch_size to 1\n"
     ]
    }
   ],
   "source": [
    "from torch.utils.data import default_collate\n",
    "batch_size = 1\n",
    "print(f\"changed batch_size to {batch_size}\")\n",
    "\n",
    "## Test ##\n",
    "datasets_to_include = \"HCP\"\n",
    "assert \"HCP\" in datasets_to_include\n",
    "test_dataset = create_hcp_flat(root=hcp_flat_path, \n",
    "                clip_mode=\"event\", frames=num_frames, shuffle=False, gsr=gsr, sub_list = 'test')\n",
    "test_dl = wds.WebLoader(\n",
    "    test_dataset.batched(batch_size, partial=False, collation_fn=default_collate),\n",
    "    batch_size=None,\n",
    "    shuffle=False,\n",
    "    num_workers=num_workers,\n",
    "    pin_memory=True,\n",
    ")\n",
    "\n",
    "## Train ##\n",
    "assert \"HCP\" in datasets_to_include\n",
    "train_dataset = create_hcp_flat(root=hcp_flat_path, \n",
    "                clip_mode=\"event\", frames=num_frames, shuffle=False, gsr=gsr, sub_list = 'train')\n",
    "train_dl = wds.WebLoader(\n",
    "    train_dataset.batched(batch_size, partial=False, collation_fn=default_collate),\n",
    "    batch_size=None,\n",
    "    shuffle=False,\n",
    "    num_workers=num_workers,\n",
    "    pin_memory=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c43a5055-8afd-468a-93bf-32f94bd1d042",
   "metadata": {},
   "source": [
    "# Start extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "d347bfb0-b1e3-4cac-a792-b56311e7923c",
   "metadata": {},
   "outputs": [],
   "source": [
    "cnt = 9999 # need to change this"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "6507067f-1ece-46ac-ad8c-24ef7a9b3a58",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "@torch.no_grad()\n",
    "def extract_features(dl, global_pool=True):\n",
    "    for samples in tqdm(dl,total=cnt): \n",
    "        samples_meta = samples['meta']\n",
    "        features = model(samples['image'].to(device),global_pool=global_pool, forward_features = True)\n",
    "        features = features.flatten(1)\n",
    "        features = features.cpu().numpy()\n",
    "        meta_dict = {}\n",
    "        for key, value in samples_meta.items():\n",
    "            if type(value) == torch.Tensor:\n",
    "                value = value.cpu().numpy()\n",
    "            meta_dict[key] = value\n",
    "        for feat, meta in zip(features, samples_meta):\n",
    "            yield {\"feature\": feat, **meta_dict}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "8b75050d-ea61-489c-a777-7725935a6a74",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/weka/proj-fmri/ckadirt/fMRI-foundation-model/src/checkpoints/HCPflat_large_gsrFalse__gpFalse/epoch99/HCP\n"
     ]
    }
   ],
   "source": [
    "out_folder = f'{outdir}_gp{global_pool}/{latest_checkpoint[:-4]}/HCP'\n",
    "print(out_folder)\n",
    "os.makedirs(out_folder,exist_ok=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "03905231-1e22-4aca-865f-322be2bf426f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Start extract\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "12082it [15:26, 13.04it/s]                                                                                                                                                                                   \n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'gg_ratas' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[24], line 13\u001b[0m\n\u001b[1;32m     11\u001b[0m     \u001b[38;5;28;01mfor\u001b[39;00m sample \u001b[38;5;129;01min\u001b[39;00m extract_features(test_dl, global_pool):\n\u001b[1;32m     12\u001b[0m         writer\u001b[38;5;241m.\u001b[39mwrite(sample)\n\u001b[0;32m---> 13\u001b[0m \u001b[43mgg_ratas\u001b[49m\n\u001b[1;32m     14\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m BufferedParquetWriter(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00moutdir_parquet\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m/train.parquet\u001b[39m\u001b[38;5;124m\"\u001b[39m, blocking\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m) \u001b[38;5;28;01mas\u001b[39;00m writer:\n\u001b[1;32m     15\u001b[0m     \u001b[38;5;28;01mfor\u001b[39;00m sample \u001b[38;5;129;01min\u001b[39;00m extract_features(train_dl, global_pool):\n",
      "\u001b[0;31mNameError\u001b[0m: name 'gg_ratas' is not defined"
     ]
    }
   ],
   "source": [
    "\n",
    "# Ensure the output Parquet directory exists\n",
    "outdir_parquet = os.path.join(f'{outdir}_gp{global_pool}/{latest_checkpoint[:-4]}', 'HCP')\n",
    "os.makedirs(outdir_parquet, exist_ok=True)  # <-- Add this line\n",
    "\n",
    "utils.seed_everything(seed)\n",
    "\n",
    "print(\"Start extract\")\n",
    "start_time = time.time()\n",
    "\n",
    "with BufferedParquetWriter(f\"{outdir_parquet}/test.parquet\", blocking=True) as writer:\n",
    "    for sample in extract_features(test_dl, global_pool):\n",
    "        writer.write(sample)\n",
    "\n",
    "with BufferedParquetWriter(f\"{outdir_parquet}/train.parquet\", blocking=True) as writer:\n",
    "    for sample in extract_features(train_dl, global_pool):\n",
    "        writer.write(sample)\n",
    "\n",
    "total_time = time.time() - start_time\n",
    "total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n",
    "print(\"Extract time {}\".format(total_time_str))\n",
    "print(torch.cuda.memory_allocated())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a4a54990-0790-4ee9-bef0-f8f19a7cabd1",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "foundation_env",
   "language": "python",
   "name": "foundation_env"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}