Advancing the Volumetric Analysis of Ultra-Low-Field Brain MRI Using Image-to-Image Translation.
The 5 matches · 1 of them tie a paragraph to a whole file, not to given lines: a weak match, whose lines are not tinted
- [1] § Methods › CycleGAN Framework and Network Architecture ↔ models/residual_transformers.py, lines 285–348 · score 0.90 · residual CNN, channel compression, Residual Transformer, ART blocks, ResNet blocks, reshaped
- [2] § Methods › CycleGAN Model Training › Input Augmentations ↔ utils/NiftiDataset.py, lines 928–977 · score 0.90 · recursive Gaussian filtering, random Gaussian noise, spline deformation, augmentation, flipping, brightness
- [3] § Methods › CycleGAN Model Training › CycleGAN Pre‐Training ↔ models/cycle_gan_model.py, lines 83–109 · score 0.61 · L1 loss, GAN loss, cycle, PyTorch, GPU, trained
- [4] § Methods › CycleGAN Model Training › CycleGAN Model Training ↔ options/train_options.py, the whole file · a weak match · score 0.54 · adamW, lr, decay, epochs, training, T1w
- [5] § Methods › CycleGAN Framework and Network Architecture ↔ models/networks3D.py, lines 83–105 · score 0.53 · ResViT, generator models, residual, ResNet, layers, transformers
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
Python · 671 lines · 29 KB · MIT · 1 match
- # coding=utf-8
- from __future__ import absolute_import
- from __future__ import division
- from __future__ import print_function
- import copy
- import logging
- import math
- from os.path import join as pjoin
- import torch
- import torch.nn as nn
- import numpy as np
- from torch.nn import CrossEntropyLoss, Dropout, Softmax, Linear, Conv3d, LayerNorm
- from torch.nn.modules.utils import _pair
- import torch.nn.functional as F
- import torch.utils.checkpoint as checkpoint
- from scipy import ndimage
- from . import transformer_configs as configs
- logger = logging.getLogger(__name__)
- ATTENTION_Q = "MultiHeadDotProductAttention_1/query"
- ATTENTION_K = "MultiHeadDotProductAttention_1/key"
- ATTENTION_V = "MultiHeadDotProductAttention_1/value"
- ATTENTION_OUT = "MultiHeadDotProductAttention_1/out"
- FC_0 = "MlpBlock_3/Dense_0"
- FC_1 = "MlpBlock_3/Dense_1"
- ATTENTION_NORM = "LayerNorm_0"
- MLP_NORM = "LayerNorm_2"
- def np2th(weights, conv=False):
- """Possibly convert HWIO to OIHW. - Used for Loading Weights"""
- if conv:
- weights = weights.transpose([3, 2, 0, 1])
- return torch.from_numpy(weights)
- class Attention(nn.Module):
- def __init__(self, config, vis):
- super(Attention, self).__init__()
- self.vis = vis
- self.num_attention_heads = config.transformer["num_heads"]
- self.attention_head_size = int(config.hidden_size / self.num_attention_heads)
- self.all_head_size = self.num_attention_heads * self.attention_head_size##paraphrase
- self.query = Linear(config.hidden_size, self.all_head_size)
- self.key = Linear(config.hidden_size, self.all_head_size)
- self.value = Linear(config.hidden_size, self.all_head_size)
- self.out = Linear(config.hidden_size, config.hidden_size)
- self.attn_dropout = Dropout(config.transformer["attention_dropout_rate"])
- self.proj_dropout = Dropout(config.transformer["attention_dropout_rate"])
- self.softmax = Softmax(dim=-1)
- def transpose_for_scores(self, x):
- new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
- x = x.view(*new_x_shape)
- return x.permute(0, 2, 1, 3)
- def forward(self, hidden_states):
- mixed_query_layer = self.query(hidden_states)
- mixed_key_layer = self.key(hidden_states)
- mixed_value_layer = self.value(hidden_states)
- query_layer = self.transpose_for_scores(mixed_query_layer)
- key_layer = self.transpose_for_scores(mixed_key_layer)
- value_layer = self.transpose_for_scores(mixed_value_layer)
- attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
- attention_scores = attention_scores / math.sqrt(self.attention_head_size)
- attention_probs = self.softmax(attention_scores)
- weights = attention_probs if self.vis else None
- attention_probs = self.attn_dropout(attention_probs)
- context_layer = torch.matmul(attention_probs, value_layer)
- context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
- new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
- context_layer = context_layer.view(*new_context_layer_shape)
- attention_output = self.out(context_layer)
- attention_output = self.proj_dropout(attention_output)
- return attention_output, weights
- class Mlp(nn.Module):
- def __init__(self, config):
- super(Mlp, self).__init__()
- self.fc1 = Linear(config.hidden_size, config.transformer["mlp_dim"])
- self.fc2 = Linear(config.transformer["mlp_dim"], config.hidden_size)
- self.act_fn = torch.nn.functional.gelu
- self.dropout = Dropout(config.transformer["dropout_rate"])
- self._init_weights()
- def _init_weights(self):
- nn.init.xavier_uniform_(self.fc1.weight)
- nn.init.xavier_uniform_(self.fc2.weight)
- nn.init.normal_(self.fc1.bias, std=1e-6)
- nn.init.normal_(self.fc2.bias, std=1e-6)
- def forward(self, x):
- x = self.fc1(x)
- x = self.act_fn(x)
- x = self.dropout(x)
- x = self.fc2(x)
- x = self.dropout(x)
- return x
- class Embeddings(nn.Module):
- """Construct the embeddings from patch, position embeddings.
- """
- def __init__(self, config, img_size, in_channels=3, input_dim=3, old=1):
- super(Embeddings, self).__init__()
- self.config = config
- img_size = _pair(img_size)
- grid_size = config.patches["grid"]
- patch_size = (img_size[0] // 16 // grid_size[0],
- img_size[1] // 16 // grid_size[1],
- img_size[2] // 16 // grid_size[2])
- patch_size_real = (patch_size[0] * 16,
- patch_size[1] * 16,
- patch_size[2] * 16)
- n_patches = (img_size[0] // patch_size_real[0]) * \
- (img_size[1] // patch_size_real[1]) * \
- (img_size[2] // patch_size_real[2])
- in_channels = 1024
- #Learnable patch embeddings
- self.patch_embeddings = Conv3d(in_channels=in_channels,
- out_channels=config.hidden_size,
- kernel_size=patch_size,
- stride=patch_size)
- #learnable positional encodings
- self.positional_encoding = nn.Parameter(torch.zeros(1, n_patches, config.hidden_size))
- self.dropout = Dropout(config.transformer["dropout_rate"])
- def forward(self, x):
- x = self.patch_embeddings(x)
- x = x.flatten(2)
- x = x.transpose(-1, -2)
- embeddings = x + self.positional_encoding
- embeddings = self.dropout(embeddings)
- return embeddings
- class Block(nn.Module):
- def __init__(self, config, vis):
- super(Block, self).__init__()
- self.hidden_size = config.hidden_size
- self.attention_norm = LayerNorm(config.hidden_size, eps=1e-6)
- self.ffn_norm = LayerNorm(config.hidden_size, eps=1e-6)
- self.ffn = Mlp(config)
- self.attn = Attention(config, vis)
- def forward(self, x):
- h = x
- x = self.attention_norm(x)
- x, weights = self.attn(x)
- x = x + h
- h = x
- x = self.ffn_norm(x)
- x = self.ffn(x)
- x = x + h
- return x, weights
- def load_from(self, weights, n_block):
- ROOT = f"Transformer/encoderblock_{n_block}"
- with torch.no_grad():
- query_weight = np2th(weights[pjoin(ROOT, ATTENTION_Q, "kernel")]).view(self.hidden_size, self.hidden_size).t()
- key_weight = np2th(weights[pjoin(ROOT, ATTENTION_K, "kernel")]).view(self.hidden_size, self.hidden_size).t()
- value_weight = np2th(weights[pjoin(ROOT, ATTENTION_V, "kernel")]).view(self.hidden_size, self.hidden_size).t()
- out_weight = np2th(weights[pjoin(ROOT, ATTENTION_OUT, "kernel")]).view(self.hidden_size, self.hidden_size).t()
- query_bias = np2th(weights[pjoin(ROOT, ATTENTION_Q, "bias")]).view(-1)
- key_bias = np2th(weights[pjoin(ROOT, ATTENTION_K, "bias")]).view(-1)
- value_bias = np2th(weights[pjoin(ROOT, ATTENTION_V, "bias")]).view(-1)
- out_bias = np2th(weights[pjoin(ROOT, ATTENTION_OUT, "bias")]).view(-1)
- self.attn.query.weight.copy_(query_weight)
- self.attn.key.weight.copy_(key_weight)
- self.attn.value.weight.copy_(value_weight)
- self.attn.out.weight.copy_(out_weight)
- self.attn.query.bias.copy_(query_bias)
- self.attn.key.bias.copy_(key_bias)
- self.attn.value.bias.copy_(value_bias)
- self.attn.out.bias.copy_(out_bias)
- mlp_weight_0 = np2th(weights[pjoin(ROOT, FC_0, "kernel")]).t()
- mlp_weight_1 = np2th(weights[pjoin(ROOT, FC_1, "kernel")]).t()
- mlp_bias_0 = np2th(weights[pjoin(ROOT, FC_0, "bias")]).t()
- mlp_bias_1 = np2th(weights[pjoin(ROOT, FC_1, "bias")]).t()
- self.ffn.fc1.weight.copy_(mlp_weight_0)
- self.ffn.fc2.weight.copy_(mlp_weight_1)
- self.ffn.fc1.bias.copy_(mlp_bias_0)
- self.ffn.fc2.bias.copy_(mlp_bias_1)
- self.attention_norm.weight.copy_(np2th(weights[pjoin(ROOT, ATTENTION_NORM, "scale")]))
- self.attention_norm.bias.copy_(np2th(weights[pjoin(ROOT, ATTENTION_NORM, "bias")]))
- self.ffn_norm.weight.copy_(np2th(weights[pjoin(ROOT, MLP_NORM, "scale")]))
- self.ffn_norm.bias.copy_(np2th(weights[pjoin(ROOT, MLP_NORM, "bias")]))
- class Encoder(nn.Module):
- def __init__(self, config, vis):
- super(Encoder, self).__init__()
- self.vis = vis
- self.layer = nn.ModuleList()
- self.encoder_norm = LayerNorm(config.hidden_size, eps=1e-6)
- for _ in range(config.transformer["num_layers"]):
- layer = Block(config, vis)
- self.layer.append(copy.deepcopy(layer))
- def forward(self, hidden_states):
- attn_weights = []
- for layer_block in self.layer:
- hidden_states, weights = layer_block(hidden_states)
- if self.vis:
- attn_weights.append(weights)
- encoded = self.encoder_norm(hidden_states)
- return encoded, attn_weights
- class Transformer(nn.Module):
- def __init__(self,config, img_size, vis,in_channels=3, old=1):
- super(Transformer, self).__init__()
- self.embeddings = Embeddings(config, img_size=img_size, input_dim=in_channels, old=old)
- self.encoder = Encoder(config, vis)
- def forward(self, input_ids):
- embedding_output, features = self.embeddings(input_ids)
- encoded, attn_weights = self.encoder(embedding_output) # (B, n_patch, hidden)
- return encoded, features
- # Define a resnet block
- class ResnetBlock(nn.Module):
- def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias, dim2=None):
- super(ResnetBlock, self).__init__()
- self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)
- def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):
- conv_block = []
- p = 0
- #use_dropout= use_dropo
- if padding_type == 'reflect':
- conv_block += [nn.ReflectionPad3d(1)]
- elif padding_type == 'replicate':
- conv_block += [nn.ReplicationPad3d(1)]
- elif padding_type == 'zero':
- p = 1
- else:
- raise NotImplementedError('padding [%s] is not implemented' % padding_type)
- conv_block += [nn.Conv3d(dim, dim, kernel_size=3, padding=p, bias=use_bias),
- norm_layer(dim), nn.ReLU(True)]
- if use_dropout:
- conv_block += [nn.Dropout(0.5)]
- p = 0
- if padding_type == 'reflect':
- conv_block += [nn.ReflectionPad3d(1)]
- elif padding_type == 'replicate':
- conv_block += [nn.ReplicationPad3d(1)]
- elif padding_type == 'zero':
- p = 1
- else:
- raise NotImplementedError('padding [%s] is not implemented' % padding_type)
- conv_block += [nn.Conv3d(dim, dim, kernel_size=3, padding=p, bias=use_bias),
- norm_layer(dim)]
- return nn.Sequential(*conv_block)
- def forward(self, x):
- out = x + self.conv_block(x)
- return out
- class ART_block(nn.Module):
- def __init__(self,config, input_dim, img_size=224, transformer=None):
- super(ART_block, self).__init__()
- self.transformer = transformer
- self.config = config
- ngf = 64
- mult = 4
- use_bias = False
- norm_layer = nn.BatchNorm3d
- padding_type = 'reflect'
- if self.transformer:
- # Downsample
- model = [nn.Conv3d(ngf * 4, ngf * 8, kernel_size=3, stride=2, padding=1, bias=use_bias),
- norm_layer(ngf * 8), nn.ReLU(True)]
- model += [nn.Conv3d(ngf * 8, 1024, kernel_size=3, stride=2, padding=1, bias=use_bias),
- norm_layer(1024), nn.ReLU(True)]
- setattr(self, 'downsample', nn.Sequential(*model))
- #Patch embedings
- self.embeddings = Embeddings(config, img_size=img_size, input_dim=input_dim)
- # Upsampling block
- model = [nn.ConvTranspose3d(self.config.hidden_size, ngf * 8,
- kernel_size=3, stride=2,
- padding=1, output_padding=1,
- bias=use_bias),
- norm_layer(ngf * 8),
- nn.ReLU(True)]
- model += [nn.ConvTranspose3d(ngf * 8, ngf * 4,
- kernel_size=3, stride=2,
- padding=1, output_padding=1,
- bias=use_bias),
- norm_layer(ngf * 4),
- nn.ReLU(True)]
- setattr(self, 'upsample', nn.Sequential(*model))
- #Channel compression
- self.cc = channel_compression(ngf * 8, ngf * 4)
- # Residual CNN
- model = [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer,
- use_dropout=False, use_bias=use_bias)]
- setattr(self, 'residual_cnn', nn.Sequential(*model))
- def forward(self, x):
- if self.transformer:
- # downsample
- down_sampled = self.downsample(x)
- # embed
- embedding_output = self.embeddings(down_sampled)
- # feed to transformer
- transformer_out, attn_weights = self.transformer(embedding_output)
- # reshape from (B, n_patch, hidden) to (B, h, w, hidden)
- B, n_patch, hidden = transformer_out.size()
- h, w, d = int(np.cbrt(n_patch)), int(np.cbrt(n_patch)), int(np.cbrt(n_patch))
- transformer_out = transformer_out.permute(0, 2, 1)
- transformer_out = transformer_out.contiguous().view(B, hidden, h, w, d)
- # upsample transformer output
- transformer_out = self.upsample(transformer_out)
- # concat transformer output and resnet output
- x = torch.cat([transformer_out, x], dim=1)
- # channel compression
- x = self.cc(x)
- # residual CNN
- x = self.residual_cnn(x)
- return x
- ########Generator############
- class ResViT(nn.Module):
- def __init__(self, config, input_dim, img_size=224, output_dim=3, vis=False):
- super(ResViT, self).__init__()
- self.transformer_encoder = Encoder(config, vis)
- self.config = config
- output_nc = output_dim
- ngf = 64
- use_bias = False
- norm_layer = nn.BatchNorm3d
- padding_type = 'reflect'
- mult = 4
- ############################################################################################
- # Layer1-Encoder1
- model = [nn.ReflectionPad3d(3),
- nn.Conv3d(input_dim, ngf, kernel_size=7, padding=0,
- bias=use_bias),
- norm_layer(ngf),
- nn.ReLU(True)]
- setattr(self, 'encoder_1', nn.Sequential(*model))
- ############################################################################################
- # Layer2-Encoder2
- n_downsampling = 2
- model = []
- i = 0
- mult = 2 ** i
- model = [nn.Conv3d(ngf * mult, ngf * mult * 2, kernel_size=3,
- stride=2, padding=1, bias=use_bias),
- norm_layer(ngf * mult * 2),
- nn.ReLU(True)]
- setattr(self, 'encoder_2', nn.Sequential(*model))
- ############################################################################################
- # Layer3-Encoder3
- model = []
- i = 1
- mult = 2 ** i
- model = [nn.Conv3d(ngf * mult, ngf * mult * 2, kernel_size=3,
- stride=2, padding=1, bias=use_bias),
- norm_layer(ngf * mult * 2),
- nn.ReLU(True)]
- setattr(self, 'encoder_3', nn.Sequential(*model))
- ####################################ART Blocks##############################################
- self.art_1 = ART_block(self.config, input_dim, img_size, transformer=self.transformer_encoder)
- self.art_2 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_3 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_4 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_5 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_6 = ART_block(self.config, input_dim, img_size, transformer=self.transformer_encoder)
- self.art_7 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_8 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_9 = ART_block(self.config, input_dim, img_size, transformer=None)
- ############################################################################################
- # Layer13-Decoder1
- n_downsampling = 2
- i = 0
- mult = 2 ** (n_downsampling - i)
- model = []
- model = [nn.ConvTranspose3d(ngf * mult, int(ngf * mult / 2),
- kernel_size=3, stride=2,
- padding=1, output_padding=1,
- bias=use_bias),
- norm_layer(int(ngf * mult / 2)),
- nn.ReLU(True)]
- setattr(self, 'decoder_1', nn.Sequential(*model))
- ############################################################################################
- # Layer14-Decoder2
- i = 1
- mult = 2 ** (n_downsampling - i)
- model = []
- model = [nn.ConvTranspose3d(ngf * mult, int(ngf * mult / 2),
- kernel_size=3, stride=2,
- padding=1, output_padding=1,
- bias=use_bias),
- norm_layer(int(ngf * mult / 2)),
- nn.ReLU(True)]
- setattr(self, 'decoder_2', nn.Sequential(*model))
- ############################################################################################
- # Layer15-Decoder3
- model = []
- model = [nn.ReflectionPad3d(3)]
- model += [nn.Conv3d(ngf, output_dim, kernel_size=7, padding=0)]
- model += [nn.Tanh()]
- setattr(self, 'decoder_3', nn.Sequential(*model))
- ############################################################################################
- def forward(self, x):
- # encoder
- x = checkpoint.checkpoint(self.encoder_1, x)
- x = checkpoint.checkpoint(self.encoder_2, x)
- x = checkpoint.checkpoint(self.encoder_3, x)
- # Information Bottleneck
- x = checkpoint.checkpoint(self.art_1, x)
- x = checkpoint.checkpoint(self.art_2, x)
- x = checkpoint.checkpoint(self.art_3, x)
- x = checkpoint.checkpoint(self.art_4, x)
- x = checkpoint.checkpoint(self.art_5, x)
- x = checkpoint.checkpoint(self.art_6, x)
- x = checkpoint.checkpoint(self.art_7, x)
- x = checkpoint.checkpoint(self.art_8, x)
- x = checkpoint.checkpoint(self.art_9, x)
- # decoder
- x = checkpoint.checkpoint(self.decoder_1, x)
- x = checkpoint.checkpoint(self.decoder_2, x)
- x = checkpoint.checkpoint(self.decoder_3, x)
- return x
- def load_from(self, weights):
- with torch.no_grad():
- res_weight = weights
- if self.config.name == 'b16':
- self.art_1.embeddings.patch_embeddings.weight.copy_(np2th(weights["embedding/kernel"], conv=True))
- self.art_1.embeddings.patch_embeddings.bias.copy_(np2th(weights["embedding/bias"]))
- self.art_6.embeddings.patch_embeddings.weight.copy_(np2th(weights["embedding/kernel"], conv=True))
- self.art_6.embeddings.patch_embeddings.bias.copy_(np2th(weights["embedding/bias"]))
- self.transformer_encoder.encoder_norm.weight.copy_(np2th(weights["Transformer/encoder_norm/scale"]))
- self.transformer_encoder.encoder_norm.bias.copy_(np2th(weights["Transformer/encoder_norm/bias"]))
- posemb = np2th(weights["Transformer/posembed_input/pos_embedding"])
- posemb_new = self.art_1.embeddings.positional_encoding
- if posemb.size() == posemb_new.size():
- self.art_1.embeddings.positional_encoding.copy_(posemb)
- elif posemb.size()[1] - 1 == posemb_new.size()[1]:
- posemb = posemb[:, 1:]
- self.art_1.embeddings.positional_encoding1.copy_(posemb)
- else:
- logger.info("load_pretrained: resized variant: %s to %s" % (posemb.size(), posemb_new.size()))
- ntok_new = posemb_new.size(1)
- _, posemb_grid = posemb[:, :1], posemb[0, 1:]
- gs_old = int(np.sqrt(len(posemb_grid)))
- gs_new = int(np.sqrt(ntok_new))
- print('load_pretrained: grid-size from %s to %s' % (gs_old, gs_new))
- posemb_grid = posemb_grid.reshape(gs_old, gs_old, -1)
- zoom = (gs_new / gs_old, gs_new / gs_old, 1)
- posemb_grid = ndimage.zoom(posemb_grid, zoom, order=1) # th2np
- posemb_grid = posemb_grid.reshape(1, gs_new * gs_new, -1)
- posemb = posemb_grid
- self.art_1.embeddings.positional_encoding.copy_(np2th(posemb))
- #############
- posemb = np2th(weights["Transformer/posembed_input/pos_embedding"])
- posemb_new = self.art_6.embeddings.positional_encoding
- if posemb.size() == posemb_new.size():
- self.art_6.embeddings.positional_encoding.copy_(posemb)
- elif posemb.size()[1] - 1 == posemb_new.size()[1]:
- posemb = posemb[:, 1:]
- self.art_6.embeddings.positional_encoding.copy_(posemb)
- else:
- logger.info("load_pretrained: resized variant: %s to %s" % (posemb.size(), posemb_new.size()))
- ntok_new = posemb_new.size(1)
- _, posemb_grid = posemb[:, :1], posemb[0, 1:]
- gs_old = int(np.sqrt(len(posemb_grid)))
- gs_new = int(np.sqrt(ntok_new))
- print('load_pretrained: grid-size from %s to %s' % (gs_old, gs_new))
- posemb_grid = posemb_grid.reshape(gs_old, gs_old, -1)
- zoom = (gs_new / gs_old, gs_new / gs_old, 1)
- posemb_grid = ndimage.zoom(posemb_grid, zoom, order=1) # th2np
- posemb_grid = posemb_grid.reshape(1, gs_new * gs_new, -1)
- posemb = posemb_grid
- self.art_6.embeddings.positional_encoding.copy_(np2th(posemb))
- # Encoder whole
- for bname, block in self.transformer_encoder.named_children():
- for uname, unit in block.named_children():
- unit.load_from(weights, n_block=uname)
- class Res_CNN(nn.Module):
- def __init__(self, config, input_dim, img_size=224, output_dim=3, vis=False):
- super(Res_CNN, self).__init__()
- self.config = config
- output_nc = output_dim
- ngf = 64
- use_bias = False
- norm_layer = nn.BatchNorm3d
- padding_type = 'reflect'
- mult = 4
- ############################################################################################
- # Layer1-Encoder1
- model = [nn.ReflectionPad3d(3),
- nn.Conv3d(input_dim, ngf, kernel_size=7, padding=0,
- bias=use_bias),
- norm_layer(ngf),
- nn.ReLU(True)]
- setattr(self, 'encoder_1', nn.Sequential(*model))
- ############################################################################################
- # Layer2-Encoder2
- n_downsampling = 2
- model = []
- i = 0
- mult = 2 ** i
- model = [nn.Conv3d(ngf * mult, ngf * mult * 2, kernel_size=3,
- stride=2, padding=1, bias=use_bias),
- norm_layer(ngf * mult * 2),
- nn.ReLU(True)]
- setattr(self, 'encoder_2', nn.Sequential(*model))
- ############################################################################################
- # Layer3-Encoder3
- model = []
- i = 1
- mult = 2 ** i
- model = [nn.Conv3d(ngf * mult, ngf * mult * 2, kernel_size=3,
- stride=2, padding=1, bias=use_bias),
- norm_layer(ngf * mult * 2),
- nn.ReLU(True)]
- setattr(self, 'encoder_3', nn.Sequential(*model))
- ####################################ART Blocks##############################################
- mult = 4
- self.art_1 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_2 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_3 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_4 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_5 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_6 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_7 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_8 = ART_block(self.config, input_dim, img_size, transformer=None)
- self.art_9 = ART_block(self.config, input_dim, img_size, transformer=None)
- ############################################################################################
- # Layer13-Decoder1
- n_downsampling = 2
- i = 0
- mult = 2 ** (n_downsampling - i)
- model = []
- model = [nn.ConvTranspose3d(ngf * mult, int(ngf * mult / 2),
- kernel_size=3, stride=2,
- padding=1, output_padding=1,
- bias=use_bias),
- norm_layer(int(ngf * mult / 2)),
- nn.ReLU(True)]
- setattr(self, 'decoder_1', nn.Sequential(*model))
- ############################################################################################
- # Layer14-Decoder2
- i = 1
- mult = 2 ** (n_downsampling - i)
- model = []
- model = [nn.ConvTranspose3d(ngf * mult, int(ngf * mult / 2),
- kernel_size=3, stride=2,
- padding=1, output_padding=1,
- bias=use_bias),
- norm_layer(int(ngf * mult / 2)),
- nn.ReLU(True)]
- setattr(self, 'decoder_2', nn.Sequential(*model))
- ############################################################################################
- # Layer15-Decoder3
- model = []
- model = [nn.ReflectionPad3d(3)]
- model += [nn.Conv3d(ngf, output_dim, kernel_size=7, padding=0)]
- model += [nn.Tanh()]
- setattr(self, 'decoder_3', nn.Sequential(*model))
- ############################################################################################
- def forward(self, x):
- # Encoder
- x = self.encoder_1(x)
- x = self.encoder_2(x)
- x = self.encoder_3(x)
- # Information bottleneck
- x = self.art_1(x)
- x = self.art_2(x)
- x = self.art_3(x)
- x = self.art_4(x)
- x = self.art_5(x)
- x = self.art_6(x)
- x = self.art_7(x)
- x = self.art_8(x)
- x = self.art_9(x)
- # Decoder
- x = self.decoder_1(x)
- x = self.decoder_2(x)
- x = self.decoder_3(x)
- return x
- class channel_compression(nn.Module):
- def __init__(self, in_channels, out_channels, stride=1):
- """
- Args:
- in_channels (int): Number of input channels.
- out_channels (int): Number of output channels.
- stride (int): Controls the stride.
- """
- super(channel_compression, self).__init__()
- self.skip = nn.Sequential()
- if stride != 1 or in_channels != out_channels:
- self.skip = nn.Sequential(
- nn.Conv3d(in_channels=in_channels, out_channels=out_channels,
- kernel_size=1, stride=stride, bias=False),
- nn.BatchNorm3d(out_channels))
- else:
- self.skip = None
- self.block = nn.Sequential(
- nn.Conv3d(in_channels=in_channels, out_channels=out_channels,
- kernel_size=3, padding=1, stride=1, bias=False),
- nn.BatchNorm3d(out_channels),
- nn.ReLU(),
- nn.Conv3d(in_channels=out_channels, out_channels=out_channels,
- kernel_size=3, padding=1, stride=1, bias=False),
- nn.BatchNorm3d(out_channels))
- def forward(self, x):
- out = self.block(x)
- out += (x if self.skip is None else self.skip(x))
- out = F.relu(out)
- return out
- CONFIGS = {
- 'ViT-B_16': configs.get_b16_config(),
- 'ViT-L_16': configs.get_l16_config(),
- 'Res-ViT-B_16': configs.get_resvit_b16_config(),
- 'Res-ViT-L_16': configs.get_resvit_l16_config()
- }
residual_transformers.py at commit 0a8fd15, under MIT · at the source
Overview
- Bernard and Irene Schwartz Center for Biomedical Imaging, Department of Radiology New York University Grossman School of Medicine New York New York USA
- Vilcek Institute of Graduate Biomedical Sciences, New York University Grossman School of Medicine New York New York USA
- Center for Advanced Imaging Innovation and Research (CAI2R), Department of Radiology New York University Grossman School of Medicine New York New York USA
Abstract
The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.
Repository
Its files are read in the Code ↔ Paper reader above, with 5 matches between paragraphs and lines of code.
peterjhsu/CycleGAN-3D-ULF
0a8fd1521c455ae2a0ac30c6e0ffe3f78c54927e, 23 July 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
19 files
- models/
__init__.py — Python, 37 lines - models/
base_model.py — Python, 235 lines - models/
cycle_gan_model.py — Python, 226 lines, 1 match - models/
networks3D.py — Python, 543 lines, 1 match - models/
residual_transformers.py — Python, 671 lines, 1 match - models/
test_model.py — Python, 50 lines - models/
transformer_configs.py — Python, 78 lines - options/
__init__.py — Python, 1 line - options/
base_options.py — Python, 121 lines - options/
test_options.py — Python, 15 lines - options/
train_options.py — Python, 25 lines, 1 match - scripts/
test_model.sh — Shell, 30 lines - scripts/
train_model.sh — Shell, 19 lines - scripts/
val_model.sh — Shell, 16 lines - utils/
NiftiDataset.py — Python, 1,135 lines, 1 match - utils/
utils.py — Python, 32 lines - utils/
visualizer.py — Python, 27 lines - LICENSE — License, 9 lines
- README.md — Text, 101 lines
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:
- 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 17 scripts, each with its path and the digest of its content;
- 5 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.
Code and data availability statement
The paper has a code and data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:
- it points to the authors' code: peterjhsu/
CycleGAN-3D-ULF
Read it in the paper: doi.org/10.1002/mrm.70488.
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 2, 28 September 2026
- Publisher: — → Wiley
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 4 authors, 6 keywords, 11 MeSH terms, 2 funders, 90 references.
Cite
This paper
Hsu, P., Marchetto, E., Johnson, P. M., & Veraart, J. (2026). Advancing the Volumetric Analysis of Ultra-Low-Field Brain MRI Using Image-to-Image Translation. Magnetic resonance in medicine, 96(5), 2458-2473. https://
BibTeX
@article{hsu2026advancin
author = {Hsu, Peter and Marchetto, Elisa and Johnson, Patricia M. and Veraart, Jelle},
title = {{Advancing the Volumetric Analysis of Ultra-Low-Field Brain MRI Using Image-to-Image Translation}},
journal = {Magnetic resonance in medicine},
year = {2026},
month = jul,
volume = {96},
number = {5},
pages = {2458--2473},
publisher = {Wiley},
issn = {0740-3194},
doi = {10.1002/
url = {https://
pmid = {42487246},
pmcid = {PMC13527236}
}
RIS
TY - JOUR
AU - Hsu, Peter
AU - Marchetto, Elisa
AU - Johnson, Patricia M.
AU - Veraart, Jelle
TI - Advancing the Volumetric Analysis of Ultra-Low-Field Brain MRI Using Image-to-Image Translation
T2 - Magnetic resonance in medicine
J2 - Magn Reson Med
PY - 2026
DA - 2026/
VL - 96
IS - 5
SP - 2458
EP - 2473
SN - 0740-3194
PB - Wiley
DO - 10.1002/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1002/
"type": "article-journal",
"title": "Advancing the Volumetric Analysis of Ultra-Low-Field Brain MRI Using Image-to-Image Translation",
"container-title": "Magnetic resonance in medicine",
"author": [
{
"family": "Hsu",
"given": "Peter"
},
{
"family": "Marchetto",
"given": "Elisa"
},
{
"family": "Johnson",
"given": "Patricia M."
},
{
"family": "Veraart",
"given": "Jelle"
}
],
"container-title-short":
"volume": "96",
"issue": "5",
"page": "2458-2473",
"DOI": "10.1002/
"PMID": "42487246",
"PMCID": "PMC13527236",
"ISSN": "0740-3194",
"publisher": "Wiley",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
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.1162/imag.a.1352 [code]
- Brain-age in ultra-low-field MRI: How well does it work?Journal: Imaging neuroscience (Cambridge, Mass.)In common: MONAI, PyTorch, SciPy, 1 other tool, methods / tools, structural MRI / diffusion, 11 references
- [2] doi:10.1016/j.jmro.2026.100225 [code]
- Feasibility, image quality, and analytic usability of mobile 64 mT ultra-low-field MRI for infant brain imaging at 3 and 12 months in southern Malawi.Journal: Journal of magnetic resonance openIn common: structural MRI / diffusion, 11 references
- [3] doi:10.1016/j.patter.2026.101538 [code]
- A multi-modal foundation model for brain disease diagnosis and medical imaging.Journal: Patterns (New York, N.Y.)In common: MONAI, PyTorch, SciPy, 2 other tools, 4 references
- [4] doi:10.1002/hbm.70547 [code]
- miniMORPH: A Morphometry Pipeline for Low-Field MRI in Infants.Journal: Human brain mappingIn common: Matplotlib, NumPy, structural MRI / diffusion, 7 references
- [5] doi:10.64898/2026.07.15.26357954 [code]
- Portable Ultra-Low Field MRI Deep-Learning Algorithms for White Matter Lesion Segmentation Improve Accuracy and Reflect Clinical Disability in Multiple SclerosisJournal: medRxiv (preprint)In common: SimpleITK, PyTorch, SciPy, 2 other tools, structural MRI / diffusion, 4 references
- [6] doi:10.1002/advs.76596 [code]
- DDSurfer: A Weakly-Supervised Dual-Stream Deep Learning Framework for Cortical Surface Reconstruction From Diffusion MRI.Journal: Advanced science (Weinheim, Baden-Wurttemberg, Germany)In common: SimpleITK, PyTorch, SciPy, 1 other tool, methods / tools, structural MRI / diffusion, 5 references
- [7] doi:10.1080/01652176.2026.2696026
- Canine brain imaging with a new low-field portable (0.05 T) MRI scanner: a pilot &
lt;i& gt;in vivo& lt;/ i& gt; comparison to conventional 1.5 T. Journal: The veterinary quarterlyIn common: structural MRI / diffusion, 6 references - [8] doi:10.1162/imag.a.1183 [code]
- Learning-based segmentation of diffusion-weighted MR images with arbitrary &
lt;i& gt;q& lt;/ i& gt;-space samplings. Journal: Imaging neuroscience (Cambridge, Mass.)In common: PyTorch, SciPy, Matplotlib, 1 other tool, methods / tools, structural MRI / diffusion, 6 references - [9] doi:10.1016/j.crmeth.2026.101473 [code]
- AmygdalaGo-BOLT for boundary-aware segmentation of the human amygdala.Journal: Cell reports methodsIn common: MONAI, SimpleITK, PyTorch, 3 other tools, methods / tools, structural MRI / diffusion, 1 reference
- [10] doi:10.1002/hipo.70124 [code]
- Association Between Anterior Hippocampal Gyrification and Episodic Memory Performance in Neurotypical Young Adults.Journal: HippocampusIn common: SimpleITK, PyTorch, SciPy, 2 other tools, structural MRI / diffusion, 3 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.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 17 scripts, and 5 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:435d3e944b054ed3…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
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.
