|
| 1 | +import argparse |
| 2 | +import torch |
| 3 | +import torch.nn as nn |
| 4 | +import torch.nn.parallel |
| 5 | +import torch.backends.cudnn as cudnn |
| 6 | +import torch.optim |
| 7 | +import torch.utils.data |
| 8 | +import torch.utils.data.distributed |
| 9 | +import detr.util.misc as utils |
| 10 | +import sys |
| 11 | +sys.path.append("./detr") |
| 12 | +from detr.datasets import get_coco_api_from_dataset |
| 13 | +from val_transform_datasets import build_dataset |
| 14 | +from model import build |
| 15 | +import onnx |
| 16 | +import onnx_graphsurgeon as gs |
| 17 | + |
| 18 | +from sparsebit.quantization import QuantModel, parse_qconfig |
| 19 | + |
| 20 | +from evaluation import evaluate |
| 21 | + |
| 22 | +parser = argparse.ArgumentParser(description="PyTorch ImageNet Training") |
| 23 | +parser.add_argument("qconfig", help="the path of quant config") |
| 24 | +parser.add_argument( |
| 25 | + "-a", |
| 26 | + "--arch", |
| 27 | + metavar="ARCH", |
| 28 | + default="deit_tiny_patch16_224", |
| 29 | + help="ViT model architecture. (default: deit_tiny)", |
| 30 | +) |
| 31 | +parser.add_argument( |
| 32 | + "-j", |
| 33 | + "--num_workers", |
| 34 | + default=2, |
| 35 | + type=int, |
| 36 | + metavar="N", |
| 37 | + help="number of data loading workers (default: 4)", |
| 38 | +) |
| 39 | +parser.add_argument( |
| 40 | + "-b", |
| 41 | + "--batch-size", |
| 42 | + default=1, |
| 43 | + type=int, |
| 44 | + metavar="N", |
| 45 | + help="mini-batch size (default: 64), this is the total " |
| 46 | + "batch size of all GPUs on the current node when " |
| 47 | + "using Data Parallel or Distributed Data Parallel", |
| 48 | +) |
| 49 | +parser.add_argument( |
| 50 | + "-p", |
| 51 | + "--print-freq", |
| 52 | + default=10, |
| 53 | + type=int, |
| 54 | + metavar="N", |
| 55 | + help="print frequency (default: 10)", |
| 56 | +) |
| 57 | + |
| 58 | +# * Backbone |
| 59 | +parser.add_argument('--backbone', default='resnet50', type=str, |
| 60 | + help="Name of the convolutional backbone to use") |
| 61 | +parser.add_argument('--dilation', action='store_true', |
| 62 | + help="If true, we replace stride with dilation in the last convolutional block (DC5)") |
| 63 | +parser.add_argument('--position_embedding', default='sine', type=str, choices=('sine', 'learned'), |
| 64 | + help="Type of positional embedding to use on top of the image features") |
| 65 | + |
| 66 | + |
| 67 | +# * Transformer |
| 68 | +parser.add_argument('--enc_layers', default=6, type=int, |
| 69 | + help="Number of encoding layers in the transformer") |
| 70 | +parser.add_argument('--dec_layers', default=6, type=int, |
| 71 | + help="Number of decoding layers in the transformer") |
| 72 | +parser.add_argument('--dim_feedforward', default=2048, type=int, |
| 73 | + help="Intermediate size of the feedforward layers in the transformer blocks") |
| 74 | +parser.add_argument('--hidden_dim', default=256, type=int, |
| 75 | + help="Size of the embeddings (dimension of the transformer)") |
| 76 | +parser.add_argument('--dropout', default=0.1, type=float, |
| 77 | + help="Dropout applied in the transformer") |
| 78 | +parser.add_argument('--nheads', default=8, type=int, |
| 79 | + help="Number of attention heads inside the transformer's attentions") |
| 80 | +parser.add_argument('--num_queries', default=100, type=int, |
| 81 | + help="Number of query slots") |
| 82 | +parser.add_argument('--pre_norm', action='store_true') |
| 83 | + |
| 84 | +# Loss |
| 85 | +parser.add_argument('--aux_loss', dest='aux_loss', action='store_true', |
| 86 | + help="Enables auxiliary decoding losses (loss at each layer)") |
| 87 | +# * Matcher |
| 88 | +parser.add_argument('--set_cost_class', default=1, type=float, |
| 89 | + help="Class coefficient in the matching cost") |
| 90 | +parser.add_argument('--set_cost_bbox', default=5, type=float, |
| 91 | + help="L1 box coefficient in the matching cost") |
| 92 | +parser.add_argument('--set_cost_giou', default=2, type=float, |
| 93 | + help="giou box coefficient in the matching cost") |
| 94 | +# * Loss coefficients |
| 95 | +parser.add_argument('--mask_loss_coef', default=1, type=float) |
| 96 | +parser.add_argument('--dice_loss_coef', default=1, type=float) |
| 97 | +parser.add_argument('--bbox_loss_coef', default=5, type=float) |
| 98 | +parser.add_argument('--giou_loss_coef', default=2, type=float) |
| 99 | +parser.add_argument('--eos_coef', default=0.1, type=float, |
| 100 | + help="Relative classification weight of the no-object class") |
| 101 | + |
| 102 | +#configs for coco dataset |
| 103 | +parser.add_argument('--dataset_file', default='coco') |
| 104 | +parser.add_argument('--coco_path', type=str) |
| 105 | +parser.add_argument('--masks', action='store_true', |
| 106 | + help="Train segmentation head if the flag is provided") |
| 107 | +parser.add_argument('--output_dir', default='', |
| 108 | + help='path where to save, empty for no saving') |
| 109 | + |
| 110 | +parser.add_argument('--device', default='cuda', |
| 111 | + help='device to use for training / testing') |
| 112 | + |
| 113 | +def main(): |
| 114 | + args = parser.parse_args() |
| 115 | + device = args.device |
| 116 | + |
| 117 | + # get pretrained model from https://github.com/facebookresearch/detr |
| 118 | + model = torch.hub.load('facebookresearch/detr:main', 'detr_resnet50', pretrained=True) |
| 119 | + model, criterion, postprocessors = build(args, model) |
| 120 | + |
| 121 | + qconfig = parse_qconfig(args.qconfig) |
| 122 | + qmodel = QuantModel(model, config=qconfig).to(device) |
| 123 | + |
| 124 | + cudnn.benchmark = True |
| 125 | + |
| 126 | + dataset_val = build_dataset(image_set='val', args=args) |
| 127 | + sampler_val = torch.utils.data.SequentialSampler(dataset_val) |
| 128 | + data_loader_val = torch.utils.data.DataLoader(dataset_val, args.batch_size, sampler=sampler_val, |
| 129 | + drop_last=False, collate_fn=utils.collate_fn, num_workers=args.num_workers) |
| 130 | + base_ds = get_coco_api_from_dataset(dataset_val) |
| 131 | + |
| 132 | + dataset_calib = build_dataset(image_set='train', args=args) |
| 133 | + sampler_calib = torch.utils.data.RandomSampler(dataset_calib) |
| 134 | + data_loader_calib = torch.utils.data.DataLoader(dataset_calib, args.batch_size, sampler=sampler_calib, |
| 135 | + drop_last=False, collate_fn=utils.collate_fn, num_workers=args.num_workers) |
| 136 | + |
| 137 | + |
| 138 | + qmodel.eval() |
| 139 | + with torch.no_grad(): |
| 140 | + qmodel.prepare_calibration() |
| 141 | + # forward calibration-set |
| 142 | + calibration_size = 16 |
| 143 | + cur_size = 0 |
| 144 | + for samples, _ in data_loader_calib: |
| 145 | + sample = samples.tensors.to(device) |
| 146 | + qmodel(sample) |
| 147 | + cur_size += args.batch_size |
| 148 | + if cur_size >= calibration_size: |
| 149 | + break |
| 150 | + qmodel.calc_qparams() |
| 151 | + qmodel.set_quant(w_quant=True, a_quant=True) |
| 152 | + |
| 153 | + test_stats, coco_evaluator = evaluate(qmodel, criterion, postprocessors, |
| 154 | + data_loader_val, base_ds, device, args.output_dir) |
| 155 | + |
| 156 | + qmodel.export_onnx(torch.randn(1, 3, 800, 1200), name="qDETR.onnx") |
| 157 | + |
| 158 | + # graph = gs.import_onnx(onnx.load("qDETR.onnx")) |
| 159 | + # Reshapes = [node for node in graph.nodes if node.op == "Reshape"] |
| 160 | + # for node in Reshapes: |
| 161 | + # if isinstance(node.inputs[1], gs.Constant): |
| 162 | + # if node.inputs[1].values[1]==7600: |
| 163 | + # node.inputs[1].values[1] = 8 |
| 164 | + # elif node.inputs[1].values[1]==950: |
| 165 | + # node.inputs[1].values[1] = 1 |
| 166 | + # elif node.inputs[1].values[1]==100: |
| 167 | + # node.inputs[1].values[1] = 1 |
| 168 | + # elif node.inputs[1].values[1]==800: |
| 169 | + # node.inputs[1].values[1] = 8 |
| 170 | + |
| 171 | + # onnx.save(gs.export_onnx(graph), "qDETR.onnx") |
| 172 | + |
| 173 | + |
| 174 | + |
| 175 | + |
| 176 | +if __name__ == "__main__": |
| 177 | + main() |
0 commit comments