d3v-26 commited on
Commit
7475b01
·
verified ·
1 Parent(s): d3309cc

Remove test_models.py - for local use only

Browse files
Files changed (1) hide show
  1. test_models.py +0 -279
test_models.py DELETED
@@ -1,279 +0,0 @@
1
- ---
2
- license: other
3
- license_name: uk-biobank-mta
4
- license_link: https://www.ukbiobank.ac.uk/media/p3el3p0f/mta-v20-final-29mar2021-clean.pdf
5
- tags:
6
- - medical
7
- - mri
8
- - brain-segmentation
9
- - self-supervised-learning
10
- - swin-transformer
11
- - monai
12
- - uk-biobank
13
- - brats
14
- - atlas
15
- pipeline_tag: image-segmentation
16
- ---
17
-
18
- # BrainSegFounder: UK Biobank Brain MRI Foundation Models
19
-
20
- ## Overview
21
-
22
- This repository contains pretrained model weights derived from UK Biobank MRI data and downstream medical imaging datasets. These weights correspond to the self-supervised pretraining and supervised finetuning stages described in the **BrainSegFounder** framework.
23
-
24
- **Paper:** [BrainSegFounder: Self-supervised Learning for Brain MRI Segmentation](https://doi.org/10.1016/j.media.2024.103301)
25
-
26
- **Please cite this paper if you use these model weights.**
27
-
28
- ### Available Model Weights
29
-
30
- This repository includes:
31
-
32
- | Model File | Description | Training Data | Subjects |
33
- |------------|-------------|---------------|----------|
34
- | `model_weights_UKB-pretrain.pt` | SSL pretraining weights | UK Biobank MRI (fields 20252-20253) | ~41,000 |
35
- | `model_weights_BRATS-pretrain.pt` | SSL pretraining weights | UKB + BraTS (multimodal MRI) | 42,470 |
36
- | `model_weights_BRATS-finetune.pt` | SwinUNETR finetuning weights | BraTS tumor segmentation | 1,470 |
37
- | `model_weights_ATLAS-pretrain.pt` | SSL pretraining weights | UKB + ATLAS v2.0 (multimodal MRI) | 42,271 |
38
- | `model_weights_ATLAS-finetune.pt` | SwinUNETR finetuning weights | ATLAS stroke lesion segmentation | 1,271 |
39
- | `SSL_Head.py` | Source code | SSL head implementation for pretraining | - |
40
-
41
- This README provides instructions for loading the weights, architecture descriptions, dataset information, and required UK Biobank privacy/policy statements.
42
-
43
-
44
- ## Quick Start
45
-
46
- ### Installation
47
-
48
- All models use MONAI components and require:
49
-
50
- ```bash
51
- pip install git+https://github.com/Project-MONAI/MONAI.git@a23c7f54
52
- pip install torch
53
- ```
54
-
55
- ### Usage Examples
56
-
57
- #### Loading UKB-only Pretraining Weights
58
-
59
- ```python
60
- import torch
61
- from huggingface_hub import hf_hub_download
62
- from SSL_Head import SSLHead # Download SSL_Head.py from this repo
63
- from argparse import Namespace
64
-
65
- # Download model weights
66
- model_path = hf_hub_download(
67
- repo_id="smilelab/BrainSegFounder",
68
- filename="model_weights_UKB-pretrain.pt"
69
- )
70
-
71
- # Configure model
72
- args = Namespace(
73
- in_channels=2, # T1 + T2
74
- spatial_dims=3,
75
- bottleneck_depth=768,
76
- feature_size=48,
77
- num_swin_blocks_per_stage=[2,2,2,2],
78
- num_heads_per_stage=[3,6,12,24],
79
- dropout_path_rate=0.0,
80
- use_checkpoint=False
81
- )
82
-
83
- # Load model
84
- model = SSLHead(args)
85
- checkpoint = torch.load(model_path, map_location="cpu")
86
-
87
- # Extract state_dict (checkpoints have nested structure)
88
- if isinstance(checkpoint, dict) and 'state_dict' in checkpoint:
89
- state_dict = checkpoint['state_dict']
90
- else:
91
- state_dict = checkpoint
92
-
93
- model.load_state_dict(state_dict)
94
- model.eval()
95
- ```
96
-
97
- #### Loading Multimodal Pretraining Weights (UKB + BraTS/ATLAS)
98
-
99
- ```python
100
- import torch
101
- from huggingface_hub import hf_hub_download
102
- from SSL_Head import SSLHead
103
- from argparse import Namespace
104
-
105
- # Download BRATS or ATLAS pretrain weights
106
- model_path = hf_hub_download(
107
- repo_id="smilelab/BrainSegFounder",
108
- filename="model_weights_BRATS-pretrain.pt" # or model_weights_ATLAS-pretrain.pt
109
- )
110
-
111
- args = Namespace(
112
- in_channels=2,
113
- spatial_dims=3,
114
- bottleneck_depth=768,
115
- feature_size=48,
116
- num_swin_blocks_per_stage=[2,2,2,2],
117
- num_heads_per_stage=[3,6,12,24],
118
- dropout_path_rate=0.0,
119
- use_checkpoint=False
120
- )
121
-
122
- model = SSLHead(args)
123
- checkpoint = torch.load(model_path, map_location="cpu")
124
-
125
- # Extract state_dict (checkpoints have nested structure)
126
- if isinstance(checkpoint, dict) and 'state_dict' in checkpoint:
127
- state_dict = checkpoint['state_dict']
128
- else:
129
- state_dict = checkpoint
130
-
131
- model.load_state_dict(state_dict)
132
- model.eval()
133
- ```
134
-
135
- #### Loading Finetuned Segmentation Weights (SwinUNETR)
136
-
137
- ```python
138
- import torch
139
- from huggingface_hub import hf_hub_download
140
- from monai.networks.nets import SwinUNETR
141
-
142
- # Download BRATS or ATLAS finetune weights
143
- model_path = hf_hub_download(
144
- repo_id="smilelab/BrainSegFounder",
145
- filename="model_weights_BRATS-finetune.pt" # or model_weights_ATLAS-finetune.pt
146
- )
147
-
148
- # Configure SwinUNETR
149
- depths = [2, 2, 2, 2]
150
- num_heads = [3, 6, 12, 24]
151
-
152
- # MONAI 1.x+ uses spatial_dims=3, older versions use img_size=(96,96,96)
153
- model = SwinUNETR(
154
- spatial_dims=3, # Use img_size=(96, 96, 96) for MONAI 0.x
155
- in_channels=4,
156
- out_channels=3,
157
- feature_size=48,
158
- use_checkpoint=False,
159
- depths=depths,
160
- num_heads=num_heads
161
- )
162
-
163
- checkpoint = torch.load(model_path, map_location="cpu")
164
-
165
- # Extract state_dict (checkpoints have nested structure)
166
- if isinstance(checkpoint, dict) and 'state_dict' in checkpoint:
167
- state_dict = checkpoint['state_dict']
168
- else:
169
- state_dict = checkpoint
170
-
171
- model.load_state_dict(state_dict)
172
- model.eval()
173
- ```
174
-
175
- ## Architecture Description
176
-
177
- This project uses two architectures:
178
-
179
- 1. **SSLHead** - Self-supervised pretraining model built on a 3D Swin Transformer encoder
180
- 2. **SwinUNETR** - Supervised segmentation model for downstream tasks
181
-
182
- ### SSLHead (Pretraining Model)
183
-
184
- The SSL pretraining model is a 3D SwinViT encoder equipped with self-supervised learning heads for **rotation prediction** and **contrastive representation learning**, as well as a VAE-style trilinear decoder for volume reconstruction.
185
-
186
- **Key components:**
187
-
188
- - **Backbone**: 3D Swin Transformer (`SwinViT` from MONAI)
189
- - Patch size: `[2,2,2]`
190
- - Window size: `[7,7,7]`
191
- - Embedding dimension: 48
192
- - Depths: `[2,2,2,2]`
193
- - Number of heads: `[3,6,12,24]`
194
- - **Bottleneck dimension**: 768
195
- - **Self-supervised heads**:
196
- - Rotation prediction: `nn.Linear(768, 4)`
197
- - Contrastive learning: `nn.Linear(768, 512)`
198
- - **Reconstruction decoder**: 5-stage upsampling with 3D convolutions + InstanceNorm + LeakyReLU (trilinear interpolation)
199
-
200
- The SSLHead combines three self-supervised learning objectives in equal proportion:
201
- - **Reconstruction loss**: VAE-style image reconstruction
202
- - **Rotation prediction**: 4-way rotation classification
203
- - **Contrastive loss**: Feature representation learning
204
-
205
- See [SSL_Head.py](SSL_Head.py) for the complete implementation.
206
-
207
- ### SwinUNETR (Finetuning Model)
208
-
209
- The finetuning model uses MONAI's 3D **SwinUNETR**, which integrates a Swin Transformer encoder with a U-Net-style hierarchical decoder for dense segmentation tasks.
210
-
211
- **Key components:**
212
- - Patch-based 3D Swin Transformer encoder
213
- - U-Net-style symmetric decoder with skip connections
214
- - Depths: `[2,2,2,2]`
215
- - Number of heads: `[3,6,12,24]`
216
- - Input image size: `(96, 96, 96)`
217
- - Output channels: 3 (task-dependent segmentation classes)
218
-
219
- Both architectures are implemented using **MONAI** (commit `a23c7f54`).
220
-
221
- ## Training Data
222
-
223
- ### UK Biobank (Pretraining)
224
-
225
- - **Subjects**: ~41,000
226
- - **Data fields**: 20252 (T1-weighted MRI), 20253 (T2-weighted MRI)
227
- - **Preprocessing**: Standard MONAI transforms (resizing and normalization)
228
- - **Used in**: `model_weights_UKB-pretrain.pt`
229
-
230
- ### BraTS (Pretraining and Finetuning)
231
-
232
- - **Subjects**: 1,470
233
- - **Task**: Brain tumor segmentation
234
- - **Modalities**: Multi-modal 3D MRI
235
- - **Preprocessing**: Standard normalization and cropping
236
- - **Used in**: `model_weights_BRATS-pretrain.pt`, `model_weights_BRATS-finetune.pt`
237
-
238
- ### ATLAS v2.0 (Pretraining and Finetuning)
239
-
240
- - **Subjects**: 1,271
241
- - **Task**: Stroke lesion segmentation
242
- - **Preprocessing**: Standard MONAI transforms
243
- - **Used in**: `model_weights_ATLAS-pretrain.pt`, `model_weights_ATLAS-finetune.pt`
244
-
245
- ## Citation
246
-
247
- If you use these model weights, please cite:
248
-
249
- ```bibtex
250
- @article{brainsegfounder2024,
251
- title={BrainSegFounder: Self-supervised Learning for Brain MRI Segmentation},
252
- journal={Medical Image Analysis},
253
- year={2024},
254
- doi={10.1016/j.media.2024.103301},
255
- url={https://doi.org/10.1016/j.media.2024.103301}
256
- }
257
- ```
258
-
259
- ## Privacy and Data Protection Statement
260
-
261
- The returned model parameters do **not** contain any UK Biobank participant-level data, do not embed identifiable features, and cannot be used to reconstruct or infer individual-level MRI volumes.
262
-
263
- The models store only aggregated statistical representations learned across tens of thousands of participants. They do not contain per-participant embeddings, IDs, or reconstructed images.
264
-
265
- This submission complies with the UK Biobank requirement that *any parameters derived from UKB data be returned as derived variables*, while ensuring that no participant-level data or re-identifiable elements are included.
266
-
267
- ## License and Allowed Use
268
-
269
- These derived variables (model weights) may be accessed by future approved UK Biobank researchers under UK Biobank's standard access procedures.
270
-
271
- The model architectures and research software used to train these models remain the intellectual property of the submitting researcher. The learned parameters, however, are derived from UK Biobank data and are therefore returned in accordance with:
272
- - The UK Biobank Material Transfer Agreement (MTA)
273
- - The UK Biobank "Use of Artificial Intelligence Applications and Models" policy
274
-
275
- **License**: The model weights are subject to the [UK Biobank Material Transfer Agreement](https://www.ukbiobank.ac.uk/media/p3el3p0f/mta-v20-final-29mar2021-clean.pdf).
276
-
277
- ## Contact
278
-
279
- For questions about these models or collaborations, please open an issue in this repository or contact the authors through the paper.