text: import argparse
  import os
  import random
  import shutil
  import time
  import warnings
  
  import torch
  import torch.nn as nn
  import torch.nn.parallel
  import torch.backends.cudnn as cudnn
  import torch.distributed as dist
  import torch.optim as optim
  import torch.utils.data
  import torch.utils.data.distributed
  import torchvision.transforms as transforms
  import torchvision.datasets as datasets
  import torchvision.models as models
  from collections import OrderedDict
  
  
  from torch.autograd import Variable
  from torch.utils.data import Dataset, DataLoader
  from PIL import Image
  
  model_names = sorted(name for name in models.__dict__
      if name.islower() and not name.startswith("__")
      and callable(models.__dict__[name]))
  
  parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
  parser.add_argument('data', metavar='DIR',
                      help='path to dataset')
  parser.add_argument('--arch', '-a', metavar='ARCH', default='resnet18',
                      choices=model_names,
                      help='model architecture: ' +
                          ' | '.join(model_names) +
                          ' (default: resnet18)')
  parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
                      help='number of data loading workers (default: 4)')
  parser.add_argument('--epochs', default=90, type=int, metavar='N',
                      help='number of total epochs to run')
  parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
                      help='manual epoch number (useful on restarts)')
  parser.add_argument('-b', '--batch-size', default=256, type=int,
                      metavar='N', help='mini-batch size (default: 256)')
  parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,
                      metavar='LR', help='initial learning rate')
  parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
                      help='momentum')
  parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
                      metavar='W', help='weight decay (default: 1e-4)')
  parser.add_argument('--print-freq', '-p', default=10, type=int,
                      metavar='N', help='print frequency (default: 10)')
  parser.add_argument('--resume', default='', type=str, metavar='PATH',
                      help='path to latest checkpoint (default: none)')
  parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',
                      help='evaluate model on validation set')
  parser.add_argument('--pretrained', dest='pretrained', action='store_true',
                      help='use pre-trained model')
  parser.add_argument('--world-size', default=1, type=int,
                      help='number of distributed processes')
  parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
                      help='url used to set up distributed training')
  parser.add_argument('--dist-backend', default='gloo', type=str,
                      help='distributed backend')
  parser.add_argument('--seed', default=None, type=int,
                      help='seed for initializing training. ')
  parser.add_argument('--gpu', default=None, type=int,
                      help='GPU id to use.')
  parser.add_argument('--percent',default=0.1,type=float)
  parser.add_argument('--savename',default=0.1,type=float)
  parser.add_argument('--save',default='',type=str)
  
  best_prec1 = 0
  mean = [ 0.485, 0.456, 0.406 ]
  std = [ 0.229, 0.224, 0.225 ]
  
  transform = transforms.Compose([
      transforms.Scale(256),
      transforms.CenterCrop(224),
      transforms.ToTensor(),
      transforms.Normalize(mean = mean, std = std),
      ])
  
  def default_loader(path):
      return Image.open(path).convert('RGB')
  
  class MyDataset(torch.utils.data.Dataset):
      def __init__(self, txt, transform=None, target_transform=None, loader=default_loader):
          fh = open(txt, 'r')
          imgs = []
          for line in fh:
              line = line.rstrip()
              line = line.strip('\n')
              line = line.rstrip()
              words = line.split()
              imgs.append((words[0],int(words[1])))
          self.imgs = imgs
          self.transform = transform
          self.target_transform = target_transform
          self.loader = loader
  
      def __getitem__(self, index):
          fn, label = self.imgs[index]
          img = self.loader(fn)
          if self.transform is not None:
              img = self.transform(img)
          return img,label
  
      def __len__(self):
          return len(self.imgs)
  
  def main():
      global args, best_prec1
      args = parser.parse_args()
  
      if args.seed is not None:
          random.seed(args.seed)
          torch.manual_seed(args.seed)
          cudnn.deterministic = True
          warnings.warn('You have chosen to seed training. '
                        'This will turn on the CUDNN deterministic setting, '
                        'which can slow down your training considerably! '
                        'You may see unexpected behavior when restarting '
                        'from checkpoints.')
  
      if args.gpu is not None:
          warnings.warn('You have chosen a specific GPU. This will completely '
                        'disable data parallelism.')
  
      if not os.path.exists(args.save):
          os.mkdir(args.save)
  
      args.distributed = args.world_size > 1
  
      if args.distributed:
          dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
                                  world_size=args.world_size)
  
  
  
      # create model
      if args.pretrained:
          print("=> using pre-trained model '{}'".format(args.arch))
          model = models.__dict__[args.arch](pretrained=True)
      else:
          print("=> creating model '{}'".format(args.arch))
          model = models.__dict__[args.arch]()
          num_ftrs = model.classifier[6].in_features
          model.classifier[6] = nn.Linear(num_ftrs, 102)
  
  
      if args.gpu is not None:
          model = model.cuda(args.gpu)
      elif args.distributed:
          model.cuda()
          model = torch.nn.parallel.DistributedDataParallel(model)
      else:
          if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):
              model.features = torch.nn.DataParallel(model.features)
              model.cuda()
          else:
              model = torch.nn.DataParallel(model).cuda()
  
      if args.resume:
          # Load checkpoint.
          if os.path.isfile(args.resume):
              print("=> loading checkpoint '{}'".format(args.resume))
              checkpoint = torch.load(args.resume).get('state_dict')
              #print(checkpoint.keys())  
  
              model.load_state_dict(checkpoint)
  
          else:
              print("=> no checkpoint found at '{}'".format(args.resume))
  
  
      train_data = MyDataset(txt=args.data+'dataset-trn.txt', transform=transform)
      val_dataset = MyDataset(txt=args.data+'dataset-val.txt', transform=transform)
  
      train_loader = torch.utils.data.DataLoader(train_data , batch_size=args.batch_size, shuffle=True,
          num_workers=args.workers, pin_memory=True)
      val_loader = torch.utils.data.DataLoader(val_dataset , batch_size=args.batch_size, shuffle=False,
          num_workers=args.workers, pin_memory=True)
  
  
      criterion = nn.CrossEntropyLoss().cuda(args.gpu)
  
      model.cuda(args.gpu)
      print("--------------before pruning  ---------------")
      test_acc0 = validate(val_loader, model, criterion) 
      #############################################################################################################################
      total = 0
      for m in model.modules():
          if isinstance(m, nn.Conv2d):
              total += m.weight.data.numel()
  
      zero_param = get_conv_zero_param(model)
      total_noZero = total - zero_param
  
      conv_weights = torch.zeros(total).cuda()
      index = 0
      for m in model.modules():
          if isinstance(m, nn.Conv2d):
              size = m.weight.data.numel()
              conv_weights[index:(index+size)] = m.weight.data.view(-1).abs().clone()
              index += size
  
      y, i = torch.sort(conv_weights)
      thre_index = int(total * args.percent)
      thre = y[thre_index]
  
      pruned = 0
      print('Pruning threshold: {}'.format(thre))
      zero_flag = False
      for k, m in enumerate(model.modules()):
          if isinstance(m, nn.Conv2d):
              weight_copy = m.weight.data.abs().clone()
              mask = weight_copy.gt(thre).float().cuda()
              pruned = pruned + mask.numel() - torch.sum(mask)
              m.weight.data.mul_(mask)
              if int(torch.sum(mask)) == 0:
                  zero_flag = True
              print('layer index: {:d} \t total params: {:d} \t remaining params: {:d}'.
                  format(k, mask.numel(), int(torch.sum(mask))))
      print('Total conv params: {}, Pruned conv params: {}, Pruned ratio: {}'.format(total, pruned, pruned/total))
      ##############################################################################################################################
      print("--------------After weight-pruning  ---------------")
  
      test_acc1 = validate(val_loader, model, criterion)
  
      save_checkpoint({
              'epoch': 0,
              'state_dict': model.state_dict(),
              'acc': test_acc1,
              'best_acc': 0.,
          }, False, checkpoint=args.save)
  
      with open(os.path.join(args.save, 'prune.txt'), 'w') as f:
          f.write('Before pruning: Test Acc:  %.2f\n' % (test_acc0))
          f.write('Total conv params: {}, Pruned conv params: {}, Pruned ratio: {}\n'.format(total, pruned, pruned/total))
          f.write('After Pruning: Test Acc:  %.2f\n' % (test_acc1))
  
          if zero_flag:
              f.write("There exists a layer with 0 parameters left.")
      return
  
  def validate(val_loader, model, criterion):
      batch_time = AverageMeter()
      losses = AverageMeter()
      top1 = AverageMeter()
      top5 = AverageMeter()
  
      # switch to evaluate mode
      model.eval()
  
      with torch.no_grad():
          end = time.time()
          for i, (input, target) in enumerate(val_loader):
              if args.gpu is not None:
                  input = input.cuda(args.gpu, non_blocking=True)
              target = target.cuda(args.gpu, non_blocking=True)
  
              # compute output
              output = model(input)
              loss = criterion(output, target)
  
              # measure accuracy and record loss
              prec1, prec5 = accuracy(output, target, topk=(1, 5))
              losses.update(loss.item(), input.size(0))
              top1.update(prec1[0], input.size(0))
              top5.update(prec5[0], input.size(0))
  
              # measure elapsed time
              batch_time.update(time.time() - end)
              end = time.time()
  
              if i % args.print_freq == 0:
                  print('Test: [{0}/{1}]\t'
                        'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
                        'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
                        'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
                        'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
                         i, len(val_loader), batch_time=batch_time, loss=losses,
                         top1=top1, top5=top5))
  
          print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
                .format(top1=top1, top5=top5))
  
      return top1.avg
  
  def save_checkpoint(state, is_best, checkpoint, filename=''):
      filename = "pruned_vgg"+ str(int(args.savename*100)) +".pth.tar"
      filepath = os.path.join(checkpoint, filename)
      torch.save(state, filepath)
      
  def get_conv_zero_param(model):
      total = 0
      for m in model.modules():
          if isinstance(m, nn.Conv2d):
              total += torch.sum(m.weight.data.eq(0))
      return total
  
  def accuracy(output, target, topk=(1,)):
      """Computes the precision@k for the specified values of k"""
      with torch.no_grad():
          maxk = max(topk)
          batch_size = target.size(0)
  
          _, pred = output.topk(maxk, 1, True, True)
          pred = pred.t()
          correct = pred.eq(target.view(1, -1).expand_as(pred))
  
          res = []
          for k in topk:
              correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
              res.append(correct_k.mul_(100.0 / batch_size))
          return res
  
  class AverageMeter(object):
      """Computes and stores the average and current value"""
      def __init__(self):
          self.reset()
  
      def reset(self):
          self.val = 0
          self.avg = 0
          self.sum = 0
          self.count = 0
  
      def update(self, val, n=1):
          self.val = val
          self.sum += val * n
          self.count += n
          self.avg = self.sum / self.count
  
  if __name__ == '__main__':
      main()