FILE sources/0244/repo/CIDNet-main/architecture/CIDNet.py
SHA256 aacb1d009f06847958221998d4247e16733953ecbb84059dd0b90a1c3e738a68
LINES 1-80
    1  import torch.nn as nn
    2  import torch
    3  import torch.nn.functional as F
    4  from einops import rearrange
    5  import math
    6  import warnings
    7  from torch import einsum
    8  
    9  
   10  class TopkOperation(nn.Module):
   11      def __init__(self, dim, ratio_list) -> None:
   12          super().__init__()
   13  
   14          self.dim = dim
   15          self.ratio_list = ratio_list
   16          self.attn_list = nn.ParameterList([
   17              nn.Parameter(torch.tensor([0.2]), requires_grad=True) for i in range(len(ratio_list))
   18          ])
   19  
   20      def forward(self, attn, v):
   21          out = 0
   22          for i, ratio in enumerate(self.ratio_list):
   23              index = torch.topk(attn, k=int(self.dim * ratio), dim=-1, largest=True)[1]
   24              mask = torch.zeros_like(attn, requires_grad=False)
   25              mask = mask.scatter_(-1, index, 1.)
   26              attn_i = torch.where(mask > 0, attn, torch.full_like(attn, float('-inf')))
   27              attn_i = attn_i.softmax(dim=-1)
   28              out = out + (attn_i @ v) * self.attn_list[i]
   29          return out
   30  
   31  
   32  class Topk_WindowSpectralAttn(nn.Module):
   33      def __init__(
   34              self,
   35              dim,
   36              dim_head,
   37              heads,
   38              window_size=8
   39      ):
   40          super().__init__()
   41          self.num_heads = heads
   42          self.dim_head = dim_head
   43          self.to_qkv = nn.Conv2d(dim, dim_head * heads * 3, 1, bias=False)
   44          self.rescale = nn.Parameter(torch.ones(heads, 1, 1, 1))
   45          self.proj = nn.Conv2d(dim_head * heads, dim, 1, bias=True)
   46          self.pos_emb = nn.Sequential(
   47              nn.Conv2d(dim, dim, 3, 1, 1, bias=False, groups=dim),
   48              nn.GELU(),
   49              nn.Conv2d(dim, dim, 3, 1, 1, bias=False, groups=dim),
   50          )
   51          self.dim = dim
   52          self.window_size = window_size
   53          self.topk = TopkOperation(self.dim_head, ratio_list=[1/2, 2/3, 3/4, 4/5])
   54  
   55      def forward(self, x_in):
   56          """
   57          x_in: [b,c,h,w]
   58          return out: [b,c,h,w]
   59          """
   60          b, c, h, w = x_in.shape
   61          N = self.window_size
   62          nH = h // N
   63          nW = w // N
   64          qkv = self.to_qkv(x_in)
   65          q_inp, k_inp, v_inp = torch.chunk(qkv, chunks=3, dim=1)
   66          q, k, v = map(lambda t: rearrange(t, 'b (n d) (nh h) (nw w) -> b n (nh nw) (h w) d',n=self.num_heads, h=N, w=N),
   67                                  (q_inp, k_inp, v_inp))
   68          v = v.transpose(-2, -1)
   69          q = F.normalize(q, dim=-2, p=2)
   70          k = F.normalize(k, dim=-2, p=2)
   71          attn = (k.transpose(-2, -1) @ q)   # A = K^T*Q
   72          attn = attn * self.rescale
   73          x = self.topk(attn, v)
   74          x = rearrange(x, 'b n (nh nw) d (h w) -> b (n d) (nh h) (nw w)', nh=nH, nw=nW, h=N, w=N)
   75          out_c = self.proj(x)
   76          out_p = self.pos_emb(v_inp)
   77          out = out_c + out_p
   78  
   79          return out
   80      
LINES 141-179
  141  ## Channel Attention Layer
  142  class CALayer(nn.Module):
  143      def __init__(self, channel, reduction=16, bias=False):
  144          super(CALayer, self).__init__()
  145          # global average pooling: feature --> point
  146          self.avg_pool = nn.AdaptiveAvgPool2d(1)
  147          # feature channel downscale and upscale --> channel weight
  148          self.conv_du = nn.Sequential(
  149              nn.Conv2d(channel, channel // reduction, 1, padding=0, bias=bias),
  150              nn.ReLU(inplace=True),
  151              nn.Conv2d(channel // reduction, channel, 1, padding=0, bias=bias),
  152              nn.Sigmoid()
  153          )
  154  
  155      def forward(self, x):
  156          y = self.avg_pool(x) 
  157          y = self.conv_du(y)
  158          return x * y
  159  
  160  
  161  
  162  class SAM(nn.Module):
  163      def __init__(self, in_c, ch, bias=True):
  164          super(SAM, self).__init__()
  165          self.conv1 = conv(in_c, ch, 3, bias=bias)
  166          self.conv2 = conv(ch, ch, 1, bias=bias)
  167          self.ca = CALayer(ch, reduction=8)
  168          self.head = nn.Sequential(
  169              nn.Conv2d(ch, ch // 4, 3, padding=1),
  170              nn.ReLU(inplace=True),
  171              nn.Conv2d(ch // 4, 2, 3, padding=1),
  172              nn.Softplus() 
  173          )       
  174      def forward(self, x, x_phi):
  175          img = torch.cat([x, x_phi], dim=1)
  176          feat = self.conv2(self.conv1(img))
  177          noise_map1 = self.head(self.ca(feat)) + 1e-6     
  178          return noise_map1[:,0].squeeze(1), noise_map1[:,1].squeeze(1)
  179  

FILE sources/0244/repo/CIDNet-main/train.py
SHA256 0045d63e85e555c75b6e55e9b22f3983b3316f1c7656f8b85f61c82145eadc12
LINES 1-152
    1  import os
    2  import torch
    3  import scipy.io as scio
    4  import time
    5  import numpy as np
    6  from torch.autograd import Variable
    7  import datetime
    8  import torch.nn.functional as F
    9  import random
   10  import torchvision.utils as vutils
   11  import matplotlib.pyplot as plt
   12  from PIL import Image
   13  from option import opt
   14  from architecture import *
   15  from utils import *
   16  
   17  print(opt)
   18  os.environ["CUDA_DEVICE_ORDER"] = 'PCI_BUS_ID'
   19  os.environ["CUDA_VISIBLE_DEVICES"] = opt.gpu_id
   20  scaler = torch.GradScaler(device="cuda")
   21  
   22  def set_seed(seed):
   23      torch.manual_seed(seed)
   24      torch.cuda.manual_seed(seed)
   25      torch.cuda.manual_seed_all(seed)
   26      np.random.seed(seed)
   27      random.seed(seed)
   28      torch.backends.cudnn.benchmark = False
   29      torch.backends.cudnn.deterministic = True
   30      os.environ['PYTHONHASHSEED'] = str(seed)
   31      os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
   32      
   33  
   34  set_seed(42)  
   35  
   36  # init mask
   37  mask3d_batch_train, input_mask_train = init_mask(opt.mask_path, opt.input_mask, opt.batch_size)
   38  mask3d_batch_test, input_mask_test = init_mask(opt.mask_path, opt.input_mask, 10)
   39  
   40  # dataset
   41  train_set = LoadTraining(opt.data_path)
   42  test_data = LoadTest(opt.test_path)
   43  
   44  # saving path
   45  date_time = str(datetime.datetime.now())
   46  date_time = time2file_name(date_time)
   47  result_path = opt.outf + opt.name + '/result/'
   48  model_path = opt.outf + opt.name + '/model/'
   49  if not os.path.exists(result_path):
   50      os.makedirs(result_path)
   51  if not os.path.exists(model_path):
   52      os.makedirs(model_path)
   53      
   54  model = model_generator(opt.method, opt.pretrained_model_path).cuda()
   55  model = torch.compile(model)
   56  
   57  # optimizing
   58  optimizer = torch.optim.Adam(model.parameters(), lr=opt.learning_rate, betas=(0.9, 0.999))
   59  if opt.scheduler=='MultiStepLR':
   60      scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=opt.milestones, gamma=opt.gamma)
   61  elif opt.scheduler=='CosineAnnealingLR':
   62      scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, opt.max_epoch, eta_min=1e-6)
   63  mse = torch.nn.MSELoss().cuda()
   64  
   65  
   66  def train(epoch, logger):
   67      epoch_loss = 0
   68      begin = time.time()
   69      batch_num = int(np.floor(opt.epoch_sam_num / opt.batch_size))
   70      iteration_results = None
   71      
   72      for i in range(batch_num):
   73          gt_batch = shuffle_crop(train_set, opt.batch_size)
   74          gt = Variable(gt_batch).cuda().float()
   75          
   76          # chroma-intensity decomposition
   77          gt_chroma, gt_intensity = chroma_intensity_decom(gt)
   78          mask3d_batch_train_new = mask3d_batch_train*gt_intensity
   79          input_meas = init_meas(gt_chroma, mask3d_batch_train_new, opt.input_setting)
   80          input_mask_train_new = chroma_intensity_mask(input_mask_train, gt_intensity, input_mask_sign=opt.input_mask)
   81          
   82          is_last_batch = (i == batch_num - 1)
   83          
   84          # model forward
   85          optimizer.zero_grad()
   86          with torch.autocast("cuda", enabled=True):
   87              model_out = model(input_meas, input_mask_train_new)
   88              loss = torch.sqrt(mse(model_out, gt_chroma))
   89  
   90          epoch_loss += loss.item()
   91          scaler.scale(loss).backward()
   92          scaler.step(optimizer)
   93          scaler.update()
   94          
   95      end = time.time()
   96      logger.info("===> Epoch {} Complete: Avg. Loss: {:.6f} time: {:.2f}".
   97                  format(epoch, epoch_loss / batch_num, (end - begin)))
   98      return epoch_loss / batch_num
   99  
  100  def test(epoch, logger):
  101      psnr_list, ssim_list = [], []
  102      test_gt = test_data.cuda().float()
  103      test_gt_chroma, test_gt_intensity = chroma_intensity_decom(test_gt)
  104      mask3d_batch_test_new = mask3d_batch_test*test_gt_intensity     
  105      input_meas = init_meas(test_gt_chroma, mask3d_batch_test_new, opt.input_setting)
  106      input_mask_test_new = chroma_intensity_mask(input_mask_test, test_gt_intensity, input_mask_sign=opt.input_mask)
  107      model.eval()
  108      begin = time.time()
  109      with torch.no_grad():
  110          model_out = model(input_meas, input_mask_test_new)
  111          model_out = model_out*test_gt_intensity
  112      
  113      end = time.time()    
  114      for k in range(test_gt.shape[0]):
  115          psnr_val = torch_psnr(model_out[k, :, :, :], test_gt[k, :, :, :])
  116          ssim_val = torch_ssim(model_out[k, :, :, :], test_gt[k, :, :, :])
  117          psnr_list.append(psnr_val.detach().cpu().numpy())
  118          ssim_list.append(ssim_val.detach().cpu().numpy())
  119      pred = np.transpose(model_out.detach().cpu().numpy(), (0, 2, 3, 1)).astype(np.float32)
  120      truth = np.transpose(test_gt.cpu().numpy(), (0, 2, 3, 1)).astype(np.float32)
  121      psnr_mean = np.mean(np.asarray(psnr_list))
  122      ssim_mean = np.mean(np.asarray(ssim_list))
  123      logger.info('===> Epoch {}: testing psnr = {:.2f}, ssim = {:.3f}, time: {:.2f}'
  124                  .format(epoch, psnr_mean, ssim_mean,(end - begin)))
  125      model.train()
  126      return pred, truth, psnr_list, ssim_list, psnr_mean, ssim_mean
  127  
  128  def main():
  129      logger = gen_log(model_path)
  130      logger.info("Learning rate:{}, batch_size:{}.\n".format(opt.learning_rate, opt.batch_size))
  131      psnr_max = 0
  132      for epoch in range(1, opt.max_epoch + 1):
  133          # training
  134          epoch_loss = train(epoch, logger)
  135          # testing
  136          (pred, truth, psnr_all, ssim_all, psnr_mean, ssim_mean) = test(epoch, logger)
  137          scheduler.step()
  138          if psnr_mean > psnr_max:
  139              psnr_max = psnr_mean
  140              if psnr_mean > 28:
  141                  name = result_path + '/' + 'Test_{}_{:.2f}_{:.3f}'.format(epoch, psnr_max, ssim_mean) + '.mat'
  142                  scio.savemat(name, {'truth': truth, 'pred': pred, 'psnr_list': psnr_all, 'ssim_list': ssim_all})
  143                  checkpoint(model, epoch, model_path, logger)
  144  
  145      
  146  
  147  if __name__ == '__main__':
  148      torch.backends.cudnn.enabled = True
  149      torch.backends.cudnn.benchmark = True
  150      main()
  151  
  152  

FILE sources/0244/repo/CIDNet-main/option.py
SHA256 8964d3c4fa9efaad46082c9308660a4dbb075e6cd1e30582c8505388e03aeed2
LINES 1-48
    1  import argparse
    2  import template
    3  
    4  parser = argparse.ArgumentParser(description="HyperSpectral Image Reconstruction Toolbox")
    5  parser.add_argument('--template', default='cidnet',
    6                      help='You can set various templates in option.py')
    7  parser.add_argument('--name', default='xxx',
    8                      help='name of experiment')
    9  
   10  # Hardware specifications
   11  parser.add_argument("--gpu_id", type=str, default='0')
   12  
   13  # Data specifications
   14  parser.add_argument('--data_root', type=str, default='/home/wangxiaodong/dataset/CASSI_dataset/CASSI_dataset', help='dataset directory')
   15  
   16  # Saving specifications
   17  parser.add_argument('--outf', type=str, default='./exp/CIDNet/', help='saving_path')
   18  
   19  # Model specifications
   20  parser.add_argument('--method', type=str, default='cidnet_9stg', help='method name')
   21  parser.add_argument('--pretrained_model_path', type=str, default=None, help='pretrained model directory')
   22  parser.add_argument("--input_setting", type=str, default='H',
   23                      help='the input measurement of the network: H, HM or Y')
   24  parser.add_argument("--input_mask", type=str, default='Phi',
   25                      help='the input mask of the network: Phi, Phi_PhiPhiT, Mask or None')  # Phi: shift_mask   Mask: mask
   26  
   27  # Training specifications
   28  parser.add_argument('--batch_size', type=int, default=5, help='the number of HSIs per batch')
   29  parser.add_argument("--max_epoch", type=int, default=300, help='total epoch')
   30  parser.add_argument("--scheduler", type=str, default='MultiStepLR', help='MultiStepLR or CosineAnnealingLR')
   31  parser.add_argument("--milestones", type=int, default=[50,100,150,200,250], help='milestones for MultiStepLR')
   32  parser.add_argument("--gamma", type=float, default=0.5, help='learning rate decay for MultiStepLR')
   33  parser.add_argument("--epoch_sam_num", type=int, default=5000, help='the number of samples per epoch')
   34  parser.add_argument("--learning_rate", type=float, default=0.0004)
   35  
   36  opt = parser.parse_args()
   37  template.set_template(opt)
   38  
   39  # dataset
   40  opt.data_path = f"{opt.data_root}/cave_1024_28/"
   41  opt.mask_path = f"{opt.data_root}/TSA_simu_data/"
   42  opt.test_path = f"{opt.data_root}/TSA_simu_data/Truth/"
   43  
   44  for arg in vars(opt):
   45      if vars(opt)[arg] == 'True':
   46          vars(opt)[arg] = True
   47      elif vars(opt)[arg] == 'False':
   48          vars(opt)[arg] = False

FILE sources/0244/repo/CIDNet-main/utils.py
SHA256 553052aada5c5cd75cd16ee1e9ddd2a42b983d783b33854d97770fb0bba1f168
LINES 53-83
   53  def LoadTest(path_test):
   54      scene_list = os.listdir(path_test)
   55      scene_list.sort()
   56      test_data = np.zeros((len(scene_list), 256, 256, 28))
   57      for i in range(len(scene_list)):
   58          scene_path = path_test + scene_list[i]
   59          img = sio.loadmat(scene_path)['img']
   60          test_data[i, :, :, :] = img
   61      test_data = torch.from_numpy(np.transpose(test_data, (0, 3, 1, 2)))
   62      return test_data
   63  
   64  def LoadMeasurement(path_test_meas):
   65      img = sio.loadmat(path_test_meas)['simulation_test']
   66      test_data = img
   67      test_data = torch.from_numpy(test_data)
   68      return test_data
   69  
   70  # We find that this calculation method is more close to DGSMP's.
   71  def torch_psnr(img, ref):  # input [28,256,256]
   72      img = (img*256).round()
   73      ref = (ref*256).round()
   74      nC = img.shape[0]
   75      psnr = 0
   76      for i in range(nC):
   77          mse = torch.mean((img[i, :, :] - ref[i, :, :]) ** 2)
   78          psnr += 10 * torch.log10((255*255)/mse)
   79      return psnr / nC
   80  
   81  def torch_ssim(img, ref):  # input [28,256,256]
   82      return ssim(torch.unsqueeze(img, 0), torch.unsqueeze(ref, 0), 1)
   83  
LINES 233-265
  233  def checkpoint(model, epoch, model_path, logger):
  234      model_out_path = model_path + "/model_epoch_{}.pth".format(epoch)
  235      torch.save(model.state_dict(), model_out_path)
  236      logger.info("Checkpoint saved to {}".format(model_out_path))
  237  
  238  def chroma_intensity_decom(gt):
  239      channel = gt.shape[1]
  240      intensity = gt.sum(dim=1, keepdim=True) 
  241      intensity_safe = intensity + 1e-8
  242      chroma = gt / intensity_safe  
  243      return chroma*channel, intensity/channel 
  244  
  245  
  246  def chroma_intensity_mask(input_mask_train, gt_intensity, input_mask_sign, step=2):
  247      if input_mask_sign == 'Phi_PhiPhiT':
  248          Phi, _ = input_mask_train
  249      elif input_mask_sign == 'Phi':
  250          Phi = input_mask_train
  251      elif input_mask_sign == 'Mask':
  252          Phi = input_mask_train
  253      else:
  254          Phi = None
  255      batch, nC, H, W = Phi.shape[0], Phi.shape[1], Phi.shape[2], Phi.shape[3]
  256      W0 = W - (nC - 1) * step
  257      gt_intensity_shift = torch.zeros(batch, nC, H, W).cuda().float()
  258      for i in range(nC):
  259          gt_intensity_shift[:, i, :, step * i:step * i + W0] = gt_intensity.squeeze(1)
  260          
  261      Phi_new = Phi*gt_intensity_shift
  262      Phi_s_new = torch.sum(Phi_new**2,1)
  263      Phi_s_new[Phi_s_new==0] = 1
  264      
  265      return (Phi_new, Phi_s_new)

