File size: 20,799 Bytes
232c308 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 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 479 480 481 | import torch
import torch.nn as nn
# Import densenet as backbone
import model.densenet as backbone
from model.utils import MarginLoss, CFE_refine, UFE_E2, UCFCFusion
# Task-Common Feature Extraction module
class CFE(nn.Module):
def __init__(self, in_channels=3, num_classes=3, Arcm=0.5, multi=3, factor=1):
super(CFE, self).__init__()
dim_mlp = 1024
self.name = 'CFE'
# Initialize DenseNet backbone with specified input channels
self.E1 = backbone.maskdense121(in_channels=in_channels)
# Initialize refinement module with specified input channels and factor
self.refine = CFE_refine(in_channels=[64, 128, 256, 512, 1024, 1024], factor=factor)
# Initialize margin loss for SFTFPPredict with specified parameters
self.SFTFPPredict = MarginLoss(in_features=dim_mlp, out_features=2, s=64.0, m=Arcm)
# Initialize ModuleLists for normal vs tumour classification and tumour classification
self.S1Predict = nn.ModuleList([])
self.S2Predict = nn.ModuleList([])
# Populate the ModuleLists with MarginLoss modules
for i in range(multi):
self.S1Predict.append(MarginLoss(in_features=dim_mlp, out_features=num_classes + 1, s=64.0, m=Arcm))
self.S2Predict.append(MarginLoss(in_features=dim_mlp // factor, out_features=num_classes, s=64.0, m=Arcm))
# Adaptive average pooling layer for 3D inputs
self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1))
def GetS1Predict(self, features_all, label_list):
size_img = label_list[0].size(0)
out_cls_list_NG = []
# Iterate over the first three classification tasks
for ssl_index in range(0, 3):
# Extract features for the current task
features_cls = features_all[size_img * ssl_index:size_img + size_img * ssl_index, :]
# Apply the S1Predict margin loss
out_cls_NG = self.S1Predict[ssl_index](features_cls, label_list[ssl_index])
out_cls_list_NG.append(out_cls_NG)
return out_cls_list_NG
# Binary classification: returns true class labels for loss computation
def GetS2Predict(self, features_all, label_list):
size_img = label_list[0].size(0)
out_cls_labels = []
out_cls_list = []
# Iterate over the first three classification tasks
for ssl_index in range(0, 3):
# Extract features for the current task
features_cls = features_all[size_img * ssl_index:size_img + size_img * ssl_index, :]
# Select features where label indicates glioma (label > 0)
index_glioma = label_list[ssl_index] > 0
features_cls_glioma = features_cls[index_glioma, :]
# Adjust labels by subtracting 1 for binary classification
features_cls_labels = label_list[ssl_index][index_glioma] - 1
# Apply the S2Predict margin loss
out_cls = self.S2Predict[ssl_index](features_cls_glioma, features_cls_labels)
out_cls_list.append(out_cls)
out_cls_labels.append(features_cls_labels)
return out_cls_list, out_cls_labels
# Forward pass with three-class labels
# Labels: 0 = no tumor, 1 & 2 = two classes for normal binary classification
def forward(self, input, labels_NG, label_list):
from torch.utils.checkpoint import checkpoint
# --- SURGICAL VRAM OPTIMIZATION: Process heavy 3D volumes in chunks of 2 ---
chunk_size = 1
t1_l, t2_list, t3_list, t4_list, t5_list = [], [], [], [], []
for i in range(0, input.size(0), chunk_size):
chunk = input[i : i + chunk_size]
chunk.requires_grad_() # Required for checkpointing to trigger backward pass
t1, t2, t3, t4, t5 = checkpoint(self.E1, chunk, use_reentrant=False)
t1_l.append(t1)
t2_list.append(t2)
t3_list.append(t3)
t4_list.append(t4)
t5_list.append(t5)
features_t1 = torch.cat(t1_l, dim=0)
features_t2 = torch.cat(t2_list, dim=0)
features_t3 = torch.cat(t3_list, dim=0)
features_t4 = torch.cat(t4_list, dim=0)
features_t5 = torch.cat(t5_list, dim=0)
# --------------------------------------------------------------------------
# Apply average pooling and flatten the features
Fi = self.avgpool(features_t5)
Fi = torch.flatten(Fi, 1)
# Concatenate all normal vs tumour labels
labels_NG_all = torch.cat(labels_NG, 0)
# Predict normal vs tumour logits
logits_NG = self.SFTFPPredict(Fi, labels_NG_all)
# Refine features using the CFE_refine module
Fs1, Fs2 = self.refine(features_t1, features_t2, features_t3, features_t4, features_t5)
# Apply average pooling and flatten Fs1
Fs1 = self.avgpool(Fs1)
Fs1 = torch.flatten(Fs1, 1)
# Apply average pooling and flatten Fs2
Fs2 = self.avgpool(Fs2)
Fs2 = torch.flatten(Fs2, 1)
# Get predictions for normal vs tumour classification
out_cls_list_NG = self.GetS1Predict(Fs1, label_list)
# Get predictions for tumour classification
out_cls_list, out_cls_labels = self.GetS2Predict(Fs2, label_list)
return logits_NG, labels_NG_all, out_cls_list_NG, out_cls_list, out_cls_labels
def predict(self, inputs, ssl_index):
with torch.no_grad():
# --- SURGICAL VRAM OPTIMIZATION: Process heavy 3D volumes in chunks of 2 ---
chunk_size = 1
t1_l, t2_list, t3_list, t4_list, t5_list = [], [], [], [], []
for i in range(0, inputs.size(0), chunk_size):
chunk = inputs[i : i + chunk_size]
t1, t2, t3, t4, t5 = self.E1(chunk)
t1_l.append(t1)
t2_list.append(t2)
t3_list.append(t3)
t4_list.append(t4)
t5_list.append(t5)
features_t1 = torch.cat(t1_l, dim=0)
features_t2 = torch.cat(t2_list, dim=0)
features_t3 = torch.cat(t3_list, dim=0)
features_t4 = torch.cat(t4_list, dim=0)
features_t5 = torch.cat(t5_list, dim=0)
# --------------------------------------------------------------------------
# Refine features
Fs1, Fs2 = self.refine(features_t1, features_t2, features_t3, features_t4, features_t5)
# Apply average pooling and flatten Fs2
Fs2 = self.avgpool(Fs2)
Fs2 = torch.flatten(Fs2, 1)
# Get prediction from the S2Predict module
out = self.S2Predict[ssl_index].predict(Fs2)
return out
def get_Sharefeatures(self, inputs):
with torch.no_grad():
# --- SURGICAL VRAM OPTIMIZATION: Process heavy 3D volumes in chunks of 2 ---
chunk_size = 1
t1_l, t2_list, t3_list, t4_list, t5_list = [], [], [], [], []
for i in range(0, inputs.size(0), chunk_size):
chunk = inputs[i : i + chunk_size]
t1, t2, t3, t4, t5 = self.E1(chunk)
t1_l.append(t1)
t2_list.append(t2)
t3_list.append(t3)
t4_list.append(t4)
t5_list.append(t5)
features_t1 = torch.cat(t1_l, dim=0)
features_t2 = torch.cat(t2_list, dim=0)
features_t3 = torch.cat(t3_list, dim=0)
features_t4 = torch.cat(t4_list, dim=0)
features_t5 = torch.cat(t5_list, dim=0)
# --------------------------------------------------------------------------
# Get shared features using the refine module
Fc = self.refine.getFc(features_t1, features_t2, features_t3, features_t4, features_t5)
return features_t1, Fc
# Task-Specific Unique Feature Extraction module
class UFE(nn.Module):
def __init__(self, num_classes=3, Arcm=0.5, multi=3, factor=1):
super(UFE, self).__init__()
dim_mlp = 1024
self.name = 'UFE'
# Initialize UFE_E2 module with specified input channels and factor
self.E2 = UFE_E2(in_channels=[3, 64, 128, 256, 512, 1024, 1024], factor=factor)
# Initialize Classifier ModuleList with MarginLoss modules
self.Classifer = nn.ModuleList([])
for i in range(multi):
self.Classifer.append(MarginLoss(in_features=dim_mlp, out_features=num_classes, s=64.0, m=Arcm))
# Adaptive average pooling layer for 3D inputs
self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1))
# Binary classification: returns true class labels for loss computation
def class_glioma(self, features_all, label_list):
size_img = label_list[0].size(0)
out_cls_labels = []
out_cls_list = []
# Iterate over the first three classification tasks
for ssl_index in range(0, 3):
# Extract features for the current task
features_cls = features_all[size_img * ssl_index:size_img + size_img * ssl_index, :]
# Get the labels for the current task
features_cls_labels = label_list[ssl_index]
# Apply the classifier margin loss
out_cls = self.Classifer[ssl_index](features_cls, features_cls_labels)
out_cls_list.append(out_cls)
out_cls_labels.append(features_cls_labels)
return out_cls_list, out_cls_labels
def forward(self, input, label_list, condition, Fl):
# Learn unique features by removing shared features through non-linear projection
Fuhc_prime = self.E2(input, Fl, condition)
# Apply average pooling and flatten the features
Fuhc_prime_avg = self.avgpool(Fuhc_prime)
Fuhc_prime_avg = torch.flatten(Fuhc_prime_avg, 1)
# Get classification outputs and labels for glioma classification
out_cls_list, out_cls_labels = self.class_glioma(Fuhc_prime_avg, label_list)
return Fuhc_prime, out_cls_list, out_cls_labels
def get_Uniquefeatures(self, input, condition, Fl):
# Learn unique features by removing shared features through non-linear projection
Fuhc_prime = self.E2(input, Fl, condition)
return Fuhc_prime
# Unique-Common Feature Collaborative Classification module
class UCFC(nn.Module):
def __init__(self, num_classes=2, multi=3, factor=1):
super(UCFC, self).__init__()
dim_mlp = 1024
# Define the final fusion block with UCFCFusion, BatchNorm, and ReLU
self.block_final = nn.Sequential(
UCFCFusion(channel=dim_mlp,
ochannel=dim_mlp // factor,
img_size=[5, 6, 5],
fusion_num=2),
nn.BatchNorm3d(dim_mlp),
nn.ReLU()
)
# Define the fully connected block with Conv3d, BatchNorm, and ReLU
self.block_fc = nn.Sequential(
nn.Conv3d(in_channels=dim_mlp * 2,
out_channels=dim_mlp,
kernel_size=3,
padding=1,
stride=1,
bias=False),
nn.BatchNorm3d(dim_mlp // factor),
nn.ReLU()
)
# Initialize Classifier ModuleList with Linear layers
self.Classifer = nn.ModuleList([])
for i in range(multi):
self.Classifer.append(nn.Linear(dim_mlp // factor, num_classes))
# Adaptive average pooling layer for 3D inputs
self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1))
# Binary classification: returns true class labels for loss computation
def class_glioma(self, features_all, label_list):
size_img = label_list[0].size(0)
out_cls_labels = []
out_cls_list = []
# Iterate over the first three classification tasks
for ssl_index in range(0, 3):
# Extract features for the current task
features_cls = features_all[size_img * ssl_index:size_img + size_img * ssl_index, :]
# Get the labels for the current task
features_cls_labels = label_list[ssl_index]
# Apply the classifier linear layer
out_cls = self.Classifer[ssl_index](features_cls)
out_cls_list.append(out_cls)
out_cls_labels.append(features_cls_labels)
return out_cls_list, out_cls_labels
def forward(self, Fuhc_prime, Fc, label_list):
# Apply the fully connected block to Fc
Fc = self.block_fc(Fc)
# Concatenate unique and shared features
featuresF = torch.cat((Fuhc_prime, Fc), 1)
# Apply the final fusion block
featuresF = self.block_final(featuresF)
# Apply average pooling and flatten the features
featuresF = self.avgpool(featuresF)
featuresF = torch.flatten(featuresF, 1)
# Get classification outputs and labels for glioma classification
out_cls_list, out_cls_labels = self.class_glioma(featuresF, label_list)
return out_cls_list, out_cls_labels
def predict(self, Fuhc_prime, Fc, ssl_index):
with torch.no_grad():
# Apply the fully connected block to Fc
Fc = self.block_fc(Fc)
# Concatenate unique and shared features
featuresF = torch.cat((Fuhc_prime, Fc), 1)
# Apply the final fusion block
featuresF = self.block_final(featuresF)
# Apply average pooling and flatten the features
featuresF = self.avgpool(featuresF)
featuresF = torch.flatten(featuresF, 1)
# Get prediction from the classifier linear layer
out = self.Classifer[ssl_index](featuresF)
return out
# Cooperative Multi-Task Learning Network
class CMTLNet(nn.Module):
def __init__(self, in_channels=3, num_classes=2, Arcm=0.5, multi=3, factor=1):
super(CMTLNet, self).__init__()
self.ShareTask = CFE(in_channels=in_channels, num_classes=num_classes, Arcm=Arcm, multi=multi, factor=factor)
self.UniqueTask = UFE(num_classes=num_classes, Arcm=Arcm, multi=multi, factor=factor)
self.UCFC = UCFC(num_classes=num_classes, multi=multi, factor=factor)
self.name = 'CMTLNet'
# --- NEW SURVIVAL HEAD ---
self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1))
self.survival_head = nn.Linear(2048, 1) # 2048 is the actual dim from the shared Fc feature
def _set_requires_grad(self, nets, requires_grad):
# Helper function to set the requires_grad attribute for networks
if not isinstance(nets, list):
nets = [nets]
for net in nets:
if net is not None:
for param in net.parameters():
param.requires_grad = requires_grad
def forward(self, input, label_list, condition):
self._set_requires_grad(self.ShareTask, False)
with torch.no_grad():
Fl, Fc = self.ShareTask.get_Sharefeatures(input)
Fuhc_prime, out_cls_list_UFE, out_cls_labels_UFE = self.UniqueTask(input, label_list, condition, Fl)
out_cls_list_UCFC, out_cls_labels_UCFC = self.UCFC(Fuhc_prime, Fc, label_list)
# --- PREDICT RISK SCORE ---
risk_features = self.avgpool(Fc)
risk_features = torch.flatten(risk_features, 1)
assert risk_features.shape[-1] == self.survival_head.in_features, (
f"risk_features={risk_features.shape}, "
f"expected last dim={self.survival_head.in_features}"
)
risk_scores = self.survival_head(risk_features)
# Return risk_scores as the final output
return out_cls_list_UFE, out_cls_labels_UFE, out_cls_list_UCFC, out_cls_labels_UCFC, risk_scores
def predict(self, inputs, ssl_index):
with torch.no_grad():
# Create a condition tensor based on the ssl_index
ssl_index_condition = \
torch.tensor(ssl_index, dtype=torch.long, device=inputs.device).repeat(1, inputs.size(0))[0]
# Get shared features from the ShareTask
Fl, Fc = self.ShareTask.get_Sharefeatures(inputs)
# Get unique features from the UniqueTask
Fuhc_prime = self.UniqueTask.get_Uniquefeatures(inputs, ssl_index_condition, Fl)
# Get prediction from the UCFC fusion module
out = self.UCFC.predict(Fuhc_prime, Fc, ssl_index)
return out
if __name__ == "__main__":
# First stage: Train CFE module.
# In this stage, the first batch simulates data without tumors, labeled as 0 (INT in Fig. 2 of the original paper).
# The second and third batches simulate data with tumors, labeled as 1 and 2 respectively.
# Label 1 corresponds to IDH WildType, LGG, or 1p/19g Intact.
# Label 2 corresponds to IDH Mutated, HGG, or lp/19g Co-deleted.
# Generate random input tensors for the 1p19q, IDH, and LHG tasks
input_1p19q = torch.randn(3, 3, 160, 192, 160)
input_IDH = torch.randn(3, 3, 160, 192, 160)
input_LHG = torch.randn(3, 3, 160, 192, 160)
# Define labels for each task
label_1p19q = torch.tensor([0, 1, 2], dtype=torch.long)
label_IDH = torch.tensor([0, 1, 2], dtype=torch.long)
label_LHG = torch.tensor([0, 1, 2], dtype=torch.long)
# Combine labels into a list
label_list = [label_1p19q, label_IDH, label_LHG]
# Concatenate inputs from different tasks along the batch dimension
input = torch.cat((input_1p19q, input_IDH, input_LHG), 0)
# Define normal vs tumor labels for each task
labels_NG_1p19q = torch.tensor([0, 1, 1], dtype=torch.long)
labels_NG_IDH = torch.tensor([0, 1, 1], dtype=torch.long)
labels_NG_LHG = torch.tensor([0, 1, 1], dtype=torch.long)
# Combine normal vs tumor labels into a list
labels_NG_list = [labels_NG_1p19q, labels_NG_IDH, labels_NG_LHG]
# Initialize the CFE model with specified parameters
model = CFE(in_channels=3, num_classes=2, Arcm=0.5, multi=3)
# Perform a forward pass through the CFE model
(logits_NG, labels_NG_all,
out_cls_list_NG,
out_cls_list, out_cls_labels) = model(input, labels_NG_list, label_list)
# Print the outputs from the CFE model
print(logits_NG.size())
print(labels_NG_all.size())
print(out_cls_list_NG[0].size())
print(out_cls_list[0].size())
print(out_cls_labels[0].size())
# -------------------------------------------------------------------
# Second stage: Train CMTLNet.
# In this stage, all inputs contain tumors (IT in Fig. 2 of the original paper).
# The labels correspond to 0 and 1.
# Label 0 corresponds to IDH WildType, LGG, or 1p/19g Intact.
# Label 1 corresponds to IDH Mutated, HGG, or lp/19g Co-deleted.
# Generate random input tensors for the 1p19q, IDH, and LHG tasks
input_1p19q = torch.randn(2, 3, 160, 192, 160)
input_IDH = torch.randn(2, 3, 160, 192, 160)
input_LHG = torch.randn(2, 3, 160, 192, 160)
# Define labels for each task
label_1p19q = torch.tensor([0, 1], dtype=torch.long)
label_IDH = torch.tensor([0, 1], dtype=torch.long)
label_LHG = torch.tensor([0, 1], dtype=torch.long)
# Combine labels into a list
label_list = [label_1p19q, label_IDH, label_LHG]
# Concatenate inputs from different tasks along the batch dimension
input = torch.cat((input_1p19q, input_IDH, input_LHG), 0)
# Define condition tensor indicating the task for each input
# Condition 0 for 1p19q prediction task, 1 for IDH prediction task, and 2 for LHG prediction task
condition = torch.tensor([0, 0, 1, 1, 2, 2], dtype=torch.long, device=input.device)
# Initialize the CMTLNet model with specified parameters
model = CMTLNet(in_channels=3, num_classes=2, Arcm=0.5, multi=3)
# Perform a forward pass through the CMTLNet model (UPDATED TO EXPECT 5 OUTPUTS)
out_cls_list_UFE, out_cls_labels_UFE, out_cls_list_UCFC, out_cls_labels_UCFC, risk_scores = model(input, label_list, condition)
# Print the lengths of the classification output lists and label lists
print(out_cls_list_UFE[0].size())
print(out_cls_labels_UFE[0].size())
print(out_cls_list_UCFC[0].size())
print(out_cls_labels_UCFC[0].size())
# -------------------------------------------------------------------
# Final model inference:
# For the 1p19q prediction task, set ssl_index to 0.
# For the IDH prediction task, set ssl_index to 1.
# For the LHG prediction task, set ssl_index to 2.
# Perform prediction using the CMTLNet model for the IDH prediction task (ssl_index=1)
logits = model.predict(input, ssl_index=1)
# Print the size of the prediction logits
print(logits.size()) |