diff --git a/app.py b/app.py index b2843bb77daea6035d417ca2a0a67b58288b3ab3..fd913c32d8cc08aaaf10d5518c9133f9242de8d0 100644 --- a/app.py +++ b/app.py @@ -1,38 +1,65 @@ import gradio as gr -#import spaces -#from huggingface_hub import hf_hub_download -from detect import run - -def yolov9_inference(model_id, image_size, conf_threshold, iou_threshold, input_path = None): - - # if img_path is not None: - # # Load the model - # # model_path = download_models(model_id) - # model = load_model(model_id) - # # Set model parameters - # model.conf = conf_threshold - # model.iou = iou_threshold - # # Perform inference - # results = model(img_path, size=image_size) - # # Optionally, show detection bounding boxes on image - # output = results.render() - # return output[0] - # else: - model = run(weights=model_id, imgsz=(image_size,image_size), conf_thres=conf_threshold, iou_thres=iou_threshold, source=input_path, hide_conf=True, device='cpu') - return model, model +from detect_strongsort import run +import os +import threading + +should_continue = True + + +def yolov9_inference(model_id, image_size, conf_threshold, iou_threshold, img_path=None, vid_path=None): + global should_continue + img_extensions = ['.jpg', '.jpeg', '.png', '.gif'] # Add more image extensions if needed + vid_extensions = ['.mp4', '.avi', '.mov', '.mkv'] # Add more video extensions if needed + + input_path = None + if img_path is not None: + _, img_extension = os.path.splitext(img_path) + if img_extension.lower() in img_extensions: + input_path = img_path + elif vid_path is not None: + _, vid_extension = os.path.splitext(vid_path) + if vid_extension.lower() in vid_extensions: + input_path = vid_path + + output_path = run(yolo_weights=model_id, imgsz=(image_size,image_size), conf_thres=conf_threshold, iou_thres=iou_threshold, source=input_path, device='cpu', strong_sort_weights = "osnet_x0_25_msmt17.pt", hide_conf= True) + # Assuming output_path is the path to the output file + _, output_extension = os.path.splitext(output_path) + if output_extension.lower() in img_extensions: + output_image = output_path # Load the image file here + output_video = None + elif output_extension.lower() in vid_extensions: + output_image = None + output_video = output_path # Load the video file here + + return output_image, output_video, output_path + +def inference(model_id, image_size, conf_threshold, iou_threshold, img_path=None, vid_path=None): + global should_continue + should_continue = True + output_image, output_video, output_path = yolov9_inference(model_id, image_size, conf_threshold, iou_threshold, img_path, vid_path) + return output_image, output_video, output_path + + +def stop_processing(): + global should_continue + should_continue = False + return "Stop..." def app(): with gr.Blocks(): with gr.Row(): with gr.Column(): - img_path = gr.Image(type="filepath", label="Image") - input_path = gr.Video(label="Input video") + gr.HTML("

Input Parameters

") + img_path = gr.File(label="Image") + vid_path = gr.File(label="Video") model_id = gr.Dropdown( label="Model", choices=[ "last_best_model.pt", + "best_model-converted.pt" ], - value="./last_best_model.pt", + value="./last_best_model.pt" + ) image_size = gr.Slider( label="Image Size", @@ -56,21 +83,26 @@ def app(): value=0.5, ) yolov9_infer = gr.Button(value="Inference") - + stop_button = gr.Button(value="Stop") with gr.Column(): - output = gr.Video(label="Output") + gr.HTML("

Output

") + output_image = gr.Image(type="numpy",label="Output Image") + output_video = gr.Video(label="Output Video") output_path = gr.Textbox(label="Output path") + yolov9_infer.click( - fn=yolov9_inference, + fn=inference, inputs=[ model_id, image_size, conf_threshold, iou_threshold, - input_path + img_path, + vid_path ], - outputs=[output, output_path], + outputs=[output_image, output_video, output_path], ) + stop_button.click(stop_processing) gradio_app = gr.Blocks() @@ -81,8 +113,18 @@ with gradio_app: YOLOv9: Real-time Object Detection """) + css = """ + body { + background-color: #f0f0f0; + } + h1 { + color: #4CAF50; + } + """ with gr.Row(): with gr.Column(): app() gradio_app.launch(debug=True) + + diff --git a/detect_strongsort.py b/detect_strongsort.py new file mode 100644 index 0000000000000000000000000000000000000000..360ceedec711b61d2684643bfb9ba41f5e0ce555 --- /dev/null +++ b/detect_strongsort.py @@ -0,0 +1,392 @@ +import argparse + +import os +# limit the number of cpus used by high performance libraries +os.environ["OMP_NUM_THREADS"] = "1" +os.environ["OPENBLAS_NUM_THREADS"] = "1" +os.environ["MKL_NUM_THREADS"] = "1" +os.environ["VECLIB_MAXIMUM_THREADS"] = "1" +os.environ["NUMEXPR_NUM_THREADS"] = "1" +import platform +import sys +import numpy as np +from pathlib import Path +import torch +import torch.backends.cudnn as cudnn +from numpy import random +from time import time + + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[0] # yolov5 strongsort root directory +WEIGHTS = ROOT / 'weights' +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +if str(ROOT / 'yolov9') not in sys.path: + sys.path.append(str(ROOT / 'yolov9')) # add yolov5 ROOT to PATH +if str(ROOT / 'strong_sort') not in sys.path: + sys.path.append(str(ROOT / 'strong_sort')) # add strong_sort ROOT to PATH +ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative +from models.experimental import attempt_load +from models.common import DetectMultiBackend +from utils.dataloaders import LoadImages, LoadStreams, LoadScreenshots +from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2, + increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh) +from utils.torch_utils import select_device, time_sync, smart_inference_mode +from utils.plots import Annotator, colors, save_one_box +from strong_sort.utils.parser import get_config +from strong_sort.strong_sort import StrongSORT + + +VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv' # include video suffixes + + +def plot_one_box(x, img, color=None, label=None, line_thickness=3): + # Plots one bounding box on image img + tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness + color = color or [random.randint(0, 255) for _ in range(3)] + c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) + cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA) + if label: + tf = max(tl - 1, 1) # font thickness + t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] + c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3 + cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled + cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) + + + +@smart_inference_mode() +def run( + source='0', + data = ROOT / 'data/coco.yaml', # data.yaml path + yolo_weights=WEIGHTS / 'yolo.pt', # model.pt path(s), + strong_sort_weights=WEIGHTS / 'osnet_x0_25_msmt17.pt', # model.pt path, + config_strongsort=ROOT / 'strong_sort/configs/strong_sort.yaml', + imgsz=(640, 640), # inference size (height, width) + conf_thres=0.25, # confidence threshold + iou_thres=0.45, # NMS IOU threshold + max_det=1000, # maximum detections per image + device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu + view_img=False, # show results + save_txt=False, # save results to *.txt + save_conf=False, # save confidences in --save-txt labels + save_crop=False, # save cropped prediction boxes + nosave=False, # do not save images/videos + classes=None, # filter by class: --class 0, or --class 0 2 3 + agnostic_nms=False, # class-agnostic NMS + augment=False, # augmented inference + visualize=False, # visualize features + update=False, # update all models + project=ROOT / 'runs/track', # save results to project/name + name='exp', # save results to project/name + exist_ok=False, # existing project/name ok, do not increment + line_thickness=3, # bounding box thickness (pixels) + hide_labels=False, # hide labels + hide_conf=False, # hide confidences + half=False, # use FP16 half-precision inference + dnn=False, # use OpenCV DNN for ONNX inference + vid_stride=1, # video frame-rate stride +): + + source = str(source) + save_img = not nosave and not source.endswith('.txt') # save inference images + is_file = Path(source).suffix[1:] in (VID_FORMATS) + is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) + webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file) + screenshot = source.lower().startswith('screen') + + if is_url and is_file: + source = check_file(source) # download + + # Directories + if not isinstance(yolo_weights, list): # single yolo model + exp_name = Path(yolo_weights).stem + elif type(yolo_weights) is list and len(yolo_weights) == 1: # single models after --yolo_weights + exp_name = Path(yolo_weights[0]).stem + yolo_weights = Path(yolo_weights[0]) + else: # multiple models after --yolo_weights + exp_name = 'ensemble' + exp_name = name if name else exp_name + "_" + Path(strong_sort_weights).stem + save_dir = increment_path(Path(project) / exp_name, exist_ok=exist_ok) # increment run + save_dir = Path(save_dir) + (save_dir / 'tracks' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir + + # Load model + device = select_device(device) + model = DetectMultiBackend(yolo_weights, device=device, dnn=dnn, data=data, fp16=half) + stride, names, pt = model.stride, model.names, model.pt + imgsz = check_img_size(imgsz, s=stride) # check image size + + # Dataloader + + # Dataloader + bs = 1 # batch_size + if webcam: + view_img = check_imshow(warn=True) + dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) + bs = len(dataset) + elif screenshot: + dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt) + else: + dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) + vid_path, vid_writer,txt_path = [None] * bs, [None] * bs, [None] * bs + + + # initialize StrongSORT + cfg = get_config() + cfg.merge_from_file(config_strongsort) + + # Create as many strong sort instances as there are video sources + strongsort_list = [] + for i in range(bs): + strongsort_list.append( + StrongSORT( + strong_sort_weights, + device, + half, + #max_dist=cfg.STRONGSORT.MAX_DIST, + max_iou_distance=cfg.STRONGSORT.MAX_IOU_DISTANCE, + max_age=cfg.STRONGSORT.MAX_AGE, + n_init=cfg.STRONGSORT.N_INIT, + nn_budget=cfg.STRONGSORT.NN_BUDGET, + mc_lambda=cfg.STRONGSORT.MC_LAMBDA, + ema_alpha=cfg.STRONGSORT.EMA_ALPHA, + + ) + ) + strongsort_list[i].model.warmup() + outputs = [None] * bs + + colors = [[random.randint(0, 255) for _ in range(3)] for _ in names] + + # Run tracking + model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup + seen, windows, dt,sdt = 0, [], (Profile(), Profile(), Profile(), Profile()),[0.0, 0.0, 0.0, 0.0] + curr_frames, prev_frames = [None] * bs, [None] * bs + for frame_idx, (path, im, im0s, vid_cap, s) in enumerate(dataset): + # s = '' + t1 = time_sync() + with dt[0]: + im = torch.from_numpy(im).to(model.device) + im = im.half() if model.fp16 else im.float() # uint8 to fp16/32 + im /= 255 # 0 - 255 to 0.0 - 1.0 + if len(im.shape) == 3: + im = im[None] # expand for batch dim + t2 = time_sync() + sdt[0] += t2 - t1 + + # Inference + with dt[1]: + visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False + pred = model(im, augment=augment, visualize=visualize) + pred = pred[0][1] + t3 = time_sync() + sdt[1] += t3 - t2 + + # Apply NMS + with dt[2]: + pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) + sdt[2] += time_sync() - t3 + + # Second-stage classifier (optional) + # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s) + + + # Process detections + for i, det in enumerate(pred): # detections per image + seen += 1 + if webcam: # bs >= 1 + p, im0, _ = path[i], im0s[i].copy(), dataset.count + p = Path(p) # to Path + s += f'{i}: ' + # txt_file_name = p.name + txt_file_name = p.stem + f'_{i}' # Unique text file name + # save_path = str(save_dir / p.name) + str(i) # im.jpg, vid.mp4, ... + save_path = str(save_dir / p.stem) + f'_{i}' # Unique video file name + + else: + p, im0, _ = path, im0s.copy(), getattr(dataset, 'frame', 0) + + + p = Path(p) # to Path + # video file + if source.endswith(VID_FORMATS): + txt_file_name = p.stem + save_path = str(save_dir / p.name) # im.jpg, vid.mp4, ... + # folder with imgs + else: + txt_file_name = p.parent.name # get folder name containing current img + save_path = str(save_dir / p.parent.name) # im.jpg, vid.mp4, ... + + curr_frames[i] = im0 + + txt_path = str(save_dir / 'tracks' / txt_file_name) # im.txt + s += '%gx%g ' % im.shape[2:] # print string + gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh + imc = im0.copy() if save_crop else im0 # for save_crop + annotator = Annotator(im0, line_width=line_thickness, example=str(names)) + + if cfg.STRONGSORT.ECC: # camera motion compensation + strongsort_list[i].tracker.camera_update(prev_frames[i], curr_frames[i]) + + if det is not None and len(det): + # Rescale boxes from img_size to im0 size + det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round() + + # Print results + for c in det[:, -1].unique(): + n = (det[:, -1] == c).sum() # detections per class + s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string + + xywhs = xyxy2xywh(det[:, 0:4]) + confs = det[:, 4] + clss = det[:, 5] + + # pass detections to strongsort + t4 = time_sync() + outputs[i] = strongsort_list[i].update(xywhs.cpu(), confs.cpu(), clss.cpu(), im0) + t5 = time_sync() + sdt[3] += t5 - t4 + + # Write results + for j, (output, conf) in enumerate(zip(outputs[i], confs)): + xyxy = output[0:4] + id = output[4] + cls = output[5] + # for *xyxy, conf, cls in reversed(det): + if save_txt: # Write to file + xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh + # line = (id , cls, *xywh, conf) if save_conf else (cls, *xywh) # label format + line = ( int(p.stem), frame_idx, id , cls, *xywh, conf) if save_conf else ( p.stem, frame_idx, cls, *xywh) # label format + with open(txt_path + '.txt', 'a') as file: + file.write(('%g ' * len(line) + '\n') % line) + + if save_img or save_crop or view_img: # Add bbox to image + c = int(cls) # integer class + label = None if hide_labels else (names[c] if hide_conf else f' { id } {names[c]} {conf:.2f}') + plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=2) + if save_crop: + save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) + + + # # draw boxes for visualization + # if len(outputs[i]) > 0: + # for j, (output, conf) in enumerate(zip(outputs[i], confs)): + + # bboxes = output[0:4] + # id = output[4] + # cls = output[5] + + # if save_txt: + # # to MOT format + # bbox_left = output[0] + # bbox_top = output[1] + # bbox_w = output[2] - output[0] + # bbox_h = output[3] - output[1] + # # format video_name frame id xmin ymin width height score class + # with open(txt_path + '.txt', 'a') as file: + # file.write(f'{p.stem} {frame_idx} {id} {bbox_left} {bbox_top} {bbox_w} {bbox_h} {conf:.2f} {cls}\n') + + # if save_img or save_crop or view_img: # Add bbox to image + # c = int(cls) # integer class + # id = int(id) # integer id + # label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') + # plot_one_box(bboxes, im0, label=label, color=colors[int(cls)], line_thickness=2) + # if save_crop: + # txt_file_name = txt_file_name if (isinstance(path, list) and len(path) > 1) else '' + # save_one_box(bboxes, imc, file=save_dir / 'crops' / txt_file_name / names[c] / f'{id}' / f'{p.stem}.jpg', BGR=True) + + print(f'{s}Done. YOLO:({t3 - t2:.3f}s), StrongSORT:({t5 - t4:.3f}s)') + + else: + strongsort_list[i].increment_ages() + print('No detections') + + # Stream results + im0 = annotator.result() + if view_img: + if platform.system() == 'Linux' and p not in windows: + windows.append(p) + cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux) + cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0]) + cv2.imshow(str(p), im0) + cv2.waitKey(1) # 1 millisecond + + # Save results (image with detections) + if save_img: + if dataset.mode == 'image': + cv2.imwrite(save_path, im0) + else: # 'video' or 'stream' + if vid_path[i] != save_path: # new video + vid_path[i] = save_path + if isinstance(vid_writer[i], cv2.VideoWriter): + vid_writer[i].release() # release previous video writer + if vid_cap: # video + fps = vid_cap.get(cv2.CAP_PROP_FPS) + w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + else: # stream + fps, w, h = 30, im0.shape[1], im0.shape[0] + save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos + vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc('m','p','4','v'), fps, (w, h)) + vid_writer[i].write(im0) + + prev_frames[i] = curr_frames[i] + + # Print time (inference-only) + LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms") + # Print results + LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape, %.1fms StrongSORT' % tuple(1E3 * x / seen for x in sdt)) + if save_txt or save_img: + s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' + LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}") + if update: + strip_optimizer(yolo_weights[0]) # update model (to fix SourceChangeWarning) + return save_path +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--yolo-weights', nargs='+', type=str, default=WEIGHTS / 'yolov9.pt', help='model.pt path(s)') + parser.add_argument('--strong-sort-weights', type=str, default=WEIGHTS / 'osnet_x0_25_msmt17.pt') + parser.add_argument('--config-strongsort', type=str, default='strong_sort/configs/strong_sort.yaml') + parser.add_argument('--source', type=str, default='0', help='file/dir/URL/glob, 0 for webcam') + parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path') + parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w') + parser.add_argument('--conf-thres', type=float, default=0.5, help='confidence threshold') + parser.add_argument('--iou-thres', type=float, default=0.5, help='NMS IoU threshold') + parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--view-img', action='store_true', help='show results') + parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') + parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') + parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') + parser.add_argument('--nosave', action='store_true', help='do not save images/videos') + # class 0 is person, 1 is bycicle, 2 is car... 79 is oven + parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3') + parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') + parser.add_argument('--augment', action='store_true', help='augmented inference') + parser.add_argument('--visualize', action='store_true', help='visualize features') + parser.add_argument('--update', action='store_true', help='update all models') + parser.add_argument('--project', default=ROOT / 'runs/track', help='save results to project/name') + parser.add_argument('--name', default='exp', help='save results to project/name') + parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') + parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') + parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') + parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') + parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') + parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride') + parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference') + opt = parser.parse_args() + opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand + + return opt + + +def main(opt): + # check_requirements(requirements=ROOT / 'requirements.txt', exclude=('tensorboard', 'thop')) + run(**vars(opt)) + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) \ No newline at end of file diff --git a/strong_sort/.gitignore b/strong_sort/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..37ed2f4dc4a1ca945a0d807274bfe2f6cc7e2fec --- /dev/null +++ b/strong_sort/.gitignore @@ -0,0 +1,13 @@ +# Folders +__pycache__/ +build/ +*.egg-info + + +# Files +*.weights +*.t7 +*.mp4 +*.avi +*.so +*.txt diff --git a/strong_sort/LICENSE b/strong_sort/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..92a1ed5dc27676f33e306463d532e4969fbc42ae --- /dev/null +++ b/strong_sort/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Ziqiang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/strong_sort/README.md b/strong_sort/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6073f8064faeaa5dfe6ec9642830b5506d02276f --- /dev/null +++ b/strong_sort/README.md @@ -0,0 +1,137 @@ +# Deep Sort with PyTorch + +![](demo/demo.gif) + +## Update(1-1-2020) +Changes +- fix bugs +- refactor code +- accerate detection by adding nms on gpu + +## Latest Update(07-22) +Changes +- bug fix (Thanks @JieChen91 and @yingsen1 for bug reporting). +- using batch for feature extracting for each frame, which lead to a small speed up. +- code improvement. + +Futher improvement direction +- Train detector on specific dataset rather than the official one. +- Retrain REID model on pedestrain dataset for better performance. +- Replace YOLOv3 detector with advanced ones. + +**Any contributions to this repository is welcome!** + + +## Introduction +This is an implement of MOT tracking algorithm deep sort. Deep sort is basicly the same with sort but added a CNN model to extract features in image of human part bounded by a detector. This CNN model is indeed a RE-ID model and the detector used in [PAPER](https://arxiv.org/abs/1703.07402) is FasterRCNN , and the original source code is [HERE](https://github.com/nwojke/deep_sort). +However in original code, the CNN model is implemented with tensorflow, which I'm not familier with. SO I re-implemented the CNN feature extraction model with PyTorch, and changed the CNN model a little bit. Also, I use **YOLOv3** to generate bboxes instead of FasterRCNN. + +## Dependencies +- python 3 (python2 not sure) +- numpy +- scipy +- opencv-python +- sklearn +- torch >= 0.4 +- torchvision >= 0.1 +- pillow +- vizer +- edict + +## Quick Start +0. Check all dependencies installed +```bash +pip install -r requirements.txt +``` +for user in china, you can specify pypi source to accelerate install like: +```bash +pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple +``` + +1. Clone this repository +``` +git clone git@github.com:ZQPei/deep_sort_pytorch.git +``` + +2. Download YOLOv3 parameters +``` +cd detector/YOLOv3/weight/ +wget https://pjreddie.com/media/files/yolov3.weights +wget https://pjreddie.com/media/files/yolov3-tiny.weights +cd ../../../ +``` + +3. Download deepsort parameters ckpt.t7 +``` +cd deep_sort/deep/checkpoint +# download ckpt.t7 from +https://drive.google.com/drive/folders/1xhG0kRH1EX5B9_Iz8gQJb7UNnn_riXi6 to this folder +cd ../../../ +``` + +4. Compile nms module +```bash +cd detector/YOLOv3/nms +sh build.sh +cd ../../.. +``` + +Notice: +If compiling failed, the simplist way is to **Upgrade your pytorch >= 1.1 and torchvision >= 0.3" and you can avoid the troublesome compiling problems which are most likely caused by either `gcc version too low` or `libraries missing`. + +5. Run demo +``` +usage: python yolov3_deepsort.py VIDEO_PATH + [--help] + [--frame_interval FRAME_INTERVAL] + [--config_detection CONFIG_DETECTION] + [--config_deepsort CONFIG_DEEPSORT] + [--display] + [--display_width DISPLAY_WIDTH] + [--display_height DISPLAY_HEIGHT] + [--save_path SAVE_PATH] + [--cpu] + +# yolov3 + deepsort +python yolov3_deepsort.py [VIDEO_PATH] + +# yolov3_tiny + deepsort +python yolov3_deepsort.py [VIDEO_PATH] --config_detection ./configs/yolov3_tiny.yaml + +# yolov3 + deepsort on webcam +python3 yolov3_deepsort.py /dev/video0 --camera 0 + +# yolov3_tiny + deepsort on webcam +python3 yolov3_deepsort.py /dev/video0 --config_detection ./configs/yolov3_tiny.yaml --camera 0 +``` +Use `--display` to enable display. +Results will be saved to `./output/results.avi` and `./output/results.txt`. + +All files above can also be accessed from BaiduDisk! +linker:[BaiduDisk](https://pan.baidu.com/s/1YJ1iPpdFTlUyLFoonYvozg) +passwd:fbuw + +## Training the RE-ID model +The original model used in paper is in original_model.py, and its parameter here [original_ckpt.t7](https://drive.google.com/drive/folders/1xhG0kRH1EX5B9_Iz8gQJb7UNnn_riXi6). + +To train the model, first you need download [Market1501](http://www.liangzheng.com.cn/Project/project_reid.html) dataset or [Mars](http://www.liangzheng.com.cn/Project/project_mars.html) dataset. + +Then you can try [train.py](deep_sort/deep/train.py) to train your own parameter and evaluate it using [test.py](deep_sort/deep/test.py) and [evaluate.py](deep_sort/deep/evalute.py). +![train.jpg](deep_sort/deep/train.jpg) + +## Demo videos and images +[demo.avi](https://drive.google.com/drive/folders/1xhG0kRH1EX5B9_Iz8gQJb7UNnn_riXi6) +[demo2.avi](https://drive.google.com/drive/folders/1xhG0kRH1EX5B9_Iz8gQJb7UNnn_riXi6) + +![1.jpg](demo/1.jpg) +![2.jpg](demo/2.jpg) + + +## References +- paper: [Simple Online and Realtime Tracking with a Deep Association Metric](https://arxiv.org/abs/1703.07402) + +- code: [nwojke/deep_sort](https://github.com/nwojke/deep_sort) + +- paper: [YOLOv3](https://pjreddie.com/media/files/papers/YOLOv3.pdf) + +- code: [Joseph Redmon/yolov3](https://pjreddie.com/darknet/yolo/) diff --git a/strong_sort/__init__.py b/strong_sort/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2a942db84cf98158525c7a8e0a05799ee96fbba8 --- /dev/null +++ b/strong_sort/__init__.py @@ -0,0 +1,11 @@ +from .strong_sort import StrongSORT + + +__all__ = ['StrongSORT', 'build_tracker'] + + +def build_tracker(cfg, use_cuda): + return StrongSORT(cfg.STRONGSORT.REID_CKPT, + max_dist=cfg.STRONGSORT.MAX_DIST, min_confidence=cfg.STRONGSORT.MIN_CONFIDENCE, + nms_max_overlap=cfg.STRONGSORT.NMS_MAX_OVERLAP, max_iou_distance=cfg.STRONGSORT.MAX_IOU_DISTANCE, + max_age=cfg.STRONGSORT.MAX_AGE, n_init=cfg.STRONGSORT.N_INIT, nn_budget=cfg.STRONGSORT.NN_BUDGET, use_cuda=use_cuda) diff --git a/strong_sort/configs/strong_sort.yaml b/strong_sort/configs/strong_sort.yaml new file mode 100644 index 0000000000000000000000000000000000000000..579f4228665ec7265991993c05ebd0c94fa39378 --- /dev/null +++ b/strong_sort/configs/strong_sort.yaml @@ -0,0 +1,10 @@ +STRONGSORT: + ECC: True # activate camera motion compensation + MC_LAMBDA: 0.995 # matching with both appearance (1 - MC_LAMBDA) and motion cost + EMA_ALPHA: 0.9 # updates appearance state in an exponential moving average manner + MAX_DIST: 0.2 # The matching threshold. Samples with larger distance are considered an invalid match + MAX_IOU_DISTANCE: 0.7 # Gating threshold. Associations with cost larger than this value are disregarded. + MAX_AGE: 30 # Maximum number of missed misses before a track is deleted + N_INIT: 1 # Number of frames that a track remains in initialization phase + NN_BUDGET: 100 # Maximum size of the appearance descriptors gallery + diff --git a/strong_sort/deep/__init__.py b/strong_sort/deep/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/strong_sort/deep/checkpoint/.gitkeep b/strong_sort/deep/checkpoint/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/strong_sort/deep/reid/.flake8 b/strong_sort/deep/reid/.flake8 new file mode 100644 index 0000000000000000000000000000000000000000..4fc103cb101294ae7c3ad8ed536feb660ae6c0d6 --- /dev/null +++ b/strong_sort/deep/reid/.flake8 @@ -0,0 +1,18 @@ +[flake8] +ignore = + # At least two spaces before inline comment + E261, + # Line lengths are recommended to be no greater than 79 characters + E501, + # Missing whitespace around arithmetic operator + E226, + # Blank line contains whitespace + W293, + # Do not use bare 'except' + E722, + # Line break after binary operator + W504, + # isort found an import in the wrong position + I001 +max-line-length = 79 +exclude = __init__.py, build, torchreid/metrics/rank_cylib/ \ No newline at end of file diff --git a/strong_sort/deep/reid/.gitignore b/strong_sort/deep/reid/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6c093a6c68b79305e926a5332c239d2d8193765b --- /dev/null +++ b/strong_sort/deep/reid/.gitignore @@ -0,0 +1,140 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Cython eval code +*.c +*.html + +# OS X +.DS_Store +.Spotlight-V100 +.Trashes +._* + +# ReID +reid-data/ +log/ +saved-models/ +model-zoo/ +debug* diff --git a/strong_sort/deep/reid/.isort.cfg b/strong_sort/deep/reid/.isort.cfg new file mode 100644 index 0000000000000000000000000000000000000000..8039326b5c5825760806cfb5e1667fc0815fc3f2 --- /dev/null +++ b/strong_sort/deep/reid/.isort.cfg @@ -0,0 +1,10 @@ +[isort] +line_length=79 +multi_line_output=3 +length_sort=true +known_standard_library=numpy,setuptools +known_myself=torchreid +known_third_party=matplotlib,cv2,torch,torchvision,PIL,yacs +no_lines_before=STDLIB,THIRDPARTY +sections=FUTURE,STDLIB,THIRDPARTY,myself,FIRSTPARTY,LOCALFOLDER +default_section=FIRSTPARTY \ No newline at end of file diff --git a/strong_sort/deep/reid/.style.yapf b/strong_sort/deep/reid/.style.yapf new file mode 100644 index 0000000000000000000000000000000000000000..29d8e52cc8d04fb2f6a71cdb400fb9e55bdeea45 --- /dev/null +++ b/strong_sort/deep/reid/.style.yapf @@ -0,0 +1,7 @@ +[style] +BASED_ON_STYLE = pep8 +BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF = true +SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN = true +DEDENT_CLOSING_BRACKETS = true +SPACES_BEFORE_COMMENT = 1 +ARITHMETIC_PRECEDENCE_INDICATION = true \ No newline at end of file diff --git a/strong_sort/deep/reid/LICENSE b/strong_sort/deep/reid/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d2bcb88271ffbb1b7255fe202c562d590e91b533 --- /dev/null +++ b/strong_sort/deep/reid/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Kaiyang Zhou + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/strong_sort/deep/reid/README.rst b/strong_sort/deep/reid/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..57be7a86baa6cd89c28cfb03f28a84ee0e21cb5e --- /dev/null +++ b/strong_sort/deep/reid/README.rst @@ -0,0 +1,317 @@ +Torchreid +=========== +Torchreid is a library for deep-learning person re-identification, written in `PyTorch `_ and developed for our ICCV'19 project, `Omni-Scale Feature Learning for Person Re-Identification `_. + +It features: + +- multi-GPU training +- support both image- and video-reid +- end-to-end training and evaluation +- incredibly easy preparation of reid datasets +- multi-dataset training +- cross-dataset evaluation +- standard protocol used by most research papers +- highly extensible (easy to add models, datasets, training methods, etc.) +- implementations of state-of-the-art deep reid models +- access to pretrained reid models +- advanced training techniques +- visualization tools (tensorboard, ranks, etc.) + + +Code: https://github.com/KaiyangZhou/deep-person-reid. + +Documentation: https://kaiyangzhou.github.io/deep-person-reid/. + +How-to instructions: https://kaiyangzhou.github.io/deep-person-reid/user_guide. + +Model zoo: https://kaiyangzhou.github.io/deep-person-reid/MODEL_ZOO. + +Tech report: https://arxiv.org/abs/1910.10093. + +You can find some research projects that are built on top of Torchreid `here `_. + + +What's new +------------ +- [Aug 2021] We have released the ImageNet-pretrained models of ``osnet_ain_x0_75``, ``osnet_ain_x0_5`` and ``osnet_ain_x0_25``. The pretraining setup follows `pycls `_. +- [Apr 2021] We have updated the appendix in the `TPAMI version of OSNet `_ to include results in the multi-source domain generalization setting. The trained models can be found in the `Model Zoo `_. +- [Apr 2021] We have added a script to automate the process of calculating average results over multiple splits. For more details please see ``tools/parse_test_res.py``. +- [Apr 2021] ``v1.4.0``: We added the person search dataset, `CUHK-SYSU `_. Please see the `documentation `_ regarding how to download the dataset (it contains cropped person images). +- [Apr 2021] All models in the model zoo have been moved to google drive. Please raise an issue if any model's performance is inconsistent with the numbers shown in the model zoo page (could be caused by wrong links). +- [Mar 2021] `OSNet `_ will appear in the TPAMI journal! Compared with the conference version, which focuses on discriminative feature learning using the omni-scale building block, this journal extension further considers generalizable feature learning by integrating `instance normalization layers `_ with the OSNet architecture. We hope this journal paper can motivate more future work to taclke the generalization issue in cross-dataset re-ID. +- [Mar 2021] Generalization across domains (datasets) in person re-ID is crucial in real-world applications, which is closely related to the topic of *domain generalization*. Interested in learning how the field of domain generalization has developed over the last decade? Check our recent survey in this topic at https://arxiv.org/abs/2103.02503, with coverage on the history, datasets, related problems, methodologies, potential directions, and so on (*methods designed for generalizable re-ID are also covered*!). +- [Feb 2021] ``v1.3.6`` Added `University-1652 `_, a new dataset for multi-view multi-source geo-localization (credit to `Zhedong Zheng `_). +- [Feb 2021] ``v1.3.5``: Now the `cython code `_ works on Windows (credit to `lablabla `_). +- [Jan 2021] Our recent work, `MixStyle `_ (mixing instance-level feature statistics of samples of different domains for improving domain generalization), has been accepted to ICLR'21. The code has been released at https://github.com/KaiyangZhou/mixstyle-release where the person re-ID part is based on Torchreid. +- [Jan 2021] A new evaluation metric called `mean Inverse Negative Penalty (mINP)` for person re-ID has been introduced in `Deep Learning for Person Re-identification: A Survey and Outlook (TPAMI 2021) `_. Their code can be accessed at ``_. +- [Aug 2020] ``v1.3.3``: Fixed bug in ``visrank`` (caused by not unpacking ``dsetid``). +- [Aug 2020] ``v1.3.2``: Added ``_junk_pids`` to ``grid`` and ``prid``. This avoids using mislabeled gallery images for training when setting ``combineall=True``. +- [Aug 2020] ``v1.3.0``: (1) Added ``dsetid`` to the existing 3-tuple data source, resulting in ``(impath, pid, camid, dsetid)``. This variable denotes the dataset ID and is useful when combining multiple datasets for training (as a dataset indicator). E.g., when combining ``market1501`` and ``cuhk03``, the former will be assigned ``dsetid=0`` while the latter will be assigned ``dsetid=1``. (2) Added ``RandomDatasetSampler``. Analogous to ``RandomDomainSampler``, ``RandomDatasetSampler`` samples a certain number of images (``batch_size // num_datasets``) from each of specified datasets (the amount is determined by ``num_datasets``). +- [Aug 2020] ``v1.2.6``: Added ``RandomDomainSampler`` (it samples ``num_cams`` cameras each with ``batch_size // num_cams`` images to form a mini-batch). +- [Jun 2020] ``v1.2.5``: (1) Dataloader's output from ``__getitem__`` has been changed from ``list`` to ``dict``. Previously, an element, e.g. image tensor, was fetched with ``imgs=data[0]``. Now it should be obtained by ``imgs=data['img']``. See this `commit `_ for detailed changes. (2) Added ``k_tfm`` as an option to image data loader, which allows data augmentation to be applied ``k_tfm`` times *independently* to an image. If ``k_tfm > 1``, ``imgs=data['img']`` returns a list with ``k_tfm`` image tensors. +- [May 2020] Added the person attribute recognition code used in `Omni-Scale Feature Learning for Person Re-Identification (ICCV'19) `_. See ``projects/attribute_recognition/``. +- [May 2020] ``v1.2.1``: Added a simple API for feature extraction (``torchreid/utils/feature_extractor.py``). See the `documentation `_ for the instruction. +- [Apr 2020] Code for reproducing the experiments of `deep mutual learning `_ in the `OSNet paper `__ (Supp. B) has been released at ``projects/DML``. +- [Apr 2020] Upgraded to ``v1.2.0``. The engine class has been made more model-agnostic to improve extensibility. See `Engine `_ and `ImageSoftmaxEngine `_ for more details. Credit to `Dassl.pytorch `_. +- [Dec 2019] Our `OSNet paper `_ has been updated, with additional experiments (in section B of the supplementary) showing some useful techniques for improving OSNet's performance in practice. +- [Nov 2019] ``ImageDataManager`` can load training data from target datasets by setting ``load_train_targets=True``, and the train-loader can be accessed with ``train_loader_t = datamanager.train_loader_t``. This feature is useful for domain adaptation research. + + +Installation +--------------- + +Make sure `conda `_ is installed. + + +.. code-block:: bash + + # cd to your preferred directory and clone this repo + git clone https://github.com/KaiyangZhou/deep-person-reid.git + + # create environment + cd deep-person-reid/ + conda create --name torchreid python=3.7 + conda activate torchreid + + # install dependencies + # make sure `which python` and `which pip` point to the correct path + pip install -r requirements.txt + + # install torch and torchvision (select the proper cuda version to suit your machine) + conda install pytorch torchvision cudatoolkit=9.0 -c pytorch + + # install torchreid (don't need to re-build it if you modify the source code) + python setup.py develop + + +Get started: 30 seconds to Torchreid +------------------------------------- +1. Import ``torchreid`` + +.. code-block:: python + + import torchreid + +2. Load data manager + +.. code-block:: python + + datamanager = torchreid.data.ImageDataManager( + root="reid-data", + sources="market1501", + targets="market1501", + height=256, + width=128, + batch_size_train=32, + batch_size_test=100, + transforms=["random_flip", "random_crop"] + ) + +3 Build model, optimizer and lr_scheduler + +.. code-block:: python + + model = torchreid.models.build_model( + name="resnet50", + num_classes=datamanager.num_train_pids, + loss="softmax", + pretrained=True + ) + + model = model.cuda() + + optimizer = torchreid.optim.build_optimizer( + model, + optim="adam", + lr=0.0003 + ) + + scheduler = torchreid.optim.build_lr_scheduler( + optimizer, + lr_scheduler="single_step", + stepsize=20 + ) + +4. Build engine + +.. code-block:: python + + engine = torchreid.engine.ImageSoftmaxEngine( + datamanager, + model, + optimizer=optimizer, + scheduler=scheduler, + label_smooth=True + ) + +5. Run training and test + +.. code-block:: python + + engine.run( + save_dir="log/resnet50", + max_epoch=60, + eval_freq=10, + print_freq=10, + test_only=False + ) + + +A unified interface +----------------------- +In "deep-person-reid/scripts/", we provide a unified interface to train and test a model. See "scripts/main.py" and "scripts/default_config.py" for more details. The folder "configs/" contains some predefined configs which you can use as a starting point. + +Below we provide an example to train and test `OSNet (Zhou et al. ICCV'19) `_. Assume :code:`PATH_TO_DATA` is the directory containing reid datasets. The environmental variable :code:`CUDA_VISIBLE_DEVICES` is omitted, which you need to specify if you have a pool of gpus and want to use a specific set of them. + +Conventional setting +^^^^^^^^^^^^^^^^^^^^^ + +To train OSNet on Market1501, do + +.. code-block:: bash + + python scripts/main.py \ + --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \ + --transforms random_flip random_erase \ + --root $PATH_TO_DATA + + +The config file sets Market1501 as the default dataset. If you wanna use DukeMTMC-reID, do + +.. code-block:: bash + + python scripts/main.py \ + --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \ + -s dukemtmcreid \ + -t dukemtmcreid \ + --transforms random_flip random_erase \ + --root $PATH_TO_DATA \ + data.save_dir log/osnet_x1_0_dukemtmcreid_softmax_cosinelr + +The code will automatically (download and) load the ImageNet pretrained weights. After the training is done, the model will be saved as "log/osnet_x1_0_market1501_softmax_cosinelr/model.pth.tar-250". Under the same folder, you can find the `tensorboard `_ file. To visualize the learning curves using tensorboard, you can run :code:`tensorboard --logdir=log/osnet_x1_0_market1501_softmax_cosinelr` in the terminal and visit :code:`http://localhost:6006/` in your web browser. + +Evaluation is automatically performed at the end of training. To run the test again using the trained model, do + +.. code-block:: bash + + python scripts/main.py \ + --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \ + --root $PATH_TO_DATA \ + model.load_weights log/osnet_x1_0_market1501_softmax_cosinelr/model.pth.tar-250 \ + test.evaluate True + + +Cross-domain setting +^^^^^^^^^^^^^^^^^^^^^ + +Suppose you wanna train OSNet on DukeMTMC-reID and test its performance on Market1501, you can do + +.. code-block:: bash + + python scripts/main.py \ + --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad.yaml \ + -s dukemtmcreid \ + -t market1501 \ + --transforms random_flip color_jitter \ + --root $PATH_TO_DATA + +Here we only test the cross-domain performance. However, if you also want to test the performance on the source dataset, i.e. DukeMTMC-reID, you can set :code:`-t dukemtmcreid market1501`, which will evaluate the model on the two datasets separately. + +Different from the same-domain setting, here we replace :code:`random_erase` with :code:`color_jitter`. This can improve the generalization performance on the unseen target dataset. + +Pretrained models are available in the `Model Zoo `_. + + +Datasets +-------- + +Image-reid datasets +^^^^^^^^^^^^^^^^^^^^^ +- `Market1501 `_ +- `CUHK03 `_ +- `DukeMTMC-reID `_ +- `MSMT17 `_ +- `VIPeR `_ +- `GRID `_ +- `CUHK01 `_ +- `SenseReID `_ +- `QMUL-iLIDS `_ +- `PRID `_ + +Geo-localization datasets +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- `University-1652 `_ + +Video-reid datasets +^^^^^^^^^^^^^^^^^^^^^^^ +- `MARS `_ +- `iLIDS-VID `_ +- `PRID2011 `_ +- `DukeMTMC-VideoReID `_ + + +Models +------- + +ImageNet classification models +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- `ResNet `_ +- `ResNeXt `_ +- `SENet `_ +- `DenseNet `_ +- `Inception-ResNet-V2 `_ +- `Inception-V4 `_ +- `Xception `_ +- `IBN-Net `_ + +Lightweight models +^^^^^^^^^^^^^^^^^^^ +- `NASNet `_ +- `MobileNetV2 `_ +- `ShuffleNet `_ +- `ShuffleNetV2 `_ +- `SqueezeNet `_ + +ReID-specific models +^^^^^^^^^^^^^^^^^^^^^^ +- `MuDeep `_ +- `ResNet-mid `_ +- `HACNN `_ +- `PCB `_ +- `MLFN `_ +- `OSNet `_ +- `OSNet-AIN `_ + + +Useful links +------------- +- `OSNet-IBN1-Lite (test-only code with lite docker container) `_ +- `Deep Learning for Person Re-identification: A Survey and Outlook `_ + + +Citation +--------- +If you use this code or the models in your research, please give credit to the following papers: + +.. code-block:: bash + + @article{torchreid, + title={Torchreid: A Library for Deep Learning Person Re-Identification in Pytorch}, + author={Zhou, Kaiyang and Xiang, Tao}, + journal={arXiv preprint arXiv:1910.10093}, + year={2019} + } + + @inproceedings{zhou2019osnet, + title={Omni-Scale Feature Learning for Person Re-Identification}, + author={Zhou, Kaiyang and Yang, Yongxin and Cavallaro, Andrea and Xiang, Tao}, + booktitle={ICCV}, + year={2019} + } + + @article{zhou2021osnet, + title={Learning Generalisable Omni-Scale Representations for Person Re-Identification}, + author={Zhou, Kaiyang and Yang, Yongxin and Cavallaro, Andrea and Xiang, Tao}, + journal={TPAMI}, + year={2021} + } diff --git a/strong_sort/deep/reid/configs/im_osnet_ain_x1_0_softmax_256x128_amsgrad_cosine.yaml b/strong_sort/deep/reid/configs/im_osnet_ain_x1_0_softmax_256x128_amsgrad_cosine.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c8b63ec3ea11798edf50d3a052b87f0b5494a645 --- /dev/null +++ b/strong_sort/deep/reid/configs/im_osnet_ain_x1_0_softmax_256x128_amsgrad_cosine.yaml @@ -0,0 +1,35 @@ +model: + name: 'osnet_ain_x1_0' + pretrained: True + +data: + type: 'image' + sources: ['market1501'] + targets: ['market1501', 'dukemtmcreid'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip', 'color_jitter'] + save_dir: 'log/osnet_ain_x1_0_market1501_softmax_cosinelr' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'amsgrad' + lr: 0.0015 + max_epoch: 100 + batch_size: 64 + fixbase_epoch: 10 + open_layers: ['classifier'] + lr_scheduler: 'cosine' + +test: + batch_size: 300 + dist_metric: 'cosine' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/configs/im_osnet_ibn_x1_0_softmax_256x128_amsgrad.yaml b/strong_sort/deep/reid/configs/im_osnet_ibn_x1_0_softmax_256x128_amsgrad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b4f89033d1337f8ab173d920bd5f3357981e350f --- /dev/null +++ b/strong_sort/deep/reid/configs/im_osnet_ibn_x1_0_softmax_256x128_amsgrad.yaml @@ -0,0 +1,36 @@ +model: + name: 'osnet_ibn_x1_0' + pretrained: True + +data: + type: 'image' + sources: ['market1501'] + targets: ['dukemtmcreid'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip', 'color_jitter'] + save_dir: 'log/osnet_ibn_x1_0_market2duke_softmax' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'amsgrad' + lr: 0.0015 + max_epoch: 150 + batch_size: 64 + fixbase_epoch: 10 + open_layers: ['classifier'] + lr_scheduler: 'single_step' + stepsize: [60] + +test: + batch_size: 300 + dist_metric: 'euclidean' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/configs/im_osnet_x0_25_softmax_256x128_amsgrad.yaml b/strong_sort/deep/reid/configs/im_osnet_x0_25_softmax_256x128_amsgrad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d256a6b27399a6aca15ce264ae8f6853afca37c5 --- /dev/null +++ b/strong_sort/deep/reid/configs/im_osnet_x0_25_softmax_256x128_amsgrad.yaml @@ -0,0 +1,36 @@ +model: + name: 'osnet_x0_25' + pretrained: True + +data: + type: 'image' + sources: ['market1501'] + targets: ['market1501'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip'] + save_dir: 'log/osnet_x0_25_market1501_softmax' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'amsgrad' + lr: 0.003 + max_epoch: 180 + batch_size: 128 + fixbase_epoch: 10 + open_layers: ['classifier'] + lr_scheduler: 'single_step' + stepsize: [80] + +test: + batch_size: 300 + dist_metric: 'euclidean' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/configs/im_osnet_x0_5_softmax_256x128_amsgrad.yaml b/strong_sort/deep/reid/configs/im_osnet_x0_5_softmax_256x128_amsgrad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..467305f8ba7f25d4794732ccc4ebd53de9f9927d --- /dev/null +++ b/strong_sort/deep/reid/configs/im_osnet_x0_5_softmax_256x128_amsgrad.yaml @@ -0,0 +1,36 @@ +model: + name: 'osnet_x0_5' + pretrained: True + +data: + type: 'image' + sources: ['market1501'] + targets: ['market1501'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip'] + save_dir: 'log/osnet_x0_5_market1501_softmax' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'amsgrad' + lr: 0.003 + max_epoch: 180 + batch_size: 128 + fixbase_epoch: 10 + open_layers: ['classifier'] + lr_scheduler: 'single_step' + stepsize: [80] + +test: + batch_size: 300 + dist_metric: 'euclidean' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/configs/im_osnet_x0_75_softmax_256x128_amsgrad.yaml b/strong_sort/deep/reid/configs/im_osnet_x0_75_softmax_256x128_amsgrad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..04203fd0fbe7f5c4185d7d20ec251dcf1ba6398b --- /dev/null +++ b/strong_sort/deep/reid/configs/im_osnet_x0_75_softmax_256x128_amsgrad.yaml @@ -0,0 +1,36 @@ +model: + name: 'osnet_x0_75' + pretrained: True + +data: + type: 'image' + sources: ['market1501'] + targets: ['market1501'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip'] + save_dir: 'log/osnet_x0_75_market1501_softmax' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'amsgrad' + lr: 0.0015 + max_epoch: 150 + batch_size: 64 + fixbase_epoch: 10 + open_layers: ['classifier'] + lr_scheduler: 'single_step' + stepsize: [60] + +test: + batch_size: 300 + dist_metric: 'euclidean' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/configs/im_osnet_x1_0_softmax_256x128_amsgrad.yaml b/strong_sort/deep/reid/configs/im_osnet_x1_0_softmax_256x128_amsgrad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f1c970fed20c7aae81b7c5424caa94bbc7bf939e --- /dev/null +++ b/strong_sort/deep/reid/configs/im_osnet_x1_0_softmax_256x128_amsgrad.yaml @@ -0,0 +1,36 @@ +model: + name: 'osnet_x1_0' + pretrained: True + +data: + type: 'image' + sources: ['market1501'] + targets: ['market1501'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip'] + save_dir: 'log/osnet_x1_0_market1501_softmax' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'amsgrad' + lr: 0.0015 + max_epoch: 150 + batch_size: 64 + fixbase_epoch: 10 + open_layers: ['classifier'] + lr_scheduler: 'single_step' + stepsize: [60] + +test: + batch_size: 300 + dist_metric: 'euclidean' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml b/strong_sort/deep/reid/configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml new file mode 100644 index 0000000000000000000000000000000000000000..29750bc2e3cce5747ab703905f74fcbed74b5a57 --- /dev/null +++ b/strong_sort/deep/reid/configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml @@ -0,0 +1,35 @@ +model: + name: 'osnet_x1_0' + pretrained: True + +data: + type: 'image' + sources: ['market1501'] + targets: ['market1501'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip'] + save_dir: 'log/osnet_x1_0_market1501_softmax_cosinelr' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'amsgrad' + lr: 0.0015 + max_epoch: 250 + batch_size: 64 + fixbase_epoch: 10 + open_layers: ['classifier'] + lr_scheduler: 'cosine' + +test: + batch_size: 300 + dist_metric: 'euclidean' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/configs/im_r50_softmax_256x128_amsgrad.yaml b/strong_sort/deep/reid/configs/im_r50_softmax_256x128_amsgrad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61735898ac1f2e72220f739445a186f787dfe568 --- /dev/null +++ b/strong_sort/deep/reid/configs/im_r50_softmax_256x128_amsgrad.yaml @@ -0,0 +1,36 @@ +model: + name: 'resnet50_fc512' + pretrained: True + +data: + type: 'image' + sources: ['market1501'] + targets: ['market1501'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip'] + save_dir: 'log/resnet50_market1501_softmax' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'amsgrad' + lr: 0.0003 + max_epoch: 60 + batch_size: 32 + fixbase_epoch: 5 + open_layers: ['classifier'] + lr_scheduler: 'single_step' + stepsize: [20] + +test: + batch_size: 100 + dist_metric: 'euclidean' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/configs/im_r50fc512_softmax_256x128_amsgrad.yaml b/strong_sort/deep/reid/configs/im_r50fc512_softmax_256x128_amsgrad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5ec2b705db03439220fb257d7e54195844b8cdef --- /dev/null +++ b/strong_sort/deep/reid/configs/im_r50fc512_softmax_256x128_amsgrad.yaml @@ -0,0 +1,36 @@ +model: + name: 'resnet50_fc512' + pretrained: True + +data: + type: 'image' + sources: ['market1501'] + targets: ['market1501'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip'] + save_dir: 'log/resnet50_fc512_market1501_softmax' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'amsgrad' + lr: 0.0003 + max_epoch: 60 + batch_size: 32 + fixbase_epoch: 5 + open_layers: ['fc', 'classifier'] + lr_scheduler: 'single_step' + stepsize: [20] + +test: + batch_size: 100 + dist_metric: 'euclidean' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/AWESOME_REID.md b/strong_sort/deep/reid/docs/AWESOME_REID.md new file mode 100644 index 0000000000000000000000000000000000000000..31215356af8f15f40263542167b1ced97f4f402e --- /dev/null +++ b/strong_sort/deep/reid/docs/AWESOME_REID.md @@ -0,0 +1,69 @@ +# Awesome-ReID +Here is a collection of ReID-related research with links to papers and code. You are welcome to submit [PR](https://help.github.com/articles/creating-a-pull-request/)s if you find something missing. + + +- [TPAMI21] Learning Generalisable Omni-Scale Representations for Person Re-Identification [[paper](https://arxiv.org/abs/1910.06827)][[code](https://github.com/KaiyangZhou/deep-person-reid)] + +- [TPAMI21] Deep Learning for Person Re-identification: A Survey and Outlook [[paper](https://arxiv.org/abs/2001.04193)] [[code](https://github.com/mangye16/ReID-Survey)] + +- [ICCV19] RGB-Infrared Cross-Modality Person Re-Identification via Joint Pixel and Feature Alignment. [[paper](http://openaccess.thecvf.com/content_ICCV_2019/papers/Wang_RGB-Infrared_Cross-Modality_Person_Re-Identification_via_Joint_Pixel_and_Feature_Alignment_ICCV_2019_paper.pdf)] [[code](https://github.com/wangguanan/AlignGAN)] + +- [ICCV19] Unsupervised Graph Association for Person Re-identification. [[paper](https://github.com/yichuan9527/Unsupervised-Graph-Association-for-Person-Re-identification)] [[code](https://github.com/yichuan9527/Unsupervised-Graph-Association-for-Person-Re-identification)] + +- [ICCV19] Self-similarity Grouping: A Simple Unsupervised Cross Domain Adaptation Approach for Person Re-identification. [[paper](http://openaccess.thecvf.com/content_ICCV_2019/papers/Fu_Self-Similarity_Grouping_A_Simple_Unsupervised_Cross_Domain_Adaptation_Approach_for_ICCV_2019_paper.pdf)] [[code](https://github.com/OasisYang/SSG)] + +- [ICCV19] Spectral Feature Transformation for Person Re-Identification. [[paper](http://openaccess.thecvf.com/content_ICCV_2019/papers/Luo_Spectral_Feature_Transformation_for_Person_Re-Identification_ICCV_2019_paper.pdf)] [[code](https://github.com/LuckyDC/SFT_REID)] + +- [ICCV19] Beyond Human Parts: Dual Part-Aligned Representations for Person Re-Identification. [[paper](http://openaccess.thecvf.com/content_ICCV_2019/papers/Guo_Beyond_Human_Parts_Dual_Part-Aligned_Representations_for_Person_Re-Identification_ICCV_2019_paper.pdf)] [[code](https://github.com/ggjy/P2Net.pytorch)] + +- [ICCV19] Co-segmentation Inspired Attention Networks for Video-based Person Re-identification. [[paper](http://openaccess.thecvf.com/content_ICCV_2019/papers/Subramaniam_Co-Segmentation_Inspired_Attention_Networks_for_Video-Based_Person_Re-Identification_ICCV_2019_paper.pdf)][[code](https://github.com/InnovArul/vidreid_cosegmentation)] + +- [ICCV19] Mixed High-Order Attention Network for Person Re-Identification. [[paper](https://arxiv.org/abs/1908.05819)][[code](https://github.com/chenbinghui1/MHN)] + +- [ICCV19] ABD-Net: Attentive but Diverse Person Re-Identification. [[paper](https://arxiv.org/abs/1908.01114)] [[code](https://github.com/TAMU-VITA/ABD-Net)] + +- [ICCV19] Omni-Scale Feature Learning for Person Re-Identification. [[paper](https://arxiv.org/abs/1905.00953)] [[code](https://github.com/KaiyangZhou/deep-person-reid)] + +- [CVPR19] Joint Discriminative and Generative Learning for Person Re-identification. [[paper](https://arxiv.org/abs/1904.07223)][[code](https://github.com/NVlabs/DG-Net)] +- [CVPR19] Invariance Matters: Exemplar Memory for Domain Adaptive Person Re-identification. [[paper](https://arxiv.org/abs/1904.01990)][[code](https://github.com/zhunzhong07/ECN)] +- [CVPR19] Dissecting Person Re-identification from the Viewpoint of Viewpoint. [[paper](https://arxiv.org/abs/1812.02162)][[code](https://github.com/sxzrt/Dissecting-Person-Re-ID-from-the-Viewpoint-of-Viewpoint)] +- [CVPR19] Unsupervised Person Re-identification by Soft Multilabel Learning. [[paper](https://arxiv.org/abs/1903.06325)][[code](https://github.com/KovenYu/MAR)] +- [CVPR19] Patch-based Discriminative Feature Learning for Unsupervised Person Re-identification. [[paper](https://kovenyu.com/publication/2019-cvpr-pedal/)][[code](https://github.com/QizeYang/PAUL)] + +- [AAAI19] Spatial and Temporal Mutual Promotion for Video-based Person Re-identification. [[paper](https://arxiv.org/abs/1812.10305)][[code](https://github.com/yolomax/person-reid-lib)] + +- [AAAI19] Spatial-Temporal Person Re-identification. [[paper](https://arxiv.org/abs/1812.03282)][[code](https://github.com/Wanggcong/Spatial-Temporal-Re-identification)] + +- [AAAI19] Horizontal Pyramid Matching for Person Re-identification. [[paper](https://arxiv.org/abs/1804.05275)][[code](https://github.com/OasisYang/HPM)] + +- [AAAI19] Backbone Can Not be Trained at Once: Rolling Back to Pre-trained Network for Person Re-identification. [[paper](https://arxiv.org/abs/1901.06140)][[code](https://github.com/youngminPIL/rollback)] + +- [AAAI19] A Bottom-Up Clustering Approach to Unsupervised Person Re-identification. [[paper](https://vana77.github.io/vana77.github.io/images/AAAI19.pdf)][[code](https://github.com/vana77/Bottom-up-Clustering-Person-Re-identification)] + +- [NIPS18] FD-GAN: Pose-guided Feature Distilling GAN for Robust Person Re-identification. [[paper](https://arxiv.org/abs/1810.02936)][[code](https://github.com/yxgeee/FD-GAN)] + +- [ECCV18] Generalizing A Person Retrieval Model Hetero- and Homogeneously. [[paper](http://openaccess.thecvf.com/content_ECCV_2018/papers/Zhun_Zhong_Generalizing_A_Person_ECCV_2018_paper.pdf)][[code](https://github.com/zhunzhong07/HHL)] + +- [ECCV18] Pose-Normalized Image Generation for Person Re-identification. [[paper](https://arxiv.org/abs/1712.02225)][[code](https://github.com/naiq/PN_GAN)] + +- [CVPR18] Camera Style Adaptation for Person Re-Identification. [[paper](https://arxiv.org/abs/1711.10295)][[code](https://github.com/zhunzhong07/CamStyle)] + +- [CVPR18] Deep Group-Shuffling Random Walk for Person Re-Identification. [[paper](https://arxiv.org/abs/1807.11178)][[code](https://github.com/YantaoShen/kpm_rw_person_reid)] + +- [CVPR18] End-to-End Deep Kronecker-Product Matching for Person Re-identification. [[paper](https://arxiv.org/abs/1807.11182)][[code](https://github.com/YantaoShen/kpm_rw_person_reid)] + +- [CVPR18] Features for Multi-Target Multi-Camera Tracking and Re-Identification. [[paper](https://arxiv.org/abs/1803.10859)][[code](https://github.com/ergysr/DeepCC)] + +- [CVPR18] Group Consistent Similarity Learning via Deep CRF for Person Re-Identification. [[paper](http://openaccess.thecvf.com/content_cvpr_2018/papers/Chen_Group_Consistent_Similarity_CVPR_2018_paper.pdf)][[code](https://github.com/dapengchen123/crf_affinity)] + +- [CVPR18] Harmonious Attention Network for Person Re-Identification. [[paper](https://arxiv.org/abs/1802.08122)][[code](https://github.com/KaiyangZhou/deep-person-reid)] + +- [CVPR18] Human Semantic Parsing for Person Re-Identification. [[paper](https://arxiv.org/abs/1804.00216)][[code](https://github.com/emrahbasaran/SPReID)] + +- [CVPR18] Multi-Level Factorisation Net for Person Re-Identification. [[paper](https://arxiv.org/abs/1803.09132)][[code](https://github.com/KaiyangZhou/deep-person-reid)] + +- [CVPR18] Resource Aware Person Re-identification across Multiple Resolutions. [[paper](https://arxiv.org/abs/1805.08805)][[code](https://github.com/mileyan/DARENet)] + +- [CVPR18] Exploit the Unknown Gradually: One-Shot Video-Based Person Re-Identification by Stepwise Learning. [[paper](https://yu-wu.net/pdf/CVPR2018_Exploit-Unknown-Gradually.pdf)][[code](https://github.com/Yu-Wu/Exploit-Unknown-Gradually)] + +- [ArXiv18] Revisiting Temporal Modeling for Video-based Person ReID. [[paper](https://arxiv.org/abs/1805.02104)][[code](https://github.com/jiyanggao/Video-Person-ReID)] diff --git a/strong_sort/deep/reid/docs/MODEL_ZOO.md b/strong_sort/deep/reid/docs/MODEL_ZOO.md new file mode 100644 index 0000000000000000000000000000000000000000..8a9306fe0dccf6259add21bf1de1bdfbd5deeb7f --- /dev/null +++ b/strong_sort/deep/reid/docs/MODEL_ZOO.md @@ -0,0 +1,93 @@ +# Model Zoo + +- Results are presented in the format of **. +- When computing model size and FLOPs, only layers that are used at test time are considered (see `torchreid.utils.compute_model_complexity`). +- Asterisk (\*) means the model is trained from scratch. +- `combineall=True` means all images in the dataset are used for model training. +- Why not use heavy data augmentation like [random erasing](https://arxiv.org/abs/1708.04896) for model training? It's because heavy data augmentation might harm the cross-dataset generalization performance (see [this paper](https://arxiv.org/abs/1708.04896)). + + +## ImageNet pretrained models + + +| Model | Download | +| :--- | :---: | +| shufflenet | [model](https://drive.google.com/file/d/1RFnYcHK1TM-yt3yLsNecaKCoFO4Yb6a-/view?usp=sharing) | +| mobilenetv2_x1_0 | [model](https://drive.google.com/file/d/1K7_CZE_L_Tf-BRY6_vVm0G-0ZKjVWh3R/view?usp=sharing) | +| mobilenetv2_x1_4 | [model](https://drive.google.com/file/d/10c0ToIGIVI0QZTx284nJe8QfSJl5bIta/view?usp=sharing) | +| mlfn | [model](https://drive.google.com/file/d/1PP8Eygct5OF4YItYRfA3qypYY9xiqHuV/view?usp=sharing) | +| osnet_x1_0 | [model](https://drive.google.com/file/d/1LaG1EJpHrxdAxKnSCJ_i0u-nbxSAeiFY/view?usp=sharing) | +| osnet_x0_75 | [model](https://drive.google.com/file/d/1uwA9fElHOk3ZogwbeY5GkLI6QPTX70Hq/view?usp=sharing) | +| osnet_x0_5 | [model](https://drive.google.com/file/d/16DGLbZukvVYgINws8u8deSaOqjybZ83i/view?usp=sharing) | +| osnet_x0_25 | [model](https://drive.google.com/file/d/1rb8UN5ZzPKRc_xvtHlyDh-cSz88YX9hs/view?usp=sharing) | +| osnet_ibn_x1_0 | [model](https://drive.google.com/file/d/1sr90V6irlYYDd4_4ISU2iruoRG8J__6l/view?usp=sharing) | +| osnet_ain_x1_0 | [model](https://drive.google.com/file/d/1-CaioD9NaqbHK_kzSMW8VE4_3KcsRjEo/view?usp=sharing) | +| osnet_ain_x0_75 | [model](https://drive.google.com/file/d/1apy0hpsMypqstfencdH-jKIUEFOW4xoM/view?usp=sharing) | +| osnet_ain_x0_5 | [model](https://drive.google.com/file/d/1KusKvEYyKGDTUBVRxRiz55G31wkihB6l/view?usp=sharing) | +| osnet_ain_x0_25 | [model](https://drive.google.com/file/d/1SxQt2AvmEcgWNhaRb2xC4rP6ZwVDP0Wt/view?usp=sharing) | + + +## Same-domain ReID + + +| Model | # Param (10^6) | GFLOPs | Loss | Input | Transforms | Distance | market1501 | dukemtmcreid | msmt17 | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +| resnet50 | 23.5 | 2.7 | softmax | (256, 128) | `random_flip`, `random_crop` | `euclidean` | [87.9 (70.4)](https://drive.google.com/file/d/1dUUZ4rHDWohmsQXCRe2C_HbYkzz94iBV/view?usp=sharing) | [78.3 (58.9)](https://drive.google.com/file/d/17ymnLglnc64NRvGOitY3BqMRS9UWd1wg/view?usp=sharing) | [63.2 (33.9)](https://drive.google.com/file/d/1ep7RypVDOthCRIAqDnn4_N-UhkkFHJsj/view?usp=sharing) | +| resnet50_fc512 | 24.6 | 4.1 | softmax | (256, 128) | `random_flip`, `random_crop` | `euclidean` | [90.8 (75.3)](https://drive.google.com/file/d/1kv8l5laX_YCdIGVCetjlNdzKIA3NvsSt/view?usp=sharing) | [81.0 (64.0)](https://drive.google.com/file/d/13QN8Mp3XH81GK4BPGXobKHKyTGH50Rtx/view?usp=sharing) | [69.6 (38.4)](https://drive.google.com/file/d/1fDJLcz4O5wxNSUvImIIjoaIF9u1Rwaud/view?usp=sharing) | +| mlfn | 32.5 | 2.8 | softmax | (256, 128) | `random_flip`, `random_crop` | `euclidean` | [90.1 (74.3)](https://drive.google.com/file/d/1wXcvhA_b1kpDfrt9s2Pma-MHxtj9pmvS/view?usp=sharing) | [81.1 (63.2)](https://drive.google.com/file/d/1rExgrTNb0VCIcOnXfMsbwSUW1h2L1Bum/view?usp=sharing) | [66.4 (37.2)](https://drive.google.com/file/d/18JzsZlJb3Wm7irCbZbZ07TN4IFKvR6p-/view?usp=sharing) | +| hacnn* | 4.5 | 0.5 | softmax | (160, 64) | `random_flip`, `random_crop` | `euclidean` | [90.9 (75.6)](https://drive.google.com/file/d/1LRKIQduThwGxMDQMiVkTScBwR7WidmYF/view?usp=sharing) | [80.1 (63.2)](https://drive.google.com/file/d/1zNm6tP4ozFUCUQ7Sv1Z98EAJWXJEhtYH/view?usp=sharing) | [64.7 (37.2)](https://drive.google.com/file/d/1MsKRtPM5WJ3_Tk2xC0aGOO7pM3VaFDNZ/view?usp=sharing) | +| mobilenetv2_x1_0 | 2.2 | 0.2 | softmax | (256, 128) | `random_flip`, `random_crop` | `euclidean` | [85.6 (67.3)](https://drive.google.com/file/d/18DgHC2ZJkjekVoqBWszD8_Xiikz-fewp/view?usp=sharing) | [74.2 (54.7)](https://drive.google.com/file/d/1q1WU2FETRJ3BXcpVtfJUuqq4z3psetds/view?usp=sharing) | [57.4 (29.3)](https://drive.google.com/file/d/1j50Hv14NOUAg7ZeB3frzfX-WYLi7SrhZ/view?usp=sharing) | +| mobilenetv2_x1_4 | 4.3 | 0.4 | softmax | (256, 128) | `random_flip`, `random_crop` | `euclidean` | [87.0 (68.5)](https://drive.google.com/file/d/1t6JCqphJG-fwwPVkRLmGGyEBhGOf2GO5/view?usp=sharing) | [76.2 (55.8)](https://drive.google.com/file/d/12uD5FeVqLg9-AFDju2L7SQxjmPb4zpBN/view?usp=sharing) | [60.1 (31.5)](https://drive.google.com/file/d/1ZY5P2Zgm-3RbDpbXM0kIBMPvspeNIbXz/view?usp=sharing) | +| osnet_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip` | `euclidean` | [94.2 (82.6)](https://drive.google.com/file/d/1vduhq5DpN2q1g4fYEZfPI17MJeh9qyrA/view?usp=sharing) | [87.0 (70.2)](https://drive.google.com/file/d/1QZO_4sNf4hdOKKKzKc-TZU9WW1v6zQbq/view?usp=sharing) | [74.9 (43.8)](https://drive.google.com/file/d/112EMUfBPYeYg70w-syK6V6Mx8-Qb9Q1M/view?usp=sharing) | +| osnet_x0_75 | 1.3 | 0.57 | softmax | (256, 128) | `random_flip` | `euclidean` | [93.7 (81.2)](https://drive.google.com/file/d/1ozRaDSQw_EQ8_93OUmjDbvLXw9TnfPer/view?usp=sharing) | [85.8 (69.8)](https://drive.google.com/file/d/1IE3KRaTPp4OUa6PGTFL_d5_KQSJbP0Or/view?usp=sharing) | [72.8 (41.4)](https://drive.google.com/file/d/1QEGO6WnJ-BmUzVPd3q9NoaO_GsPNlmWc/view?usp=sharing) | +| osnet_x0_5 | 0.6 | 0.27 | softmax | (256, 128) | `random_flip` | `euclidean` | [92.5 (79.8)](https://drive.google.com/file/d/1PLB9rgqrUM7blWrg4QlprCuPT7ILYGKT/view?usp=sharing) | [85.1 (67.4)](https://drive.google.com/file/d/1KoUVqmiST175hnkALg9XuTi1oYpqcyTu/view?usp=sharing) | [69.7 (37.5)](https://drive.google.com/file/d/1UT3AxIaDvS2PdxzZmbkLmjtiqq7AIKCv/view?usp=sharing) | +| osnet_x0_25 | 0.2 | 0.08 | softmax | (256, 128) | `random_flip` | `euclidean` | [91.2 (75.0)](https://drive.google.com/file/d/1z1UghYvOTtjx7kEoRfmqSMu-z62J6MAj/view?usp=sharing) | [82.0 (61.4)](https://drive.google.com/file/d/1eumrtiXT4NOspjyEV4j8cHmlOaaCGk5l/view?usp=sharing) | [61.4 (29.5)](https://drive.google.com/file/d/1sSwXSUlj4_tHZequ_iZ8w_Jh0VaRQMqF/view?usp=sharing) | + + +## Cross-domain ReID + +#### Market1501 -> DukeMTMC-reID + + +| Model | # Param (10^6) | GFLOPs | Loss | Input | Transforms | Distance | Rank-1 | Rank-5 | Rank-10 | mAP | Download | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +| osnet_ibn_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `euclidean` | 48.5 | 62.3 | 67.4 | 26.7 | [model](https://drive.google.com/file/d/1uWW7_z_IcUmRNPqQOrEBdsvic94fWH37/view?usp=sharing) | +| osnet_ain_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `cosine` | 52.4 | 66.1 | 71.2 | 30.5 | [model](https://drive.google.com/file/d/14bNFGm0FhwHEkEpYKqKiDWjLNhXywFAd/view?usp=sharing) | + + +#### DukeMTMC-reID -> Market1501 + + +| Model | # Param (10^6) | GFLOPs | Loss | Input | Transforms | Distance | Rank-1 | Rank-5 | Rank-10 | mAP | Download | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +| osnet_ibn_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `euclidean` | 57.7 | 73.7 | 80.0 | 26.1 | [model](https://drive.google.com/file/d/1CNxL1IP0BjcE1TSttiVOID1VNipAjiF3/view?usp=sharing) | +| osnet_ain_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `cosine` | 61.0 | 77.0 | 82.5 | 30.6 | [model](https://drive.google.com/file/d/1hypJvq8G04SOby6jvF337GEkg5K_bmCw/view?usp=sharing) | + + +#### MSMT17 (`combineall=True`) -> Market1501 & DukeMTMC-reID + + +| Model | # Param (10^6) | GFLOPs | Loss | Input | Transforms | Distance | msmt17 -> market1501 | msmt17 -> dukemtmcreid | Download | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +| resnet50 | 23.5 | 2.7 | softmax | (256, 128) | `random_flip`, `color_jitter` | `euclidean` | 46.3 (22.8) | 52.3 (32.1) | [model](https://drive.google.com/file/d/1yiBteqgIZoOeywE8AhGmEQl7FTVwrQmf/view?usp=sharing) | +| osnet_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `euclidean` | 66.6 (37.5) | 66.0 (45.3) | [model](https://drive.google.com/file/d/1IosIFlLiulGIjwW3H8uMRmx3MzPwf86x/view?usp=sharing) | +| osnet_x0_75 | 1.3 | 0.57 | softmax | (256, 128) | `random_flip`, `color_jitter` | `euclidean` | 63.6 (35.5) | 65.3 (44.5) | [model](https://drive.google.com/file/d/1fhjSS_7SUGCioIf2SWXaRGPqIY9j7-uw/view?usp=sharing) | +| osnet_x0_5 | 0.6 | 0.27 | softmax | (256, 128) | `random_flip`, `color_jitter` | `euclidean` | 64.3 (34.9) | 65.2 (43.3) | [model](https://drive.google.com/file/d/1DHgmb6XV4fwG3n-CnCM0zdL9nMsZ9_RF/view?usp=sharing) | +| osnet_x0_25 | 0.2 | 0.08 | softmax | (256, 128) | `random_flip`, `color_jitter` | `euclidean` | 59.9 (31.0) | 61.5 (39.6) | [model](https://drive.google.com/file/d/1Kkx2zW89jq_NETu4u42CFZTMVD5Hwm6e/view?usp=sharing) | +| osnet_ibn_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `euclidean` | 66.5 (37.2) | 67.4 (45.6) | [model](https://drive.google.com/file/d/1q3Sj2ii34NlfxA4LvmHdWO_75NDRmECJ/view?usp=sharing) | +| osnet_ain_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `cosine` | 70.1 (43.3) | 71.1 (52.7) | [model](https://drive.google.com/file/d/1SigwBE6mPdqiJMqhuIY4aqC7--5CsMal/view?usp=sharing) | + + +#### Multi-source domain generalization + +The models below are trained using multiple source datasets, as described in [Zhou et al. TPAMI'21](https://arxiv.org/abs/1910.06827). + +Regarding the abbreviations, MS is MSMT17; M is Market1501; D is DukeMTMC-reID; and C is CUHK03. + +All models were trained with [im_osnet_ain_x1_0_softmax_256x128_amsgrad_cosine.yaml](https://github.com/KaiyangZhou/deep-person-reid/blob/master/configs/im_osnet_ain_x1_0_softmax_256x128_amsgrad_cosine.yaml) and `max_epoch=50`. + +| Model | # Param (10^6) | GFLOPs | Loss | Input | Transforms | Distance | MS+D+C->M | MS+M+C->D | MS+D+M->C |D+M+C->MS | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +| osnet_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `cosine` | [72.5 (44.2)](https://drive.google.com/file/d/1tuYY1vQXReEd8N8_npUkc7npPDDmjNCV/view?usp=sharing) | [65.2 (47.0)](https://drive.google.com/file/d/1UxUI4NsE108UCvcy3O1Ufe73nIVPKCiu/view?usp=sharing) | [23.9 (23.3)](https://drive.google.com/file/d/1kAA6qHJvbaJtyh1b39ZyEqWROwUgWIhl/view?usp=sharing) | [33.2 (12.6)](https://drive.google.com/file/d/1wAHuYVTzj8suOwqCNcEmu6YdbVnHDvA2/view?usp=sharing) | +| osnet_ibn_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `cosine` | [73.0 (44.9)](https://drive.google.com/file/d/14sH6yZwuNHPTElVoEZ26zozOOZIej5Mf/view?usp=sharing) | [64.6 (45.7)](https://drive.google.com/file/d/1Sk-2SSwKAF8n1Z4p_Lm_pl0E6v2WlIBn/view?usp=sharing) | [25.7 (25.4)](https://drive.google.com/file/d/1actHP7byqWcK4eBE1ojnspSMdo7k2W4G/view?usp=sharing) | [39.8 (16.2)](https://drive.google.com/file/d/1BGOSdLdZgqHe2qFafatb-5sPY40JlYfp/view?usp=sharing) | +| osnet_ain_x1_0 | 2.2 | 0.98 | softmax | (256, 128) | `random_flip`, `color_jitter` | `cosine` | [73.3 (45.8)](https://drive.google.com/file/d/1nIrszJVYSHf3Ej8-j6DTFdWz8EnO42PB/view?usp=sharing) | [65.6 (47.2)](https://drive.google.com/file/d/1YjJ1ZprCmaKG6MH2P9nScB9FL_Utf9t1/view?usp=sharing) | [27.4 (27.1)](https://drive.google.com/file/d/1IxIg5P0cei3KPOJQ9ZRWDE_Mdrz01ha2/view?usp=sharing) | [40.2 (16.2)](https://drive.google.com/file/d/1KcoUKzLmsUoGHI7B6as_Z2fXL50gzexS/view?usp=sharing) | diff --git a/strong_sort/deep/reid/docs/Makefile b/strong_sort/deep/reid/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..298ea9e213e8c4c11f0431077510d4e325733c65 --- /dev/null +++ b/strong_sort/deep/reid/docs/Makefile @@ -0,0 +1,19 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/conf.py b/strong_sort/deep/reid/docs/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..4d27eedbac1d47dd6d1226b37e846a07364a0f1c --- /dev/null +++ b/strong_sort/deep/reid/docs/conf.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +# +# Configuration file for the Sphinx documentation builder. +# +# This file does only contain a selection of the most common options. For a +# full list see the documentation: +# http://www.sphinx-doc.org/en/master/config + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys + +sys.path.insert(0, os.path.abspath('..')) + +# -- Project information ----------------------------------------------------- + +project = u'torchreid' +copyright = u'2019, Kaiyang Zhou' +author = u'Kaiyang Zhou' + +version_file = '../torchreid/__init__.py' +with open(version_file, 'r') as f: + exec(compile(f.read(), version_file, 'exec')) +__version__ = locals()['__version__'] + +# The short X.Y version +version = __version__ +# The full version, including alpha/beta/rc tags +release = __version__ + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinxcontrib.napoleon', + 'sphinx.ext.viewcode', + 'sphinx.ext.githubpages', + 'sphinx_markdown_tables', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +source_suffix = ['.rst', '.md'] +# source_suffix = '.rst' +source_parsers = {'.md': 'recommonmark.parser.CommonMarkParser'} + +# The master toctree document. +master_doc = 'index' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = None + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. +# +# html_sidebars = {} + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'torchreiddoc' + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, 'torchreid.tex', u'torchreid Documentation', + u'Kaiyang Zhou', 'manual' + ), +] + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'torchreid', u'torchreid Documentation', [author], 1) +] + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, 'torchreid', u'torchreid Documentation', author, + 'torchreid', 'One line description of project.', 'Miscellaneous' + ), +] + +# -- Options for Epub output ------------------------------------------------- + +# Bibliographic Dublin Core info. +epub_title = project + +# The unique identifier of the text. This can be a ISBN number +# or the project homepage. +# +# epub_identifier = '' + +# A unique identification for the text. +# +# epub_uid = '' + +# A list of files that should not be packed into the epub file. +epub_exclude_files = ['search.html'] + +# -- Extension configuration ------------------------------------------------- diff --git a/strong_sort/deep/reid/docs/datasets.rst b/strong_sort/deep/reid/docs/datasets.rst new file mode 100644 index 0000000000000000000000000000000000000000..31f861133a4040e4228348e18e03cb0cd969a53a --- /dev/null +++ b/strong_sort/deep/reid/docs/datasets.rst @@ -0,0 +1,264 @@ +.. _datasets: + +Datasets +========= + +Here we provide a comprehensive guide on how to prepare the datasets. + +Suppose you want to store the reid data in a directory called "path/to/reid-data/", you need to specify the ``root`` as *root='path/to/reid-data/'* when initializing ``DataManager``. Below we use ``$REID`` to denote "path/to/reid-data". + +Please refer to :ref:`torchreid_data` for details regarding the arguments. + + +.. note:: + Dataset with a :math:`\dagger` symbol means that the process is automated, so you can directly call the dataset in ``DataManager`` (which automatically downloads the dataset and organizes the data structure). However, we also provide a way below to help the manual setup in case the automation fails. + + +.. note:: + The keys to use specific datasets are enclosed in the parantheses beside the datasets' names. + + +.. note:: + You are suggested to use the provided names for dataset folders such as "market1501" for Market1501 and "dukemtmcreid" for DukeMTMC-reID when doing the manual setup, otherwise you need to modify the source code accordingly (i.e. the ``dataset_dir`` attribute). + +.. note:: + Some download links provided by the original authors might not work. You can email `Kaiyang Zhou `_ to reqeust new links. Please do provide your full name, institution, and purpose of using the data in the email (best use your work email address). + +.. contents:: + :local: + + +Image Datasets +-------------- + +Market1501 :math:`^\dagger` (``market1501``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Create a directory named "market1501" under ``$REID``. +- Download the dataset to "market1501" from http://www.liangzheng.org/Project/project_reid.html and extract the files. +- The data structure should look like + +.. code-block:: none + + market1501/ + Market-1501-v15.09.15/ + query/ + bounding_box_train/ + bounding_box_test/ + +- To use the extra 500K distractors (i.e. Market1501 + 500K), go to the **Market-1501+500k Dataset** section at http://www.liangzheng.org/Project/project_reid.html, download the zip file "distractors_500k.zip" and extract it under "market1501/Market-1501-v15.09.15". The argument to use these 500K distrctors is ``market1501_500k`` in ``ImageDataManager``. + + +CUHK03 (``cuhk03``) +^^^^^^^^^^^^^^^^^^^^^ +- Create a folder named "cuhk03" under ``$REID``. +- Download the dataset to "cuhk03/" from http://www.ee.cuhk.edu.hk/~xgwang/CUHK_identification.html and extract "cuhk03_release.zip", resulting in "cuhk03/cuhk03_release/". +- Download the new split (767/700) from `person-re-ranking `_. What you need are "cuhk03_new_protocol_config_detected.mat" and "cuhk03_new_protocol_config_labeled.mat". Put these two mat files under "cuhk03/". +- The data structure should look like + +.. code-block:: none + + cuhk03/ + cuhk03_release/ + cuhk03_new_protocol_config_detected.mat + cuhk03_new_protocol_config_labeled.mat + + +- In the default mode, we load data using the new split (767/700). If you wanna use the original (20) splits (1367/100), please set ``cuhk03_classic_split`` to True in ``ImageDataManager``. As the CMC is computed differently from Market1501 for the 1367/100 split (see `here `_), you need to enable ``use_metric_cuhk03`` in ``ImageDataManager`` to activate the *single-gallery-shot* metric for fair comparison with some methods that adopt the old splits (*do not need to report mAP*). In addition, we support both *labeled* and *detected* modes. The default mode loads *detected* images. Enable ``cuhk03_labeled`` in ``ImageDataManager`` if you wanna train and test on *labeled* images. + +.. note:: + The code will extract images in "cuhk-03.mat" and save them under "cuhk03/images_detected" and "cuhk03/images_labeled". Also, four json files will be automatically generated, i.e. "splits_classic_detected.json", "splits_classic_labeled.json", "splits_new_detected.json" and "splits_new_labeled.json". If the parent path of ``$REID`` is changed, these json files should be manually deleted. The code can automatically generate new json files to match the new path. + + +DukeMTMC-reID :math:`^\dagger` (``dukemtmcreid``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Create a directory called "dukemtmc-reid" under ``$REID``. +- Download "DukeMTMC-reID" from http://vision.cs.duke.edu/DukeMTMC/ and extract it under "dukemtmc-reid". +- The data structure should look like + +.. code-block:: none + + dukemtmc-reid/ + DukeMTMC-reID/ + query/ + bounding_box_train/ + bounding_box_test/ + ... + +MSMT17 (``msmt17``) +^^^^^^^^^^^^^^^^^^^^^ +- Create a directory called "msmt17" under ``$REID``. +- Download the dataset from http://www.pkuvmc.com/publications/msmt17.html to "msmt17" and extract the files. +- The data structure should look like + +.. code-block:: none + + msmt17/ + MSMT17_V1/ # or MSMT17_V2 + train/ + test/ + list_train.txt + list_query.txt + list_gallery.txt + list_val.txt + +VIPeR :math:`^\dagger` (``viper``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- The download link is http://users.soe.ucsc.edu/~manduchi/VIPeR.v1.0.zip. +- Organize the dataset in a folder named "viper" as follows + +.. code-block:: none + + viper/ + VIPeR/ + cam_a/ + cam_b/ + +GRID :math:`^\dagger` (``grid``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- The download link is http://personal.ie.cuhk.edu.hk/~ccloy/files/datasets/underground_reid.zip. +- Organize the dataset in a folder named "grid" as follows + +.. code-block:: none + + grid/ + underground_reid/ + probe/ + gallery/ + ... + +CUHK01 (``cuhk01``) +^^^^^^^^^^^^^^^^^^^^^^^^ +- Create a folder named "cuhk01" under ``$REID``. +- Download "CUHK01.zip" from http://www.ee.cuhk.edu.hk/~xgwang/CUHK_identification.html and place it under "cuhk01/". +- The code can automatically extract the files, or you can do it yourself. +- The data structure should look like + +.. code-block:: none + + cuhk01/ + campus/ + +SenseReID (``sensereid``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Create "sensereid" under ``$REID``. +- Download the dataset from this `link `_ and extract it to "sensereid". +- Organize the data to be like + +.. code-block:: none + + sensereid/ + SenseReID/ + test_probe/ + test_gallery/ + +QMUL-iLIDS :math:`^\dagger` (``ilids``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Create a folder named "ilids" under ``$REID``. +- Download the dataset from http://www.eecs.qmul.ac.uk/~jason/data/i-LIDS_Pedestrian.tgz and organize it to look like + +.. code-block:: none + + ilids/ + i-LIDS_Pedestrian/ + Persons/ + +PRID (``prid``) +^^^^^^^^^^^^^^^^^^^ +- Create a directory named "prid2011" under ``$REID``. +- Download the dataset from https://www.tugraz.at/institute/icg/research/team-bischof/lrs/downloads/PRID11/ and extract it under "prid2011". +- The data structure should end up with + +.. code-block:: none + + prid2011/ + prid_2011/ + single_shot/ + multi_shot/ + +CUHK02 (``cuhk02``) +^^^^^^^^^^^^^^^^^^^^^ +- Create a folder named "cuhk02" under ``$REID``. +- Download the data from http://www.ee.cuhk.edu.hk/~xgwang/CUHK_identification.html and put it under "cuhk02/". +- Extract the file so the data structure looks like + +.. code-block:: none + + cuhk02/ + Dataset/ + P1/ + P2/ + P3/ + P4/ + P5/ + +CUHKSYSU (``cuhksysu``) +^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Create a folder named "cuhksysu" under ``$REID``. +- Download the data to "cuhksysu/" from this `google drive link `_. +- Extract the zip file under "cuhksysu/". +- The data structure should look like + +.. code-block:: none + + cuhksysu/ + cropped_images + + +Video Datasets +-------------- + +MARS (``mars``) +^^^^^^^^^^^^^^^^^ +- Create "mars/" under ``$REID``. +- Download the dataset from http://www.liangzheng.com.cn/Project/project_mars.html and place it in "mars/". +- Extract "bbox_train.zip" and "bbox_test.zip". +- Download the split metadata from https://github.com/liangzheng06/MARS-evaluation/tree/master/info and put "info/" in "mars/". +- The data structure should end up with + +.. code-block:: none + + mars/ + bbox_test/ + bbox_train/ + info/ + +iLIDS-VID :math:`^\dagger` (``ilidsvid``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Create "ilids-vid" under ``$REID``. +- Download the dataset from https://xiatian-zhu.github.io/downloads_qmul_iLIDS-VID_ReID_dataset.html to "ilids-vid". +- Organize the data structure to match + +.. code-block:: none + + ilids-vid/ + i-LIDS-VID/ + train-test people splits/ + +PRID2011 (``prid2011``) +^^^^^^^^^^^^^^^^^^^^^^^^^ +- Create a directory named "prid2011" under ``$REID``. +- Download the dataset from https://www.tugraz.at/institute/icg/research/team-bischof/lrs/downloads/PRID11/ and extract it under "prid2011". +- Download the split created by *iLIDS-VID* from `this google drive `_ and put it under "prid2011/". Following the standard protocol, only 178 persons whose sequences are more than a threshold are used. +- The data structure should end up with + +.. code-block:: none + + prid2011/ + splits_prid2011.json + prid_2011/ + single_shot/ + multi_shot/ + +DukeMTMC-VideoReID :math:`^\dagger` (``dukemtmcvidreid``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Create "dukemtmc-vidreid" under ``$REID``. +- Download "DukeMTMC-VideoReID" from http://vision.cs.duke.edu/DukeMTMC/ and unzip the file to "dukemtmc-vidreid/". +- The data structure should look like + +.. code-block:: none + + dukemtmc-vidreid/ + DukeMTMC-VideoReID/ + train/ + query/ + gallery/ diff --git a/strong_sort/deep/reid/docs/evaluation.rst b/strong_sort/deep/reid/docs/evaluation.rst new file mode 100644 index 0000000000000000000000000000000000000000..979ec7532c738e03495e9b96bf7de0c40020547e --- /dev/null +++ b/strong_sort/deep/reid/docs/evaluation.rst @@ -0,0 +1,21 @@ +Evaluation +========== + +Image ReID +----------- +- **Market1501**, **DukeMTMC-reID**, **CUHK03 (767/700 split)** and **MSMT17** have fixed split so keeping ``split_id=0`` is fine. +- **CUHK03 (classic split)** has 20 fixed splits, so do ``split_id=0~19``. +- **VIPeR** contains 632 identities each with 2 images under two camera views. Evaluation should be done for 10 random splits. Each split randomly divides 632 identities to 316 train ids (632 images) and the other 316 test ids (632 images). Note that, in each random split, there are two sub-splits, one using camera-A as query and camera-B as gallery while the other one using camera-B as query and camera-A as gallery. Thus, there are totally 20 splits generated with ``split_id`` starting from 0 to 19. Models can be trained on ``split_id=[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]`` (because ``split_id=0`` and ``split_id=1`` share the same train set, and so on and so forth.). At test time, models trained on ``split_id=0`` can be directly evaluated on ``split_id=1``, models trained on ``split_id=2`` can be directly evaluated on ``split_id=3``, and so on and so forth. +- **CUHK01** is similar to VIPeR in the split generation. +- **GRID** , **iLIDS** and **PRID** have 10 random splits, so evaluation should be done by varying ``split_id`` from 0 to 9. +- **SenseReID** has no training images and is used for evaluation only. + + +.. note:: + The ``split_id`` argument is defined in ``ImageDataManager`` and ``VideoDataManager``. Please refer to :ref:`torchreid_data`. + + +Video ReID +----------- +- **MARS** and **DukeMTMC-VideoReID** have fixed single split so using ``split_id=0`` is ok. +- **iLIDS-VID** and **PRID2011** have 10 predefined splits so evaluation should be done by varying ``split_id`` from 0 to 9. \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/figures/actmap.jpg b/strong_sort/deep/reid/docs/figures/actmap.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1a0522b7e026f5c96ec5c2af21ae275a74dc5ac8 Binary files /dev/null and b/strong_sort/deep/reid/docs/figures/actmap.jpg differ diff --git a/strong_sort/deep/reid/docs/figures/ranking_results.jpg b/strong_sort/deep/reid/docs/figures/ranking_results.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a759dfc17cac44734fe6a3ae03db58ea96485aef Binary files /dev/null and b/strong_sort/deep/reid/docs/figures/ranking_results.jpg differ diff --git a/strong_sort/deep/reid/docs/index.rst b/strong_sort/deep/reid/docs/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..c437deaff36e09a775ec783e0a7f68c35379aaf8 --- /dev/null +++ b/strong_sort/deep/reid/docs/index.rst @@ -0,0 +1,35 @@ +.. include:: ../README.rst + + +.. toctree:: + :hidden: + + user_guide + datasets + evaluation + +.. toctree:: + :caption: Package Reference + :hidden: + + pkg/data + pkg/engine + pkg/losses + pkg/metrics + pkg/models + pkg/optim + pkg/utils + +.. toctree:: + :caption: Resources + :hidden: + + AWESOME_REID.md + MODEL_ZOO.md + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/pkg/data.rst b/strong_sort/deep/reid/docs/pkg/data.rst new file mode 100644 index 0000000000000000000000000000000000000000..3dc47d6ae9790042d0902b6cf1612112539886ce --- /dev/null +++ b/strong_sort/deep/reid/docs/pkg/data.rst @@ -0,0 +1,86 @@ +.. _torchreid_data: + +torchreid.data +============== + + +Data Manager +--------------------------- + +.. automodule:: torchreid.data.datamanager + :members: + + +Sampler +----------------------- + +.. automodule:: torchreid.data.sampler + :members: + + +Transforms +--------------------------- + +.. automodule:: torchreid.data.transforms + :members: + + +Dataset +--------------------------- + +.. automodule:: torchreid.data.datasets.dataset + :members: + + +.. automodule:: torchreid.data.datasets.__init__ + :members: + + +Image Datasets +------------------------------ + +.. automodule:: torchreid.data.datasets.image.market1501 + :members: + +.. automodule:: torchreid.data.datasets.image.cuhk03 + :members: + +.. automodule:: torchreid.data.datasets.image.dukemtmcreid + :members: + +.. automodule:: torchreid.data.datasets.image.msmt17 + :members: + +.. automodule:: torchreid.data.datasets.image.viper + :members: + +.. automodule:: torchreid.data.datasets.image.grid + :members: + +.. automodule:: torchreid.data.datasets.image.cuhk01 + :members: + +.. automodule:: torchreid.data.datasets.image.ilids + :members: + +.. automodule:: torchreid.data.datasets.image.sensereid + :members: + +.. automodule:: torchreid.data.datasets.image.prid + :members: + + +Video Datasets +------------------------------ + +.. automodule:: torchreid.data.datasets.video.mars + :members: + +.. automodule:: torchreid.data.datasets.video.ilidsvid + :members: + +.. automodule:: torchreid.data.datasets.video.prid2011 + :members: + +.. automodule:: torchreid.data.datasets.video.dukemtmcvidreid + :members: \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/pkg/engine.rst b/strong_sort/deep/reid/docs/pkg/engine.rst new file mode 100644 index 0000000000000000000000000000000000000000..ae2bc6859c090af48304dbb3d383efebe73ea9b2 --- /dev/null +++ b/strong_sort/deep/reid/docs/pkg/engine.rst @@ -0,0 +1,31 @@ +.. _torchreid_engine: + +torchreid.engine +================== + + +Base Engine +------------ + +.. autoclass:: torchreid.engine.engine.Engine + :members: + + +Image Engines +------------- + +.. autoclass:: torchreid.engine.image.softmax.ImageSoftmaxEngine + :members: + + +.. autoclass:: torchreid.engine.image.triplet.ImageTripletEngine + :members: + + +Video Engines +------------- + +.. autoclass:: torchreid.engine.video.softmax.VideoSoftmaxEngine + + +.. autoclass:: torchreid.engine.video.triplet.VideoTripletEngine \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/pkg/losses.rst b/strong_sort/deep/reid/docs/pkg/losses.rst new file mode 100644 index 0000000000000000000000000000000000000000..33fd9bc46fdbb141aee78cce63618dd99fc51f9d --- /dev/null +++ b/strong_sort/deep/reid/docs/pkg/losses.rst @@ -0,0 +1,18 @@ +.. _torchreid_losses: + +torchreid.losses +================= + + +Softmax +-------- + +.. automodule:: torchreid.losses.cross_entropy_loss + :members: + + +Triplet +------- + +.. automodule:: torchreid.losses.hard_mine_triplet_loss + :members: \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/pkg/metrics.rst b/strong_sort/deep/reid/docs/pkg/metrics.rst new file mode 100644 index 0000000000000000000000000000000000000000..5a52a90128a944061a609f982e21b1a9e53204e5 --- /dev/null +++ b/strong_sort/deep/reid/docs/pkg/metrics.rst @@ -0,0 +1,25 @@ +.. _torchreid_metrics: + +torchreid.metrics +================= + + +Distance +--------- + +.. automodule:: torchreid.metrics.distance + :members: + + +Accuracy +-------- + +.. automodule:: torchreid.metrics.accuracy + :members: + + +Rank +----- + +.. automodule:: torchreid.metrics.rank + :members: evaluate_rank \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/pkg/models.rst b/strong_sort/deep/reid/docs/pkg/models.rst new file mode 100644 index 0000000000000000000000000000000000000000..685bc73e81521627b91c9f3098e26c603c3e7b41 --- /dev/null +++ b/strong_sort/deep/reid/docs/pkg/models.rst @@ -0,0 +1,43 @@ +.. _torchreid_models: + +torchreid.models +================= + +Interface +--------- + +.. automodule:: torchreid.models.__init__ + :members: + + +ImageNet Classification Models +------------------------------- + +.. autoclass:: torchreid.models.resnet.ResNet +.. autoclass:: torchreid.models.senet.SENet +.. autoclass:: torchreid.models.densenet.DenseNet +.. autoclass:: torchreid.models.inceptionresnetv2.InceptionResNetV2 +.. autoclass:: torchreid.models.inceptionv4.InceptionV4 +.. autoclass:: torchreid.models.xception.Xception + + +Lightweight Models +------------------ + +.. autoclass:: torchreid.models.nasnet.NASNetAMobile +.. autoclass:: torchreid.models.mobilenetv2.MobileNetV2 +.. autoclass:: torchreid.models.shufflenet.ShuffleNet +.. autoclass:: torchreid.models.squeezenet.SqueezeNet +.. autoclass:: torchreid.models.shufflenetv2.ShuffleNetV2 + + +ReID-specific Models +-------------------- + +.. autoclass:: torchreid.models.mudeep.MuDeep +.. autoclass:: torchreid.models.resnetmid.ResNetMid +.. autoclass:: torchreid.models.hacnn.HACNN +.. autoclass:: torchreid.models.pcb.PCB +.. autoclass:: torchreid.models.mlfn.MLFN +.. autoclass:: torchreid.models.osnet.OSNet +.. autoclass:: torchreid.models.osnet_ain.OSNet \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/pkg/optim.rst b/strong_sort/deep/reid/docs/pkg/optim.rst new file mode 100644 index 0000000000000000000000000000000000000000..560162340938ab8ad4221e547154c3d923a59f8c --- /dev/null +++ b/strong_sort/deep/reid/docs/pkg/optim.rst @@ -0,0 +1,18 @@ +.. _torchreid_optim: + +torchreid.optim +================= + + +Optimizer +---------- + +.. automodule:: torchreid.optim.optimizer + :members: build_optimizer + + +LR Scheduler +------------- + +.. automodule:: torchreid.optim.lr_scheduler + :members: build_lr_scheduler \ No newline at end of file diff --git a/strong_sort/deep/reid/docs/pkg/utils.rst b/strong_sort/deep/reid/docs/pkg/utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..1545bc29c88f98cd0a7750e42776a3fd682bd93d --- /dev/null +++ b/strong_sort/deep/reid/docs/pkg/utils.rst @@ -0,0 +1,41 @@ +.. _torchreid_utils: + +torchreid.utils +================= + +Average Meter +-------------- + +.. automodule:: torchreid.utils.avgmeter + :members: + + +Loggers +------- + +.. automodule:: torchreid.utils.loggers + :members: + + +Generic Tools +--------------- +.. automodule:: torchreid.utils.tools + :members: + + +ReID Tools +---------- + +.. automodule:: torchreid.utils.reidtools + :members: + + +Torch Tools +------------ + +.. automodule:: torchreid.utils.torchtools + :members: + + +.. automodule:: torchreid.utils.model_complexity + :members: diff --git a/strong_sort/deep/reid/docs/user_guide.rst b/strong_sort/deep/reid/docs/user_guide.rst new file mode 100644 index 0000000000000000000000000000000000000000..5415109fab92a170e87e5af1917f35d3ece76026 --- /dev/null +++ b/strong_sort/deep/reid/docs/user_guide.rst @@ -0,0 +1,351 @@ +How-to +============ + +.. contents:: + :local: + + +Prepare datasets +----------------- +See :ref:`datasets`. + + +Find model keys +----------------- +Keys are listed under the *Public keys* section within each model class in :ref:`torchreid_models`. + + +Show available models +---------------------- + +.. code-block:: python + + import torchreid + torchreid.models.show_avai_models() + + +Change the training sampler +----------------------------- +The default ``train_sampler`` is "RandomSampler". You can give the specific sampler name as input to ``train_sampler``, e.g. ``train_sampler='RandomIdentitySampler'`` for triplet loss. + + +Choose an optimizer/lr_scheduler +---------------------------------- +Please refer to the source code of ``build_optimizer``/``build_lr_scheduler`` in :ref:`torchreid_optim` for details. + + +Resume training +---------------- +Suppose the checkpoint is saved in "log/resnet50/model.pth.tar-30", you can do + +.. code-block:: python + + start_epoch = torchreid.utils.resume_from_checkpoint( + 'log/resnet50/model.pth.tar-30', + model, + optimizer + ) + + engine.run( + save_dir='log/resnet50', + max_epoch=60, + start_epoch=start_epoch + ) + + +Compute model complexity +-------------------------- +We provide a tool in ``torchreid.utils.model_complexity.py`` to automatically compute the model complexity, i.e. number of parameters and FLOPs. + +.. code-block:: python + + from torchreid import models, utils + + model = models.build_model(name='resnet50', num_classes=1000) + num_params, flops = utils.compute_model_complexity(model, (1, 3, 256, 128)) + + # show detailed complexity for each module + utils.compute_model_complexity(model, (1, 3, 256, 128), verbose=True) + + # count flops for all layers including ReLU and BatchNorm + utils.compute_model_complexity(model, (1, 3, 256, 128), verbose=True, only_conv_linear=False) + +Note that (1) this function only provides an estimate of the theoretical time complexity rather than the actual running time which depends on implementations and hardware; (2) the FLOPs is only counted for layers that are used at test time. This means that redundant layers such as person ID classification layer will be ignored. The inference graph depends on how you define the computations in ``forward()``. + + +Combine multiple datasets +--------------------------- +Easy. Just give whatever datasets (keys) you want to the ``sources`` argument when instantiating a data manager. For example, + +.. code-block:: python + + datamanager = torchreid.data.ImageDataManager( + root='reid-data', + sources=['market1501', 'dukemtmcreid', 'cuhk03', 'msmt17'], + height=256, + width=128, + batch_size=32 + ) + +In this example, the target datasets are Market1501, DukeMTMC-reID, CUHK03 and MSMT17 as the ``targets`` argument is not specified. Please refer to ``Engine.test()`` in :ref:`torchreid_engine` for details regarding how evaluation is performed. + + +Do cross-dataset evaluation +----------------------------- +Easy. Just give whatever datasets (keys) you want to the argument ``targets``, like + +.. code-block:: python + + datamanager = torchreid.data.ImageDataManager( + root='reid-data', + sources='market1501', + targets='dukemtmcreid', # or targets='cuhk03' or targets=['dukemtmcreid', 'cuhk03'] + height=256, + width=128, + batch_size=32 + ) + + +Combine train, query and gallery +--------------------------------- +This can be easily done by setting ``combineall=True`` when instantiating a data manager. Below is an example of using Market1501, + +.. code-block:: python + + datamanager = torchreid.data.ImageDataManager( + root='reid-data', + sources='market1501', + height=256, + width=128, + batch_size=32, + market1501_500k=False, + combineall=True # it's me, here + ) + +More specifically, with ``combineall=False``, you will get + +.. code-block:: none + + => Loaded Market1501 + ---------------------------------------- + subset | # ids | # images | # cameras + ---------------------------------------- + train | 751 | 12936 | 6 + query | 750 | 3368 | 6 + gallery | 751 | 15913 | 6 + --------------------------------------- + +with ``combineall=True``, you will get + +.. code-block:: none + + => Loaded Market1501 + ---------------------------------------- + subset | # ids | # images | # cameras + ---------------------------------------- + train | 1501 | 29419 | 6 + query | 750 | 3368 | 6 + gallery | 751 | 15913 | 6 + --------------------------------------- + + +Optimize layers with different learning rates +----------------------------------------------- +A common practice for fine-tuning pretrained models is to use a smaller learning rate for base layers and a large learning rate for randomly initialized layers (referred to as ``new_layers``). ``torchreid.optim.optimizer`` has implemented such feature. What you need to do is to set ``staged_lr=True`` and give the names of ``new_layers`` such as "classifier". + +Below is an example of setting different learning rates for base layers and new layers in ResNet50, + +.. code-block:: python + + # New layer "classifier" has a learning rate of 0.01 + # The base layers have a learning rate of 0.001 + optimizer = torchreid.optim.build_optimizer( + model, + optim='sgd', + lr=0.01, + staged_lr=True, + new_layers='classifier', + base_lr_mult=0.1 + ) + +Please refer to :ref:`torchreid_optim` for more details. + + +Do two-stepped transfer learning +------------------------------------- +To prevent the pretrained layers from being damaged by harmful gradients back-propagated from randomly initialized layers, one can adopt the *two-stepped transfer learning strategy* presented in `Deep Transfer Learning for Person Re-identification `_. The basic idea is to pretrain the randomly initialized layers for few epochs while keeping the base layers frozen before training all layers end-to-end. + +This has been implemented in ``Engine.train()`` (see :ref:`torchreid_engine`). The arguments related to this feature are ``fixbase_epoch`` and ``open_layers``. Intuitively, ``fixbase_epoch`` denotes the number of epochs to keep the base layers frozen; ``open_layers`` means which layer is open for training. + +For example, say you want to pretrain the classification layer named "classifier" in ResNet50 for 5 epochs before training all layers, you can do + +.. code-block:: python + + engine.run( + save_dir='log/resnet50', + max_epoch=60, + eval_freq=10, + print_freq=10, + test_only=False, + fixbase_epoch=5, + open_layers='classifier' + ) + # or open_layers=['fc', 'classifier'] if there is another fc layer that + # is randomly initialized, like resnet50_fc512 + +Note that ``fixbase_epoch`` is counted into ``max_epoch``. In the above example, the base network will be fixed for 5 epochs and then open for training for 55 epochs. Thus, if you want to freeze some layers throughout the training, what you can do is to set ``fixbase_epoch`` equal to ``max_epoch`` and put the layer names in ``open_layers`` which you want to train. + + +Test a trained model +---------------------- +You can load a trained model using :code:`torchreid.utils.load_pretrained_weights(model, weight_path)` and set ``test_only=True`` in ``engine.run()``. + + +Fine-tune a model pre-trained on reid datasets +----------------------------------------------- +Use :code:`torchreid.utils.load_pretrained_weights(model, weight_path)` to load the pre-trained weights and then fine-tune on the dataset you want. + + +Visualize learning curves with tensorboard +-------------------------------------------- +The ``SummaryWriter()`` for tensorboard will be automatically initialized in ``engine.run()`` when you are training your model. Therefore, you do not need to do extra jobs. After the training is done, the ``*tf.events*`` file will be saved in ``save_dir``. Then, you just call ``tensorboard --logdir=your_save_dir`` in your terminal and visit ``http://localhost:6006/`` in a web browser. See `pytorch tensorboard `_ for further information. + + +Visualize ranking results +--------------------------- +This can be achieved by setting ``visrank`` to true in ``engine.run()``. ``visrank_topk`` determines the top-k images to be visualized (Default is ``visrank_topk=10``). Note that ``visrank`` can only be used in test mode, i.e. ``test_only=True`` in ``engine.run()``. The output will be saved under ``save_dir/visrank_DATASETNAME`` where each plot contains the top-k similar gallery images given a query. An example is shown below where red and green denote incorrect and correct matches respectively. + +.. image:: figures/ranking_results.jpg + :width: 800px + :align: center + + +Visualize activation maps +-------------------------- +To understand where the CNN focuses on to extract features for ReID, you can visualize the activation maps as in `OSNet `_. This is implemented in ``tools/visualize_actmap.py`` (check the code for more details). An example running command is + +.. code-block:: shell + + python tools/visualize_actmap.py \ + --root $DATA/reid \ + -d market1501 \ + -m osnet_x1_0 \ + --weights PATH_TO_PRETRAINED_WEIGHTS \ + --save-dir log/visactmap_osnet_x1_0_market1501 + +The output will look like (from left to right: image, activation map, overlapped image) + +.. image:: figures/actmap.jpg + :width: 300px + :align: center + + +.. note:: + In order to visualize activation maps, the CNN needs to output the last convolutional feature maps at eval mode. See ``torchreid/models/osnet.py`` for example. + + +Use your own dataset +---------------------- +1. Write your own dataset class. Below is a template for image dataset. However, it can also be applied to a video dataset class, for which you simply change ``ImageDataset`` to ``VideoDataset``. + +.. code-block:: python + + from __future__ import absolute_import + from __future__ import print_function + from __future__ import division + + import sys + import os + import os.path as osp + + from torchreid.data import ImageDataset + + + class NewDataset(ImageDataset): + dataset_dir = 'new_dataset' + + def __init__(self, root='', **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + + # All you need to do here is to generate three lists, + # which are train, query and gallery. + # Each list contains tuples of (img_path, pid, camid), + # where + # - img_path (str): absolute path to an image. + # - pid (int): person ID, e.g. 0, 1. + # - camid (int): camera ID, e.g. 0, 1. + # Note that + # - pid and camid should be 0-based. + # - query and gallery should share the same pid scope (e.g. + # pid=0 in query refers to the same person as pid=0 in gallery). + # - train, query and gallery share the same camid scope (e.g. + # camid=0 in train refers to the same camera as camid=0 + # in query/gallery). + train = ... + query = ... + gallery = ... + + super(NewDataset, self).__init__(train, query, gallery, **kwargs) + + +2. Register your dataset. + +.. code-block:: python + + import torchreid + torchreid.data.register_image_dataset('new_dataset', NewDataset) + + +3. Initialize a data manager with your dataset. + +.. code-block:: python + + # use your own dataset only + datamanager = torchreid.data.ImageDataManager( + root='reid-data', + sources='new_dataset' + ) + # combine with other datasets + datamanager = torchreid.data.ImageDataManager( + root='reid-data', + sources=['new_dataset', 'dukemtmcreid'] + ) + # cross-dataset evaluation + datamanager = torchreid.data.ImageDataManager( + root='reid-data', + sources=['new_dataset', 'dukemtmcreid'], + targets='market1501' # or targets=['market1501', 'cuhk03'] + ) + + + +Design your own Engine +------------------------ +A new Engine should be designed if you have your own loss function. The base Engine class ``torchreid.engine.Engine`` has implemented some generic methods which you can inherit to avoid re-writing. Please refer to the source code for more details. You are suggested to see how ``ImageSoftmaxEngine`` and ``ImageTripletEngine`` are constructed (also ``VideoSoftmaxEngine`` and ``VideoTripletEngine``). All you need to implement might be just a ``forward_backward()`` function. + + +Use Torchreid as a feature extractor in your projects +------------------------------------------------------- +We have provided a simple API for feature extraction, which accepts input of various types such as a list of image paths or numpy arrays. More details can be found in the code at ``torchreid/utils/feature_extractor.py``. Here we show a simple example of how to extract features given a list of image paths. + +.. code-block:: python + + from torchreid.utils import FeatureExtractor + + extractor = FeatureExtractor( + model_name='osnet_x1_0', + model_path='a/b/c/model.pth.tar', + device='cuda' + ) + + image_list = [ + 'a/b/c/image001.jpg', + 'a/b/c/image002.jpg', + 'a/b/c/image003.jpg', + 'a/b/c/image004.jpg', + 'a/b/c/image005.jpg' + ] + + features = extractor(image_list) + print(features.shape) # output (5, 512) diff --git a/strong_sort/deep/reid/linter.sh b/strong_sort/deep/reid/linter.sh new file mode 100644 index 0000000000000000000000000000000000000000..9db34f9f86e44fad1263758a6ccaf09eb816c11a --- /dev/null +++ b/strong_sort/deep/reid/linter.sh @@ -0,0 +1,11 @@ +echo "Running isort" +isort -y -sp . +echo "Done" + +echo "Running yapf" +yapf -i -r -vv -e build . +echo "Done" + +echo "Running flake8" +flake8 . +echo "Done" \ No newline at end of file diff --git a/strong_sort/deep/reid/projects/DML/README.md b/strong_sort/deep/reid/projects/DML/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e81be7fe73b201236534d2785c6b2de7a231e017 --- /dev/null +++ b/strong_sort/deep/reid/projects/DML/README.md @@ -0,0 +1,16 @@ +# Deep mutual learning + +This repo implements [Deep Mutual Learning (CVPR'18)](https://zpascal.net/cvpr2018/Zhang_Deep_Mutual_Learning_CVPR_2018_paper.pdf) (DML) for person re-id. + +We used this code in our [OSNet](https://arxiv.org/pdf/1905.00953.pdf) paper (see Supp. B). The training command to reproduce the result of "triplet + DML" (Table 12f in the paper) is +```bash +python main.py \ +--config-file im_osnet_x1_0_dml_256x128_amsgrad_cosine.yaml \ +--root $DATA +``` + +`$DATA` corresponds to the path to your dataset folder. + +Change `model.deploy` to `both` if you wanna enable model ensembling. + +If you have any questions, please raise an issue in the Issues area. \ No newline at end of file diff --git a/strong_sort/deep/reid/projects/DML/default_config.py b/strong_sort/deep/reid/projects/DML/default_config.py new file mode 100644 index 0000000000000000000000000000000000000000..9b15e35f5e33028eac0cca3c92dee3c7a97130b7 --- /dev/null +++ b/strong_sort/deep/reid/projects/DML/default_config.py @@ -0,0 +1,207 @@ +from yacs.config import CfgNode as CN + + +def get_default_config(): + cfg = CN() + + # model + cfg.model = CN() + cfg.model.name = 'resnet50' + cfg.model.pretrained = True # automatically load pretrained model weights if available + cfg.model.load_weights1 = '' # path to model-1 weights + cfg.model.load_weights2 = '' # path to model-2 weights + cfg.model.resume1 = '' # path to checkpoint for resume training + cfg.model.resume2 = '' # path to checkpoint for resume training + cfg.model.deploy = 'model1' # model1, model2 or both + + # data + cfg.data = CN() + cfg.data.type = 'image' + cfg.data.root = 'reid-data' + cfg.data.sources = ['market1501'] + cfg.data.targets = ['market1501'] + cfg.data.workers = 4 # number of data loading workers + cfg.data.split_id = 0 # split index + cfg.data.height = 256 # image height + cfg.data.width = 128 # image width + cfg.data.combineall = False # combine train, query and gallery for training + cfg.data.transforms = ['random_flip'] # data augmentation + cfg.data.norm_mean = [0.485, 0.456, 0.406] # default is imagenet mean + cfg.data.norm_std = [0.229, 0.224, 0.225] # default is imagenet std + cfg.data.save_dir = 'log' # path to save log + cfg.data.load_train_targets = False + + # specific datasets + cfg.market1501 = CN() + cfg.market1501.use_500k_distractors = False # add 500k distractors to the gallery set for market1501 + cfg.cuhk03 = CN() + cfg.cuhk03.labeled_images = False # use labeled images, if False, use detected images + cfg.cuhk03.classic_split = False # use classic split by Li et al. CVPR14 + cfg.cuhk03.use_metric_cuhk03 = False # use cuhk03's metric for evaluation + + # sampler + cfg.sampler = CN() + cfg.sampler.train_sampler = 'RandomSampler' + cfg.sampler.num_instances = 4 # number of instances per identity for RandomIdentitySampler + + # video reid setting + cfg.video = CN() + cfg.video.seq_len = 15 # number of images to sample in a tracklet + cfg.video.sample_method = 'evenly' # how to sample images from a tracklet + cfg.video.pooling_method = 'avg' # how to pool features over a tracklet + + # train + cfg.train = CN() + cfg.train.optim = 'adam' + cfg.train.lr = 0.0003 + cfg.train.weight_decay = 5e-4 + cfg.train.max_epoch = 60 + cfg.train.start_epoch = 0 + cfg.train.batch_size = 32 + cfg.train.fixbase_epoch = 0 # number of epochs to fix base layers + cfg.train.open_layers = [ + 'classifier' + ] # layers for training while keeping others frozen + cfg.train.staged_lr = False # set different lr to different layers + cfg.train.new_layers = ['classifier'] # newly added layers with default lr + cfg.train.base_lr_mult = 0.1 # learning rate multiplier for base layers + cfg.train.lr_scheduler = 'single_step' + cfg.train.stepsize = [20] # stepsize to decay learning rate + cfg.train.gamma = 0.1 # learning rate decay multiplier + cfg.train.print_freq = 20 # print frequency + cfg.train.seed = 1 # random seed + + # optimizer + cfg.sgd = CN() + cfg.sgd.momentum = 0.9 # momentum factor for sgd and rmsprop + cfg.sgd.dampening = 0. # dampening for momentum + cfg.sgd.nesterov = False # Nesterov momentum + cfg.rmsprop = CN() + cfg.rmsprop.alpha = 0.99 # smoothing constant + cfg.adam = CN() + cfg.adam.beta1 = 0.9 # exponential decay rate for first moment + cfg.adam.beta2 = 0.999 # exponential decay rate for second moment + + # loss + cfg.loss = CN() + cfg.loss.name = 'triplet' + cfg.loss.softmax = CN() + cfg.loss.softmax.label_smooth = True # use label smoothing regularizer + cfg.loss.triplet = CN() + cfg.loss.triplet.margin = 0.3 # distance margin + cfg.loss.triplet.weight_t = 1. # weight to balance hard triplet loss + cfg.loss.triplet.weight_x = 0. # weight to balance cross entropy loss + cfg.loss.dml = CN() + cfg.loss.dml.weight_ml = 1. # weight for mutual learning loss + + # test + cfg.test = CN() + cfg.test.batch_size = 100 + cfg.test.dist_metric = 'euclidean' # distance metric, ['euclidean', 'cosine'] + cfg.test.normalize_feature = False # normalize feature vectors before computing distance + cfg.test.ranks = [1, 5, 10, 20] # cmc ranks + cfg.test.evaluate = False # test only + cfg.test.eval_freq = -1 # evaluation frequency (-1 means to only test after training) + cfg.test.start_eval = 0 # start to evaluate after a specific epoch + cfg.test.rerank = False # use person re-ranking + cfg.test.visrank = False # visualize ranked results (only available when cfg.test.evaluate=True) + cfg.test.visrank_topk = 10 # top-k ranks to visualize + + return cfg + + +def imagedata_kwargs(cfg): + return { + 'root': cfg.data.root, + 'sources': cfg.data.sources, + 'targets': cfg.data.targets, + 'height': cfg.data.height, + 'width': cfg.data.width, + 'transforms': cfg.data.transforms, + 'norm_mean': cfg.data.norm_mean, + 'norm_std': cfg.data.norm_std, + 'use_gpu': cfg.use_gpu, + 'split_id': cfg.data.split_id, + 'combineall': cfg.data.combineall, + 'load_train_targets': cfg.data.load_train_targets, + 'batch_size_train': cfg.train.batch_size, + 'batch_size_test': cfg.test.batch_size, + 'workers': cfg.data.workers, + 'num_instances': cfg.sampler.num_instances, + 'train_sampler': cfg.sampler.train_sampler, + # image + 'cuhk03_labeled': cfg.cuhk03.labeled_images, + 'cuhk03_classic_split': cfg.cuhk03.classic_split, + 'market1501_500k': cfg.market1501.use_500k_distractors, + } + + +def videodata_kwargs(cfg): + return { + 'root': cfg.data.root, + 'sources': cfg.data.sources, + 'targets': cfg.data.targets, + 'height': cfg.data.height, + 'width': cfg.data.width, + 'transforms': cfg.data.transforms, + 'norm_mean': cfg.data.norm_mean, + 'norm_std': cfg.data.norm_std, + 'use_gpu': cfg.use_gpu, + 'split_id': cfg.data.split_id, + 'combineall': cfg.data.combineall, + 'batch_size_train': cfg.train.batch_size, + 'batch_size_test': cfg.test.batch_size, + 'workers': cfg.data.workers, + 'num_instances': cfg.sampler.num_instances, + 'train_sampler': cfg.sampler.train_sampler, + # video + 'seq_len': cfg.video.seq_len, + 'sample_method': cfg.video.sample_method + } + + +def optimizer_kwargs(cfg): + return { + 'optim': cfg.train.optim, + 'lr': cfg.train.lr, + 'weight_decay': cfg.train.weight_decay, + 'momentum': cfg.sgd.momentum, + 'sgd_dampening': cfg.sgd.dampening, + 'sgd_nesterov': cfg.sgd.nesterov, + 'rmsprop_alpha': cfg.rmsprop.alpha, + 'adam_beta1': cfg.adam.beta1, + 'adam_beta2': cfg.adam.beta2, + 'staged_lr': cfg.train.staged_lr, + 'new_layers': cfg.train.new_layers, + 'base_lr_mult': cfg.train.base_lr_mult + } + + +def lr_scheduler_kwargs(cfg): + return { + 'lr_scheduler': cfg.train.lr_scheduler, + 'stepsize': cfg.train.stepsize, + 'gamma': cfg.train.gamma, + 'max_epoch': cfg.train.max_epoch + } + + +def engine_run_kwargs(cfg): + return { + 'save_dir': cfg.data.save_dir, + 'max_epoch': cfg.train.max_epoch, + 'start_epoch': cfg.train.start_epoch, + 'fixbase_epoch': cfg.train.fixbase_epoch, + 'open_layers': cfg.train.open_layers, + 'start_eval': cfg.test.start_eval, + 'eval_freq': cfg.test.eval_freq, + 'test_only': cfg.test.evaluate, + 'print_freq': cfg.train.print_freq, + 'dist_metric': cfg.test.dist_metric, + 'normalize_feature': cfg.test.normalize_feature, + 'visrank': cfg.test.visrank, + 'visrank_topk': cfg.test.visrank_topk, + 'use_metric_cuhk03': cfg.cuhk03.use_metric_cuhk03, + 'ranks': cfg.test.ranks, + 'rerank': cfg.test.rerank + } diff --git a/strong_sort/deep/reid/projects/DML/dml.py b/strong_sort/deep/reid/projects/DML/dml.py new file mode 100644 index 0000000000000000000000000000000000000000..546e573d6ba5d3d41bebbb51062bf9ad451d7344 --- /dev/null +++ b/strong_sort/deep/reid/projects/DML/dml.py @@ -0,0 +1,149 @@ +from __future__ import division, print_function, absolute_import +import torch +from torch.nn import functional as F + +from torchreid.utils import open_all_layers, open_specified_layers +from torchreid.engine import Engine +from torchreid.losses import TripletLoss, CrossEntropyLoss + + +class ImageDMLEngine(Engine): + + def __init__( + self, + datamanager, + model1, + optimizer1, + scheduler1, + model2, + optimizer2, + scheduler2, + margin=0.3, + weight_t=0.5, + weight_x=1., + weight_ml=1., + use_gpu=True, + label_smooth=True, + deploy='model1' + ): + super(ImageDMLEngine, self).__init__(datamanager, use_gpu) + + self.model1 = model1 + self.optimizer1 = optimizer1 + self.scheduler1 = scheduler1 + self.register_model('model1', model1, optimizer1, scheduler1) + + self.model2 = model2 + self.optimizer2 = optimizer2 + self.scheduler2 = scheduler2 + self.register_model('model2', model2, optimizer2, scheduler2) + + self.weight_t = weight_t + self.weight_x = weight_x + self.weight_ml = weight_ml + + assert deploy in ['model1', 'model2', 'both'] + self.deploy = deploy + + self.criterion_t = TripletLoss(margin=margin) + self.criterion_x = CrossEntropyLoss( + num_classes=self.datamanager.num_train_pids, + use_gpu=self.use_gpu, + label_smooth=label_smooth + ) + + def forward_backward(self, data): + imgs, pids = self.parse_data_for_train(data) + + if self.use_gpu: + imgs = imgs.cuda() + pids = pids.cuda() + + outputs1, features1 = self.model1(imgs) + loss1_x = self.compute_loss(self.criterion_x, outputs1, pids) + loss1_t = self.compute_loss(self.criterion_t, features1, pids) + + outputs2, features2 = self.model2(imgs) + loss2_x = self.compute_loss(self.criterion_x, outputs2, pids) + loss2_t = self.compute_loss(self.criterion_t, features2, pids) + + loss1_ml = self.compute_kl_div( + outputs2.detach(), outputs1, is_logit=True + ) + loss2_ml = self.compute_kl_div( + outputs1.detach(), outputs2, is_logit=True + ) + + loss1 = 0 + loss1 += loss1_x * self.weight_x + loss1 += loss1_t * self.weight_t + loss1 += loss1_ml * self.weight_ml + + loss2 = 0 + loss2 += loss2_x * self.weight_x + loss2 += loss2_t * self.weight_t + loss2 += loss2_ml * self.weight_ml + + self.optimizer1.zero_grad() + loss1.backward() + self.optimizer1.step() + + self.optimizer2.zero_grad() + loss2.backward() + self.optimizer2.step() + + loss_dict = { + 'loss1_x': loss1_x.item(), + 'loss1_t': loss1_t.item(), + 'loss1_ml': loss1_ml.item(), + 'loss2_x': loss1_x.item(), + 'loss2_t': loss1_t.item(), + 'loss2_ml': loss1_ml.item() + } + + return loss_dict + + @staticmethod + def compute_kl_div(p, q, is_logit=True): + if is_logit: + p = F.softmax(p, dim=1) + q = F.softmax(q, dim=1) + return -(p * torch.log(q + 1e-8)).sum(1).mean() + + def two_stepped_transfer_learning( + self, epoch, fixbase_epoch, open_layers, model=None + ): + """Two stepped transfer learning. + + The idea is to freeze base layers for a certain number of epochs + and then open all layers for training. + + Reference: https://arxiv.org/abs/1611.05244 + """ + model1 = self.model1 + model2 = self.model2 + + if (epoch + 1) <= fixbase_epoch and open_layers is not None: + print( + '* Only train {} (epoch: {}/{})'.format( + open_layers, epoch + 1, fixbase_epoch + ) + ) + open_specified_layers(model1, open_layers) + open_specified_layers(model2, open_layers) + else: + open_all_layers(model1) + open_all_layers(model2) + + def extract_features(self, input): + if self.deploy == 'model1': + return self.model1(input) + + elif self.deploy == 'model2': + return self.model2(input) + + else: + features = [] + features.append(self.model1(input)) + features.append(self.model2(input)) + return torch.cat(features, 1) diff --git a/strong_sort/deep/reid/projects/DML/im_osnet_x1_0_dml_256x128_amsgrad_cosine.yaml b/strong_sort/deep/reid/projects/DML/im_osnet_x1_0_dml_256x128_amsgrad_cosine.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3a240b142eae2d124d98166077eb7e572a30be25 --- /dev/null +++ b/strong_sort/deep/reid/projects/DML/im_osnet_x1_0_dml_256x128_amsgrad_cosine.yaml @@ -0,0 +1,42 @@ +model: + name: 'osnet_x1_0' + pretrained: True + deploy: 'model1' + +data: + type: 'image' + sources: ['market1501'] + targets: ['market1501'] + height: 256 + width: 128 + combineall: False + transforms: ['random_flip', 'random_erase'] + save_dir: 'log/osnet_x1_0_market1501_dml_cosinelr' + +loss: + name: 'triplet' + softmax: + label_smooth: True + triplet: + margin: 0.3 + weight_t: 0.5 + weight_x: 1. + dml: + weight_ml: 1. + +train: + optim: 'amsgrad' + lr: 0.0015 + max_epoch: 250 + batch_size: 64 + fixbase_epoch: 10 + open_layers: ['classifier'] + lr_scheduler: 'cosine' + +test: + batch_size: 300 + dist_metric: 'cosine' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False \ No newline at end of file diff --git a/strong_sort/deep/reid/projects/DML/main.py b/strong_sort/deep/reid/projects/DML/main.py new file mode 100644 index 0000000000000000000000000000000000000000..9af33d93ba16b80e56b65caeb2ad45f8ad0ac5da --- /dev/null +++ b/strong_sort/deep/reid/projects/DML/main.py @@ -0,0 +1,166 @@ +import sys +import copy +import time +import os.path as osp +import argparse +import torch +import torch.nn as nn + +import torchreid +from torchreid.utils import ( + Logger, check_isfile, set_random_seed, collect_env_info, + resume_from_checkpoint, load_pretrained_weights, compute_model_complexity +) + +from dml import ImageDMLEngine +from default_config import ( + imagedata_kwargs, optimizer_kwargs, engine_run_kwargs, get_default_config, + lr_scheduler_kwargs +) + + +def reset_config(cfg, args): + if args.root: + cfg.data.root = args.root + if args.sources: + cfg.data.sources = args.sources + if args.targets: + cfg.data.targets = args.targets + if args.transforms: + cfg.data.transforms = args.transforms + + +def main(): + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter + ) + parser.add_argument( + '--config-file', type=str, default='', help='path to config file' + ) + parser.add_argument( + '-s', + '--sources', + type=str, + nargs='+', + help='source datasets (delimited by space)' + ) + parser.add_argument( + '-t', + '--targets', + type=str, + nargs='+', + help='target datasets (delimited by space)' + ) + parser.add_argument( + '--transforms', type=str, nargs='+', help='data augmentation' + ) + parser.add_argument( + '--root', type=str, default='', help='path to data root' + ) + parser.add_argument( + 'opts', + default=None, + nargs=argparse.REMAINDER, + help='Modify config options using the command-line' + ) + args = parser.parse_args() + + cfg = get_default_config() + cfg.use_gpu = torch.cuda.is_available() + if args.config_file: + cfg.merge_from_file(args.config_file) + reset_config(cfg, args) + cfg.merge_from_list(args.opts) + set_random_seed(cfg.train.seed) + + log_name = 'test.log' if cfg.test.evaluate else 'train.log' + log_name += time.strftime('-%Y-%m-%d-%H-%M-%S') + sys.stdout = Logger(osp.join(cfg.data.save_dir, log_name)) + + print('Show configuration\n{}\n'.format(cfg)) + print('Collecting env info ...') + print('** System info **\n{}\n'.format(collect_env_info())) + + if cfg.use_gpu: + torch.backends.cudnn.benchmark = True + + datamanager = torchreid.data.ImageDataManager(**imagedata_kwargs(cfg)) + + print('Building model-1: {}'.format(cfg.model.name)) + model1 = torchreid.models.build_model( + name=cfg.model.name, + num_classes=datamanager.num_train_pids, + loss=cfg.loss.name, + pretrained=cfg.model.pretrained, + use_gpu=cfg.use_gpu + ) + num_params, flops = compute_model_complexity( + model1, (1, 3, cfg.data.height, cfg.data.width) + ) + print('Model complexity: params={:,} flops={:,}'.format(num_params, flops)) + + print('Copying model-1 to model-2') + model2 = copy.deepcopy(model1) + + if cfg.model.load_weights1 and check_isfile(cfg.model.load_weights1): + load_pretrained_weights(model1, cfg.model.load_weights1) + + if cfg.model.load_weights2 and check_isfile(cfg.model.load_weights2): + load_pretrained_weights(model2, cfg.model.load_weights2) + + if cfg.use_gpu: + model1 = nn.DataParallel(model1).cuda() + model2 = nn.DataParallel(model2).cuda() + + optimizer1 = torchreid.optim.build_optimizer( + model1, **optimizer_kwargs(cfg) + ) + scheduler1 = torchreid.optim.build_lr_scheduler( + optimizer1, **lr_scheduler_kwargs(cfg) + ) + + optimizer2 = torchreid.optim.build_optimizer( + model2, **optimizer_kwargs(cfg) + ) + scheduler2 = torchreid.optim.build_lr_scheduler( + optimizer2, **lr_scheduler_kwargs(cfg) + ) + + if cfg.model.resume1 and check_isfile(cfg.model.resume1): + cfg.train.start_epoch = resume_from_checkpoint( + cfg.model.resume1, + model1, + optimizer=optimizer1, + scheduler=scheduler1 + ) + + if cfg.model.resume2 and check_isfile(cfg.model.resume2): + resume_from_checkpoint( + cfg.model.resume2, + model2, + optimizer=optimizer2, + scheduler=scheduler2 + ) + + print('Building DML-engine for image-reid') + engine = ImageDMLEngine( + datamanager, + model1, + optimizer1, + scheduler1, + model2, + optimizer2, + scheduler2, + margin=cfg.loss.triplet.margin, + weight_t=cfg.loss.triplet.weight_t, + weight_x=cfg.loss.triplet.weight_x, + weight_ml=cfg.loss.dml.weight_ml, + use_gpu=cfg.use_gpu, + label_smooth=cfg.loss.softmax.label_smooth, + deploy=cfg.model.deploy + ) + engine.run(**engine_run_kwargs(cfg)) + + +if __name__ == '__main__': + main() diff --git a/strong_sort/deep/reid/projects/OSNet_AIN/README.md b/strong_sort/deep/reid/projects/OSNet_AIN/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b3131830ef92ebfda98f13e9e3c0d0eac4b8c4a6 --- /dev/null +++ b/strong_sort/deep/reid/projects/OSNet_AIN/README.md @@ -0,0 +1,38 @@ +# Differentiable NAS for OSNet-AIN + +## Introduction +This repository contains the neural architecture search (NAS) code (based on [Torchreid](https://arxiv.org/abs/1910.10093)) for [OSNet-AIN](https://arxiv.org/abs/1910.06827), an extension of [OSNet](https://arxiv.org/abs/1905.00953) that achieves strong performance on cross-domain person re-identification (re-ID) benchmarks (*without using any target data*). OSNet-AIN builds on the idea of using [instance normalisation](https://arxiv.org/abs/1607.08022) (IN) layers to eliminate instance-specific contrast in images for domain-generalisable representation learning. This is inspired by the [neural style transfer](https://arxiv.org/abs/1703.06868) works that use IN to remove image styles. Though IN naturally suits the cross-domain person re-ID task, it still remains unclear that where to insert IN to a re-ID CNN can maximise the performance gain. To avoid exhaustively evaluating all possible designs, OSNet-AIN learns to search for the optimal OSNet+IN design from data using a differentiable NAS algorithm. For technical details, please refer to our paper at https://arxiv.org/abs/1910.06827. + +
+ +
+ +## Training +Assume the reid data is stored at `$DATA`. Run +``` +python main.py --config-file nas.yaml --root $DATA +``` + +The structure of the found architecture will be shown at the end of training. + +The default config was designed for 8 Tesla V100 32GB GPUs. You can modify the batch size based on your device memory. + +**Note** that the test result obtained at the end of architecture search is not meaningful (due to the stochastic sampling layers). Therefore, do not rely on the result to judge the model performance. Instead, you should construct the found architecture in `osnet_child.py` and re-train and evaluate the model on the reid datasets. + +## Citation +If you find this code useful to your research, please consider citing the following papers. +``` +@article{zhou2021osnet, + title={Learning Generalisable Omni-Scale Representations for Person Re-Identification}, + author={Zhou, Kaiyang and Yang, Yongxin and Cavallaro, Andrea and Xiang, Tao}, + journal={TPAMI}, + year={2021} +} + +@inproceedings{zhou2019osnet, + title={Omni-Scale Feature Learning for Person Re-Identification}, + author={Zhou, Kaiyang and Yang, Yongxin and Cavallaro, Andrea and Xiang, Tao}, + booktitle={ICCV}, + year={2019} +} +``` \ No newline at end of file diff --git a/strong_sort/deep/reid/projects/OSNet_AIN/default_config.py b/strong_sort/deep/reid/projects/OSNet_AIN/default_config.py new file mode 100644 index 0000000000000000000000000000000000000000..733a9f026202eca60722963ef735341cd9368650 --- /dev/null +++ b/strong_sort/deep/reid/projects/OSNet_AIN/default_config.py @@ -0,0 +1,210 @@ +from yacs.config import CfgNode as CN + + +def get_default_config(): + cfg = CN() + + # model + cfg.model = CN() + cfg.model.name = 'resnet50' + cfg.model.pretrained = True # automatically load pretrained model weights if available + cfg.model.load_weights = '' # path to model weights + cfg.model.resume = '' # path to checkpoint for resume training + + # NAS + cfg.nas = CN() + cfg.nas.mc_iter = 1 # Monte Carlo sampling + cfg.nas.init_lmda = 10. # initial lambda value + cfg.nas.min_lmda = 1. # minimum lambda value + cfg.nas.lmda_decay_step = 20 # decay step for lambda + cfg.nas.lmda_decay_rate = 0.5 # decay rate for lambda + cfg.nas.fixed_lmda = False # keep lambda unchanged + + # data + cfg.data = CN() + cfg.data.type = 'image' + cfg.data.root = 'reid-data' + cfg.data.sources = ['market1501'] + cfg.data.targets = ['market1501'] + cfg.data.workers = 4 # number of data loading workers + cfg.data.split_id = 0 # split index + cfg.data.height = 256 # image height + cfg.data.width = 128 # image width + cfg.data.combineall = False # combine train, query and gallery for training + cfg.data.transforms = ['random_flip'] # data augmentation + cfg.data.norm_mean = [0.485, 0.456, 0.406] # default is imagenet mean + cfg.data.norm_std = [0.229, 0.224, 0.225] # default is imagenet std + cfg.data.save_dir = 'log' # path to save log + + # specific datasets + cfg.market1501 = CN() + cfg.market1501.use_500k_distractors = False # add 500k distractors to the gallery set for market1501 + cfg.cuhk03 = CN() + cfg.cuhk03.labeled_images = False # use labeled images, if False, use detected images + cfg.cuhk03.classic_split = False # use classic split by Li et al. CVPR14 + cfg.cuhk03.use_metric_cuhk03 = False # use cuhk03's metric for evaluation + + # sampler + cfg.sampler = CN() + cfg.sampler.train_sampler = 'RandomSampler' + cfg.sampler.num_instances = 4 # number of instances per identity for RandomIdentitySampler + + # video reid setting + cfg.video = CN() + cfg.video.seq_len = 15 # number of images to sample in a tracklet + cfg.video.sample_method = 'evenly' # how to sample images from a tracklet + cfg.video.pooling_method = 'avg' # how to pool features over a tracklet + + # train + cfg.train = CN() + cfg.train.optim = 'adam' + cfg.train.lr = 0.0003 + cfg.train.weight_decay = 5e-4 + cfg.train.max_epoch = 60 + cfg.train.start_epoch = 0 + cfg.train.batch_size = 32 + cfg.train.fixbase_epoch = 0 # number of epochs to fix base layers + cfg.train.open_layers = [ + 'classifier' + ] # layers for training while keeping others frozen + cfg.train.staged_lr = False # set different lr to different layers + cfg.train.new_layers = ['classifier'] # newly added layers with default lr + cfg.train.base_lr_mult = 0.1 # learning rate multiplier for base layers + cfg.train.lr_scheduler = 'single_step' + cfg.train.stepsize = [20] # stepsize to decay learning rate + cfg.train.gamma = 0.1 # learning rate decay multiplier + cfg.train.print_freq = 20 # print frequency + cfg.train.seed = 1 # random seed + + # optimizer + cfg.sgd = CN() + cfg.sgd.momentum = 0.9 # momentum factor for sgd and rmsprop + cfg.sgd.dampening = 0. # dampening for momentum + cfg.sgd.nesterov = False # Nesterov momentum + cfg.rmsprop = CN() + cfg.rmsprop.alpha = 0.99 # smoothing constant + cfg.adam = CN() + cfg.adam.beta1 = 0.9 # exponential decay rate for first moment + cfg.adam.beta2 = 0.999 # exponential decay rate for second moment + + # loss + cfg.loss = CN() + cfg.loss.name = 'softmax' + cfg.loss.softmax = CN() + cfg.loss.softmax.label_smooth = True # use label smoothing regularizer + cfg.loss.triplet = CN() + cfg.loss.triplet.margin = 0.3 # distance margin + cfg.loss.triplet.weight_t = 1. # weight to balance hard triplet loss + cfg.loss.triplet.weight_x = 0. # weight to balance cross entropy loss + + # test + cfg.test = CN() + cfg.test.batch_size = 100 + cfg.test.dist_metric = 'euclidean' # distance metric, ['euclidean', 'cosine'] + cfg.test.normalize_feature = False # normalize feature vectors before computing distance + cfg.test.ranks = [1, 5, 10, 20] # cmc ranks + cfg.test.evaluate = False # test only + cfg.test.eval_freq = -1 # evaluation frequency (-1 means to only test after training) + cfg.test.start_eval = 0 # start to evaluate after a specific epoch + cfg.test.rerank = False # use person re-ranking + cfg.test.visrank = False # visualize ranked results (only available when cfg.test.evaluate=True) + cfg.test.visrank_topk = 10 # top-k ranks to visualize + cfg.test.visactmap = False # visualize CNN activation maps + + return cfg + + +def imagedata_kwargs(cfg): + return { + 'root': cfg.data.root, + 'sources': cfg.data.sources, + 'targets': cfg.data.targets, + 'height': cfg.data.height, + 'width': cfg.data.width, + 'transforms': cfg.data.transforms, + 'norm_mean': cfg.data.norm_mean, + 'norm_std': cfg.data.norm_std, + 'use_gpu': cfg.use_gpu, + 'split_id': cfg.data.split_id, + 'combineall': cfg.data.combineall, + 'batch_size_train': cfg.train.batch_size, + 'batch_size_test': cfg.test.batch_size, + 'workers': cfg.data.workers, + 'num_instances': cfg.sampler.num_instances, + 'train_sampler': cfg.sampler.train_sampler, + # image + 'cuhk03_labeled': cfg.cuhk03.labeled_images, + 'cuhk03_classic_split': cfg.cuhk03.classic_split, + 'market1501_500k': cfg.market1501.use_500k_distractors, + } + + +def videodata_kwargs(cfg): + return { + 'root': cfg.data.root, + 'sources': cfg.data.sources, + 'targets': cfg.data.targets, + 'height': cfg.data.height, + 'width': cfg.data.width, + 'transforms': cfg.data.transforms, + 'norm_mean': cfg.data.norm_mean, + 'norm_std': cfg.data.norm_std, + 'use_gpu': cfg.use_gpu, + 'split_id': cfg.data.split_id, + 'combineall': cfg.data.combineall, + 'batch_size_train': cfg.train.batch_size, + 'batch_size_test': cfg.test.batch_size, + 'workers': cfg.data.workers, + 'num_instances': cfg.sampler.num_instances, + 'train_sampler': cfg.sampler.train_sampler, + # video + 'seq_len': cfg.video.seq_len, + 'sample_method': cfg.video.sample_method + } + + +def optimizer_kwargs(cfg): + return { + 'optim': cfg.train.optim, + 'lr': cfg.train.lr, + 'weight_decay': cfg.train.weight_decay, + 'momentum': cfg.sgd.momentum, + 'sgd_dampening': cfg.sgd.dampening, + 'sgd_nesterov': cfg.sgd.nesterov, + 'rmsprop_alpha': cfg.rmsprop.alpha, + 'adam_beta1': cfg.adam.beta1, + 'adam_beta2': cfg.adam.beta2, + 'staged_lr': cfg.train.staged_lr, + 'new_layers': cfg.train.new_layers, + 'base_lr_mult': cfg.train.base_lr_mult + } + + +def lr_scheduler_kwargs(cfg): + return { + 'lr_scheduler': cfg.train.lr_scheduler, + 'stepsize': cfg.train.stepsize, + 'gamma': cfg.train.gamma, + 'max_epoch': cfg.train.max_epoch + } + + +def engine_run_kwargs(cfg): + return { + 'save_dir': cfg.data.save_dir, + 'max_epoch': cfg.train.max_epoch, + 'start_epoch': cfg.train.start_epoch, + 'fixbase_epoch': cfg.train.fixbase_epoch, + 'open_layers': cfg.train.open_layers, + 'start_eval': cfg.test.start_eval, + 'eval_freq': cfg.test.eval_freq, + 'test_only': cfg.test.evaluate, + 'print_freq': cfg.train.print_freq, + 'dist_metric': cfg.test.dist_metric, + 'normalize_feature': cfg.test.normalize_feature, + 'visrank': cfg.test.visrank, + 'visrank_topk': cfg.test.visrank_topk, + 'use_metric_cuhk03': cfg.cuhk03.use_metric_cuhk03, + 'ranks': cfg.test.ranks, + 'rerank': cfg.test.rerank + } diff --git a/strong_sort/deep/reid/projects/OSNet_AIN/main.py b/strong_sort/deep/reid/projects/OSNet_AIN/main.py new file mode 100644 index 0000000000000000000000000000000000000000..f59177073dfafe1b4b712691c780af32b30fcd2c --- /dev/null +++ b/strong_sort/deep/reid/projects/OSNet_AIN/main.py @@ -0,0 +1,145 @@ +import os +import sys +import time +import os.path as osp +import argparse +import torch +import torch.nn as nn + +import torchreid +from torchreid.utils import ( + Logger, check_isfile, set_random_seed, collect_env_info, + resume_from_checkpoint, compute_model_complexity +) + +import osnet_search as osnet_models +from softmax_nas import ImageSoftmaxNASEngine +from default_config import ( + imagedata_kwargs, optimizer_kwargs, engine_run_kwargs, get_default_config, + lr_scheduler_kwargs +) + + +def reset_config(cfg, args): + if args.root: + cfg.data.root = args.root + if args.sources: + cfg.data.sources = args.sources + if args.targets: + cfg.data.targets = args.targets + if args.transforms: + cfg.data.transforms = args.transforms + + +def main(): + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter + ) + parser.add_argument( + '--config-file', type=str, default='', help='path to config file' + ) + parser.add_argument( + '-s', + '--sources', + type=str, + nargs='+', + help='source datasets (delimited by space)' + ) + parser.add_argument( + '-t', + '--targets', + type=str, + nargs='+', + help='target datasets (delimited by space)' + ) + parser.add_argument( + '--transforms', type=str, nargs='+', help='data augmentation' + ) + parser.add_argument( + '--root', type=str, default='', help='path to data root' + ) + parser.add_argument( + '--gpu-devices', + type=str, + default='', + ) + parser.add_argument( + 'opts', + default=None, + nargs=argparse.REMAINDER, + help='Modify config options using the command-line' + ) + args = parser.parse_args() + + cfg = get_default_config() + cfg.use_gpu = torch.cuda.is_available() + if args.config_file: + cfg.merge_from_file(args.config_file) + reset_config(cfg, args) + cfg.merge_from_list(args.opts) + set_random_seed(cfg.train.seed) + + if cfg.use_gpu and args.gpu_devices: + # if gpu_devices is not specified, all available gpus will be used + os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_devices + log_name = 'test.log' if cfg.test.evaluate else 'train.log' + log_name += time.strftime('-%Y-%m-%d-%H-%M-%S') + sys.stdout = Logger(osp.join(cfg.data.save_dir, log_name)) + + print('Show configuration\n{}\n'.format(cfg)) + print('Collecting env info ...') + print('** System info **\n{}\n'.format(collect_env_info())) + + if cfg.use_gpu: + torch.backends.cudnn.benchmark = True + + datamanager = torchreid.data.ImageDataManager(**imagedata_kwargs(cfg)) + + print('Building model: {}'.format(cfg.model.name)) + model = osnet_models.build_model( + cfg.model.name, num_classes=datamanager.num_train_pids + ) + num_params, flops = compute_model_complexity( + model, (1, 3, cfg.data.height, cfg.data.width) + ) + print('Model complexity: params={:,} flops={:,}'.format(num_params, flops)) + + if cfg.use_gpu: + model = nn.DataParallel(model).cuda() + + optimizer = torchreid.optim.build_optimizer(model, **optimizer_kwargs(cfg)) + scheduler = torchreid.optim.build_lr_scheduler( + optimizer, **lr_scheduler_kwargs(cfg) + ) + + if cfg.model.resume and check_isfile(cfg.model.resume): + cfg.train.start_epoch = resume_from_checkpoint( + cfg.model.resume, model, optimizer=optimizer + ) + + print('Building NAS engine') + engine = ImageSoftmaxNASEngine( + datamanager, + model, + optimizer, + scheduler=scheduler, + use_gpu=cfg.use_gpu, + label_smooth=cfg.loss.softmax.label_smooth, + mc_iter=cfg.nas.mc_iter, + init_lmda=cfg.nas.init_lmda, + min_lmda=cfg.nas.min_lmda, + lmda_decay_step=cfg.nas.lmda_decay_step, + lmda_decay_rate=cfg.nas.lmda_decay_rate, + fixed_lmda=cfg.nas.fixed_lmda + ) + engine.run(**engine_run_kwargs(cfg)) + + print('*** Display the found architecture ***') + if cfg.use_gpu: + model.module.build_child_graph() + else: + model.build_child_graph() + + +if __name__ == '__main__': + main() diff --git a/strong_sort/deep/reid/projects/OSNet_AIN/nas.yaml b/strong_sort/deep/reid/projects/OSNet_AIN/nas.yaml new file mode 100644 index 0000000000000000000000000000000000000000..507b2ecfe44e8a7ab54d74c74aef808fea1a4951 --- /dev/null +++ b/strong_sort/deep/reid/projects/OSNet_AIN/nas.yaml @@ -0,0 +1,44 @@ +model: + name: 'osnet_nas' + pretrained: False + +nas: + mc_iter: 1 + init_lmda: 10. + min_lmda: 1. + lmda_decay_step: 20 + lmda_decay_rate: 0.5 + fixed_lmda: False + +data: + type: 'image' + sources: ['msmt17'] + targets: ['market1501'] + height: 256 + width: 128 + combineall: True + transforms: ['random_flip', 'color_jitter'] + save_dir: 'log/osnet_nas' + +loss: + name: 'softmax' + softmax: + label_smooth: True + +train: + optim: 'sgd' + lr: 0.1 + max_epoch: 120 + batch_size: 512 + fixbase_epoch: 0 + open_layers: ['classifier'] + lr_scheduler: 'cosine' + +test: + batch_size: 300 + dist_metric: 'cosine' + normalize_feature: False + evaluate: False + eval_freq: -1 + rerank: False + visactmap: False \ No newline at end of file diff --git a/strong_sort/deep/reid/projects/OSNet_AIN/osnet_child.py b/strong_sort/deep/reid/projects/OSNet_AIN/osnet_child.py new file mode 100644 index 0000000000000000000000000000000000000000..b47d747d03d90748fff902e67e49e05a65b82d0c --- /dev/null +++ b/strong_sort/deep/reid/projects/OSNet_AIN/osnet_child.py @@ -0,0 +1,535 @@ +from __future__ import division, absolute_import +from torch import nn +from torch.nn import functional as F + + +########## +# Basic layers +########## +class ConvLayer(nn.Module): + """Convolution layer (conv + bn + relu).""" + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + groups=1, + IN=False + ): + super(ConvLayer, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + bias=False, + groups=groups + ) + if IN: + self.bn = nn.InstanceNorm2d(out_channels, affine=True) + else: + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return self.relu(x) + + +class Conv1x1(nn.Module): + """1x1 convolution + bn + relu.""" + + def __init__(self, in_channels, out_channels, stride=1, groups=1): + super(Conv1x1, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 1, + stride=stride, + padding=0, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return self.relu(x) + + +class Conv1x1Linear(nn.Module): + """1x1 convolution + bn (w/o non-linearity).""" + + def __init__(self, in_channels, out_channels, stride=1, bn=True): + super(Conv1x1Linear, self).__init__() + self.conv = nn.Conv2d( + in_channels, out_channels, 1, stride=stride, padding=0, bias=False + ) + self.bn = None + if bn: + self.bn = nn.BatchNorm2d(out_channels) + + def forward(self, x): + x = self.conv(x) + if self.bn is not None: + x = self.bn(x) + return x + + +class Conv3x3(nn.Module): + """3x3 convolution + bn + relu.""" + + def __init__(self, in_channels, out_channels, stride=1, groups=1): + super(Conv3x3, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 3, + stride=stride, + padding=1, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return self.relu(x) + + +class LightConv3x3(nn.Module): + """Lightweight 3x3 convolution. + + 1x1 (linear) + dw 3x3 (nonlinear). + """ + + def __init__(self, in_channels, out_channels): + super(LightConv3x3, self).__init__() + self.conv1 = nn.Conv2d( + in_channels, out_channels, 1, stride=1, padding=0, bias=False + ) + self.conv2 = nn.Conv2d( + out_channels, + out_channels, + 3, + stride=1, + padding=1, + bias=False, + groups=out_channels + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv1(x) + x = self.conv2(x) + x = self.bn(x) + return self.relu(x) + + +class LightConvStream(nn.Module): + """Lightweight convolution stream.""" + + def __init__(self, in_channels, out_channels, depth): + super(LightConvStream, self).__init__() + assert depth >= 1, 'depth must be equal to or larger than 1, but got {}'.format( + depth + ) + layers = [] + layers += [LightConv3x3(in_channels, out_channels)] + for i in range(depth - 1): + layers += [LightConv3x3(out_channels, out_channels)] + self.layers = nn.Sequential(*layers) + + def forward(self, x): + return self.layers(x) + + +########## +# Building blocks for omni-scale feature learning +########## +class ChannelGate(nn.Module): + """A mini-network that generates channel-wise gates conditioned on input tensor.""" + + def __init__( + self, + in_channels, + num_gates=None, + return_gates=False, + gate_activation='sigmoid', + reduction=16, + layer_norm=False + ): + super(ChannelGate, self).__init__() + if num_gates is None: + num_gates = in_channels + self.return_gates = return_gates + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.fc1 = nn.Conv2d( + in_channels, + in_channels // reduction, + kernel_size=1, + bias=True, + padding=0 + ) + self.norm1 = None + if layer_norm: + self.norm1 = nn.LayerNorm((in_channels // reduction, 1, 1)) + self.relu = nn.ReLU(inplace=True) + self.fc2 = nn.Conv2d( + in_channels // reduction, + num_gates, + kernel_size=1, + bias=True, + padding=0 + ) + if gate_activation == 'sigmoid': + self.gate_activation = nn.Sigmoid() + elif gate_activation == 'relu': + self.gate_activation = nn.ReLU(inplace=True) + elif gate_activation == 'linear': + self.gate_activation = None + else: + raise RuntimeError( + "Unknown gate activation: {}".format(gate_activation) + ) + + def forward(self, x): + input = x + x = self.global_avgpool(x) + x = self.fc1(x) + if self.norm1 is not None: + x = self.norm1(x) + x = self.relu(x) + x = self.fc2(x) + if self.gate_activation is not None: + x = self.gate_activation(x) + if self.return_gates: + return x + return input * x + + +class OSBlock(nn.Module): + """Omni-scale feature learning block.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlock, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + return F.relu(out) + + +class OSBlockINv1(nn.Module): + """Omni-scale feature learning block with instance normalization.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlockINv1, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels, bn=False) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + self.IN = nn.InstanceNorm2d(out_channels, affine=True) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + x3 = self.IN(x3) # IN inside residual + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + return F.relu(out) + + +class OSBlockINv2(nn.Module): + """Omni-scale feature learning block with instance normalization.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlockINv2, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + self.IN = nn.InstanceNorm2d(out_channels, affine=True) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + out = self.IN(out) # IN outside residual + return F.relu(out) + + +class OSBlockINv3(nn.Module): + """Omni-scale feature learning block with instance normalization.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlockINv3, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels, bn=False) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + self.IN_in = nn.InstanceNorm2d(out_channels, affine=True) + self.IN_out = nn.InstanceNorm2d(out_channels, affine=True) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + x3 = self.IN_in(x3) # IN inside residual + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + out = self.IN_out(out) # IN outside residual + return F.relu(out) + + +########## +# Network architecture +########## +class OSNet(nn.Module): + """Omni-Scale Network. + + Reference: + - Zhou et al. Omni-Scale Feature Learning for Person Re-Identification. ICCV, 2019. + - Zhou et al. Learning Generalisable Omni-Scale Representations + for Person Re-Identification. TPAMI, 2021. + """ + + def __init__( + self, + num_classes, + blocks, + layers, + channels, + feature_dim=512, + loss='softmax', + conv1_IN=True, + **kwargs + ): + super(OSNet, self).__init__() + num_blocks = len(blocks) + assert num_blocks == len(layers) + assert num_blocks == len(channels) - 1 + self.loss = loss + self.feature_dim = feature_dim + + # convolutional backbone + self.conv1 = ConvLayer( + 3, channels[0], 7, stride=2, padding=3, IN=conv1_IN + ) + self.maxpool = nn.MaxPool2d(3, stride=2, padding=1) + self.conv2 = self._make_layer( + blocks[0], layers[0], channels[0], channels[1] + ) + self.pool2 = nn.Sequential( + Conv1x1(channels[1], channels[1]), nn.AvgPool2d(2, stride=2) + ) + self.conv3 = self._make_layer( + blocks[1], layers[1], channels[1], channels[2] + ) + self.pool3 = nn.Sequential( + Conv1x1(channels[2], channels[2]), nn.AvgPool2d(2, stride=2) + ) + self.conv4 = self._make_layer( + blocks[2], layers[2], channels[2], channels[3] + ) + self.conv5 = Conv1x1(channels[3], channels[3]) + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + # fully connected layer + self.fc = self._construct_fc_layer( + self.feature_dim, channels[3], dropout_p=None + ) + # identity classification layer + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self._init_params() + + def _make_layer(self, blocks, layer, in_channels, out_channels): + layers = [] + layers += [blocks[0](in_channels, out_channels)] + for i in range(1, len(blocks)): + layers += [blocks[i](out_channels, out_channels)] + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + if fc_dims is None or fc_dims < 0: + self.feature_dim = input_dim + return None + + if isinstance(fc_dims, int): + fc_dims = [fc_dims] + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.InstanceNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.maxpool(x) + x = self.conv2(x) + x = self.pool2(x) + x = self.conv3(x) + x = self.pool3(x) + x = self.conv4(x) + return self.conv5(x) + + def forward(self, x, return_featuremaps=False, **kwargs): + x = self.featuremaps(x) + if return_featuremaps: + return x + v = self.global_avgpool(x) + v = v.view(v.size(0), -1) + if self.fc is not None: + v = self.fc(v) + if not self.training: + return v + y = self.classifier(v) + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) + + +########## +# Instantiation +########## +def osnet_ain_x1_0( + num_classes=1000, pretrained=True, loss='softmax', **kwargs +): + model = OSNet( + num_classes, + blocks=[ + [OSBlockINv1, OSBlockINv1], [OSBlock, OSBlockINv1], + [OSBlockINv1, OSBlock] + ], + layers=[2, 2, 2], + channels=[64, 256, 384, 512], + loss=loss, + conv1_IN=True, + **kwargs + ) + return model + + +__models = {'osnet_ain_x1_0': osnet_ain_x1_0} + + +def build_model(name, num_classes=100): + avai_models = list(__models.keys()) + if name not in avai_models: + raise KeyError( + 'Unknown model: {}. Must be one of {}'.format(name, avai_models) + ) + return __models[name](num_classes=num_classes) diff --git a/strong_sort/deep/reid/projects/OSNet_AIN/osnet_search.py b/strong_sort/deep/reid/projects/OSNet_AIN/osnet_search.py new file mode 100644 index 0000000000000000000000000000000000000000..182014489ab013bdf44a1cd213ce369deee76478 --- /dev/null +++ b/strong_sort/deep/reid/projects/OSNet_AIN/osnet_search.py @@ -0,0 +1,584 @@ +from __future__ import division, absolute_import +import torch +from torch import nn +from torch.nn import functional as F + +EPS = 1e-12 +NORM_AFFINE = False # enable affine transformations for normalization layer + + +########## +# Basic layers +########## +class IBN(nn.Module): + """Instance + Batch Normalization.""" + + def __init__(self, num_channels): + super(IBN, self).__init__() + half1 = int(num_channels / 2) + self.half = half1 + half2 = num_channels - half1 + self.IN = nn.InstanceNorm2d(half1, affine=NORM_AFFINE) + self.BN = nn.BatchNorm2d(half2, affine=NORM_AFFINE) + + def forward(self, x): + split = torch.split(x, self.half, 1) + out1 = self.IN(split[0].contiguous()) + out2 = self.BN(split[1].contiguous()) + return torch.cat((out1, out2), 1) + + +class ConvLayer(nn.Module): + """Convolution layer (conv + bn + relu).""" + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + groups=1, + IN=False + ): + super(ConvLayer, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + bias=False, + groups=groups + ) + if IN: + self.bn = nn.InstanceNorm2d(out_channels, affine=NORM_AFFINE) + else: + self.bn = nn.BatchNorm2d(out_channels, affine=NORM_AFFINE) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return self.relu(x) + + +class Conv1x1(nn.Module): + """1x1 convolution + bn + relu.""" + + def __init__( + self, in_channels, out_channels, stride=1, groups=1, ibn=False + ): + super(Conv1x1, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 1, + stride=stride, + padding=0, + bias=False, + groups=groups + ) + if ibn: + self.bn = IBN(out_channels) + else: + self.bn = nn.BatchNorm2d(out_channels, affine=NORM_AFFINE) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return self.relu(x) + + +class Conv1x1Linear(nn.Module): + """1x1 convolution + bn (w/o non-linearity).""" + + def __init__(self, in_channels, out_channels, stride=1, bn=True): + super(Conv1x1Linear, self).__init__() + self.conv = nn.Conv2d( + in_channels, out_channels, 1, stride=stride, padding=0, bias=False + ) + self.bn = None + if bn: + self.bn = nn.BatchNorm2d(out_channels, affine=NORM_AFFINE) + + def forward(self, x): + x = self.conv(x) + if self.bn is not None: + x = self.bn(x) + return x + + +class Conv3x3(nn.Module): + """3x3 convolution + bn + relu.""" + + def __init__(self, in_channels, out_channels, stride=1, groups=1): + super(Conv3x3, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 3, + stride=stride, + padding=1, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels, affine=NORM_AFFINE) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return self.relu(x) + + +class LightConv3x3(nn.Module): + """Lightweight 3x3 convolution. + + 1x1 (linear) + dw 3x3 (nonlinear). + """ + + def __init__(self, in_channels, out_channels): + super(LightConv3x3, self).__init__() + self.conv1 = nn.Conv2d( + in_channels, out_channels, 1, stride=1, padding=0, bias=False + ) + self.conv2 = nn.Conv2d( + out_channels, + out_channels, + 3, + stride=1, + padding=1, + bias=False, + groups=out_channels + ) + self.bn = nn.BatchNorm2d(out_channels, affine=NORM_AFFINE) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv1(x) + x = self.conv2(x) + x = self.bn(x) + return self.relu(x) + + +class LightConvStream(nn.Module): + """Lightweight convolution stream.""" + + def __init__(self, in_channels, out_channels, depth): + super(LightConvStream, self).__init__() + assert depth >= 1, 'depth must be equal to or larger than 1, but got {}'.format( + depth + ) + layers = [] + layers += [LightConv3x3(in_channels, out_channels)] + for i in range(depth - 1): + layers += [LightConv3x3(out_channels, out_channels)] + self.layers = nn.Sequential(*layers) + + def forward(self, x): + return self.layers(x) + + +########## +# Building blocks for omni-scale feature learning +########## +class ChannelGate(nn.Module): + """A mini-network that generates channel-wise gates conditioned on input tensor.""" + + def __init__( + self, + in_channels, + num_gates=None, + return_gates=False, + gate_activation='sigmoid', + reduction=16, + layer_norm=False + ): + super(ChannelGate, self).__init__() + if num_gates is None: + num_gates = in_channels + self.return_gates = return_gates + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.fc1 = nn.Conv2d( + in_channels, + in_channels // reduction, + kernel_size=1, + bias=True, + padding=0 + ) + self.norm1 = None + if layer_norm: + self.norm1 = nn.LayerNorm((in_channels // reduction, 1, 1)) + self.relu = nn.ReLU(inplace=True) + self.fc2 = nn.Conv2d( + in_channels // reduction, + num_gates, + kernel_size=1, + bias=True, + padding=0 + ) + if gate_activation == 'sigmoid': + self.gate_activation = nn.Sigmoid() + elif gate_activation == 'relu': + self.gate_activation = nn.ReLU(inplace=True) + elif gate_activation == 'linear': + self.gate_activation = None + else: + raise RuntimeError( + "Unknown gate activation: {}".format(gate_activation) + ) + + def forward(self, x): + input = x + x = self.global_avgpool(x) + x = self.fc1(x) + if self.norm1 is not None: + x = self.norm1(x) + x = self.relu(x) + x = self.fc2(x) + if self.gate_activation is not None: + x = self.gate_activation(x) + if self.return_gates: + return x + return input * x + + +class OSBlock(nn.Module): + """Omni-scale feature learning block.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlock, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + return F.relu(out) + + +class OSBlockINv1(nn.Module): + """Omni-scale feature learning block with instance normalization.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlockINv1, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels, bn=False) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + self.IN = nn.InstanceNorm2d(out_channels, affine=NORM_AFFINE) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + x3 = self.IN(x3) # IN inside residual + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + return F.relu(out) + + +class OSBlockINv2(nn.Module): + """Omni-scale feature learning block with instance normalization.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlockINv2, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + self.IN = nn.InstanceNorm2d(out_channels, affine=NORM_AFFINE) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + out = self.IN(out) # IN outside residual + return F.relu(out) + + +class OSBlockINv3(nn.Module): + """Omni-scale feature learning block with instance normalization.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlockINv3, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels, bn=False) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + self.IN_in = nn.InstanceNorm2d(out_channels, affine=NORM_AFFINE) + self.IN_out = nn.InstanceNorm2d(out_channels, affine=NORM_AFFINE) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + x3 = self.IN_in(x3) # inside residual + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + out = self.IN_out(out) # IN outside residual + return F.relu(out) + + +class NASBlock(nn.Module): + """Neural architecture search layer.""" + + def __init__(self, in_channels, out_channels, search_space=None): + super(NASBlock, self).__init__() + self._is_child_graph = False + self.search_space = search_space + if self.search_space is None: + raise ValueError('search_space is None') + + self.os_block = nn.ModuleList() + for block in self.search_space: + self.os_block += [block(in_channels, out_channels)] + self.weights = nn.Parameter(torch.ones(len(self.search_space))) + + def build_child_graph(self): + if self._is_child_graph: + raise RuntimeError('build_child_graph() can only be called once') + + idx = self.weights.data.max(dim=0)[1].item() + self.os_block = self.os_block[idx] + self.weights = None + self._is_child_graph = True + return self.search_space[idx] + + def forward(self, x, lmda=1.): + if self._is_child_graph: + return self.os_block(x) + + uniform = torch.rand_like(self.weights) + gumbel = -torch.log(-torch.log(uniform + EPS)) + nonneg_weights = F.relu(self.weights) + logits = torch.log(nonneg_weights + EPS) + gumbel + exp = torch.exp(logits / lmda) + weights_softmax = exp / (exp.sum() + EPS) + + output = 0 + for i, weight in enumerate(weights_softmax): + output = output + weight * self.os_block[i](x) + return output + + +########## +# Network architecture +########## +class OSNet(nn.Module): + """Omni-Scale Network. + + Reference: + - Zhou et al. Omni-Scale Feature Learning for Person Re-Identification. ICCV, 2019. + - Zhou et al. Learning Generalisable Omni-Scale Representations + for Person Re-Identification. TPAMI, 2021. + """ + + def __init__( + self, + num_classes, + blocks, + layers, + channels, + feature_dim=512, + loss='softmax', + search_space=None, + **kwargs + ): + super(OSNet, self).__init__() + num_blocks = len(blocks) + assert num_blocks == len(layers) + assert num_blocks == len(channels) - 1 + # no matter what loss is specified, the model only returns the ID predictions + self.loss = loss + self.feature_dim = feature_dim + + # convolutional backbone + self.conv1 = ConvLayer(3, channels[0], 7, stride=2, padding=3, IN=True) + self.maxpool = nn.MaxPool2d(3, stride=2, padding=1) + self.conv2 = self._make_layer( + blocks[0], layers[0], channels[0], channels[1], search_space + ) + self.pool2 = nn.Sequential( + Conv1x1(channels[1], channels[1]), nn.AvgPool2d(2, stride=2) + ) + self.conv3 = self._make_layer( + blocks[1], layers[1], channels[1], channels[2], search_space + ) + self.pool3 = nn.Sequential( + Conv1x1(channels[2], channels[2]), nn.AvgPool2d(2, stride=2) + ) + self.conv4 = self._make_layer( + blocks[2], layers[2], channels[2], channels[3], search_space + ) + self.conv5 = Conv1x1(channels[3], channels[3]) + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + # fully connected layer + self.fc = self._construct_fc_layer( + self.feature_dim, channels[3], dropout_p=None + ) + # identity classification layer + self.classifier = nn.Linear(self.feature_dim, num_classes) + + def _make_layer( + self, block, layer, in_channels, out_channels, search_space + ): + layers = nn.ModuleList() + layers += [block(in_channels, out_channels, search_space=search_space)] + for i in range(1, layer): + layers += [ + block(out_channels, out_channels, search_space=search_space) + ] + return layers + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + if fc_dims is None or fc_dims < 0: + self.feature_dim = input_dim + return None + + if isinstance(fc_dims, int): + fc_dims = [fc_dims] + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim, affine=NORM_AFFINE)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def build_child_graph(self): + print('Building child graph') + for i, conv in enumerate(self.conv2): + block = conv.build_child_graph() + print('- conv2-{} Block={}'.format(i + 1, block.__name__)) + for i, conv in enumerate(self.conv3): + block = conv.build_child_graph() + print('- conv3-{} Block={}'.format(i + 1, block.__name__)) + for i, conv in enumerate(self.conv4): + block = conv.build_child_graph() + print('- conv4-{} Block={}'.format(i + 1, block.__name__)) + + def featuremaps(self, x, lmda): + x = self.conv1(x) + x = self.maxpool(x) + for conv in self.conv2: + x = conv(x, lmda) + x = self.pool2(x) + for conv in self.conv3: + x = conv(x, lmda) + x = self.pool3(x) + for conv in self.conv4: + x = conv(x, lmda) + return self.conv5(x) + + def forward(self, x, lmda=1., return_featuremaps=False): + # lmda (float): temperature parameter for concrete distribution + x = self.featuremaps(x, lmda) + if return_featuremaps: + return x + v = self.global_avgpool(x) + v = v.view(v.size(0), -1) + if self.fc is not None: + v = self.fc(v) + if not self.training: + return v + return self.classifier(v) + + +########## +# Instantiation +########## +def osnet_nas(num_classes=1000, loss='softmax', **kwargs): + # standard size (width x1.0) + return OSNet( + num_classes, + blocks=[NASBlock, NASBlock, NASBlock], + layers=[2, 2, 2], + channels=[64, 256, 384, 512], + loss=loss, + search_space=[OSBlock, OSBlockINv1, OSBlockINv2, OSBlockINv3], + **kwargs + ) + + +__NAS_models = {'osnet_nas': osnet_nas} + + +def build_model(name, num_classes=100): + avai_models = list(__NAS_models.keys()) + if name not in avai_models: + raise KeyError( + 'Unknown model: {}. Must be one of {}'.format(name, avai_models) + ) + return __NAS_models[name](num_classes=num_classes) diff --git a/strong_sort/deep/reid/projects/OSNet_AIN/softmax_nas.py b/strong_sort/deep/reid/projects/OSNet_AIN/softmax_nas.py new file mode 100644 index 0000000000000000000000000000000000000000..e2a03b6be4e82fabac4c89714c700c75d8cb1b23 --- /dev/null +++ b/strong_sort/deep/reid/projects/OSNet_AIN/softmax_nas.py @@ -0,0 +1,73 @@ +from __future__ import division, print_function, absolute_import + +from torchreid import metrics +from torchreid.engine import Engine +from torchreid.losses import CrossEntropyLoss + + +class ImageSoftmaxNASEngine(Engine): + + def __init__( + self, + datamanager, + model, + optimizer, + scheduler=None, + use_gpu=False, + label_smooth=True, + mc_iter=1, + init_lmda=1., + min_lmda=1., + lmda_decay_step=20, + lmda_decay_rate=0.5, + fixed_lmda=False + ): + super(ImageSoftmaxNASEngine, self).__init__(datamanager, use_gpu) + self.mc_iter = mc_iter + self.init_lmda = init_lmda + self.min_lmda = min_lmda + self.lmda_decay_step = lmda_decay_step + self.lmda_decay_rate = lmda_decay_rate + self.fixed_lmda = fixed_lmda + + self.model = model + self.optimizer = optimizer + self.scheduler = scheduler + self.register_model('model', model, optimizer, scheduler) + + self.criterion = CrossEntropyLoss( + num_classes=self.datamanager.num_train_pids, + use_gpu=self.use_gpu, + label_smooth=label_smooth + ) + + def forward_backward(self, data): + imgs, pids = self.parse_data_for_train(data) + + if self.use_gpu: + imgs = imgs.cuda() + pids = pids.cuda() + + # softmax temporature + if self.fixed_lmda or self.lmda_decay_step == -1: + lmda = self.init_lmda + else: + lmda = self.init_lmda * self.lmda_decay_rate**( + self.epoch // self.lmda_decay_step + ) + if lmda < self.min_lmda: + lmda = self.min_lmda + + for k in range(self.mc_iter): + outputs = self.model(imgs, lmda=lmda) + loss = self.compute_loss(self.criterion, outputs, pids) + self.optimizer.zero_grad() + loss.backward() + self.optimizer.step() + + loss_dict = { + 'loss': loss.item(), + 'acc': metrics.accuracy(outputs, pids)[0].item() + } + + return loss_dict diff --git a/strong_sort/deep/reid/projects/README.md b/strong_sort/deep/reid/projects/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fa63919ffdd31eaa0b7b6bf8032c9c589b4f233d --- /dev/null +++ b/strong_sort/deep/reid/projects/README.md @@ -0,0 +1,5 @@ +Here are some research projects built on [Torchreid](https://arxiv.org/abs/1910.10093). + ++ `OSNet_AIN`: [Learning Generalisable Omni-Scale Representations for Person Re-Identification](https://arxiv.org/abs/1910.06827) ++ `DML`: [Deep Mutual Learning (CVPR'18)](https://arxiv.org/abs/1706.00384) ++ `attribute_recognition`: [Omni-Scale Feature Learning for Person Re-Identification (ICCV'19)](https://arxiv.org/abs/1905.00953) \ No newline at end of file diff --git a/strong_sort/deep/reid/projects/attribute_recognition/README.md b/strong_sort/deep/reid/projects/attribute_recognition/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a20b6e7f1c279c065f8f2f81e078410796829951 --- /dev/null +++ b/strong_sort/deep/reid/projects/attribute_recognition/README.md @@ -0,0 +1,18 @@ +# Person Attribute Recognition +This code was developed for the experiment of person attribute recognition in [Omni-Scale Feature Learning for Person Re-Identification (ICCV'19)](https://arxiv.org/abs/1905.00953). + +## Download data +Download the PA-100K dataset from [https://github.com/xh-liu/HydraPlus-Net](https://github.com/xh-liu/HydraPlus-Net), and extract the file under the folder where you store your data (say $DATASET). The folder structure should look like +```bash +$DATASET/ + pa100k/ + data/ # images + annotation/ + annotation.mat +``` + +## Train +The training command is provided in `train.sh`. Run `bash train.sh $DATASET` to start training. + +## Test +To test a pretrained model, add the following two arguments to `train.sh`: `--load-weights $PATH_TO_WEIGHTS --evaluate`. \ No newline at end of file diff --git a/strong_sort/deep/reid/projects/attribute_recognition/datasets/__init__.py b/strong_sort/deep/reid/projects/attribute_recognition/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..664598c71865da78ce937605de3bbf29ef304152 --- /dev/null +++ b/strong_sort/deep/reid/projects/attribute_recognition/datasets/__init__.py @@ -0,0 +1,15 @@ +from __future__ import division, print_function, absolute_import + +from .pa100k import PA100K + +__datasets = {'pa100k': PA100K} + + +def init_dataset(name, **kwargs): + avai_datasets = list(__datasets.keys()) + if name not in avai_datasets: + raise ValueError( + 'Invalid dataset name. Received "{}", ' + 'but expected to be one of {}'.format(name, avai_datasets) + ) + return __datasets[name](**kwargs) diff --git a/strong_sort/deep/reid/projects/attribute_recognition/datasets/dataset.py b/strong_sort/deep/reid/projects/attribute_recognition/datasets/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce4ebff15a52140b7e713322acfbb42eb013fdc --- /dev/null +++ b/strong_sort/deep/reid/projects/attribute_recognition/datasets/dataset.py @@ -0,0 +1,87 @@ +from __future__ import division, print_function, absolute_import +import os.path as osp + +from torchreid.utils import read_image + + +class Dataset(object): + + def __init__( + self, + train, + val, + test, + attr_dict, + transform=None, + mode='train', + verbose=True, + **kwargs + ): + self.train = train + self.val = val + self.test = test + self._attr_dict = attr_dict + self._num_attrs = len(self.attr_dict) + self.transform = transform + + if mode == 'train': + self.data = self.train + elif mode == 'val': + self.data = self.val + else: + self.data = self.test + + if verbose: + self.show_summary() + + @property + def num_attrs(self): + return self._num_attrs + + @property + def attr_dict(self): + return self._attr_dict + + def __len__(self): + return len(self.data) + + def __getitem__(self, index): + img_path, attrs = self.data[index] + img = read_image(img_path) + if self.transform is not None: + img = self.transform(img) + return img, attrs, img_path + + def check_before_run(self, required_files): + """Checks if required files exist before going deeper. + Args: + required_files (str or list): string file name(s). + """ + if isinstance(required_files, str): + required_files = [required_files] + + for fpath in required_files: + if not osp.exists(fpath): + raise RuntimeError('"{}" is not found'.format(fpath)) + + def show_summary(self): + num_train = len(self.train) + num_val = len(self.val) + num_test = len(self.test) + num_total = num_train + num_val + num_test + + print('=> Loaded {}'.format(self.__class__.__name__)) + print(" ------------------------------") + print(" subset | # images") + print(" ------------------------------") + print(" train | {:8d}".format(num_train)) + print(" val | {:8d}".format(num_val)) + print(" test | {:8d}".format(num_test)) + print(" ------------------------------") + print(" total | {:8d}".format(num_total)) + print(" ------------------------------") + print(" # attributes: {}".format(len(self.attr_dict))) + print(" attributes:") + for label, attr in self.attr_dict.items(): + print(' {:3d}: {}'.format(label, attr)) + print(" ------------------------------") diff --git a/strong_sort/deep/reid/projects/attribute_recognition/datasets/pa100k.py b/strong_sort/deep/reid/projects/attribute_recognition/datasets/pa100k.py new file mode 100644 index 0000000000000000000000000000000000000000..61dd26cf54eef209e3ee3a8081802a0da8a77f66 --- /dev/null +++ b/strong_sort/deep/reid/projects/attribute_recognition/datasets/pa100k.py @@ -0,0 +1,59 @@ +from __future__ import division, print_function, absolute_import +import numpy as np +import os.path as osp +from scipy.io import loadmat + +from .dataset import Dataset + + +class PA100K(Dataset): + """Pedestrian attribute dataset. + + 80k training images + 20k test images. + + The folder structure should be: + pa100k/ + data/ # images + annotation/ + annotation.mat + """ + dataset_dir = 'pa100k' + + def __init__(self, root='', **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.data_dir = osp.join(self.dataset_dir, 'data') + self.anno_mat_path = osp.join( + self.dataset_dir, 'annotation', 'annotation.mat' + ) + + required_files = [self.data_dir, self.anno_mat_path] + self.check_before_run(required_files) + + train, val, test, attr_dict = self.extract_data() + super(PA100K, self).__init__(train, val, test, attr_dict, **kwargs) + + def extract_data(self): + # anno_mat is a dictionary with keys: ['test_images_name', 'val_images_name', + # 'train_images_name', 'val_label', 'attributes', 'test_label', 'train_label'] + anno_mat = loadmat(self.anno_mat_path) + + def _extract(key_name, key_label): + names = anno_mat[key_name] + labels = anno_mat[key_label] + num_imgs = names.shape[0] + data = [] + for i in range(num_imgs): + name = names[i, 0][0] + attrs = labels[i, :].astype(np.float32) + img_path = osp.join(self.data_dir, name) + data.append((img_path, attrs)) + return data + + train = _extract('train_images_name', 'train_label') + val = _extract('val_images_name', 'val_label') + test = _extract('test_images_name', 'test_label') + attrs = anno_mat['attributes'] + attr_dict = {i: str(attr[0][0]) for i, attr in enumerate(attrs)} + + return train, val, test, attr_dict diff --git a/strong_sort/deep/reid/projects/attribute_recognition/default_parser.py b/strong_sort/deep/reid/projects/attribute_recognition/default_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..d19a8be9716455b15d5fdffe6b99f9a3c3d8c209 --- /dev/null +++ b/strong_sort/deep/reid/projects/attribute_recognition/default_parser.py @@ -0,0 +1,243 @@ +from __future__ import print_function, absolute_import +import argparse + + +def init_parser(): + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter + ) + + # ************************************************************ + # Datasets + # ************************************************************ + parser.add_argument( + '--root', + type=str, + default='', + required=True, + help='root path to data directory' + ) + parser.add_argument( + '-d', + '--dataset', + type=str, + required=True, + help='which dataset to choose' + ) + parser.add_argument( + '-j', + '--workers', + type=int, + default=4, + help='number of data loading workers (tips: 4 or 8 times number of gpus)' + ) + parser.add_argument( + '--height', type=int, default=256, help='height of an image' + ) + parser.add_argument( + '--width', type=int, default=128, help='width of an image' + ) + + # ************************************************************ + # Optimization options + # ************************************************************ + parser.add_argument( + '--optim', + type=str, + default='adam', + help='optimization algorithm (see optimizers.py)' + ) + parser.add_argument( + '--lr', type=float, default=0.0003, help='initial learning rate' + ) + parser.add_argument( + '--weight-decay', type=float, default=5e-04, help='weight decay' + ) + # sgd + parser.add_argument( + '--momentum', + type=float, + default=0.9, + help='momentum factor for sgd and rmsprop' + ) + parser.add_argument( + '--sgd-dampening', + type=float, + default=0, + help='sgd\'s dampening for momentum' + ) + parser.add_argument( + '--sgd-nesterov', + action='store_true', + help='whether to enable sgd\'s Nesterov momentum' + ) + # rmsprop + parser.add_argument( + '--rmsprop-alpha', + type=float, + default=0.99, + help='rmsprop\'s smoothing constant' + ) + # adam/amsgrad + parser.add_argument( + '--adam-beta1', + type=float, + default=0.9, + help='exponential decay rate for adam\'s first moment' + ) + parser.add_argument( + '--adam-beta2', + type=float, + default=0.999, + help='exponential decay rate for adam\'s second moment' + ) + + # ************************************************************ + # Training hyperparameters + # ************************************************************ + parser.add_argument( + '--max-epoch', type=int, default=60, help='maximum epochs to run' + ) + parser.add_argument( + '--start-epoch', + type=int, + default=0, + help='manual epoch number (useful when restart)' + ) + parser.add_argument( + '--batch-size', type=int, default=32, help='batch size' + ) + + parser.add_argument( + '--fixbase-epoch', + type=int, + default=0, + help='number of epochs to fix base layers' + ) + parser.add_argument( + '--open-layers', + type=str, + nargs='+', + default=['classifier'], + help='open specified layers for training while keeping others frozen' + ) + + parser.add_argument( + '--staged-lr', + action='store_true', + help='set different lr to different layers' + ) + parser.add_argument( + '--new-layers', + type=str, + nargs='+', + default=['classifier'], + help='newly added layers with default lr' + ) + parser.add_argument( + '--base-lr-mult', + type=float, + default=0.1, + help='learning rate multiplier for base layers' + ) + + # ************************************************************ + # Learning rate scheduler options + # ************************************************************ + parser.add_argument( + '--lr-scheduler', + type=str, + default='multi_step', + help='learning rate scheduler (see lr_schedulers.py)' + ) + parser.add_argument( + '--stepsize', + type=int, + default=[20, 40], + nargs='+', + help='stepsize to decay learning rate' + ) + parser.add_argument( + '--gamma', type=float, default=0.1, help='learning rate decay' + ) + + # ************************************************************ + # Architecture + # ************************************************************ + parser.add_argument( + '-a', '--arch', type=str, default='', help='model architecture' + ) + parser.add_argument( + '--no-pretrained', + action='store_true', + help='do not load pretrained weights' + ) + + # ************************************************************ + # Loss + # ************************************************************ + parser.add_argument( + '--weighted-bce', action='store_true', help='use weighted BCELoss' + ) + + # ************************************************************ + # Test settings + # ************************************************************ + parser.add_argument( + '--load-weights', type=str, default='', help='load pretrained weights' + ) + parser.add_argument( + '--evaluate', action='store_true', help='evaluate only' + ) + parser.add_argument( + '--save-prediction', action='store_true', help='save prediction' + ) + + # ************************************************************ + # Miscs + # ************************************************************ + parser.add_argument( + '--print-freq', type=int, default=20, help='print frequency' + ) + parser.add_argument('--seed', type=int, default=1, help='manual seed') + parser.add_argument( + '--resume', + type=str, + default='', + metavar='PATH', + help='resume from a checkpoint' + ) + parser.add_argument( + '--save-dir', + type=str, + default='log', + help='path to save log and model weights' + ) + parser.add_argument('--use-cpu', action='store_true', help='use cpu') + + return parser + + +def optimizer_kwargs(parsed_args): + return { + 'optim': parsed_args.optim, + 'lr': parsed_args.lr, + 'weight_decay': parsed_args.weight_decay, + 'momentum': parsed_args.momentum, + 'sgd_dampening': parsed_args.sgd_dampening, + 'sgd_nesterov': parsed_args.sgd_nesterov, + 'rmsprop_alpha': parsed_args.rmsprop_alpha, + 'adam_beta1': parsed_args.adam_beta1, + 'adam_beta2': parsed_args.adam_beta2, + 'staged_lr': parsed_args.staged_lr, + 'new_layers': parsed_args.new_layers, + 'base_lr_mult': parsed_args.base_lr_mult + } + + +def lr_scheduler_kwargs(parsed_args): + return { + 'lr_scheduler': parsed_args.lr_scheduler, + 'stepsize': parsed_args.stepsize, + 'gamma': parsed_args.gamma + } diff --git a/strong_sort/deep/reid/projects/attribute_recognition/main.py b/strong_sort/deep/reid/projects/attribute_recognition/main.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb423802f4c1ee5632a2e5191a5da769ccce079 --- /dev/null +++ b/strong_sort/deep/reid/projects/attribute_recognition/main.py @@ -0,0 +1,399 @@ +from __future__ import division, print_function +import sys +import copy +import time +import numpy as np +import os.path as osp +import datetime +import warnings +import torch +import torch.nn as nn + +import torchreid +from torchreid.utils import ( + Logger, AverageMeter, check_isfile, open_all_layers, save_checkpoint, + set_random_seed, collect_env_info, open_specified_layers, + load_pretrained_weights, compute_model_complexity +) +from torchreid.data.transforms import ( + Resize, Compose, ToTensor, Normalize, Random2DTranslation, + RandomHorizontalFlip +) + +import models +import datasets +from default_parser import init_parser, optimizer_kwargs, lr_scheduler_kwargs + +parser = init_parser() +args = parser.parse_args() + + +def init_dataset(use_gpu): + normalize = Normalize( + mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] + ) + + transform_tr = Compose( + [ + Random2DTranslation(args.height, args.width, p=0.5), + RandomHorizontalFlip(), + ToTensor(), normalize + ] + ) + + transform_te = Compose( + [Resize([args.height, args.width]), + ToTensor(), normalize] + ) + + trainset = datasets.init_dataset( + args.dataset, + root=args.root, + transform=transform_tr, + mode='train', + verbose=True + ) + + valset = datasets.init_dataset( + args.dataset, + root=args.root, + transform=transform_te, + mode='val', + verbose=False + ) + + testset = datasets.init_dataset( + args.dataset, + root=args.root, + transform=transform_te, + mode='test', + verbose=False + ) + + num_attrs = trainset.num_attrs + attr_dict = trainset.attr_dict + + trainloader = torch.utils.data.DataLoader( + trainset, + batch_size=args.batch_size, + shuffle=True, + num_workers=args.workers, + pin_memory=use_gpu, + drop_last=True + ) + + valloader = torch.utils.data.DataLoader( + valset, + batch_size=args.batch_size, + shuffle=False, + num_workers=args.workers, + pin_memory=use_gpu, + drop_last=False + ) + + testloader = torch.utils.data.DataLoader( + testset, + batch_size=args.batch_size, + shuffle=False, + num_workers=args.workers, + pin_memory=use_gpu, + drop_last=False + ) + + return trainloader, valloader, testloader, num_attrs, attr_dict + + +def main(): + global args + + set_random_seed(args.seed) + use_gpu = torch.cuda.is_available() and not args.use_cpu + log_name = 'test.log' if args.evaluate else 'train.log' + sys.stdout = Logger(osp.join(args.save_dir, log_name)) + + print('** Arguments **') + arg_keys = list(args.__dict__.keys()) + arg_keys.sort() + for key in arg_keys: + print('{}: {}'.format(key, args.__dict__[key])) + print('\n') + print('Collecting env info ...') + print('** System info **\n{}\n'.format(collect_env_info())) + + if use_gpu: + torch.backends.cudnn.benchmark = True + else: + warnings.warn( + 'Currently using CPU, however, GPU is highly recommended' + ) + + dataset_vars = init_dataset(use_gpu) + trainloader, valloader, testloader, num_attrs, attr_dict = dataset_vars + + if args.weighted_bce: + print('Use weighted binary cross entropy') + print('Computing the weights ...') + bce_weights = torch.zeros(num_attrs, dtype=torch.float) + for _, attrs, _ in trainloader: + bce_weights += attrs.sum(0) # sum along the batch dim + bce_weights /= len(trainloader) * args.batch_size + print('Sample ratio for each attribute: {}'.format(bce_weights)) + bce_weights = torch.exp(-1 * bce_weights) + print('BCE weights: {}'.format(bce_weights)) + bce_weights = bce_weights.expand(args.batch_size, num_attrs) + criterion = nn.BCEWithLogitsLoss(weight=bce_weights) + + else: + print('Use plain binary cross entropy') + criterion = nn.BCEWithLogitsLoss() + + print('Building model: {}'.format(args.arch)) + model = models.build_model( + args.arch, + num_attrs, + pretrained=not args.no_pretrained, + use_gpu=use_gpu + ) + num_params, flops = compute_model_complexity( + model, (1, 3, args.height, args.width) + ) + print('Model complexity: params={:,} flops={:,}'.format(num_params, flops)) + + if args.load_weights and check_isfile(args.load_weights): + load_pretrained_weights(model, args.load_weights) + + if use_gpu: + model = nn.DataParallel(model).cuda() + criterion = criterion.cuda() + + if args.evaluate: + test(model, testloader, attr_dict, use_gpu) + return + + optimizer = torchreid.optim.build_optimizer( + model, **optimizer_kwargs(args) + ) + scheduler = torchreid.optim.build_lr_scheduler( + optimizer, **lr_scheduler_kwargs(args) + ) + + start_epoch = args.start_epoch + best_result = -np.inf + if args.resume and check_isfile(args.resume): + checkpoint = torch.load(args.resume) + model.load_state_dict(checkpoint['state_dict']) + optimizer.load_state_dict(checkpoint['optimizer']) + start_epoch = checkpoint['epoch'] + best_result = checkpoint['label_mA'] + print('Loaded checkpoint from "{}"'.format(args.resume)) + print('- start epoch: {}'.format(start_epoch)) + print('- label_mA: {}'.format(best_result)) + + time_start = time.time() + + for epoch in range(start_epoch, args.max_epoch): + train( + epoch, model, criterion, optimizer, scheduler, trainloader, use_gpu + ) + test_outputs = test(model, testloader, attr_dict, use_gpu) + label_mA = test_outputs[0] + is_best = label_mA > best_result + if is_best: + best_result = label_mA + + save_checkpoint( + { + 'state_dict': model.state_dict(), + 'epoch': epoch + 1, + 'label_mA': label_mA, + 'optimizer': optimizer.state_dict(), + }, + args.save_dir, + is_best=is_best + ) + + elapsed = round(time.time() - time_start) + elapsed = str(datetime.timedelta(seconds=elapsed)) + print('Elapsed {}'.format(elapsed)) + + +def train(epoch, model, criterion, optimizer, scheduler, trainloader, use_gpu): + losses = AverageMeter() + batch_time = AverageMeter() + data_time = AverageMeter() + model.train() + + if (epoch + 1) <= args.fixbase_epoch and args.open_layers is not None: + print( + '* Only train {} (epoch: {}/{})'.format( + args.open_layers, epoch + 1, args.fixbase_epoch + ) + ) + open_specified_layers(model, args.open_layers) + else: + open_all_layers(model) + + end = time.time() + for batch_idx, data in enumerate(trainloader): + data_time.update(time.time() - end) + + imgs, attrs = data[0], data[1] + if use_gpu: + imgs = imgs.cuda() + attrs = attrs.cuda() + + optimizer.zero_grad() + outputs = model(imgs) + loss = criterion(outputs, attrs) + loss.backward() + optimizer.step() + + batch_time.update(time.time() - end) + + losses.update(loss.item(), imgs.size(0)) + + if (batch_idx+1) % args.print_freq == 0: + # estimate remaining time + num_batches = len(trainloader) + eta_seconds = batch_time.avg * ( + num_batches - (batch_idx+1) + (args.max_epoch - + (epoch+1)) * num_batches + ) + eta_str = str(datetime.timedelta(seconds=int(eta_seconds))) + print( + 'Epoch: [{0}/{1}][{2}/{3}]\t' + 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' + 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' + 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' + 'Lr {lr:.6f}\t' + 'Eta {eta}'.format( + epoch + 1, + args.max_epoch, + batch_idx + 1, + len(trainloader), + batch_time=batch_time, + data_time=data_time, + loss=losses, + lr=optimizer.param_groups[0]['lr'], + eta=eta_str + ) + ) + + end = time.time() + + scheduler.step() + + +@torch.no_grad() +def test(model, testloader, attr_dict, use_gpu): + batch_time = AverageMeter() + model.eval() + + num_persons = 0 + prob_thre = 0.5 + ins_acc = 0 + ins_prec = 0 + ins_rec = 0 + mA_history = { + 'correct_pos': 0, + 'real_pos': 0, + 'correct_neg': 0, + 'real_neg': 0 + } + + print('Testing ...') + + for batch_idx, data in enumerate(testloader): + imgs, attrs, img_paths = data + if use_gpu: + imgs = imgs.cuda() + + end = time.time() + orig_outputs = model(imgs) + batch_time.update(time.time() - end) + + orig_outputs = orig_outputs.data.cpu().numpy() + attrs = attrs.data.numpy() + + # transform raw outputs to attributes (binary codes) + outputs = copy.deepcopy(orig_outputs) + outputs[outputs < prob_thre] = 0 + outputs[outputs >= prob_thre] = 1 + + # compute label-based metric + overlaps = outputs * attrs + mA_history['correct_pos'] += overlaps.sum(0) + mA_history['real_pos'] += attrs.sum(0) + inv_overlaps = (1-outputs) * (1-attrs) + mA_history['correct_neg'] += inv_overlaps.sum(0) + mA_history['real_neg'] += (1 - attrs).sum(0) + + outputs = outputs.astype(bool) + attrs = attrs.astype(bool) + + # compute instabce-based accuracy + intersect = (outputs & attrs).astype(float) + union = (outputs | attrs).astype(float) + ins_acc += (intersect.sum(1) / union.sum(1)).sum() + ins_prec += (intersect.sum(1) / outputs.astype(float).sum(1)).sum() + ins_rec += (intersect.sum(1) / attrs.astype(float).sum(1)).sum() + + num_persons += imgs.size(0) + + if (batch_idx+1) % args.print_freq == 0: + print( + 'Processed batch {}/{}'.format(batch_idx + 1, len(testloader)) + ) + + if args.save_prediction: + txtfile = open(osp.join(args.save_dir, 'prediction.txt'), 'a') + for idx in range(imgs.size(0)): + img_path = img_paths[idx] + probs = orig_outputs[idx, :] + labels = attrs[idx, :] + txtfile.write('{}\n'.format(img_path)) + txtfile.write('*** Correct prediction ***\n') + for attr_idx, (label, prob) in enumerate(zip(labels, probs)): + if label: + attr_name = attr_dict[attr_idx] + info = '{}: {:.1%} '.format(attr_name, prob) + txtfile.write(info) + txtfile.write('\n*** Incorrect prediction ***\n') + for attr_idx, (label, prob) in enumerate(zip(labels, probs)): + if not label and prob > 0.5: + attr_name = attr_dict[attr_idx] + info = '{}: {:.1%} '.format(attr_name, prob) + txtfile.write(info) + txtfile.write('\n\n') + txtfile.close() + + print( + '=> BatchTime(s)/BatchSize(img): {:.4f}/{}'.format( + batch_time.avg, args.batch_size + ) + ) + + ins_acc /= num_persons + ins_prec /= num_persons + ins_rec /= num_persons + ins_f1 = (2*ins_prec*ins_rec) / (ins_prec+ins_rec) + + term1 = mA_history['correct_pos'] / mA_history['real_pos'] + term2 = mA_history['correct_neg'] / mA_history['real_neg'] + label_mA_verbose = (term1+term2) * 0.5 + label_mA = label_mA_verbose.mean() + + print('* Results *') + print(' # test persons: {}'.format(num_persons)) + print(' (instance-based) accuracy: {:.1%}'.format(ins_acc)) + print(' (instance-based) precition: {:.1%}'.format(ins_prec)) + print(' (instance-based) recall: {:.1%}'.format(ins_rec)) + print(' (instance-based) f1-score: {:.1%}'.format(ins_f1)) + print(' (label-based) mean accuracy: {:.1%}'.format(label_mA)) + print(' mA for each attribute: {}'.format(label_mA_verbose)) + + return label_mA, ins_acc, ins_prec, ins_rec, ins_f1 + + +if __name__ == '__main__': + main() diff --git a/strong_sort/deep/reid/projects/attribute_recognition/models/__init__.py b/strong_sort/deep/reid/projects/attribute_recognition/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff0f0eda86c5cbc8b045a3d8469dbc7ba5a1ffcf --- /dev/null +++ b/strong_sort/deep/reid/projects/attribute_recognition/models/__init__.py @@ -0,0 +1,17 @@ +from __future__ import absolute_import + +from .osnet import * + +__model_factory = { + 'osnet_avgpool': osnet_avgpool, + 'osnet_maxpool': osnet_maxpool +} + + +def build_model(name, num_classes, pretrained=True, use_gpu=True): + avai_models = list(__model_factory.keys()) + if name not in avai_models: + raise KeyError + return __model_factory[name]( + num_classes=num_classes, pretrained=pretrained, use_gpu=use_gpu + ) diff --git a/strong_sort/deep/reid/projects/attribute_recognition/models/osnet.py b/strong_sort/deep/reid/projects/attribute_recognition/models/osnet.py new file mode 100644 index 0000000000000000000000000000000000000000..12569da08eb3c7e5c99abd3100e94b01e7924189 --- /dev/null +++ b/strong_sort/deep/reid/projects/attribute_recognition/models/osnet.py @@ -0,0 +1,414 @@ +from __future__ import division, absolute_import +import torch +from torch import nn +from torch.nn import functional as F + +__all__ = ['osnet_avgpool', 'osnet_maxpool'] + + +########## +# Basic layers +########## +class ConvLayer(nn.Module): + """Convolution layer.""" + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + groups=1 + ): + super(ConvLayer, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + +class Conv1x1(nn.Module): + """1x1 convolution.""" + + def __init__(self, in_channels, out_channels, stride=1, groups=1): + super(Conv1x1, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 1, + stride=stride, + padding=0, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + +class Conv1x1Linear(nn.Module): + """1x1 convolution without non-linearity.""" + + def __init__(self, in_channels, out_channels, stride=1): + super(Conv1x1Linear, self).__init__() + self.conv = nn.Conv2d( + in_channels, out_channels, 1, stride=stride, padding=0, bias=False + ) + self.bn = nn.BatchNorm2d(out_channels) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return x + + +class Conv3x3(nn.Module): + """3x3 convolution.""" + + def __init__(self, in_channels, out_channels, stride=1, groups=1): + super(Conv3x3, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 3, + stride=stride, + padding=1, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + +class LightConv3x3(nn.Module): + """Lightweight 3x3 convolution. + + 1x1 (linear) + dw 3x3 (nonlinear). + """ + + def __init__(self, in_channels, out_channels): + super(LightConv3x3, self).__init__() + self.conv1 = nn.Conv2d( + in_channels, out_channels, 1, stride=1, padding=0, bias=False + ) + self.conv2 = nn.Conv2d( + out_channels, + out_channels, + 3, + stride=1, + padding=1, + bias=False, + groups=out_channels + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv1(x) + x = self.conv2(x) + x = self.bn(x) + x = self.relu(x) + return x + + +########## +# Building blocks for omni-scale feature learning +########## +class ChannelGate(nn.Module): + """A mini-network that generates channel-wise gates conditioned on input.""" + + def __init__( + self, + in_channels, + num_gates=None, + return_gates=False, + gate_activation='sigmoid', + reduction=16, + layer_norm=False + ): + super(ChannelGate, self).__init__() + if num_gates is None: + num_gates = in_channels + self.return_gates = return_gates + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.fc1 = nn.Conv2d( + in_channels, + in_channels // reduction, + kernel_size=1, + bias=True, + padding=0 + ) + self.norm1 = None + if layer_norm: + self.norm1 = nn.LayerNorm((in_channels // reduction, 1, 1)) + self.relu = nn.ReLU(inplace=True) + self.fc2 = nn.Conv2d( + in_channels // reduction, + num_gates, + kernel_size=1, + bias=True, + padding=0 + ) + if gate_activation == 'sigmoid': + self.gate_activation = nn.Sigmoid() + elif gate_activation == 'relu': + self.gate_activation = nn.ReLU(inplace=True) + elif gate_activation == 'linear': + self.gate_activation = None + else: + raise RuntimeError( + "Unknown gate activation: {}".format(gate_activation) + ) + + def forward(self, x): + input = x + x = self.global_avgpool(x) + x = self.fc1(x) + if self.norm1 is not None: + x = self.norm1(x) + x = self.relu(x) + x = self.fc2(x) + if self.gate_activation is not None: + x = self.gate_activation(x) + if self.return_gates: + return x + return input * x + + +class OSBlock(nn.Module): + """Omni-scale feature learning block.""" + + def __init__(self, in_channels, out_channels, **kwargs): + super(OSBlock, self).__init__() + mid_channels = out_channels // 4 + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2a = LightConv3x3(mid_channels, mid_channels) + self.conv2b = nn.Sequential( + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + ) + self.conv2c = nn.Sequential( + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + ) + self.conv2d = nn.Sequential( + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + ) + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + + def forward(self, x): + residual = x + x1 = self.conv1(x) + x2a = self.conv2a(x1) + x2b = self.conv2b(x1) + x2c = self.conv2c(x1) + x2d = self.conv2d(x1) + x2 = self.gate(x2a) + self.gate(x2b) + self.gate(x2c) + self.gate(x2d) + x3 = self.conv3(x2) + if self.downsample is not None: + residual = self.downsample(residual) + out = x3 + residual + return F.relu(out) + + +########## +# Network architecture +########## +class BaseNet(nn.Module): + + def _make_layer( + self, block, layer, in_channels, out_channels, reduce_spatial_size + ): + layers = [] + + layers.append(block(in_channels, out_channels)) + for i in range(1, layer): + layers.append(block(out_channels, out_channels)) + + if reduce_spatial_size: + layers.append( + nn.Sequential( + Conv1x1(out_channels, out_channels), + nn.AvgPool2d(2, stride=2) + ) + ) + + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + if fc_dims is None or fc_dims < 0: + self.feature_dim = input_dim + return None + + if isinstance(fc_dims, int): + fc_dims = [fc_dims] + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + +class OSNet(BaseNet): + + def __init__( + self, + num_classes, + blocks, + layers, + channels, + feature_dim=512, + loss='softmax', + pool='avg', + **kwargs + ): + super(OSNet, self).__init__() + num_blocks = len(blocks) + assert num_blocks == len(layers) + assert num_blocks == len(channels) - 1 + self.loss = loss + + # convolutional backbone + self.conv1 = ConvLayer(3, channels[0], 7, stride=2, padding=3) + self.maxpool = nn.MaxPool2d(3, stride=2, padding=1) + self.conv2 = self._make_layer( + blocks[0], + layers[0], + channels[0], + channels[1], + reduce_spatial_size=True + ) + self.conv3 = self._make_layer( + blocks[1], + layers[1], + channels[1], + channels[2], + reduce_spatial_size=True + ) + self.conv4 = self._make_layer( + blocks[2], + layers[2], + channels[2], + channels[3], + reduce_spatial_size=False + ) + self.conv5 = Conv1x1(channels[3], channels[3]) + if pool == 'avg': + self.global_pool = nn.AdaptiveAvgPool2d(1) + else: + self.global_pool = nn.AdaptiveMaxPool2d(1) + # fully connected layer + self.fc = self._construct_fc_layer( + feature_dim, channels[3], dropout_p=None + ) + # classification layer + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self.init_params() + + def featuremaps(self, x): + x = self.conv1(x) + x = self.maxpool(x) + x = self.conv2(x) + x = self.conv3(x) + x = self.conv4(x) + x = self.conv5(x) + return x + + def forward(self, x): + x = self.featuremaps(x) + v = self.global_pool(x) + v = v.view(v.size(0), -1) + if self.fc is not None: + v = self.fc(v) + y = self.classifier(v) + if not self.training: + y = torch.sigmoid(y) + return y + + +def osnet_avgpool(num_classes=1000, loss='softmax', **kwargs): + return OSNet( + num_classes, + blocks=[OSBlock, OSBlock, OSBlock], + layers=[2, 2, 2], + channels=[64, 256, 384, 512], + loss=loss, + pool='avg', + **kwargs + ) + + +def osnet_maxpool(num_classes=1000, loss='softmax', **kwargs): + return OSNet( + num_classes, + blocks=[OSBlock, OSBlock, OSBlock], + layers=[2, 2, 2], + channels=[64, 256, 384, 512], + loss=loss, + pool='max', + **kwargs + ) diff --git a/strong_sort/deep/reid/projects/attribute_recognition/train.sh b/strong_sort/deep/reid/projects/attribute_recognition/train.sh new file mode 100644 index 0000000000000000000000000000000000000000..9080a66786671b6bf869a5ed3ed574432acf7fb7 --- /dev/null +++ b/strong_sort/deep/reid/projects/attribute_recognition/train.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# DATASET points to the directory containing pa100k/ +DATASET=$1 + +python main.py \ +--root ${DATASET} \ +-d pa100k \ +-a osnet_maxpool \ +--max-epoch 50 \ +--stepsize 30 40 \ +--batch-size 32 \ +--lr 0.065 \ +--optim sgd \ +--weighted-bce \ +--save-dir log/pa100k-osnet_maxpool \ No newline at end of file diff --git a/strong_sort/deep/reid/scripts/default_config.py b/strong_sort/deep/reid/scripts/default_config.py new file mode 100644 index 0000000000000000000000000000000000000000..da448e3637521786d56482c4fa30f47f7c7f26cf --- /dev/null +++ b/strong_sort/deep/reid/scripts/default_config.py @@ -0,0 +1,212 @@ +from yacs.config import CfgNode as CN + + +def get_default_config(): + cfg = CN() + + # model + cfg.model = CN() + cfg.model.name = 'resnet50' + cfg.model.pretrained = True # automatically load pretrained model weights if available + cfg.model.load_weights = '' # path to model weights + cfg.model.resume = '' # path to checkpoint for resume training + + # data + cfg.data = CN() + cfg.data.type = 'image' + cfg.data.root = 'reid-data' + cfg.data.sources = ['market1501'] + cfg.data.targets = ['market1501'] + cfg.data.workers = 4 # number of data loading workers + cfg.data.split_id = 0 # split index + cfg.data.height = 256 # image height + cfg.data.width = 128 # image width + cfg.data.combineall = False # combine train, query and gallery for training + cfg.data.transforms = ['random_flip'] # data augmentation + cfg.data.k_tfm = 1 # number of times to apply augmentation to an image independently + cfg.data.norm_mean = [0.485, 0.456, 0.406] # default is imagenet mean + cfg.data.norm_std = [0.229, 0.224, 0.225] # default is imagenet std + cfg.data.save_dir = 'log' # path to save log + cfg.data.load_train_targets = False # load training set from target dataset + + # specific datasets + cfg.market1501 = CN() + cfg.market1501.use_500k_distractors = False # add 500k distractors to the gallery set for market1501 + cfg.cuhk03 = CN() + cfg.cuhk03.labeled_images = False # use labeled images, if False, use detected images + cfg.cuhk03.classic_split = False # use classic split by Li et al. CVPR14 + cfg.cuhk03.use_metric_cuhk03 = False # use cuhk03's metric for evaluation + + # sampler + cfg.sampler = CN() + cfg.sampler.train_sampler = 'RandomSampler' # sampler for source train loader + cfg.sampler.train_sampler_t = 'RandomSampler' # sampler for target train loader + cfg.sampler.num_instances = 4 # number of instances per identity for RandomIdentitySampler + cfg.sampler.num_cams = 1 # number of cameras to sample in a batch (for RandomDomainSampler) + cfg.sampler.num_datasets = 1 # number of datasets to sample in a batch (for RandomDatasetSampler) + + # video reid setting + cfg.video = CN() + cfg.video.seq_len = 15 # number of images to sample in a tracklet + cfg.video.sample_method = 'evenly' # how to sample images from a tracklet + cfg.video.pooling_method = 'avg' # how to pool features over a tracklet + + # train + cfg.train = CN() + cfg.train.optim = 'adam' + cfg.train.lr = 0.0003 + cfg.train.weight_decay = 5e-4 + cfg.train.max_epoch = 60 + cfg.train.start_epoch = 0 + cfg.train.batch_size = 32 + cfg.train.fixbase_epoch = 0 # number of epochs to fix base layers + cfg.train.open_layers = [ + 'classifier' + ] # layers for training while keeping others frozen + cfg.train.staged_lr = False # set different lr to different layers + cfg.train.new_layers = ['classifier'] # newly added layers with default lr + cfg.train.base_lr_mult = 0.1 # learning rate multiplier for base layers + cfg.train.lr_scheduler = 'single_step' + cfg.train.stepsize = [20] # stepsize to decay learning rate + cfg.train.gamma = 0.1 # learning rate decay multiplier + cfg.train.print_freq = 20 # print frequency + cfg.train.seed = 1 # random seed + + # optimizer + cfg.sgd = CN() + cfg.sgd.momentum = 0.9 # momentum factor for sgd and rmsprop + cfg.sgd.dampening = 0. # dampening for momentum + cfg.sgd.nesterov = False # Nesterov momentum + cfg.rmsprop = CN() + cfg.rmsprop.alpha = 0.99 # smoothing constant + cfg.adam = CN() + cfg.adam.beta1 = 0.9 # exponential decay rate for first moment + cfg.adam.beta2 = 0.999 # exponential decay rate for second moment + + # loss + cfg.loss = CN() + cfg.loss.name = 'softmax' + cfg.loss.softmax = CN() + cfg.loss.softmax.label_smooth = True # use label smoothing regularizer + cfg.loss.triplet = CN() + cfg.loss.triplet.margin = 0.3 # distance margin + cfg.loss.triplet.weight_t = 1. # weight to balance hard triplet loss + cfg.loss.triplet.weight_x = 0. # weight to balance cross entropy loss + + # test + cfg.test = CN() + cfg.test.batch_size = 100 + cfg.test.dist_metric = 'euclidean' # distance metric, ['euclidean', 'cosine'] + cfg.test.normalize_feature = False # normalize feature vectors before computing distance + cfg.test.ranks = [1, 5, 10, 20] # cmc ranks + cfg.test.evaluate = False # test only + cfg.test.eval_freq = -1 # evaluation frequency (-1 means to only test after training) + cfg.test.start_eval = 0 # start to evaluate after a specific epoch + cfg.test.rerank = False # use person re-ranking + cfg.test.visrank = False # visualize ranked results (only available when cfg.test.evaluate=True) + cfg.test.visrank_topk = 10 # top-k ranks to visualize + + return cfg + + +def imagedata_kwargs(cfg): + return { + 'root': cfg.data.root, + 'sources': cfg.data.sources, + 'targets': cfg.data.targets, + 'height': cfg.data.height, + 'width': cfg.data.width, + 'transforms': cfg.data.transforms, + 'k_tfm': cfg.data.k_tfm, + 'norm_mean': cfg.data.norm_mean, + 'norm_std': cfg.data.norm_std, + 'use_gpu': cfg.use_gpu, + 'split_id': cfg.data.split_id, + 'combineall': cfg.data.combineall, + 'load_train_targets': cfg.data.load_train_targets, + 'batch_size_train': cfg.train.batch_size, + 'batch_size_test': cfg.test.batch_size, + 'workers': cfg.data.workers, + 'num_instances': cfg.sampler.num_instances, + 'num_cams': cfg.sampler.num_cams, + 'num_datasets': cfg.sampler.num_datasets, + 'train_sampler': cfg.sampler.train_sampler, + 'train_sampler_t': cfg.sampler.train_sampler_t, + # image dataset specific + 'cuhk03_labeled': cfg.cuhk03.labeled_images, + 'cuhk03_classic_split': cfg.cuhk03.classic_split, + 'market1501_500k': cfg.market1501.use_500k_distractors, + } + + +def videodata_kwargs(cfg): + return { + 'root': cfg.data.root, + 'sources': cfg.data.sources, + 'targets': cfg.data.targets, + 'height': cfg.data.height, + 'width': cfg.data.width, + 'transforms': cfg.data.transforms, + 'norm_mean': cfg.data.norm_mean, + 'norm_std': cfg.data.norm_std, + 'use_gpu': cfg.use_gpu, + 'split_id': cfg.data.split_id, + 'combineall': cfg.data.combineall, + 'batch_size_train': cfg.train.batch_size, + 'batch_size_test': cfg.test.batch_size, + 'workers': cfg.data.workers, + 'num_instances': cfg.sampler.num_instances, + 'num_cams': cfg.sampler.num_cams, + 'num_datasets': cfg.sampler.num_datasets, + 'train_sampler': cfg.sampler.train_sampler, + # video dataset specific + 'seq_len': cfg.video.seq_len, + 'sample_method': cfg.video.sample_method + } + + +def optimizer_kwargs(cfg): + return { + 'optim': cfg.train.optim, + 'lr': cfg.train.lr, + 'weight_decay': cfg.train.weight_decay, + 'momentum': cfg.sgd.momentum, + 'sgd_dampening': cfg.sgd.dampening, + 'sgd_nesterov': cfg.sgd.nesterov, + 'rmsprop_alpha': cfg.rmsprop.alpha, + 'adam_beta1': cfg.adam.beta1, + 'adam_beta2': cfg.adam.beta2, + 'staged_lr': cfg.train.staged_lr, + 'new_layers': cfg.train.new_layers, + 'base_lr_mult': cfg.train.base_lr_mult + } + + +def lr_scheduler_kwargs(cfg): + return { + 'lr_scheduler': cfg.train.lr_scheduler, + 'stepsize': cfg.train.stepsize, + 'gamma': cfg.train.gamma, + 'max_epoch': cfg.train.max_epoch + } + + +def engine_run_kwargs(cfg): + return { + 'save_dir': cfg.data.save_dir, + 'max_epoch': cfg.train.max_epoch, + 'start_epoch': cfg.train.start_epoch, + 'fixbase_epoch': cfg.train.fixbase_epoch, + 'open_layers': cfg.train.open_layers, + 'start_eval': cfg.test.start_eval, + 'eval_freq': cfg.test.eval_freq, + 'test_only': cfg.test.evaluate, + 'print_freq': cfg.train.print_freq, + 'dist_metric': cfg.test.dist_metric, + 'normalize_feature': cfg.test.normalize_feature, + 'visrank': cfg.test.visrank, + 'visrank_topk': cfg.test.visrank_topk, + 'use_metric_cuhk03': cfg.cuhk03.use_metric_cuhk03, + 'ranks': cfg.test.ranks, + 'rerank': cfg.test.rerank + } diff --git a/strong_sort/deep/reid/scripts/main.py b/strong_sort/deep/reid/scripts/main.py new file mode 100644 index 0000000000000000000000000000000000000000..61aa49ddd3cb8ba9c9bf1e4c281b765b8d971c10 --- /dev/null +++ b/strong_sort/deep/reid/scripts/main.py @@ -0,0 +1,191 @@ +import sys +import time +import os.path as osp +import argparse +import torch +import torch.nn as nn + +import torchreid +from torchreid.utils import ( + Logger, check_isfile, set_random_seed, collect_env_info, + resume_from_checkpoint, load_pretrained_weights, compute_model_complexity +) + +from default_config import ( + imagedata_kwargs, optimizer_kwargs, videodata_kwargs, engine_run_kwargs, + get_default_config, lr_scheduler_kwargs +) + + +def build_datamanager(cfg): + if cfg.data.type == 'image': + return torchreid.data.ImageDataManager(**imagedata_kwargs(cfg)) + else: + return torchreid.data.VideoDataManager(**videodata_kwargs(cfg)) + + +def build_engine(cfg, datamanager, model, optimizer, scheduler): + if cfg.data.type == 'image': + if cfg.loss.name == 'softmax': + engine = torchreid.engine.ImageSoftmaxEngine( + datamanager, + model, + optimizer=optimizer, + scheduler=scheduler, + use_gpu=cfg.use_gpu, + label_smooth=cfg.loss.softmax.label_smooth + ) + + else: + engine = torchreid.engine.ImageTripletEngine( + datamanager, + model, + optimizer=optimizer, + margin=cfg.loss.triplet.margin, + weight_t=cfg.loss.triplet.weight_t, + weight_x=cfg.loss.triplet.weight_x, + scheduler=scheduler, + use_gpu=cfg.use_gpu, + label_smooth=cfg.loss.softmax.label_smooth + ) + + else: + if cfg.loss.name == 'softmax': + engine = torchreid.engine.VideoSoftmaxEngine( + datamanager, + model, + optimizer=optimizer, + scheduler=scheduler, + use_gpu=cfg.use_gpu, + label_smooth=cfg.loss.softmax.label_smooth, + pooling_method=cfg.video.pooling_method + ) + + else: + engine = torchreid.engine.VideoTripletEngine( + datamanager, + model, + optimizer=optimizer, + margin=cfg.loss.triplet.margin, + weight_t=cfg.loss.triplet.weight_t, + weight_x=cfg.loss.triplet.weight_x, + scheduler=scheduler, + use_gpu=cfg.use_gpu, + label_smooth=cfg.loss.softmax.label_smooth + ) + + return engine + + +def reset_config(cfg, args): + if args.root: + cfg.data.root = args.root + if args.sources: + cfg.data.sources = args.sources + if args.targets: + cfg.data.targets = args.targets + if args.transforms: + cfg.data.transforms = args.transforms + + +def check_cfg(cfg): + if cfg.loss.name == 'triplet' and cfg.loss.triplet.weight_x == 0: + assert cfg.train.fixbase_epoch == 0, \ + 'The output of classifier is not included in the computational graph' + + +def main(): + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter + ) + parser.add_argument( + '--config-file', type=str, default='', help='path to config file' + ) + parser.add_argument( + '-s', + '--sources', + type=str, + nargs='+', + help='source datasets (delimited by space)' + ) + parser.add_argument( + '-t', + '--targets', + type=str, + nargs='+', + help='target datasets (delimited by space)' + ) + parser.add_argument( + '--transforms', type=str, nargs='+', help='data augmentation' + ) + parser.add_argument( + '--root', type=str, default='', help='path to data root' + ) + parser.add_argument( + 'opts', + default=None, + nargs=argparse.REMAINDER, + help='Modify config options using the command-line' + ) + args = parser.parse_args() + + cfg = get_default_config() + cfg.use_gpu = torch.cuda.is_available() + if args.config_file: + cfg.merge_from_file(args.config_file) + reset_config(cfg, args) + cfg.merge_from_list(args.opts) + set_random_seed(cfg.train.seed) + check_cfg(cfg) + + log_name = 'test.log' if cfg.test.evaluate else 'train.log' + log_name += time.strftime('-%Y-%m-%d-%H-%M-%S') + sys.stdout = Logger(osp.join(cfg.data.save_dir, log_name)) + + print('Show configuration\n{}\n'.format(cfg)) + print('Collecting env info ...') + print('** System info **\n{}\n'.format(collect_env_info())) + + if cfg.use_gpu: + torch.backends.cudnn.benchmark = True + + datamanager = build_datamanager(cfg) + + print('Building model: {}'.format(cfg.model.name)) + model = torchreid.models.build_model( + name=cfg.model.name, + num_classes=datamanager.num_train_pids, + loss=cfg.loss.name, + pretrained=cfg.model.pretrained, + use_gpu=cfg.use_gpu + ) + num_params, flops = compute_model_complexity( + model, (1, 3, cfg.data.height, cfg.data.width) + ) + print('Model complexity: params={:,} flops={:,}'.format(num_params, flops)) + + if cfg.model.load_weights and check_isfile(cfg.model.load_weights): + load_pretrained_weights(model, cfg.model.load_weights) + + if cfg.use_gpu: + model = nn.DataParallel(model).cuda() + + optimizer = torchreid.optim.build_optimizer(model, **optimizer_kwargs(cfg)) + scheduler = torchreid.optim.build_lr_scheduler( + optimizer, **lr_scheduler_kwargs(cfg) + ) + + if cfg.model.resume and check_isfile(cfg.model.resume): + cfg.train.start_epoch = resume_from_checkpoint( + cfg.model.resume, model, optimizer=optimizer, scheduler=scheduler + ) + + print( + 'Building {}-engine for {}-reid'.format(cfg.loss.name, cfg.data.type) + ) + engine = build_engine(cfg, datamanager, model, optimizer, scheduler) + engine.run(**engine_run_kwargs(cfg)) + + +if __name__ == '__main__': + main() diff --git a/strong_sort/deep/reid/setup.py b/strong_sort/deep/reid/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..a8ee83e8fa28b7bfbde1ed817d1bb2c4f57c33f3 --- /dev/null +++ b/strong_sort/deep/reid/setup.py @@ -0,0 +1,57 @@ +import numpy as np +import os.path as osp +from setuptools import setup, find_packages +from distutils.extension import Extension +from Cython.Build import cythonize + + +def readme(): + with open('README.rst') as f: + content = f.read() + return content + + +def find_version(): + version_file = 'torchreid/__init__.py' + with open(version_file, 'r') as f: + exec(compile(f.read(), version_file, 'exec')) + return locals()['__version__'] + + +def numpy_include(): + try: + numpy_include = np.get_include() + except AttributeError: + numpy_include = np.get_numpy_include() + return numpy_include + + +ext_modules = [ + Extension( + 'torchreid.metrics.rank_cylib.rank_cy', + ['torchreid/metrics/rank_cylib/rank_cy.pyx'], + include_dirs=[numpy_include()], + ) +] + + +def get_requirements(filename='requirements.txt'): + here = osp.dirname(osp.realpath(__file__)) + with open(osp.join(here, filename), 'r') as f: + requires = [line.replace('\n', '') for line in f.readlines()] + return requires + + +setup( + name='torchreid', + version=find_version(), + description='A library for deep learning person re-ID in PyTorch', + author='Kaiyang Zhou', + license='MIT', + long_description=readme(), + url='https://github.com/KaiyangZhou/deep-person-reid', + packages=find_packages(), + install_requires=get_requirements(), + keywords=['Person Re-Identification', 'Deep Learning', 'Computer Vision'], + ext_modules=cythonize(ext_modules) +) diff --git a/strong_sort/deep/reid/tools/compute_mean_std.py b/strong_sort/deep/reid/tools/compute_mean_std.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a5dbe8dfa746c164b951908fb0b105e4cadbfc --- /dev/null +++ b/strong_sort/deep/reid/tools/compute_mean_std.py @@ -0,0 +1,59 @@ +""" +Compute channel-wise mean and standard deviation of a dataset. + +Usage: +$ python compute_mean_std.py DATASET_ROOT DATASET_KEY + +- The first argument points to the root path where you put the datasets. +- The second argument means the specific dataset key. + +For instance, your datasets are put under $DATA and you wanna +compute the statistics of Market1501, do +$ python compute_mean_std.py $DATA market1501 +""" +import argparse + +import torchreid + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('root', type=str) + parser.add_argument('sources', type=str) + args = parser.parse_args() + + datamanager = torchreid.data.ImageDataManager( + root=args.root, + sources=args.sources, + targets=None, + height=256, + width=128, + batch_size_train=100, + batch_size_test=100, + transforms=None, + norm_mean=[0., 0., 0.], + norm_std=[1., 1., 1.], + train_sampler='SequentialSampler' + ) + train_loader = datamanager.train_loader + + print('Computing mean and std ...') + mean = 0. + std = 0. + n_samples = 0. + for data in train_loader: + data = data['img'] + batch_size = data.size(0) + data = data.view(batch_size, data.size(1), -1) + mean += data.mean(2).sum(0) + std += data.std(2).sum(0) + n_samples += batch_size + + mean /= n_samples + std /= n_samples + print('Mean: {}'.format(mean)) + print('Std: {}'.format(std)) + + +if __name__ == '__main__': + main() diff --git a/strong_sort/deep/reid/tools/parse_test_res.py b/strong_sort/deep/reid/tools/parse_test_res.py new file mode 100644 index 0000000000000000000000000000000000000000..fd5b0189d4ef130b0e772d483cf4c1e5643dff06 --- /dev/null +++ b/strong_sort/deep/reid/tools/parse_test_res.py @@ -0,0 +1,103 @@ +""" +This script aims to automate the process of calculating average results +stored in the test.log files over multiple splits. + +How to use: +For example, you have done evaluation over 20 splits on VIPeR, leading to +the following file structure + +log/ + eval_viper/ + split_0/ + test.log-xxxx + split_1/ + test.log-xxxx + split_2/ + test.log-xxxx + ... + +You can run the following command in your terminal to get the average performance: +$ python tools/parse_test_res.py log/eval_viper +""" +import os +import re +import glob +import numpy as np +import argparse +from collections import defaultdict + +from torchreid.utils import check_isfile, listdir_nohidden + + +def parse_file(filepath, regex_mAP, regex_r1, regex_r5, regex_r10, regex_r20): + results = {} + + with open(filepath, 'r') as f: + lines = f.readlines() + + for line in lines: + line = line.strip() + + match_mAP = regex_mAP.search(line) + if match_mAP: + mAP = float(match_mAP.group(1)) + results['mAP'] = mAP + + match_r1 = regex_r1.search(line) + if match_r1: + r1 = float(match_r1.group(1)) + results['r1'] = r1 + + match_r5 = regex_r5.search(line) + if match_r5: + r5 = float(match_r5.group(1)) + results['r5'] = r5 + + match_r10 = regex_r10.search(line) + if match_r10: + r10 = float(match_r10.group(1)) + results['r10'] = r10 + + match_r20 = regex_r20.search(line) + if match_r20: + r20 = float(match_r20.group(1)) + results['r20'] = r20 + + return results + + +def main(args): + regex_mAP = re.compile(r'mAP: ([\.\deE+-]+)%') + regex_r1 = re.compile(r'Rank-1 : ([\.\deE+-]+)%') + regex_r5 = re.compile(r'Rank-5 : ([\.\deE+-]+)%') + regex_r10 = re.compile(r'Rank-10 : ([\.\deE+-]+)%') + regex_r20 = re.compile(r'Rank-20 : ([\.\deE+-]+)%') + + final_res = defaultdict(list) + + directories = listdir_nohidden(args.directory, sort=True) + num_dirs = len(directories) + for directory in directories: + fullpath = os.path.join(args.directory, directory) + filepath = glob.glob(os.path.join(fullpath, 'test.log*'))[0] + check_isfile(filepath) + print(f'Parsing {filepath}') + res = parse_file( + filepath, regex_mAP, regex_r1, regex_r5, regex_r10, regex_r20 + ) + for key, value in res.items(): + final_res[key].append(value) + + print('Finished parsing') + print(f'The average results over {num_dirs} splits are shown below') + + for key, values in final_res.items(): + mean_val = np.mean(values) + print(f'{key}: {mean_val:.1f}') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('directory', type=str, help='Path to directory') + args = parser.parse_args() + main(args) diff --git a/strong_sort/deep/reid/tools/visualize_actmap.py b/strong_sort/deep/reid/tools/visualize_actmap.py new file mode 100644 index 0000000000000000000000000000000000000000..ae699913caf2431f96da6584b7ddc57ac6243214 --- /dev/null +++ b/strong_sort/deep/reid/tools/visualize_actmap.py @@ -0,0 +1,173 @@ +"""Visualizes CNN activation maps to see where the CNN focuses on to extract features. + +Reference: + - Zagoruyko and Komodakis. Paying more attention to attention: Improving the + performance of convolutional neural networks via attention transfer. ICLR, 2017 + - Zhou et al. Omni-Scale Feature Learning for Person Re-Identification. ICCV, 2019. +""" +import numpy as np +import os.path as osp +import argparse +import cv2 +import torch +from torch.nn import functional as F + +import torchreid +from torchreid.utils import ( + check_isfile, mkdir_if_missing, load_pretrained_weights +) + +IMAGENET_MEAN = [0.485, 0.456, 0.406] +IMAGENET_STD = [0.229, 0.224, 0.225] +GRID_SPACING = 10 + + +@torch.no_grad() +def visactmap( + model, + test_loader, + save_dir, + width, + height, + use_gpu, + img_mean=None, + img_std=None +): + if img_mean is None or img_std is None: + # use imagenet mean and std + img_mean = IMAGENET_MEAN + img_std = IMAGENET_STD + + model.eval() + + for target in list(test_loader.keys()): + data_loader = test_loader[target]['query'] # only process query images + # original images and activation maps are saved individually + actmap_dir = osp.join(save_dir, 'actmap_' + target) + mkdir_if_missing(actmap_dir) + print('Visualizing activation maps for {} ...'.format(target)) + + for batch_idx, data in enumerate(data_loader): + imgs, paths = data['img'], data['impath'] + if use_gpu: + imgs = imgs.cuda() + + # forward to get convolutional feature maps + try: + outputs = model(imgs, return_featuremaps=True) + except TypeError: + raise TypeError( + 'forward() got unexpected keyword argument "return_featuremaps". ' + 'Please add return_featuremaps as an input argument to forward(). When ' + 'return_featuremaps=True, return feature maps only.' + ) + + if outputs.dim() != 4: + raise ValueError( + 'The model output is supposed to have ' + 'shape of (b, c, h, w), i.e. 4 dimensions, but got {} dimensions. ' + 'Please make sure you set the model output at eval mode ' + 'to be the last convolutional feature maps'.format( + outputs.dim() + ) + ) + + # compute activation maps + outputs = (outputs**2).sum(1) + b, h, w = outputs.size() + outputs = outputs.view(b, h * w) + outputs = F.normalize(outputs, p=2, dim=1) + outputs = outputs.view(b, h, w) + + if use_gpu: + imgs, outputs = imgs.cpu(), outputs.cpu() + + for j in range(outputs.size(0)): + # get image name + path = paths[j] + imname = osp.basename(osp.splitext(path)[0]) + + # RGB image + img = imgs[j, ...] + for t, m, s in zip(img, img_mean, img_std): + t.mul_(s).add_(m).clamp_(0, 1) + img_np = np.uint8(np.floor(img.numpy() * 255)) + img_np = img_np.transpose((1, 2, 0)) # (c, h, w) -> (h, w, c) + + # activation map + am = outputs[j, ...].numpy() + am = cv2.resize(am, (width, height)) + am = 255 * (am - np.min(am)) / ( + np.max(am) - np.min(am) + 1e-12 + ) + am = np.uint8(np.floor(am)) + am = cv2.applyColorMap(am, cv2.COLORMAP_JET) + + # overlapped + overlapped = img_np*0.3 + am*0.7 + overlapped[overlapped > 255] = 255 + overlapped = overlapped.astype(np.uint8) + + # save images in a single figure (add white spacing between images) + # from left to right: original image, activation map, overlapped image + grid_img = 255 * np.ones( + (height, 3*width + 2*GRID_SPACING, 3), dtype=np.uint8 + ) + grid_img[:, :width, :] = img_np[:, :, ::-1] + grid_img[:, + width + GRID_SPACING:2*width + GRID_SPACING, :] = am + grid_img[:, 2*width + 2*GRID_SPACING:, :] = overlapped + cv2.imwrite(osp.join(actmap_dir, imname + '.jpg'), grid_img) + + if (batch_idx+1) % 10 == 0: + print( + '- done batch {}/{}'.format( + batch_idx + 1, len(data_loader) + ) + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str) + parser.add_argument('-d', '--dataset', type=str, default='market1501') + parser.add_argument('-m', '--model', type=str, default='osnet_x1_0') + parser.add_argument('--weights', type=str) + parser.add_argument('--save-dir', type=str, default='log') + parser.add_argument('--height', type=int, default=256) + parser.add_argument('--width', type=int, default=128) + args = parser.parse_args() + + use_gpu = torch.cuda.is_available() + + datamanager = torchreid.data.ImageDataManager( + root=args.root, + sources=args.dataset, + height=args.height, + width=args.width, + batch_size_train=100, + batch_size_test=100, + transforms=None, + train_sampler='SequentialSampler' + ) + test_loader = datamanager.test_loader + + model = torchreid.models.build_model( + name=args.model, + num_classes=datamanager.num_train_pids, + use_gpu=use_gpu + ) + + if use_gpu: + model = model.cuda() + + if args.weights and check_isfile(args.weights): + load_pretrained_weights(model, args.weights) + + visactmap( + model, test_loader, args.save_dir, args.width, args.height, use_gpu + ) + + +if __name__ == '__main__': + main() diff --git a/strong_sort/deep/reid/torchreid/__init__.py b/strong_sort/deep/reid/torchreid/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..35eeca675432d30bc360cede699ed9c655dccb80 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/__init__.py @@ -0,0 +1,9 @@ +from __future__ import print_function, absolute_import + +from torchreid import data, optim, utils, engine, losses, models, metrics + +__version__ = '1.4.0' +__author__ = 'Kaiyang Zhou' +__homepage__ = 'https://kaiyangzhou.github.io/' +__description__ = 'Deep learning person re-identification in PyTorch' +__url__ = 'https://github.com/KaiyangZhou/deep-person-reid' diff --git a/strong_sort/deep/reid/torchreid/data/__init__.py b/strong_sort/deep/reid/torchreid/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5318a16326d671a1b5a8ba949750124fd1d6b05c --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/__init__.py @@ -0,0 +1,7 @@ +from __future__ import print_function, absolute_import + +from .datasets import ( + Dataset, ImageDataset, VideoDataset, register_image_dataset, + register_video_dataset +) +from .datamanager import ImageDataManager, VideoDataManager diff --git a/strong_sort/deep/reid/torchreid/data/datamanager.py b/strong_sort/deep/reid/torchreid/data/datamanager.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae28cbafacb935619272f56576c4c1e2c30dfec --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datamanager.py @@ -0,0 +1,554 @@ +from __future__ import division, print_function, absolute_import +import torch + +from torchreid.data.sampler import build_train_sampler +from torchreid.data.datasets import init_image_dataset, init_video_dataset +from torchreid.data.transforms import build_transforms + + +class DataManager(object): + r"""Base data manager. + + Args: + sources (str or list): source dataset(s). + targets (str or list, optional): target dataset(s). If not given, + it equals to ``sources``. + height (int, optional): target image height. Default is 256. + width (int, optional): target image width. Default is 128. + transforms (str or list of str, optional): transformations applied to model training. + Default is 'random_flip'. + norm_mean (list or None, optional): data mean. Default is None (use imagenet mean). + norm_std (list or None, optional): data std. Default is None (use imagenet std). + use_gpu (bool, optional): use gpu. Default is True. + """ + + def __init__( + self, + sources=None, + targets=None, + height=256, + width=128, + transforms='random_flip', + norm_mean=None, + norm_std=None, + use_gpu=False + ): + self.sources = sources + self.targets = targets + self.height = height + self.width = width + + if self.sources is None: + raise ValueError('sources must not be None') + + if isinstance(self.sources, str): + self.sources = [self.sources] + + if self.targets is None: + self.targets = self.sources + + if isinstance(self.targets, str): + self.targets = [self.targets] + + self.transform_tr, self.transform_te = build_transforms( + self.height, + self.width, + transforms=transforms, + norm_mean=norm_mean, + norm_std=norm_std + ) + + self.use_gpu = (torch.cuda.is_available() and use_gpu) + + @property + def num_train_pids(self): + """Returns the number of training person identities.""" + return self._num_train_pids + + @property + def num_train_cams(self): + """Returns the number of training cameras.""" + return self._num_train_cams + + def fetch_test_loaders(self, name): + """Returns query and gallery of a test dataset, each containing + tuples of (img_path(s), pid, camid). + + Args: + name (str): dataset name. + """ + query_loader = self.test_dataset[name]['query'] + gallery_loader = self.test_dataset[name]['gallery'] + return query_loader, gallery_loader + + def preprocess_pil_img(self, img): + """Transforms a PIL image to torch tensor for testing.""" + return self.transform_te(img) + + +class ImageDataManager(DataManager): + r"""Image data manager. + + Args: + root (str): root path to datasets. + sources (str or list): source dataset(s). + targets (str or list, optional): target dataset(s). If not given, + it equals to ``sources``. + height (int, optional): target image height. Default is 256. + width (int, optional): target image width. Default is 128. + transforms (str or list of str, optional): transformations applied to model training. + Default is 'random_flip'. + k_tfm (int): number of times to apply augmentation to an image + independently. If k_tfm > 1, the transform function will be + applied k_tfm times to an image. This variable will only be + useful for training and is currently valid for image datasets only. + norm_mean (list or None, optional): data mean. Default is None (use imagenet mean). + norm_std (list or None, optional): data std. Default is None (use imagenet std). + use_gpu (bool, optional): use gpu. Default is True. + split_id (int, optional): split id (*0-based*). Default is 0. + combineall (bool, optional): combine train, query and gallery in a dataset for + training. Default is False. + load_train_targets (bool, optional): construct train-loader for target datasets. + Default is False. This is useful for domain adaptation research. + batch_size_train (int, optional): number of images in a training batch. Default is 32. + batch_size_test (int, optional): number of images in a test batch. Default is 32. + workers (int, optional): number of workers. Default is 4. + num_instances (int, optional): number of instances per identity in a batch. + Default is 4. + num_cams (int, optional): number of cameras to sample in a batch (when using + ``RandomDomainSampler``). Default is 1. + num_datasets (int, optional): number of datasets to sample in a batch (when + using ``RandomDatasetSampler``). Default is 1. + train_sampler (str, optional): sampler. Default is RandomSampler. + train_sampler_t (str, optional): sampler for target train loader. Default is RandomSampler. + cuhk03_labeled (bool, optional): use cuhk03 labeled images. + Default is False (defaul is to use detected images). + cuhk03_classic_split (bool, optional): use the classic split in cuhk03. + Default is False. + market1501_500k (bool, optional): add 500K distractors to the gallery + set in market1501. Default is False. + + Examples:: + + datamanager = torchreid.data.ImageDataManager( + root='path/to/reid-data', + sources='market1501', + height=256, + width=128, + batch_size_train=32, + batch_size_test=100 + ) + + # return train loader of source data + train_loader = datamanager.train_loader + + # return test loader of target data + test_loader = datamanager.test_loader + + # return train loader of target data + train_loader_t = datamanager.train_loader_t + """ + data_type = 'image' + + def __init__( + self, + root='', + sources=None, + targets=None, + height=256, + width=128, + transforms='random_flip', + k_tfm=1, + norm_mean=None, + norm_std=None, + use_gpu=True, + split_id=0, + combineall=False, + load_train_targets=False, + batch_size_train=32, + batch_size_test=32, + workers=4, + num_instances=4, + num_cams=1, + num_datasets=1, + train_sampler='RandomSampler', + train_sampler_t='RandomSampler', + cuhk03_labeled=False, + cuhk03_classic_split=False, + market1501_500k=False + ): + + super(ImageDataManager, self).__init__( + sources=sources, + targets=targets, + height=height, + width=width, + transforms=transforms, + norm_mean=norm_mean, + norm_std=norm_std, + use_gpu=use_gpu + ) + + print('=> Loading train (source) dataset') + trainset = [] + for name in self.sources: + trainset_ = init_image_dataset( + name, + transform=self.transform_tr, + k_tfm=k_tfm, + mode='train', + combineall=combineall, + root=root, + split_id=split_id, + cuhk03_labeled=cuhk03_labeled, + cuhk03_classic_split=cuhk03_classic_split, + market1501_500k=market1501_500k + ) + trainset.append(trainset_) + trainset = sum(trainset) + + self._num_train_pids = trainset.num_train_pids + self._num_train_cams = trainset.num_train_cams + + self.train_loader = torch.utils.data.DataLoader( + trainset, + sampler=build_train_sampler( + trainset.train, + train_sampler, + batch_size=batch_size_train, + num_instances=num_instances, + num_cams=num_cams, + num_datasets=num_datasets + ), + batch_size=batch_size_train, + shuffle=False, + num_workers=workers, + pin_memory=self.use_gpu, + drop_last=True + ) + + self.train_loader_t = None + if load_train_targets: + # check if sources and targets are identical + assert len(set(self.sources) & set(self.targets)) == 0, \ + 'sources={} and targets={} must not have overlap'.format(self.sources, self.targets) + + print('=> Loading train (target) dataset') + trainset_t = [] + for name in self.targets: + trainset_t_ = init_image_dataset( + name, + transform=self.transform_tr, + k_tfm=k_tfm, + mode='train', + combineall=False, # only use the training data + root=root, + split_id=split_id, + cuhk03_labeled=cuhk03_labeled, + cuhk03_classic_split=cuhk03_classic_split, + market1501_500k=market1501_500k + ) + trainset_t.append(trainset_t_) + trainset_t = sum(trainset_t) + + self.train_loader_t = torch.utils.data.DataLoader( + trainset_t, + sampler=build_train_sampler( + trainset_t.train, + train_sampler_t, + batch_size=batch_size_train, + num_instances=num_instances, + num_cams=num_cams, + num_datasets=num_datasets + ), + batch_size=batch_size_train, + shuffle=False, + num_workers=workers, + pin_memory=self.use_gpu, + drop_last=True + ) + + print('=> Loading test (target) dataset') + self.test_loader = { + name: { + 'query': None, + 'gallery': None + } + for name in self.targets + } + self.test_dataset = { + name: { + 'query': None, + 'gallery': None + } + for name in self.targets + } + + for name in self.targets: + # build query loader + queryset = init_image_dataset( + name, + transform=self.transform_te, + mode='query', + combineall=combineall, + root=root, + split_id=split_id, + cuhk03_labeled=cuhk03_labeled, + cuhk03_classic_split=cuhk03_classic_split, + market1501_500k=market1501_500k + ) + self.test_loader[name]['query'] = torch.utils.data.DataLoader( + queryset, + batch_size=batch_size_test, + shuffle=False, + num_workers=workers, + pin_memory=self.use_gpu, + drop_last=False + ) + + # build gallery loader + galleryset = init_image_dataset( + name, + transform=self.transform_te, + mode='gallery', + combineall=combineall, + verbose=False, + root=root, + split_id=split_id, + cuhk03_labeled=cuhk03_labeled, + cuhk03_classic_split=cuhk03_classic_split, + market1501_500k=market1501_500k + ) + self.test_loader[name]['gallery'] = torch.utils.data.DataLoader( + galleryset, + batch_size=batch_size_test, + shuffle=False, + num_workers=workers, + pin_memory=self.use_gpu, + drop_last=False + ) + + self.test_dataset[name]['query'] = queryset.query + self.test_dataset[name]['gallery'] = galleryset.gallery + + print('\n') + print(' **************** Summary ****************') + print(' source : {}'.format(self.sources)) + print(' # source datasets : {}'.format(len(self.sources))) + print(' # source ids : {}'.format(self.num_train_pids)) + print(' # source images : {}'.format(len(trainset))) + print(' # source cameras : {}'.format(self.num_train_cams)) + if load_train_targets: + print( + ' # target images : {} (unlabeled)'.format(len(trainset_t)) + ) + print(' target : {}'.format(self.targets)) + print(' *****************************************') + print('\n') + + +class VideoDataManager(DataManager): + r"""Video data manager. + + Args: + root (str): root path to datasets. + sources (str or list): source dataset(s). + targets (str or list, optional): target dataset(s). If not given, + it equals to ``sources``. + height (int, optional): target image height. Default is 256. + width (int, optional): target image width. Default is 128. + transforms (str or list of str, optional): transformations applied to model training. + Default is 'random_flip'. + norm_mean (list or None, optional): data mean. Default is None (use imagenet mean). + norm_std (list or None, optional): data std. Default is None (use imagenet std). + use_gpu (bool, optional): use gpu. Default is True. + split_id (int, optional): split id (*0-based*). Default is 0. + combineall (bool, optional): combine train, query and gallery in a dataset for + training. Default is False. + batch_size_train (int, optional): number of tracklets in a training batch. Default is 3. + batch_size_test (int, optional): number of tracklets in a test batch. Default is 3. + workers (int, optional): number of workers. Default is 4. + num_instances (int, optional): number of instances per identity in a batch. + Default is 4. + num_cams (int, optional): number of cameras to sample in a batch (when using + ``RandomDomainSampler``). Default is 1. + num_datasets (int, optional): number of datasets to sample in a batch (when + using ``RandomDatasetSampler``). Default is 1. + train_sampler (str, optional): sampler. Default is RandomSampler. + seq_len (int, optional): how many images to sample in a tracklet. Default is 15. + sample_method (str, optional): how to sample images in a tracklet. Default is "evenly". + Choices are ["evenly", "random", "all"]. "evenly" and "random" will sample ``seq_len`` + images in a tracklet while "all" samples all images in a tracklet, where the batch size + needs to be set to 1. + + Examples:: + + datamanager = torchreid.data.VideoDataManager( + root='path/to/reid-data', + sources='mars', + height=256, + width=128, + batch_size_train=3, + batch_size_test=3, + seq_len=15, + sample_method='evenly' + ) + + # return train loader of source data + train_loader = datamanager.train_loader + + # return test loader of target data + test_loader = datamanager.test_loader + + .. note:: + The current implementation only supports image-like training. Therefore, each image in a + sampled tracklet will undergo independent transformation functions. To achieve tracklet-aware + training, you need to modify the transformation functions for video reid such that each function + applies the same operation to all images in a tracklet to keep consistency. + """ + data_type = 'video' + + def __init__( + self, + root='', + sources=None, + targets=None, + height=256, + width=128, + transforms='random_flip', + norm_mean=None, + norm_std=None, + use_gpu=True, + split_id=0, + combineall=False, + batch_size_train=3, + batch_size_test=3, + workers=4, + num_instances=4, + num_cams=1, + num_datasets=1, + train_sampler='RandomSampler', + seq_len=15, + sample_method='evenly' + ): + + super(VideoDataManager, self).__init__( + sources=sources, + targets=targets, + height=height, + width=width, + transforms=transforms, + norm_mean=norm_mean, + norm_std=norm_std, + use_gpu=use_gpu + ) + + print('=> Loading train (source) dataset') + trainset = [] + for name in self.sources: + trainset_ = init_video_dataset( + name, + transform=self.transform_tr, + mode='train', + combineall=combineall, + root=root, + split_id=split_id, + seq_len=seq_len, + sample_method=sample_method + ) + trainset.append(trainset_) + trainset = sum(trainset) + + self._num_train_pids = trainset.num_train_pids + self._num_train_cams = trainset.num_train_cams + + train_sampler = build_train_sampler( + trainset.train, + train_sampler, + batch_size=batch_size_train, + num_instances=num_instances, + num_cams=num_cams, + num_datasets=num_datasets + ) + + self.train_loader = torch.utils.data.DataLoader( + trainset, + sampler=train_sampler, + batch_size=batch_size_train, + shuffle=False, + num_workers=workers, + pin_memory=self.use_gpu, + drop_last=True + ) + + print('=> Loading test (target) dataset') + self.test_loader = { + name: { + 'query': None, + 'gallery': None + } + for name in self.targets + } + self.test_dataset = { + name: { + 'query': None, + 'gallery': None + } + for name in self.targets + } + + for name in self.targets: + # build query loader + queryset = init_video_dataset( + name, + transform=self.transform_te, + mode='query', + combineall=combineall, + root=root, + split_id=split_id, + seq_len=seq_len, + sample_method=sample_method + ) + self.test_loader[name]['query'] = torch.utils.data.DataLoader( + queryset, + batch_size=batch_size_test, + shuffle=False, + num_workers=workers, + pin_memory=self.use_gpu, + drop_last=False + ) + + # build gallery loader + galleryset = init_video_dataset( + name, + transform=self.transform_te, + mode='gallery', + combineall=combineall, + verbose=False, + root=root, + split_id=split_id, + seq_len=seq_len, + sample_method=sample_method + ) + self.test_loader[name]['gallery'] = torch.utils.data.DataLoader( + galleryset, + batch_size=batch_size_test, + shuffle=False, + num_workers=workers, + pin_memory=self.use_gpu, + drop_last=False + ) + + self.test_dataset[name]['query'] = queryset.query + self.test_dataset[name]['gallery'] = galleryset.gallery + + print('\n') + print(' **************** Summary ****************') + print(' source : {}'.format(self.sources)) + print(' # source datasets : {}'.format(len(self.sources))) + print(' # source ids : {}'.format(self.num_train_pids)) + print(' # source tracklets : {}'.format(len(trainset))) + print(' # source cameras : {}'.format(self.num_train_cams)) + print(' target : {}'.format(self.targets)) + print(' *****************************************') + print('\n') diff --git a/strong_sort/deep/reid/torchreid/data/datasets/__init__.py b/strong_sort/deep/reid/torchreid/data/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..afb02a2bf2ce740ade52cb974a862e8987222088 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/__init__.py @@ -0,0 +1,119 @@ +from __future__ import print_function, absolute_import + +from .image import ( + GRID, PRID, CUHK01, CUHK02, CUHK03, MSMT17, CUHKSYSU, VIPeR, SenseReID, + Market1501, DukeMTMCreID, University1652, iLIDS +) +from .video import PRID2011, Mars, DukeMTMCVidReID, iLIDSVID +from .dataset import Dataset, ImageDataset, VideoDataset + +__image_datasets = { + 'market1501': Market1501, + 'cuhk03': CUHK03, + 'dukemtmcreid': DukeMTMCreID, + 'msmt17': MSMT17, + 'viper': VIPeR, + 'grid': GRID, + 'cuhk01': CUHK01, + 'ilids': iLIDS, + 'sensereid': SenseReID, + 'prid': PRID, + 'cuhk02': CUHK02, + 'university1652': University1652, + 'cuhksysu': CUHKSYSU +} + +__video_datasets = { + 'mars': Mars, + 'ilidsvid': iLIDSVID, + 'prid2011': PRID2011, + 'dukemtmcvidreid': DukeMTMCVidReID +} + + +def init_image_dataset(name, **kwargs): + """Initializes an image dataset.""" + avai_datasets = list(__image_datasets.keys()) + if name not in avai_datasets: + raise ValueError( + 'Invalid dataset name. Received "{}", ' + 'but expected to be one of {}'.format(name, avai_datasets) + ) + return __image_datasets[name](**kwargs) + + +def init_video_dataset(name, **kwargs): + """Initializes a video dataset.""" + avai_datasets = list(__video_datasets.keys()) + if name not in avai_datasets: + raise ValueError( + 'Invalid dataset name. Received "{}", ' + 'but expected to be one of {}'.format(name, avai_datasets) + ) + return __video_datasets[name](**kwargs) + + +def register_image_dataset(name, dataset): + """Registers a new image dataset. + + Args: + name (str): key corresponding to the new dataset. + dataset (Dataset): the new dataset class. + + Examples:: + + import torchreid + import NewDataset + torchreid.data.register_image_dataset('new_dataset', NewDataset) + # single dataset case + datamanager = torchreid.data.ImageDataManager( + root='reid-data', + sources='new_dataset' + ) + # multiple dataset case + datamanager = torchreid.data.ImageDataManager( + root='reid-data', + sources=['new_dataset', 'dukemtmcreid'] + ) + """ + global __image_datasets + curr_datasets = list(__image_datasets.keys()) + if name in curr_datasets: + raise ValueError( + 'The given name already exists, please choose ' + 'another name excluding {}'.format(curr_datasets) + ) + __image_datasets[name] = dataset + + +def register_video_dataset(name, dataset): + """Registers a new video dataset. + + Args: + name (str): key corresponding to the new dataset. + dataset (Dataset): the new dataset class. + + Examples:: + + import torchreid + import NewDataset + torchreid.data.register_video_dataset('new_dataset', NewDataset) + # single dataset case + datamanager = torchreid.data.VideoDataManager( + root='reid-data', + sources='new_dataset' + ) + # multiple dataset case + datamanager = torchreid.data.VideoDataManager( + root='reid-data', + sources=['new_dataset', 'ilidsvid'] + ) + """ + global __video_datasets + curr_datasets = list(__video_datasets.keys()) + if name in curr_datasets: + raise ValueError( + 'The given name already exists, please choose ' + 'another name excluding {}'.format(curr_datasets) + ) + __video_datasets[name] = dataset diff --git a/strong_sort/deep/reid/torchreid/data/datasets/dataset.py b/strong_sort/deep/reid/torchreid/data/datasets/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..66b1e7a6ea224e6d4fca75b9df7c0342de878553 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/dataset.py @@ -0,0 +1,482 @@ +from __future__ import division, print_function, absolute_import +import copy +import numpy as np +import os.path as osp +import tarfile +import zipfile +import torch + +from torchreid.utils import read_image, download_url, mkdir_if_missing + + +class Dataset(object): + """An abstract class representing a Dataset. + + This is the base class for ``ImageDataset`` and ``VideoDataset``. + + Args: + train (list): contains tuples of (img_path(s), pid, camid). + query (list): contains tuples of (img_path(s), pid, camid). + gallery (list): contains tuples of (img_path(s), pid, camid). + transform: transform function. + k_tfm (int): number of times to apply augmentation to an image + independently. If k_tfm > 1, the transform function will be + applied k_tfm times to an image. This variable will only be + useful for training and is currently valid for image datasets only. + mode (str): 'train', 'query' or 'gallery'. + combineall (bool): combines train, query and gallery in a + dataset for training. + verbose (bool): show information. + """ + + # junk_pids contains useless person IDs, e.g. background, + # false detections, distractors. These IDs will be ignored + # when combining all images in a dataset for training, i.e. + # combineall=True + _junk_pids = [] + + # Some datasets are only used for training, like CUHK-SYSU + # In this case, "combineall=True" is not used for them + _train_only = False + + def __init__( + self, + train, + query, + gallery, + transform=None, + k_tfm=1, + mode='train', + combineall=False, + verbose=True, + **kwargs + ): + # extend 3-tuple (img_path(s), pid, camid) to + # 4-tuple (img_path(s), pid, camid, dsetid) by + # adding a dataset indicator "dsetid" + if len(train[0]) == 3: + train = [(*items, 0) for items in train] + if len(query[0]) == 3: + query = [(*items, 0) for items in query] + if len(gallery[0]) == 3: + gallery = [(*items, 0) for items in gallery] + + self.train = train + self.query = query + self.gallery = gallery + self.transform = transform + self.k_tfm = k_tfm + self.mode = mode + self.combineall = combineall + self.verbose = verbose + + self.num_train_pids = self.get_num_pids(self.train) + self.num_train_cams = self.get_num_cams(self.train) + self.num_datasets = self.get_num_datasets(self.train) + + if self.combineall: + self.combine_all() + + if self.mode == 'train': + self.data = self.train + elif self.mode == 'query': + self.data = self.query + elif self.mode == 'gallery': + self.data = self.gallery + else: + raise ValueError( + 'Invalid mode. Got {}, but expected to be ' + 'one of [train | query | gallery]'.format(self.mode) + ) + + if self.verbose: + self.show_summary() + + def __getitem__(self, index): + raise NotImplementedError + + def __len__(self): + return len(self.data) + + def __add__(self, other): + """Adds two datasets together (only the train set).""" + train = copy.deepcopy(self.train) + + for img_path, pid, camid, dsetid in other.train: + pid += self.num_train_pids + camid += self.num_train_cams + dsetid += self.num_datasets + train.append((img_path, pid, camid, dsetid)) + + ################################### + # Note that + # 1. set verbose=False to avoid unnecessary print + # 2. set combineall=False because combineall would have been applied + # if it was True for a specific dataset; setting it to True will + # create new IDs that should have already been included + ################################### + if isinstance(train[0][0], str): + return ImageDataset( + train, + self.query, + self.gallery, + transform=self.transform, + mode=self.mode, + combineall=False, + verbose=False + ) + else: + return VideoDataset( + train, + self.query, + self.gallery, + transform=self.transform, + mode=self.mode, + combineall=False, + verbose=False, + seq_len=self.seq_len, + sample_method=self.sample_method + ) + + def __radd__(self, other): + """Supports sum([dataset1, dataset2, dataset3]).""" + if other == 0: + return self + else: + return self.__add__(other) + + def get_num_pids(self, data): + """Returns the number of training person identities. + + Each tuple in data contains (img_path(s), pid, camid, dsetid). + """ + pids = set() + for items in data: + pid = items[1] + pids.add(pid) + return len(pids) + + def get_num_cams(self, data): + """Returns the number of training cameras. + + Each tuple in data contains (img_path(s), pid, camid, dsetid). + """ + cams = set() + for items in data: + camid = items[2] + cams.add(camid) + return len(cams) + + def get_num_datasets(self, data): + """Returns the number of datasets included. + + Each tuple in data contains (img_path(s), pid, camid, dsetid). + """ + dsets = set() + for items in data: + dsetid = items[3] + dsets.add(dsetid) + return len(dsets) + + def show_summary(self): + """Shows dataset statistics.""" + pass + + def combine_all(self): + """Combines train, query and gallery in a dataset for training.""" + if self._train_only: + return + + combined = copy.deepcopy(self.train) + + # relabel pids in gallery (query shares the same scope) + g_pids = set() + for items in self.gallery: + pid = items[1] + if pid in self._junk_pids: + continue + g_pids.add(pid) + pid2label = {pid: i for i, pid in enumerate(g_pids)} + + def _combine_data(data): + for img_path, pid, camid, dsetid in data: + if pid in self._junk_pids: + continue + pid = pid2label[pid] + self.num_train_pids + combined.append((img_path, pid, camid, dsetid)) + + _combine_data(self.query) + _combine_data(self.gallery) + + self.train = combined + self.num_train_pids = self.get_num_pids(self.train) + + def download_dataset(self, dataset_dir, dataset_url): + """Downloads and extracts dataset. + + Args: + dataset_dir (str): dataset directory. + dataset_url (str): url to download dataset. + """ + if osp.exists(dataset_dir): + return + + if dataset_url is None: + raise RuntimeError( + '{} dataset needs to be manually ' + 'prepared, please follow the ' + 'document to prepare this dataset'.format( + self.__class__.__name__ + ) + ) + + print('Creating directory "{}"'.format(dataset_dir)) + mkdir_if_missing(dataset_dir) + fpath = osp.join(dataset_dir, osp.basename(dataset_url)) + + print( + 'Downloading {} dataset to "{}"'.format( + self.__class__.__name__, dataset_dir + ) + ) + download_url(dataset_url, fpath) + + print('Extracting "{}"'.format(fpath)) + try: + tar = tarfile.open(fpath) + tar.extractall(path=dataset_dir) + tar.close() + except: + zip_ref = zipfile.ZipFile(fpath, 'r') + zip_ref.extractall(dataset_dir) + zip_ref.close() + + print('{} dataset is ready'.format(self.__class__.__name__)) + + def check_before_run(self, required_files): + """Checks if required files exist before going deeper. + + Args: + required_files (str or list): string file name(s). + """ + if isinstance(required_files, str): + required_files = [required_files] + + for fpath in required_files: + if not osp.exists(fpath): + raise RuntimeError('"{}" is not found'.format(fpath)) + + def __repr__(self): + num_train_pids = self.get_num_pids(self.train) + num_train_cams = self.get_num_cams(self.train) + + num_query_pids = self.get_num_pids(self.query) + num_query_cams = self.get_num_cams(self.query) + + num_gallery_pids = self.get_num_pids(self.gallery) + num_gallery_cams = self.get_num_cams(self.gallery) + + msg = ' ----------------------------------------\n' \ + ' subset | # ids | # items | # cameras\n' \ + ' ----------------------------------------\n' \ + ' train | {:5d} | {:7d} | {:9d}\n' \ + ' query | {:5d} | {:7d} | {:9d}\n' \ + ' gallery | {:5d} | {:7d} | {:9d}\n' \ + ' ----------------------------------------\n' \ + ' items: images/tracklets for image/video dataset\n'.format( + num_train_pids, len(self.train), num_train_cams, + num_query_pids, len(self.query), num_query_cams, + num_gallery_pids, len(self.gallery), num_gallery_cams + ) + + return msg + + def _transform_image(self, tfm, k_tfm, img0): + """Transforms a raw image (img0) k_tfm times with + the transform function tfm. + """ + img_list = [] + + for k in range(k_tfm): + img_list.append(tfm(img0)) + + img = img_list + if len(img) == 1: + img = img[0] + + return img + + +class ImageDataset(Dataset): + """A base class representing ImageDataset. + + All other image datasets should subclass it. + + ``__getitem__`` returns an image given index. + It will return ``img``, ``pid``, ``camid`` and ``img_path`` + where ``img`` has shape (channel, height, width). As a result, + data in each batch has shape (batch_size, channel, height, width). + """ + + def __init__(self, train, query, gallery, **kwargs): + super(ImageDataset, self).__init__(train, query, gallery, **kwargs) + + def __getitem__(self, index): + img_path, pid, camid, dsetid = self.data[index] + img = read_image(img_path) + if self.transform is not None: + img = self._transform_image(self.transform, self.k_tfm, img) + item = { + 'img': img, + 'pid': pid, + 'camid': camid, + 'impath': img_path, + 'dsetid': dsetid + } + return item + + def show_summary(self): + num_train_pids = self.get_num_pids(self.train) + num_train_cams = self.get_num_cams(self.train) + + num_query_pids = self.get_num_pids(self.query) + num_query_cams = self.get_num_cams(self.query) + + num_gallery_pids = self.get_num_pids(self.gallery) + num_gallery_cams = self.get_num_cams(self.gallery) + + print('=> Loaded {}'.format(self.__class__.__name__)) + print(' ----------------------------------------') + print(' subset | # ids | # images | # cameras') + print(' ----------------------------------------') + print( + ' train | {:5d} | {:8d} | {:9d}'.format( + num_train_pids, len(self.train), num_train_cams + ) + ) + print( + ' query | {:5d} | {:8d} | {:9d}'.format( + num_query_pids, len(self.query), num_query_cams + ) + ) + print( + ' gallery | {:5d} | {:8d} | {:9d}'.format( + num_gallery_pids, len(self.gallery), num_gallery_cams + ) + ) + print(' ----------------------------------------') + + +class VideoDataset(Dataset): + """A base class representing VideoDataset. + + All other video datasets should subclass it. + + ``__getitem__`` returns an image given index. + It will return ``imgs``, ``pid`` and ``camid`` + where ``imgs`` has shape (seq_len, channel, height, width). As a result, + data in each batch has shape (batch_size, seq_len, channel, height, width). + """ + + def __init__( + self, + train, + query, + gallery, + seq_len=15, + sample_method='evenly', + **kwargs + ): + super(VideoDataset, self).__init__(train, query, gallery, **kwargs) + self.seq_len = seq_len + self.sample_method = sample_method + + if self.transform is None: + raise RuntimeError('transform must not be None') + + def __getitem__(self, index): + img_paths, pid, camid, dsetid = self.data[index] + num_imgs = len(img_paths) + + if self.sample_method == 'random': + # Randomly samples seq_len images from a tracklet of length num_imgs, + # if num_imgs is smaller than seq_len, then replicates images + indices = np.arange(num_imgs) + replace = False if num_imgs >= self.seq_len else True + indices = np.random.choice( + indices, size=self.seq_len, replace=replace + ) + # sort indices to keep temporal order (comment it to be order-agnostic) + indices = np.sort(indices) + + elif self.sample_method == 'evenly': + # Evenly samples seq_len images from a tracklet + if num_imgs >= self.seq_len: + num_imgs -= num_imgs % self.seq_len + indices = np.arange(0, num_imgs, num_imgs / self.seq_len) + else: + # if num_imgs is smaller than seq_len, simply replicate the last image + # until the seq_len requirement is satisfied + indices = np.arange(0, num_imgs) + num_pads = self.seq_len - num_imgs + indices = np.concatenate( + [ + indices, + np.ones(num_pads).astype(np.int32) * (num_imgs-1) + ] + ) + assert len(indices) == self.seq_len + + elif self.sample_method == 'all': + # Samples all images in a tracklet. batch_size must be set to 1 + indices = np.arange(num_imgs) + + else: + raise ValueError( + 'Unknown sample method: {}'.format(self.sample_method) + ) + + imgs = [] + for index in indices: + img_path = img_paths[int(index)] + img = read_image(img_path) + if self.transform is not None: + img = self.transform(img) + img = img.unsqueeze(0) # img must be torch.Tensor + imgs.append(img) + imgs = torch.cat(imgs, dim=0) + + item = {'img': imgs, 'pid': pid, 'camid': camid, 'dsetid': dsetid} + + return item + + def show_summary(self): + num_train_pids = self.get_num_pids(self.train) + num_train_cams = self.get_num_cams(self.train) + + num_query_pids = self.get_num_pids(self.query) + num_query_cams = self.get_num_cams(self.query) + + num_gallery_pids = self.get_num_pids(self.gallery) + num_gallery_cams = self.get_num_cams(self.gallery) + + print('=> Loaded {}'.format(self.__class__.__name__)) + print(' -------------------------------------------') + print(' subset | # ids | # tracklets | # cameras') + print(' -------------------------------------------') + print( + ' train | {:5d} | {:11d} | {:9d}'.format( + num_train_pids, len(self.train), num_train_cams + ) + ) + print( + ' query | {:5d} | {:11d} | {:9d}'.format( + num_query_pids, len(self.query), num_query_cams + ) + ) + print( + ' gallery | {:5d} | {:11d} | {:9d}'.format( + num_gallery_pids, len(self.gallery), num_gallery_cams + ) + ) + print(' -------------------------------------------') diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/__init__.py b/strong_sort/deep/reid/torchreid/data/datasets/image/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f2216e96db061ee38f7172147778a495d3124db0 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/__init__.py @@ -0,0 +1,15 @@ +from __future__ import print_function, absolute_import + +from .grid import GRID +from .prid import PRID +from .ilids import iLIDS +from .viper import VIPeR +from .cuhk01 import CUHK01 +from .cuhk02 import CUHK02 +from .cuhk03 import CUHK03 +from .msmt17 import MSMT17 +from .cuhksysu import CUHKSYSU +from .sensereid import SenseReID +from .market1501 import Market1501 +from .dukemtmcreid import DukeMTMCreID +from .university1652 import University1652 diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/cuhk01.py b/strong_sort/deep/reid/torchreid/data/datasets/image/cuhk01.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c332ef7921a8d9f501ccb6d57aa56d78a9a98a --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/cuhk01.py @@ -0,0 +1,137 @@ +from __future__ import division, print_function, absolute_import +import glob +import numpy as np +import os.path as osp +import zipfile + +from torchreid.utils import read_json, write_json + +from ..dataset import ImageDataset + + +class CUHK01(ImageDataset): + """CUHK01. + + Reference: + Li et al. Human Reidentification with Transferred Metric Learning. ACCV 2012. + + URL: ``_ + + Dataset statistics: + - identities: 971. + - images: 3884. + - cameras: 4. + + Note: CUHK01 and CUHK02 overlap. + """ + dataset_dir = 'cuhk01' + dataset_url = None + + def __init__(self, root='', split_id=0, **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.zip_path = osp.join(self.dataset_dir, 'CUHK01.zip') + self.campus_dir = osp.join(self.dataset_dir, 'campus') + self.split_path = osp.join(self.dataset_dir, 'splits.json') + + self.extract_file() + + required_files = [self.dataset_dir, self.campus_dir] + self.check_before_run(required_files) + + self.prepare_split() + splits = read_json(self.split_path) + if split_id >= len(splits): + raise ValueError( + 'split_id exceeds range, received {}, but expected between 0 and {}' + .format(split_id, + len(splits) - 1) + ) + split = splits[split_id] + + train = split['train'] + query = split['query'] + gallery = split['gallery'] + + train = [tuple(item) for item in train] + query = [tuple(item) for item in query] + gallery = [tuple(item) for item in gallery] + + super(CUHK01, self).__init__(train, query, gallery, **kwargs) + + def extract_file(self): + if not osp.exists(self.campus_dir): + print('Extracting files') + zip_ref = zipfile.ZipFile(self.zip_path, 'r') + zip_ref.extractall(self.dataset_dir) + zip_ref.close() + + def prepare_split(self): + """ + Image name format: 0001001.png, where first four digits represent identity + and last four digits represent cameras. Camera 1&2 are considered the same + view and camera 3&4 are considered the same view. + """ + if not osp.exists(self.split_path): + print('Creating 10 random splits of train ids and test ids') + img_paths = sorted(glob.glob(osp.join(self.campus_dir, '*.png'))) + img_list = [] + pid_container = set() + for img_path in img_paths: + img_name = osp.basename(img_path) + pid = int(img_name[:4]) - 1 + camid = (int(img_name[4:7]) - 1) // 2 # result is either 0 or 1 + img_list.append((img_path, pid, camid)) + pid_container.add(pid) + + num_pids = len(pid_container) + num_train_pids = num_pids // 2 + + splits = [] + for _ in range(10): + order = np.arange(num_pids) + np.random.shuffle(order) + train_idxs = order[:num_train_pids] + train_idxs = np.sort(train_idxs) + idx2label = { + idx: label + for label, idx in enumerate(train_idxs) + } + + train, test_a, test_b = [], [], [] + for img_path, pid, camid in img_list: + if pid in train_idxs: + train.append((img_path, idx2label[pid], camid)) + else: + if camid == 0: + test_a.append((img_path, pid, camid)) + else: + test_b.append((img_path, pid, camid)) + + # use cameraA as query and cameraB as gallery + split = { + 'train': train, + 'query': test_a, + 'gallery': test_b, + 'num_train_pids': num_train_pids, + 'num_query_pids': num_pids - num_train_pids, + 'num_gallery_pids': num_pids - num_train_pids + } + splits.append(split) + + # use cameraB as query and cameraA as gallery + split = { + 'train': train, + 'query': test_b, + 'gallery': test_a, + 'num_train_pids': num_train_pids, + 'num_query_pids': num_pids - num_train_pids, + 'num_gallery_pids': num_pids - num_train_pids + } + splits.append(split) + + print('Totally {} splits are created'.format(len(splits))) + write_json(splits, self.split_path) + print('Split file saved to {}'.format(self.split_path)) diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/cuhk02.py b/strong_sort/deep/reid/torchreid/data/datasets/image/cuhk02.py new file mode 100644 index 0000000000000000000000000000000000000000..dd92588d21fe6d48ca56e51e41d1e78f31095b38 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/cuhk02.py @@ -0,0 +1,97 @@ +from __future__ import division, print_function, absolute_import +import glob +import os.path as osp + +from ..dataset import ImageDataset + + +class CUHK02(ImageDataset): + """CUHK02. + + Reference: + Li and Wang. Locally Aligned Feature Transforms across Views. CVPR 2013. + + URL: ``_ + + Dataset statistics: + - 5 camera view pairs each with two cameras + - 971, 306, 107, 193 and 239 identities from P1 - P5 + - totally 1,816 identities + - image format is png + + Protocol: Use P1 - P4 for training and P5 for evaluation. + + Note: CUHK01 and CUHK02 overlap. + """ + dataset_dir = 'cuhk02' + cam_pairs = ['P1', 'P2', 'P3', 'P4', 'P5'] + test_cam_pair = 'P5' + + def __init__(self, root='', **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir, 'Dataset') + + required_files = [self.dataset_dir] + self.check_before_run(required_files) + + train, query, gallery = self.get_data_list() + + super(CUHK02, self).__init__(train, query, gallery, **kwargs) + + def get_data_list(self): + num_train_pids, camid = 0, 0 + train, query, gallery = [], [], [] + + for cam_pair in self.cam_pairs: + cam_pair_dir = osp.join(self.dataset_dir, cam_pair) + + cam1_dir = osp.join(cam_pair_dir, 'cam1') + cam2_dir = osp.join(cam_pair_dir, 'cam2') + + impaths1 = glob.glob(osp.join(cam1_dir, '*.png')) + impaths2 = glob.glob(osp.join(cam2_dir, '*.png')) + + if cam_pair == self.test_cam_pair: + # add images to query + for impath in impaths1: + pid = osp.basename(impath).split('_')[0] + pid = int(pid) + query.append((impath, pid, camid)) + camid += 1 + + # add images to gallery + for impath in impaths2: + pid = osp.basename(impath).split('_')[0] + pid = int(pid) + gallery.append((impath, pid, camid)) + camid += 1 + + else: + pids1 = [ + osp.basename(impath).split('_')[0] for impath in impaths1 + ] + pids2 = [ + osp.basename(impath).split('_')[0] for impath in impaths2 + ] + pids = set(pids1 + pids2) + pid2label = { + pid: label + num_train_pids + for label, pid in enumerate(pids) + } + + # add images to train from cam1 + for impath in impaths1: + pid = osp.basename(impath).split('_')[0] + pid = pid2label[pid] + train.append((impath, pid, camid)) + camid += 1 + + # add images to train from cam2 + for impath in impaths2: + pid = osp.basename(impath).split('_')[0] + pid = pid2label[pid] + train.append((impath, pid, camid)) + camid += 1 + num_train_pids += len(pids) + + return train, query, gallery diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/cuhk03.py b/strong_sort/deep/reid/torchreid/data/datasets/image/cuhk03.py new file mode 100644 index 0000000000000000000000000000000000000000..cd27bc2fbd5dd345352559087aa27c1d7c088fd9 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/cuhk03.py @@ -0,0 +1,307 @@ +from __future__ import division, print_function, absolute_import +import os.path as osp + +from torchreid.utils import read_json, write_json, mkdir_if_missing + +from ..dataset import ImageDataset + + +class CUHK03(ImageDataset): + """CUHK03. + + Reference: + Li et al. DeepReID: Deep Filter Pairing Neural Network for Person Re-identification. CVPR 2014. + + URL: ``_ + + Dataset statistics: + - identities: 1360. + - images: 13164. + - cameras: 6. + - splits: 20 (classic). + """ + dataset_dir = 'cuhk03' + dataset_url = None + + def __init__( + self, + root='', + split_id=0, + cuhk03_labeled=False, + cuhk03_classic_split=False, + **kwargs + ): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.data_dir = osp.join(self.dataset_dir, 'cuhk03_release') + self.raw_mat_path = osp.join(self.data_dir, 'cuhk-03.mat') + + self.imgs_detected_dir = osp.join(self.dataset_dir, 'images_detected') + self.imgs_labeled_dir = osp.join(self.dataset_dir, 'images_labeled') + + self.split_classic_det_json_path = osp.join( + self.dataset_dir, 'splits_classic_detected.json' + ) + self.split_classic_lab_json_path = osp.join( + self.dataset_dir, 'splits_classic_labeled.json' + ) + + self.split_new_det_json_path = osp.join( + self.dataset_dir, 'splits_new_detected.json' + ) + self.split_new_lab_json_path = osp.join( + self.dataset_dir, 'splits_new_labeled.json' + ) + + self.split_new_det_mat_path = osp.join( + self.dataset_dir, 'cuhk03_new_protocol_config_detected.mat' + ) + self.split_new_lab_mat_path = osp.join( + self.dataset_dir, 'cuhk03_new_protocol_config_labeled.mat' + ) + + required_files = [ + self.dataset_dir, self.data_dir, self.raw_mat_path, + self.split_new_det_mat_path, self.split_new_lab_mat_path + ] + self.check_before_run(required_files) + + self.preprocess_split() + + if cuhk03_labeled: + split_path = self.split_classic_lab_json_path if cuhk03_classic_split else self.split_new_lab_json_path + else: + split_path = self.split_classic_det_json_path if cuhk03_classic_split else self.split_new_det_json_path + + splits = read_json(split_path) + assert split_id < len( + splits + ), 'Condition split_id ({}) < len(splits) ({}) is false'.format( + split_id, len(splits) + ) + split = splits[split_id] + + train = split['train'] + query = split['query'] + gallery = split['gallery'] + + super(CUHK03, self).__init__(train, query, gallery, **kwargs) + + def preprocess_split(self): + # This function is a bit complex and ugly, what it does is + # 1. extract data from cuhk-03.mat and save as png images + # 2. create 20 classic splits (Li et al. CVPR'14) + # 3. create new split (Zhong et al. CVPR'17) + if osp.exists(self.imgs_labeled_dir) \ + and osp.exists(self.imgs_detected_dir) \ + and osp.exists(self.split_classic_det_json_path) \ + and osp.exists(self.split_classic_lab_json_path) \ + and osp.exists(self.split_new_det_json_path) \ + and osp.exists(self.split_new_lab_json_path): + return + + import h5py + import imageio + from scipy.io import loadmat + + mkdir_if_missing(self.imgs_detected_dir) + mkdir_if_missing(self.imgs_labeled_dir) + + print( + 'Extract image data from "{}" and save as png'.format( + self.raw_mat_path + ) + ) + mat = h5py.File(self.raw_mat_path, 'r') + + def _deref(ref): + return mat[ref][:].T + + def _process_images(img_refs, campid, pid, save_dir): + img_paths = [] # Note: some persons only have images for one view + for imgid, img_ref in enumerate(img_refs): + img = _deref(img_ref) + if img.size == 0 or img.ndim < 3: + continue # skip empty cell + # images are saved with the following format, index-1 (ensure uniqueness) + # campid: index of camera pair (1-5) + # pid: index of person in 'campid'-th camera pair + # viewid: index of view, {1, 2} + # imgid: index of image, (1-10) + viewid = 1 if imgid < 5 else 2 + img_name = '{:01d}_{:03d}_{:01d}_{:02d}.png'.format( + campid + 1, pid + 1, viewid, imgid + 1 + ) + img_path = osp.join(save_dir, img_name) + if not osp.isfile(img_path): + imageio.imwrite(img_path, img) + img_paths.append(img_path) + return img_paths + + def _extract_img(image_type): + print('Processing {} images ...'.format(image_type)) + meta_data = [] + imgs_dir = self.imgs_detected_dir if image_type == 'detected' else self.imgs_labeled_dir + for campid, camp_ref in enumerate(mat[image_type][0]): + camp = _deref(camp_ref) + num_pids = camp.shape[0] + for pid in range(num_pids): + img_paths = _process_images( + camp[pid, :], campid, pid, imgs_dir + ) + assert len(img_paths) > 0, \ + 'campid{}-pid{} has no images'.format(campid, pid) + meta_data.append((campid + 1, pid + 1, img_paths)) + print( + '- done camera pair {} with {} identities'.format( + campid + 1, num_pids + ) + ) + return meta_data + + meta_detected = _extract_img('detected') + meta_labeled = _extract_img('labeled') + + def _extract_classic_split(meta_data, test_split): + train, test = [], [] + num_train_pids, num_test_pids = 0, 0 + num_train_imgs, num_test_imgs = 0, 0 + for i, (campid, pid, img_paths) in enumerate(meta_data): + + if [campid, pid] in test_split: + for img_path in img_paths: + camid = int( + osp.basename(img_path).split('_')[2] + ) - 1 # make it 0-based + test.append((img_path, num_test_pids, camid)) + num_test_pids += 1 + num_test_imgs += len(img_paths) + else: + for img_path in img_paths: + camid = int( + osp.basename(img_path).split('_')[2] + ) - 1 # make it 0-based + train.append((img_path, num_train_pids, camid)) + num_train_pids += 1 + num_train_imgs += len(img_paths) + return train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs + + print('Creating classic splits (# = 20) ...') + splits_classic_det, splits_classic_lab = [], [] + for split_ref in mat['testsets'][0]: + test_split = _deref(split_ref).tolist() + + # create split for detected images + train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ + _extract_classic_split(meta_detected, test_split) + splits_classic_det.append( + { + 'train': train, + 'query': test, + 'gallery': test, + 'num_train_pids': num_train_pids, + 'num_train_imgs': num_train_imgs, + 'num_query_pids': num_test_pids, + 'num_query_imgs': num_test_imgs, + 'num_gallery_pids': num_test_pids, + 'num_gallery_imgs': num_test_imgs + } + ) + + # create split for labeled images + train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ + _extract_classic_split(meta_labeled, test_split) + splits_classic_lab.append( + { + 'train': train, + 'query': test, + 'gallery': test, + 'num_train_pids': num_train_pids, + 'num_train_imgs': num_train_imgs, + 'num_query_pids': num_test_pids, + 'num_query_imgs': num_test_imgs, + 'num_gallery_pids': num_test_pids, + 'num_gallery_imgs': num_test_imgs + } + ) + + write_json(splits_classic_det, self.split_classic_det_json_path) + write_json(splits_classic_lab, self.split_classic_lab_json_path) + + def _extract_set(filelist, pids, pid2label, idxs, img_dir, relabel): + tmp_set = [] + unique_pids = set() + for idx in idxs: + img_name = filelist[idx][0] + camid = int(img_name.split('_')[2]) - 1 # make it 0-based + pid = pids[idx] + if relabel: + pid = pid2label[pid] + img_path = osp.join(img_dir, img_name) + tmp_set.append((img_path, int(pid), camid)) + unique_pids.add(pid) + return tmp_set, len(unique_pids), len(idxs) + + def _extract_new_split(split_dict, img_dir): + train_idxs = split_dict['train_idx'].flatten() - 1 # index-0 + pids = split_dict['labels'].flatten() + train_pids = set(pids[train_idxs]) + pid2label = {pid: label for label, pid in enumerate(train_pids)} + query_idxs = split_dict['query_idx'].flatten() - 1 + gallery_idxs = split_dict['gallery_idx'].flatten() - 1 + filelist = split_dict['filelist'].flatten() + train_info = _extract_set( + filelist, pids, pid2label, train_idxs, img_dir, relabel=True + ) + query_info = _extract_set( + filelist, pids, pid2label, query_idxs, img_dir, relabel=False + ) + gallery_info = _extract_set( + filelist, + pids, + pid2label, + gallery_idxs, + img_dir, + relabel=False + ) + return train_info, query_info, gallery_info + + print('Creating new split for detected images (767/700) ...') + train_info, query_info, gallery_info = _extract_new_split( + loadmat(self.split_new_det_mat_path), self.imgs_detected_dir + ) + split = [ + { + 'train': train_info[0], + 'query': query_info[0], + 'gallery': gallery_info[0], + 'num_train_pids': train_info[1], + 'num_train_imgs': train_info[2], + 'num_query_pids': query_info[1], + 'num_query_imgs': query_info[2], + 'num_gallery_pids': gallery_info[1], + 'num_gallery_imgs': gallery_info[2] + } + ] + write_json(split, self.split_new_det_json_path) + + print('Creating new split for labeled images (767/700) ...') + train_info, query_info, gallery_info = _extract_new_split( + loadmat(self.split_new_lab_mat_path), self.imgs_labeled_dir + ) + split = [ + { + 'train': train_info[0], + 'query': query_info[0], + 'gallery': gallery_info[0], + 'num_train_pids': train_info[1], + 'num_train_imgs': train_info[2], + 'num_query_pids': query_info[1], + 'num_query_imgs': query_info[2], + 'num_gallery_pids': gallery_info[1], + 'num_gallery_imgs': gallery_info[2] + } + ] + write_json(split, self.split_new_lab_json_path) diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/cuhksysu.py b/strong_sort/deep/reid/torchreid/data/datasets/image/cuhksysu.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c9edd74d23732be4477c7c5b9a5e2fe1464c96 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/cuhksysu.py @@ -0,0 +1,60 @@ +from __future__ import division, print_function, absolute_import +import copy +import glob +import os.path as osp + +from ..dataset import ImageDataset + + +class CUHKSYSU(ImageDataset): + """CUHKSYSU. + + This dataset can only be used for model training. + + Reference: + Xiao et al. End-to-end deep learning for person search. + + URL: ``_ + + Dataset statistics: + - identities: 11,934 + - images: 34,574 + """ + _train_only = True + dataset_dir = 'cuhksysu' + + def __init__(self, root='', **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.data_dir = osp.join(self.dataset_dir, 'cropped_images') + + # image name format: p11422_s16929_1.jpg + train = self.process_dir(self.data_dir) + query = [copy.deepcopy(train[0])] + gallery = [copy.deepcopy(train[0])] + + super(CUHKSYSU, self).__init__(train, query, gallery, **kwargs) + + def process_dir(self, dirname): + img_paths = glob.glob(osp.join(dirname, '*.jpg')) + # num_imgs = len(img_paths) + + # get all identities: + pid_container = set() + for img_path in img_paths: + img_name = osp.basename(img_path) + pid = img_name.split('_')[0] + pid_container.add(pid) + pid2label = {pid: label for label, pid in enumerate(pid_container)} + + # num_pids = len(pid_container) + + # extract data + data = [] + for img_path in img_paths: + img_name = osp.basename(img_path) + pid = img_name.split('_')[0] + label = pid2label[pid] + data.append((img_path, label, 0)) # dummy camera id + + return data diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/dukemtmcreid.py b/strong_sort/deep/reid/torchreid/data/datasets/image/dukemtmcreid.py new file mode 100644 index 0000000000000000000000000000000000000000..5915da51bf831824e5b2207d8938fbc3707c4e61 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/dukemtmcreid.py @@ -0,0 +1,68 @@ +from __future__ import division, print_function, absolute_import +import re +import glob +import os.path as osp + +from ..dataset import ImageDataset + + +class DukeMTMCreID(ImageDataset): + """DukeMTMC-reID. + + Reference: + - Ristani et al. Performance Measures and a Data Set for Multi-Target, Multi-Camera Tracking. ECCVW 2016. + - Zheng et al. Unlabeled Samples Generated by GAN Improve the Person Re-identification Baseline in vitro. ICCV 2017. + + URL: ``_ + + Dataset statistics: + - identities: 1404 (train + query). + - images:16522 (train) + 2228 (query) + 17661 (gallery). + - cameras: 8. + """ + dataset_dir = 'dukemtmc-reid' + dataset_url = 'http://vision.cs.duke.edu/DukeMTMC/data/misc/DukeMTMC-reID.zip' + + def __init__(self, root='', **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + self.train_dir = osp.join( + self.dataset_dir, 'DukeMTMC-reID/bounding_box_train' + ) + self.query_dir = osp.join(self.dataset_dir, 'DukeMTMC-reID/query') + self.gallery_dir = osp.join( + self.dataset_dir, 'DukeMTMC-reID/bounding_box_test' + ) + + required_files = [ + self.dataset_dir, self.train_dir, self.query_dir, self.gallery_dir + ] + self.check_before_run(required_files) + + train = self.process_dir(self.train_dir, relabel=True) + query = self.process_dir(self.query_dir, relabel=False) + gallery = self.process_dir(self.gallery_dir, relabel=False) + + super(DukeMTMCreID, self).__init__(train, query, gallery, **kwargs) + + def process_dir(self, dir_path, relabel=False): + img_paths = glob.glob(osp.join(dir_path, '*.jpg')) + pattern = re.compile(r'([-\d]+)_c(\d)') + + pid_container = set() + for img_path in img_paths: + pid, _ = map(int, pattern.search(img_path).groups()) + pid_container.add(pid) + pid2label = {pid: label for label, pid in enumerate(pid_container)} + + data = [] + for img_path in img_paths: + pid, camid = map(int, pattern.search(img_path).groups()) + assert 1 <= camid <= 8 + camid -= 1 # index starts from 0 + if relabel: + pid = pid2label[pid] + data.append((img_path, pid, camid)) + + return data diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/grid.py b/strong_sort/deep/reid/torchreid/data/datasets/image/grid.py new file mode 100644 index 0000000000000000000000000000000000000000..96023d62ea1cbb4eae2172184e6fd48c941c81d1 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/grid.py @@ -0,0 +1,131 @@ +from __future__ import division, print_function, absolute_import +import glob +import os.path as osp +from scipy.io import loadmat + +from torchreid.utils import read_json, write_json + +from ..dataset import ImageDataset + + +class GRID(ImageDataset): + """GRID. + + Reference: + Loy et al. Multi-camera activity correlation analysis. CVPR 2009. + + URL: ``_ + + Dataset statistics: + - identities: 250. + - images: 1275. + - cameras: 8. + """ + dataset_dir = 'grid' + dataset_url = 'http://personal.ie.cuhk.edu.hk/~ccloy/files/datasets/underground_reid.zip' + _junk_pids = [0] + + def __init__(self, root='', split_id=0, **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.probe_path = osp.join( + self.dataset_dir, 'underground_reid', 'probe' + ) + self.gallery_path = osp.join( + self.dataset_dir, 'underground_reid', 'gallery' + ) + self.split_mat_path = osp.join( + self.dataset_dir, 'underground_reid', 'features_and_partitions.mat' + ) + self.split_path = osp.join(self.dataset_dir, 'splits.json') + + required_files = [ + self.dataset_dir, self.probe_path, self.gallery_path, + self.split_mat_path + ] + self.check_before_run(required_files) + + self.prepare_split() + splits = read_json(self.split_path) + if split_id >= len(splits): + raise ValueError( + 'split_id exceeds range, received {}, ' + 'but expected between 0 and {}'.format( + split_id, + len(splits) - 1 + ) + ) + split = splits[split_id] + + train = split['train'] + query = split['query'] + gallery = split['gallery'] + + train = [tuple(item) for item in train] + query = [tuple(item) for item in query] + gallery = [tuple(item) for item in gallery] + + super(GRID, self).__init__(train, query, gallery, **kwargs) + + def prepare_split(self): + if not osp.exists(self.split_path): + print('Creating 10 random splits') + split_mat = loadmat(self.split_mat_path) + trainIdxAll = split_mat['trainIdxAll'][0] # length = 10 + probe_img_paths = sorted( + glob.glob(osp.join(self.probe_path, '*.jpeg')) + ) + gallery_img_paths = sorted( + glob.glob(osp.join(self.gallery_path, '*.jpeg')) + ) + + splits = [] + for split_idx in range(10): + train_idxs = trainIdxAll[split_idx][0][0][2][0].tolist() + assert len(train_idxs) == 125 + idx2label = { + idx: label + for label, idx in enumerate(train_idxs) + } + + train, query, gallery = [], [], [] + + # processing probe folder + for img_path in probe_img_paths: + img_name = osp.basename(img_path) + img_idx = int(img_name.split('_')[0]) + camid = int( + img_name.split('_')[1] + ) - 1 # index starts from 0 + if img_idx in train_idxs: + train.append((img_path, idx2label[img_idx], camid)) + else: + query.append((img_path, img_idx, camid)) + + # process gallery folder + for img_path in gallery_img_paths: + img_name = osp.basename(img_path) + img_idx = int(img_name.split('_')[0]) + camid = int( + img_name.split('_')[1] + ) - 1 # index starts from 0 + if img_idx in train_idxs: + train.append((img_path, idx2label[img_idx], camid)) + else: + gallery.append((img_path, img_idx, camid)) + + split = { + 'train': train, + 'query': query, + 'gallery': gallery, + 'num_train_pids': 125, + 'num_query_pids': 125, + 'num_gallery_pids': 900 + } + splits.append(split) + + print('Totally {} splits are created'.format(len(splits))) + write_json(splits, self.split_path) + print('Split file saved to {}'.format(self.split_path)) diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/ilids.py b/strong_sort/deep/reid/torchreid/data/datasets/image/ilids.py new file mode 100644 index 0000000000000000000000000000000000000000..42971b03c020fb42c23e74a64ee20699220be962 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/ilids.py @@ -0,0 +1,135 @@ +from __future__ import division, print_function, absolute_import +import copy +import glob +import random +import os.path as osp +from collections import defaultdict + +from torchreid.utils import read_json, write_json + +from ..dataset import ImageDataset + + +class iLIDS(ImageDataset): + """QMUL-iLIDS. + + Reference: + Zheng et al. Associating Groups of People. BMVC 2009. + + Dataset statistics: + - identities: 119. + - images: 476. + - cameras: 8 (not explicitly provided). + """ + dataset_dir = 'ilids' + dataset_url = 'http://www.eecs.qmul.ac.uk/~jason/data/i-LIDS_Pedestrian.tgz' + + def __init__(self, root='', split_id=0, **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.data_dir = osp.join(self.dataset_dir, 'i-LIDS_Pedestrian/Persons') + self.split_path = osp.join(self.dataset_dir, 'splits.json') + + required_files = [self.dataset_dir, self.data_dir] + self.check_before_run(required_files) + + self.prepare_split() + splits = read_json(self.split_path) + if split_id >= len(splits): + raise ValueError( + 'split_id exceeds range, received {}, but ' + 'expected between 0 and {}'.format(split_id, + len(splits) - 1) + ) + split = splits[split_id] + + train, query, gallery = self.process_split(split) + + super(iLIDS, self).__init__(train, query, gallery, **kwargs) + + def prepare_split(self): + if not osp.exists(self.split_path): + print('Creating splits ...') + + paths = glob.glob(osp.join(self.data_dir, '*.jpg')) + img_names = [osp.basename(path) for path in paths] + num_imgs = len(img_names) + assert num_imgs == 476, 'There should be 476 images, but ' \ + 'got {}, please check the data'.format(num_imgs) + + # store image names + # image naming format: + # the first four digits denote the person ID + # the last four digits denote the sequence index + pid_dict = defaultdict(list) + for img_name in img_names: + pid = int(img_name[:4]) + pid_dict[pid].append(img_name) + pids = list(pid_dict.keys()) + num_pids = len(pids) + assert num_pids == 119, 'There should be 119 identities, ' \ + 'but got {}, please check the data'.format(num_pids) + + num_train_pids = int(num_pids * 0.5) + + splits = [] + for _ in range(10): + # randomly choose num_train_pids train IDs and the rest for test IDs + pids_copy = copy.deepcopy(pids) + random.shuffle(pids_copy) + train_pids = pids_copy[:num_train_pids] + test_pids = pids_copy[num_train_pids:] + + train = [] + query = [] + gallery = [] + + # for train IDs, all images are used in the train set. + for pid in train_pids: + img_names = pid_dict[pid] + train.extend(img_names) + + # for each test ID, randomly choose two images, one for + # query and the other one for gallery. + for pid in test_pids: + img_names = pid_dict[pid] + samples = random.sample(img_names, 2) + query.append(samples[0]) + gallery.append(samples[1]) + + split = {'train': train, 'query': query, 'gallery': gallery} + splits.append(split) + + print('Totally {} splits are created'.format(len(splits))) + write_json(splits, self.split_path) + print('Split file is saved to {}'.format(self.split_path)) + + def get_pid2label(self, img_names): + pid_container = set() + for img_name in img_names: + pid = int(img_name[:4]) + pid_container.add(pid) + pid2label = {pid: label for label, pid in enumerate(pid_container)} + return pid2label + + def parse_img_names(self, img_names, pid2label=None): + data = [] + + for img_name in img_names: + pid = int(img_name[:4]) + if pid2label is not None: + pid = pid2label[pid] + camid = int(img_name[4:7]) - 1 # 0-based + img_path = osp.join(self.data_dir, img_name) + data.append((img_path, pid, camid)) + + return data + + def process_split(self, split): + train_pid2label = self.get_pid2label(split['train']) + train = self.parse_img_names(split['train'], train_pid2label) + query = self.parse_img_names(split['query']) + gallery = self.parse_img_names(split['gallery']) + return train, query, gallery diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/market1501.py b/strong_sort/deep/reid/torchreid/data/datasets/image/market1501.py new file mode 100644 index 0000000000000000000000000000000000000000..7d138d1119cf2811a2570c265849d9f74f6a721d --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/market1501.py @@ -0,0 +1,88 @@ +from __future__ import division, print_function, absolute_import +import re +import glob +import os.path as osp +import warnings + +from ..dataset import ImageDataset + + +class Market1501(ImageDataset): + """Market1501. + + Reference: + Zheng et al. Scalable Person Re-identification: A Benchmark. ICCV 2015. + + URL: ``_ + + Dataset statistics: + - identities: 1501 (+1 for background). + - images: 12936 (train) + 3368 (query) + 15913 (gallery). + """ + _junk_pids = [0, -1] + dataset_dir = 'market1501' + dataset_url = 'http://188.138.127.15:81/Datasets/Market-1501-v15.09.15.zip' + + def __init__(self, root='', market1501_500k=False, **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + # allow alternative directory structure + self.data_dir = self.dataset_dir + data_dir = osp.join(self.data_dir, 'Market-1501-v15.09.15') + if osp.isdir(data_dir): + self.data_dir = data_dir + else: + warnings.warn( + 'The current data structure is deprecated. Please ' + 'put data folders such as "bounding_box_train" under ' + '"Market-1501-v15.09.15".' + ) + + self.train_dir = osp.join(self.data_dir, 'bounding_box_train') + self.query_dir = osp.join(self.data_dir, 'query') + self.gallery_dir = osp.join(self.data_dir, 'bounding_box_test') + self.extra_gallery_dir = osp.join(self.data_dir, 'images') + self.market1501_500k = market1501_500k + + required_files = [ + self.data_dir, self.train_dir, self.query_dir, self.gallery_dir + ] + if self.market1501_500k: + required_files.append(self.extra_gallery_dir) + self.check_before_run(required_files) + + train = self.process_dir(self.train_dir, relabel=True) + query = self.process_dir(self.query_dir, relabel=False) + gallery = self.process_dir(self.gallery_dir, relabel=False) + if self.market1501_500k: + gallery += self.process_dir(self.extra_gallery_dir, relabel=False) + + super(Market1501, self).__init__(train, query, gallery, **kwargs) + + def process_dir(self, dir_path, relabel=False): + img_paths = glob.glob(osp.join(dir_path, '*.jpg')) + pattern = re.compile(r'([-\d]+)_c(\d)') + + pid_container = set() + for img_path in img_paths: + pid, _ = map(int, pattern.search(img_path).groups()) + if pid == -1: + continue # junk images are just ignored + pid_container.add(pid) + pid2label = {pid: label for label, pid in enumerate(pid_container)} + + data = [] + for img_path in img_paths: + pid, camid = map(int, pattern.search(img_path).groups()) + if pid == -1: + continue # junk images are just ignored + assert 0 <= pid <= 1501 # pid == 0 means background + assert 1 <= camid <= 6 + camid -= 1 # index starts from 0 + if relabel: + pid = pid2label[pid] + data.append((img_path, pid, camid)) + + return data diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/msmt17.py b/strong_sort/deep/reid/torchreid/data/datasets/image/msmt17.py new file mode 100644 index 0000000000000000000000000000000000000000..c4741e61ea02f0fc58e6941f4058a76b9b4ccefc --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/msmt17.py @@ -0,0 +1,98 @@ +from __future__ import division, print_function, absolute_import +import os.path as osp + +from ..dataset import ImageDataset + +# Log +# 22.01.2019 +# - add v2 +# - v1 and v2 differ in dir names +# - note that faces in v2 are blurred +TRAIN_DIR_KEY = 'train_dir' +TEST_DIR_KEY = 'test_dir' +VERSION_DICT = { + 'MSMT17_V1': { + TRAIN_DIR_KEY: 'train', + TEST_DIR_KEY: 'test', + }, + 'MSMT17_V2': { + TRAIN_DIR_KEY: 'mask_train_v2', + TEST_DIR_KEY: 'mask_test_v2', + } +} + + +class MSMT17(ImageDataset): + """MSMT17. + + Reference: + Wei et al. Person Transfer GAN to Bridge Domain Gap for Person Re-Identification. CVPR 2018. + + URL: ``_ + + Dataset statistics: + - identities: 4101. + - images: 32621 (train) + 11659 (query) + 82161 (gallery). + - cameras: 15. + """ + dataset_dir = 'msmt17' + dataset_url = None + + def __init__(self, root='', **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + has_main_dir = False + for main_dir in VERSION_DICT: + if osp.exists(osp.join(self.dataset_dir, main_dir)): + train_dir = VERSION_DICT[main_dir][TRAIN_DIR_KEY] + test_dir = VERSION_DICT[main_dir][TEST_DIR_KEY] + has_main_dir = True + break + assert has_main_dir, 'Dataset folder not found' + + self.train_dir = osp.join(self.dataset_dir, main_dir, train_dir) + self.test_dir = osp.join(self.dataset_dir, main_dir, test_dir) + self.list_train_path = osp.join( + self.dataset_dir, main_dir, 'list_train.txt' + ) + self.list_val_path = osp.join( + self.dataset_dir, main_dir, 'list_val.txt' + ) + self.list_query_path = osp.join( + self.dataset_dir, main_dir, 'list_query.txt' + ) + self.list_gallery_path = osp.join( + self.dataset_dir, main_dir, 'list_gallery.txt' + ) + + required_files = [self.dataset_dir, self.train_dir, self.test_dir] + self.check_before_run(required_files) + + train = self.process_dir(self.train_dir, self.list_train_path) + val = self.process_dir(self.train_dir, self.list_val_path) + query = self.process_dir(self.test_dir, self.list_query_path) + gallery = self.process_dir(self.test_dir, self.list_gallery_path) + + # Note: to fairly compare with published methods on the conventional ReID setting, + # do not add val images to the training set. + if 'combineall' in kwargs and kwargs['combineall']: + train += val + + super(MSMT17, self).__init__(train, query, gallery, **kwargs) + + def process_dir(self, dir_path, list_path): + with open(list_path, 'r') as txt: + lines = txt.readlines() + + data = [] + + for img_idx, img_info in enumerate(lines): + img_path, pid = img_info.split(' ') + pid = int(pid) # no need to relabel + camid = int(img_path.split('_')[2]) - 1 # index starts from 0 + img_path = osp.join(dir_path, img_path) + data.append((img_path, pid, camid)) + + return data diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/prid.py b/strong_sort/deep/reid/torchreid/data/datasets/image/prid.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d6c2058ac48ccb2e793680ee34e6d8d25bcede --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/prid.py @@ -0,0 +1,107 @@ +from __future__ import division, print_function, absolute_import +import random +import os.path as osp + +from torchreid.utils import read_json, write_json + +from ..dataset import ImageDataset + + +class PRID(ImageDataset): + """PRID (single-shot version of prid-2011) + + Reference: + Hirzer et al. Person Re-Identification by Descriptive and Discriminative + Classification. SCIA 2011. + + URL: ``_ + + Dataset statistics: + - Two views. + - View A captures 385 identities. + - View B captures 749 identities. + - 200 identities appear in both views (index starts from 1 to 200). + """ + dataset_dir = 'prid2011' + dataset_url = None + _junk_pids = list(range(201, 750)) + + def __init__(self, root='', split_id=0, **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.cam_a_dir = osp.join( + self.dataset_dir, 'prid_2011', 'single_shot', 'cam_a' + ) + self.cam_b_dir = osp.join( + self.dataset_dir, 'prid_2011', 'single_shot', 'cam_b' + ) + self.split_path = osp.join(self.dataset_dir, 'splits_single_shot.json') + + required_files = [self.dataset_dir, self.cam_a_dir, self.cam_b_dir] + self.check_before_run(required_files) + + self.prepare_split() + splits = read_json(self.split_path) + if split_id >= len(splits): + raise ValueError( + 'split_id exceeds range, received {}, but expected between 0 and {}' + .format(split_id, + len(splits) - 1) + ) + split = splits[split_id] + + train, query, gallery = self.process_split(split) + + super(PRID, self).__init__(train, query, gallery, **kwargs) + + def prepare_split(self): + if not osp.exists(self.split_path): + print('Creating splits ...') + + splits = [] + for _ in range(10): + # randomly sample 100 IDs for train and use the rest 100 IDs for test + # (note: there are only 200 IDs appearing in both views) + pids = [i for i in range(1, 201)] + train_pids = random.sample(pids, 100) + train_pids.sort() + test_pids = [i for i in pids if i not in train_pids] + split = {'train': train_pids, 'test': test_pids} + splits.append(split) + + print('Totally {} splits are created'.format(len(splits))) + write_json(splits, self.split_path) + print('Split file is saved to {}'.format(self.split_path)) + + def process_split(self, split): + train_pids = split['train'] + test_pids = split['test'] + + train_pid2label = {pid: label for label, pid in enumerate(train_pids)} + + # train + train = [] + for pid in train_pids: + img_name = 'person_' + str(pid).zfill(4) + '.png' + pid = train_pid2label[pid] + img_a_path = osp.join(self.cam_a_dir, img_name) + train.append((img_a_path, pid, 0)) + img_b_path = osp.join(self.cam_b_dir, img_name) + train.append((img_b_path, pid, 1)) + + # query and gallery + query, gallery = [], [] + for pid in test_pids: + img_name = 'person_' + str(pid).zfill(4) + '.png' + img_a_path = osp.join(self.cam_a_dir, img_name) + query.append((img_a_path, pid, 0)) + img_b_path = osp.join(self.cam_b_dir, img_name) + gallery.append((img_b_path, pid, 1)) + for pid in range(201, 750): + img_name = 'person_' + str(pid).zfill(4) + '.png' + img_b_path = osp.join(self.cam_b_dir, img_name) + gallery.append((img_b_path, pid, 1)) + + return train, query, gallery diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/sensereid.py b/strong_sort/deep/reid/torchreid/data/datasets/image/sensereid.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf5f3246665a4b4f45275a8b2c7351b0cd4ad48 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/sensereid.py @@ -0,0 +1,70 @@ +from __future__ import division, print_function, absolute_import +import copy +import glob +import os.path as osp + +from ..dataset import ImageDataset + + +class SenseReID(ImageDataset): + """SenseReID. + + This dataset is used for test purpose only. + + Reference: + Zhao et al. Spindle Net: Person Re-identification with Human Body + Region Guided Feature Decomposition and Fusion. CVPR 2017. + + URL: ``_ + + Dataset statistics: + - query: 522 ids, 1040 images. + - gallery: 1717 ids, 3388 images. + """ + dataset_dir = 'sensereid' + dataset_url = None + + def __init__(self, root='', **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.query_dir = osp.join(self.dataset_dir, 'SenseReID', 'test_probe') + self.gallery_dir = osp.join( + self.dataset_dir, 'SenseReID', 'test_gallery' + ) + + required_files = [self.dataset_dir, self.query_dir, self.gallery_dir] + self.check_before_run(required_files) + + query = self.process_dir(self.query_dir) + gallery = self.process_dir(self.gallery_dir) + + # relabel + g_pids = set() + for _, pid, _ in gallery: + g_pids.add(pid) + pid2label = {pid: i for i, pid in enumerate(g_pids)} + + query = [ + (img_path, pid2label[pid], camid) for img_path, pid, camid in query + ] + gallery = [ + (img_path, pid2label[pid], camid) + for img_path, pid, camid in gallery + ] + train = copy.deepcopy(query) + copy.deepcopy(gallery) # dummy variable + + super(SenseReID, self).__init__(train, query, gallery, **kwargs) + + def process_dir(self, dir_path): + img_paths = glob.glob(osp.join(dir_path, '*.jpg')) + data = [] + + for img_path in img_paths: + img_name = osp.splitext(osp.basename(img_path))[0] + pid, camid = img_name.split('_') + pid, camid = int(pid), int(camid) + data.append((img_path, pid, camid)) + + return data diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/university1652.py b/strong_sort/deep/reid/torchreid/data/datasets/image/university1652.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1e386b04b904dca17fb5c0b1373e648cc995ec --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/university1652.py @@ -0,0 +1,110 @@ +from __future__ import division, print_function, absolute_import +import os +import glob +import os.path as osp +import gdown + +from ..dataset import ImageDataset + + +class University1652(ImageDataset): + """University-1652. + + Reference: + - Zheng et al. University-1652: A Multi-view Multi-source Benchmark for Drone-based Geo-localization. ACM MM 2020. + + URL: ``_ + OneDrive: + https://studentutsedu-my.sharepoint.com/:u:/g/personal/12639605_student_uts_edu_au/Ecrz6xK-PcdCjFdpNb0T0s8B_9J5ynaUy3q63_XumjJyrA?e=z4hpcz + [Backup] GoogleDrive: + https://drive.google.com/file/d/1iVnP4gjw-iHXa0KerZQ1IfIO0i1jADsR/view?usp=sharing + [Backup] Baidu Yun: + https://pan.baidu.com/s/1H_wBnWwikKbaBY1pMPjoqQ password: hrqp + + Dataset statistics: + - buildings: 1652 (train + query). + - The dataset split is as follows: + | Split | #imgs | #buildings | #universities| + | -------- | ----- | ----| ----| + | Training | 50,218 | 701 | 33 | + | Query_drone | 37,855 | 701 | 39 | + | Query_satellite | 701 | 701 | 39| + | Query_ground | 2,579 | 701 | 39| + | Gallery_drone | 51,355 | 951 | 39| + | Gallery_satellite | 951 | 951 | 39| + | Gallery_ground | 2,921 | 793 | 39| + - cameras: None. + + datamanager = torchreid.data.ImageDataManager( + root='reid-data', + sources='university1652', + targets='university1652', + height=256, + width=256, + batch_size_train=32, + batch_size_test=100, + transforms=['random_flip', 'random_crop'] + ) + """ + dataset_dir = 'university1652' + dataset_url = 'https://drive.google.com/uc?id=1iVnP4gjw-iHXa0KerZQ1IfIO0i1jADsR' + + def __init__(self, root='', **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + print(self.dataset_dir) + if not os.path.isdir(self.dataset_dir): + os.mkdir(self.dataset_dir) + gdown.download( + self.dataset_url, self.dataset_dir + 'data.zip', quiet=False + ) + os.system('unzip %s' % (self.dataset_dir + 'data.zip')) + self.train_dir = osp.join( + self.dataset_dir, 'University-Release/train/' + ) + self.query_dir = osp.join( + self.dataset_dir, 'University-Release/test/query_drone' + ) + self.gallery_dir = osp.join( + self.dataset_dir, 'University-Release/test/gallery_satellite' + ) + + required_files = [ + self.dataset_dir, self.train_dir, self.query_dir, self.gallery_dir + ] + self.check_before_run(required_files) + + self.fake_camid = 0 + train = self.process_dir(self.train_dir, relabel=True, train=True) + query = self.process_dir(self.query_dir, relabel=False) + gallery = self.process_dir(self.gallery_dir, relabel=False) + + super(University1652, self).__init__(train, query, gallery, **kwargs) + + def process_dir(self, dir_path, relabel=False, train=False): + IMG_EXTENSIONS = ( + '.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', + '.webp' + ) + if train: + img_paths = glob.glob(osp.join(dir_path, '*/*/*')) + else: + img_paths = glob.glob(osp.join(dir_path, '*/*')) + pid_container = set() + for img_path in img_paths: + if not img_path.lower().endswith(IMG_EXTENSIONS): + continue + pid = int(os.path.basename(os.path.dirname(img_path))) + pid_container.add(pid) + pid2label = {pid: label for label, pid in enumerate(pid_container)} + data = [] + # no camera for university + for img_path in img_paths: + if not img_path.lower().endswith(IMG_EXTENSIONS): + continue + pid = int(os.path.basename(os.path.dirname(img_path))) + if relabel: + pid = pid2label[pid] + data.append((img_path, pid, self.fake_camid)) + self.fake_camid += 1 + return data diff --git a/strong_sort/deep/reid/torchreid/data/datasets/image/viper.py b/strong_sort/deep/reid/torchreid/data/datasets/image/viper.py new file mode 100644 index 0000000000000000000000000000000000000000..161dd99e654b43b93dcd4b46646b2d0f85a2ab1f --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/image/viper.py @@ -0,0 +1,128 @@ +from __future__ import division, print_function, absolute_import +import glob +import numpy as np +import os.path as osp + +from torchreid.utils import read_json, write_json + +from ..dataset import ImageDataset + + +class VIPeR(ImageDataset): + """VIPeR. + + Reference: + Gray et al. Evaluating appearance models for recognition, reacquisition, and tracking. PETS 2007. + + URL: ``_ + + Dataset statistics: + - identities: 632. + - images: 632 x 2 = 1264. + - cameras: 2. + """ + dataset_dir = 'viper' + dataset_url = 'http://users.soe.ucsc.edu/~manduchi/VIPeR.v1.0.zip' + + def __init__(self, root='', split_id=0, **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.cam_a_dir = osp.join(self.dataset_dir, 'VIPeR', 'cam_a') + self.cam_b_dir = osp.join(self.dataset_dir, 'VIPeR', 'cam_b') + self.split_path = osp.join(self.dataset_dir, 'splits.json') + + required_files = [self.dataset_dir, self.cam_a_dir, self.cam_b_dir] + self.check_before_run(required_files) + + self.prepare_split() + splits = read_json(self.split_path) + if split_id >= len(splits): + raise ValueError( + 'split_id exceeds range, received {}, ' + 'but expected between 0 and {}'.format( + split_id, + len(splits) - 1 + ) + ) + split = splits[split_id] + + train = split['train'] + query = split['query'] # query and gallery share the same images + gallery = split['gallery'] + + train = [tuple(item) for item in train] + query = [tuple(item) for item in query] + gallery = [tuple(item) for item in gallery] + + super(VIPeR, self).__init__(train, query, gallery, **kwargs) + + def prepare_split(self): + if not osp.exists(self.split_path): + print('Creating 10 random splits of train ids and test ids') + + cam_a_imgs = sorted(glob.glob(osp.join(self.cam_a_dir, '*.bmp'))) + cam_b_imgs = sorted(glob.glob(osp.join(self.cam_b_dir, '*.bmp'))) + assert len(cam_a_imgs) == len(cam_b_imgs) + num_pids = len(cam_a_imgs) + print('Number of identities: {}'.format(num_pids)) + num_train_pids = num_pids // 2 + """ + In total, there will be 20 splits because each random split creates two + sub-splits, one using cameraA as query and cameraB as gallery + while the other using cameraB as query and cameraA as gallery. + Therefore, results should be averaged over 20 splits (split_id=0~19). + + In practice, a model trained on split_id=0 can be applied to split_id=0&1 + as split_id=0&1 share the same training data (so on and so forth). + """ + splits = [] + for _ in range(10): + order = np.arange(num_pids) + np.random.shuffle(order) + train_idxs = order[:num_train_pids] + test_idxs = order[num_train_pids:] + assert not bool(set(train_idxs) & set(test_idxs)), \ + 'Error: train and test overlap' + + train = [] + for pid, idx in enumerate(train_idxs): + cam_a_img = cam_a_imgs[idx] + cam_b_img = cam_b_imgs[idx] + train.append((cam_a_img, pid, 0)) + train.append((cam_b_img, pid, 1)) + + test_a = [] + test_b = [] + for pid, idx in enumerate(test_idxs): + cam_a_img = cam_a_imgs[idx] + cam_b_img = cam_b_imgs[idx] + test_a.append((cam_a_img, pid, 0)) + test_b.append((cam_b_img, pid, 1)) + + # use cameraA as query and cameraB as gallery + split = { + 'train': train, + 'query': test_a, + 'gallery': test_b, + 'num_train_pids': num_train_pids, + 'num_query_pids': num_pids - num_train_pids, + 'num_gallery_pids': num_pids - num_train_pids + } + splits.append(split) + + # use cameraB as query and cameraA as gallery + split = { + 'train': train, + 'query': test_b, + 'gallery': test_a, + 'num_train_pids': num_train_pids, + 'num_query_pids': num_pids - num_train_pids, + 'num_gallery_pids': num_pids - num_train_pids + } + splits.append(split) + + print('Totally {} splits are created'.format(len(splits))) + write_json(splits, self.split_path) + print('Split file saved to {}'.format(self.split_path)) diff --git a/strong_sort/deep/reid/torchreid/data/datasets/video/__init__.py b/strong_sort/deep/reid/torchreid/data/datasets/video/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f4e75d316d4b1763c82848490b6766bf7c662654 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/video/__init__.py @@ -0,0 +1,6 @@ +from __future__ import print_function, absolute_import + +from .mars import Mars +from .ilidsvid import iLIDSVID +from .prid2011 import PRID2011 +from .dukemtmcvidreid import DukeMTMCVidReID diff --git a/strong_sort/deep/reid/torchreid/data/datasets/video/dukemtmcvidreid.py b/strong_sort/deep/reid/torchreid/data/datasets/video/dukemtmcvidreid.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4c82f9e92008bdfeb6c56b79bd24b916f83922 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/video/dukemtmcvidreid.py @@ -0,0 +1,128 @@ +from __future__ import division, print_function, absolute_import +import glob +import os.path as osp +import warnings + +from torchreid.utils import read_json, write_json + +from ..dataset import VideoDataset + + +class DukeMTMCVidReID(VideoDataset): + """DukeMTMCVidReID. + + Reference: + - Ristani et al. Performance Measures and a Data Set for Multi-Target, + Multi-Camera Tracking. ECCVW 2016. + - Wu et al. Exploit the Unknown Gradually: One-Shot Video-Based Person + Re-Identification by Stepwise Learning. CVPR 2018. + + URL: ``_ + + Dataset statistics: + - identities: 702 (train) + 702 (test). + - tracklets: 2196 (train) + 2636 (test). + """ + dataset_dir = 'dukemtmc-vidreid' + dataset_url = 'http://vision.cs.duke.edu/DukeMTMC/data/misc/DukeMTMC-VideoReID.zip' + + def __init__(self, root='', min_seq_len=0, **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.train_dir = osp.join(self.dataset_dir, 'DukeMTMC-VideoReID/train') + self.query_dir = osp.join(self.dataset_dir, 'DukeMTMC-VideoReID/query') + self.gallery_dir = osp.join( + self.dataset_dir, 'DukeMTMC-VideoReID/gallery' + ) + self.split_train_json_path = osp.join( + self.dataset_dir, 'split_train.json' + ) + self.split_query_json_path = osp.join( + self.dataset_dir, 'split_query.json' + ) + self.split_gallery_json_path = osp.join( + self.dataset_dir, 'split_gallery.json' + ) + self.min_seq_len = min_seq_len + + required_files = [ + self.dataset_dir, self.train_dir, self.query_dir, self.gallery_dir + ] + self.check_before_run(required_files) + + train = self.process_dir( + self.train_dir, self.split_train_json_path, relabel=True + ) + query = self.process_dir( + self.query_dir, self.split_query_json_path, relabel=False + ) + gallery = self.process_dir( + self.gallery_dir, self.split_gallery_json_path, relabel=False + ) + + super(DukeMTMCVidReID, self).__init__(train, query, gallery, **kwargs) + + def process_dir(self, dir_path, json_path, relabel): + if osp.exists(json_path): + split = read_json(json_path) + return split['tracklets'] + + print('=> Generating split json file (** this might take a while **)') + pdirs = glob.glob(osp.join(dir_path, '*')) # avoid .DS_Store + print( + 'Processing "{}" with {} person identities'.format( + dir_path, len(pdirs) + ) + ) + + pid_container = set() + for pdir in pdirs: + pid = int(osp.basename(pdir)) + pid_container.add(pid) + pid2label = {pid: label for label, pid in enumerate(pid_container)} + + tracklets = [] + for pdir in pdirs: + pid = int(osp.basename(pdir)) + if relabel: + pid = pid2label[pid] + tdirs = glob.glob(osp.join(pdir, '*')) + for tdir in tdirs: + raw_img_paths = glob.glob(osp.join(tdir, '*.jpg')) + num_imgs = len(raw_img_paths) + + if num_imgs < self.min_seq_len: + continue + + img_paths = [] + for img_idx in range(num_imgs): + # some tracklet starts from 0002 instead of 0001 + img_idx_name = 'F' + str(img_idx + 1).zfill(4) + res = glob.glob( + osp.join(tdir, '*' + img_idx_name + '*.jpg') + ) + if len(res) == 0: + warnings.warn( + 'Index name {} in {} is missing, skip'.format( + img_idx_name, tdir + ) + ) + continue + img_paths.append(res[0]) + img_name = osp.basename(img_paths[0]) + if img_name.find('_') == -1: + # old naming format: 0001C6F0099X30823.jpg + camid = int(img_name[5]) - 1 + else: + # new naming format: 0001_C6_F0099_X30823.jpg + camid = int(img_name[6]) - 1 + img_paths = tuple(img_paths) + tracklets.append((img_paths, pid, camid)) + + print('Saving split to {}'.format(json_path)) + split_dict = {'tracklets': tracklets} + write_json(split_dict, json_path) + + return tracklets diff --git a/strong_sort/deep/reid/torchreid/data/datasets/video/ilidsvid.py b/strong_sort/deep/reid/torchreid/data/datasets/video/ilidsvid.py new file mode 100644 index 0000000000000000000000000000000000000000..c3ac1bbe6f182301f726fb8027efab6f142808c9 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/video/ilidsvid.py @@ -0,0 +1,143 @@ +from __future__ import division, print_function, absolute_import +import glob +import os.path as osp +from scipy.io import loadmat + +from torchreid.utils import read_json, write_json + +from ..dataset import VideoDataset + + +class iLIDSVID(VideoDataset): + """iLIDS-VID. + + Reference: + Wang et al. Person Re-Identification by Video Ranking. ECCV 2014. + + URL: ``_ + + Dataset statistics: + - identities: 300. + - tracklets: 600. + - cameras: 2. + """ + dataset_dir = 'ilids-vid' + dataset_url = 'http://www.eecs.qmul.ac.uk/~xiatian/iLIDS-VID/iLIDS-VID.tar' + + def __init__(self, root='', split_id=0, **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.data_dir = osp.join(self.dataset_dir, 'i-LIDS-VID') + self.split_dir = osp.join(self.dataset_dir, 'train-test people splits') + self.split_mat_path = osp.join( + self.split_dir, 'train_test_splits_ilidsvid.mat' + ) + self.split_path = osp.join(self.dataset_dir, 'splits.json') + self.cam_1_path = osp.join( + self.dataset_dir, 'i-LIDS-VID/sequences/cam1' + ) + self.cam_2_path = osp.join( + self.dataset_dir, 'i-LIDS-VID/sequences/cam2' + ) + + required_files = [self.dataset_dir, self.data_dir, self.split_dir] + self.check_before_run(required_files) + + self.prepare_split() + splits = read_json(self.split_path) + if split_id >= len(splits): + raise ValueError( + 'split_id exceeds range, received {}, but expected between 0 and {}' + .format(split_id, + len(splits) - 1) + ) + split = splits[split_id] + train_dirs, test_dirs = split['train'], split['test'] + + train = self.process_data(train_dirs, cam1=True, cam2=True) + query = self.process_data(test_dirs, cam1=True, cam2=False) + gallery = self.process_data(test_dirs, cam1=False, cam2=True) + + super(iLIDSVID, self).__init__(train, query, gallery, **kwargs) + + def prepare_split(self): + if not osp.exists(self.split_path): + print('Creating splits ...') + mat_split_data = loadmat(self.split_mat_path)['ls_set'] + + num_splits = mat_split_data.shape[0] + num_total_ids = mat_split_data.shape[1] + assert num_splits == 10 + assert num_total_ids == 300 + num_ids_each = num_total_ids // 2 + + # pids in mat_split_data are indices, so we need to transform them + # to real pids + person_cam1_dirs = sorted( + glob.glob(osp.join(self.cam_1_path, '*')) + ) + person_cam2_dirs = sorted( + glob.glob(osp.join(self.cam_2_path, '*')) + ) + + person_cam1_dirs = [ + osp.basename(item) for item in person_cam1_dirs + ] + person_cam2_dirs = [ + osp.basename(item) for item in person_cam2_dirs + ] + + # make sure persons in one camera view can be found in the other camera view + assert set(person_cam1_dirs) == set(person_cam2_dirs) + + splits = [] + for i_split in range(num_splits): + # first 50% for testing and the remaining for training, following Wang et al. ECCV'14. + train_idxs = sorted( + list(mat_split_data[i_split, num_ids_each:]) + ) + test_idxs = sorted( + list(mat_split_data[i_split, :num_ids_each]) + ) + + train_idxs = [int(i) - 1 for i in train_idxs] + test_idxs = [int(i) - 1 for i in test_idxs] + + # transform pids to person dir names + train_dirs = [person_cam1_dirs[i] for i in train_idxs] + test_dirs = [person_cam1_dirs[i] for i in test_idxs] + + split = {'train': train_dirs, 'test': test_dirs} + splits.append(split) + + print( + 'Totally {} splits are created, following Wang et al. ECCV\'14' + .format(len(splits)) + ) + print('Split file is saved to {}'.format(self.split_path)) + write_json(splits, self.split_path) + + def process_data(self, dirnames, cam1=True, cam2=True): + tracklets = [] + dirname2pid = {dirname: i for i, dirname in enumerate(dirnames)} + + for dirname in dirnames: + if cam1: + person_dir = osp.join(self.cam_1_path, dirname) + img_names = glob.glob(osp.join(person_dir, '*.png')) + assert len(img_names) > 0 + img_names = tuple(img_names) + pid = dirname2pid[dirname] + tracklets.append((img_names, pid, 0)) + + if cam2: + person_dir = osp.join(self.cam_2_path, dirname) + img_names = glob.glob(osp.join(person_dir, '*.png')) + assert len(img_names) > 0 + img_names = tuple(img_names) + pid = dirname2pid[dirname] + tracklets.append((img_names, pid, 1)) + + return tracklets diff --git a/strong_sort/deep/reid/torchreid/data/datasets/video/mars.py b/strong_sort/deep/reid/torchreid/data/datasets/video/mars.py new file mode 100644 index 0000000000000000000000000000000000000000..4128e1cbf53ca39fad8e468eed90c3d80c9310a5 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/video/mars.py @@ -0,0 +1,133 @@ +from __future__ import division, print_function, absolute_import +import os.path as osp +import warnings +from scipy.io import loadmat + +from ..dataset import VideoDataset + + +class Mars(VideoDataset): + """MARS. + + Reference: + Zheng et al. MARS: A Video Benchmark for Large-Scale Person Re-identification. ECCV 2016. + + URL: ``_ + + Dataset statistics: + - identities: 1261. + - tracklets: 8298 (train) + 1980 (query) + 9330 (gallery). + - cameras: 6. + """ + dataset_dir = 'mars' + dataset_url = None + + def __init__(self, root='', **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.train_name_path = osp.join( + self.dataset_dir, 'info/train_name.txt' + ) + self.test_name_path = osp.join(self.dataset_dir, 'info/test_name.txt') + self.track_train_info_path = osp.join( + self.dataset_dir, 'info/tracks_train_info.mat' + ) + self.track_test_info_path = osp.join( + self.dataset_dir, 'info/tracks_test_info.mat' + ) + self.query_IDX_path = osp.join(self.dataset_dir, 'info/query_IDX.mat') + + required_files = [ + self.dataset_dir, self.train_name_path, self.test_name_path, + self.track_train_info_path, self.track_test_info_path, + self.query_IDX_path + ] + self.check_before_run(required_files) + + train_names = self.get_names(self.train_name_path) + test_names = self.get_names(self.test_name_path) + track_train = loadmat(self.track_train_info_path + )['track_train_info'] # numpy.ndarray (8298, 4) + track_test = loadmat(self.track_test_info_path + )['track_test_info'] # numpy.ndarray (12180, 4) + query_IDX = loadmat(self.query_IDX_path + )['query_IDX'].squeeze() # numpy.ndarray (1980,) + query_IDX -= 1 # index from 0 + track_query = track_test[query_IDX, :] + gallery_IDX = [ + i for i in range(track_test.shape[0]) if i not in query_IDX + ] + track_gallery = track_test[gallery_IDX, :] + + train = self.process_data( + train_names, track_train, home_dir='bbox_train', relabel=True + ) + query = self.process_data( + test_names, track_query, home_dir='bbox_test', relabel=False + ) + gallery = self.process_data( + test_names, track_gallery, home_dir='bbox_test', relabel=False + ) + + super(Mars, self).__init__(train, query, gallery, **kwargs) + + def get_names(self, fpath): + names = [] + with open(fpath, 'r') as f: + for line in f: + new_line = line.rstrip() + names.append(new_line) + return names + + def process_data( + self, names, meta_data, home_dir=None, relabel=False, min_seq_len=0 + ): + assert home_dir in ['bbox_train', 'bbox_test'] + num_tracklets = meta_data.shape[0] + pid_list = list(set(meta_data[:, 2].tolist())) + + if relabel: + pid2label = {pid: label for label, pid in enumerate(pid_list)} + tracklets = [] + + for tracklet_idx in range(num_tracklets): + data = meta_data[tracklet_idx, ...] + start_index, end_index, pid, camid = data + if pid == -1: + continue # junk images are just ignored + assert 1 <= camid <= 6 + if relabel: + pid = pid2label[pid] + camid -= 1 # index starts from 0 + img_names = names[start_index - 1:end_index] + + # make sure image names correspond to the same person + pnames = [img_name[:4] for img_name in img_names] + assert len( + set(pnames) + ) == 1, 'Error: a single tracklet contains different person images' + + # make sure all images are captured under the same camera + camnames = [img_name[5] for img_name in img_names] + assert len( + set(camnames) + ) == 1, 'Error: images are captured under different cameras!' + + # append image names with directory information + img_paths = [ + osp.join(self.dataset_dir, home_dir, img_name[:4], img_name) + for img_name in img_names + ] + if len(img_paths) >= min_seq_len: + img_paths = tuple(img_paths) + tracklets.append((img_paths, pid, camid)) + + return tracklets + + def combine_all(self): + warnings.warn( + 'Some query IDs do not appear in gallery. Therefore, combineall ' + 'does not make any difference to Mars' + ) diff --git a/strong_sort/deep/reid/torchreid/data/datasets/video/prid2011.py b/strong_sort/deep/reid/torchreid/data/datasets/video/prid2011.py new file mode 100644 index 0000000000000000000000000000000000000000..3af2e4d1ffd6ccc71f2b5705090c5931602f1e3e --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/datasets/video/prid2011.py @@ -0,0 +1,80 @@ +from __future__ import division, print_function, absolute_import +import glob +import os.path as osp + +from torchreid.utils import read_json + +from ..dataset import VideoDataset + + +class PRID2011(VideoDataset): + """PRID2011. + + Reference: + Hirzer et al. Person Re-Identification by Descriptive and + Discriminative Classification. SCIA 2011. + + URL: ``_ + + Dataset statistics: + - identities: 200. + - tracklets: 400. + - cameras: 2. + """ + dataset_dir = 'prid2011' + dataset_url = None + + def __init__(self, root='', split_id=0, **kwargs): + self.root = osp.abspath(osp.expanduser(root)) + self.dataset_dir = osp.join(self.root, self.dataset_dir) + self.download_dataset(self.dataset_dir, self.dataset_url) + + self.split_path = osp.join(self.dataset_dir, 'splits_prid2011.json') + self.cam_a_dir = osp.join( + self.dataset_dir, 'prid_2011', 'multi_shot', 'cam_a' + ) + self.cam_b_dir = osp.join( + self.dataset_dir, 'prid_2011', 'multi_shot', 'cam_b' + ) + + required_files = [self.dataset_dir, self.cam_a_dir, self.cam_b_dir] + self.check_before_run(required_files) + + splits = read_json(self.split_path) + if split_id >= len(splits): + raise ValueError( + 'split_id exceeds range, received {}, but expected between 0 and {}' + .format(split_id, + len(splits) - 1) + ) + split = splits[split_id] + train_dirs, test_dirs = split['train'], split['test'] + + train = self.process_dir(train_dirs, cam1=True, cam2=True) + query = self.process_dir(test_dirs, cam1=True, cam2=False) + gallery = self.process_dir(test_dirs, cam1=False, cam2=True) + + super(PRID2011, self).__init__(train, query, gallery, **kwargs) + + def process_dir(self, dirnames, cam1=True, cam2=True): + tracklets = [] + dirname2pid = {dirname: i for i, dirname in enumerate(dirnames)} + + for dirname in dirnames: + if cam1: + person_dir = osp.join(self.cam_a_dir, dirname) + img_names = glob.glob(osp.join(person_dir, '*.png')) + assert len(img_names) > 0 + img_names = tuple(img_names) + pid = dirname2pid[dirname] + tracklets.append((img_names, pid, 0)) + + if cam2: + person_dir = osp.join(self.cam_b_dir, dirname) + img_names = glob.glob(osp.join(person_dir, '*.png')) + assert len(img_names) > 0 + img_names = tuple(img_names) + pid = dirname2pid[dirname] + tracklets.append((img_names, pid, 1)) + + return tracklets diff --git a/strong_sort/deep/reid/torchreid/data/sampler.py b/strong_sort/deep/reid/torchreid/data/sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..f69b3e02a7f111bc88595dae7a6fe64b25e0703d --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/sampler.py @@ -0,0 +1,245 @@ +from __future__ import division, absolute_import +import copy +import numpy as np +import random +from collections import defaultdict +from torch.utils.data.sampler import Sampler, RandomSampler, SequentialSampler + +AVAI_SAMPLERS = [ + 'RandomIdentitySampler', 'SequentialSampler', 'RandomSampler', + 'RandomDomainSampler', 'RandomDatasetSampler' +] + + +class RandomIdentitySampler(Sampler): + """Randomly samples N identities each with K instances. + + Args: + data_source (list): contains tuples of (img_path(s), pid, camid, dsetid). + batch_size (int): batch size. + num_instances (int): number of instances per identity in a batch. + """ + + def __init__(self, data_source, batch_size, num_instances): + if batch_size < num_instances: + raise ValueError( + 'batch_size={} must be no less ' + 'than num_instances={}'.format(batch_size, num_instances) + ) + + self.data_source = data_source + self.batch_size = batch_size + self.num_instances = num_instances + self.num_pids_per_batch = self.batch_size // self.num_instances + self.index_dic = defaultdict(list) + for index, items in enumerate(data_source): + pid = items[1] + self.index_dic[pid].append(index) + self.pids = list(self.index_dic.keys()) + assert len(self.pids) >= self.num_pids_per_batch + + # estimate number of examples in an epoch + # TODO: improve precision + self.length = 0 + for pid in self.pids: + idxs = self.index_dic[pid] + num = len(idxs) + if num < self.num_instances: + num = self.num_instances + self.length += num - num % self.num_instances + + def __iter__(self): + batch_idxs_dict = defaultdict(list) + + for pid in self.pids: + idxs = copy.deepcopy(self.index_dic[pid]) + if len(idxs) < self.num_instances: + idxs = np.random.choice( + idxs, size=self.num_instances, replace=True + ) + random.shuffle(idxs) + batch_idxs = [] + for idx in idxs: + batch_idxs.append(idx) + if len(batch_idxs) == self.num_instances: + batch_idxs_dict[pid].append(batch_idxs) + batch_idxs = [] + + avai_pids = copy.deepcopy(self.pids) + final_idxs = [] + + while len(avai_pids) >= self.num_pids_per_batch: + selected_pids = random.sample(avai_pids, self.num_pids_per_batch) + for pid in selected_pids: + batch_idxs = batch_idxs_dict[pid].pop(0) + final_idxs.extend(batch_idxs) + if len(batch_idxs_dict[pid]) == 0: + avai_pids.remove(pid) + + return iter(final_idxs) + + def __len__(self): + return self.length + + +class RandomDomainSampler(Sampler): + """Random domain sampler. + + We consider each camera as a visual domain. + + How does the sampling work: + 1. Randomly sample N cameras (based on the "camid" label). + 2. From each camera, randomly sample K images. + + Args: + data_source (list): contains tuples of (img_path(s), pid, camid, dsetid). + batch_size (int): batch size. + n_domain (int): number of cameras to sample in a batch. + """ + + def __init__(self, data_source, batch_size, n_domain): + self.data_source = data_source + + # Keep track of image indices for each domain + self.domain_dict = defaultdict(list) + for i, items in enumerate(data_source): + camid = items[2] + self.domain_dict[camid].append(i) + self.domains = list(self.domain_dict.keys()) + + # Make sure each domain can be assigned an equal number of images + if n_domain is None or n_domain <= 0: + n_domain = len(self.domains) + assert batch_size % n_domain == 0 + self.n_img_per_domain = batch_size // n_domain + + self.batch_size = batch_size + self.n_domain = n_domain + self.length = len(list(self.__iter__())) + + def __iter__(self): + domain_dict = copy.deepcopy(self.domain_dict) + final_idxs = [] + stop_sampling = False + + while not stop_sampling: + selected_domains = random.sample(self.domains, self.n_domain) + + for domain in selected_domains: + idxs = domain_dict[domain] + selected_idxs = random.sample(idxs, self.n_img_per_domain) + final_idxs.extend(selected_idxs) + + for idx in selected_idxs: + domain_dict[domain].remove(idx) + + remaining = len(domain_dict[domain]) + if remaining < self.n_img_per_domain: + stop_sampling = True + + return iter(final_idxs) + + def __len__(self): + return self.length + + +class RandomDatasetSampler(Sampler): + """Random dataset sampler. + + How does the sampling work: + 1. Randomly sample N datasets (based on the "dsetid" label). + 2. From each dataset, randomly sample K images. + + Args: + data_source (list): contains tuples of (img_path(s), pid, camid, dsetid). + batch_size (int): batch size. + n_dataset (int): number of datasets to sample in a batch. + """ + + def __init__(self, data_source, batch_size, n_dataset): + self.data_source = data_source + + # Keep track of image indices for each dataset + self.dataset_dict = defaultdict(list) + for i, items in enumerate(data_source): + dsetid = items[3] + self.dataset_dict[dsetid].append(i) + self.datasets = list(self.dataset_dict.keys()) + + # Make sure each dataset can be assigned an equal number of images + if n_dataset is None or n_dataset <= 0: + n_dataset = len(self.datasets) + assert batch_size % n_dataset == 0 + self.n_img_per_dset = batch_size // n_dataset + + self.batch_size = batch_size + self.n_dataset = n_dataset + self.length = len(list(self.__iter__())) + + def __iter__(self): + dataset_dict = copy.deepcopy(self.dataset_dict) + final_idxs = [] + stop_sampling = False + + while not stop_sampling: + selected_datasets = random.sample(self.datasets, self.n_dataset) + + for dset in selected_datasets: + idxs = dataset_dict[dset] + selected_idxs = random.sample(idxs, self.n_img_per_dset) + final_idxs.extend(selected_idxs) + + for idx in selected_idxs: + dataset_dict[dset].remove(idx) + + remaining = len(dataset_dict[dset]) + if remaining < self.n_img_per_dset: + stop_sampling = True + + return iter(final_idxs) + + def __len__(self): + return self.length + + +def build_train_sampler( + data_source, + train_sampler, + batch_size=32, + num_instances=4, + num_cams=1, + num_datasets=1, + **kwargs +): + """Builds a training sampler. + + Args: + data_source (list): contains tuples of (img_path(s), pid, camid). + train_sampler (str): sampler name (default: ``RandomSampler``). + batch_size (int, optional): batch size. Default is 32. + num_instances (int, optional): number of instances per identity in a + batch (when using ``RandomIdentitySampler``). Default is 4. + num_cams (int, optional): number of cameras to sample in a batch (when using + ``RandomDomainSampler``). Default is 1. + num_datasets (int, optional): number of datasets to sample in a batch (when + using ``RandomDatasetSampler``). Default is 1. + """ + assert train_sampler in AVAI_SAMPLERS, \ + 'train_sampler must be one of {}, but got {}'.format(AVAI_SAMPLERS, train_sampler) + + if train_sampler == 'RandomIdentitySampler': + sampler = RandomIdentitySampler(data_source, batch_size, num_instances) + + elif train_sampler == 'RandomDomainSampler': + sampler = RandomDomainSampler(data_source, batch_size, num_cams) + + elif train_sampler == 'RandomDatasetSampler': + sampler = RandomDatasetSampler(data_source, batch_size, num_datasets) + + elif train_sampler == 'SequentialSampler': + sampler = SequentialSampler(data_source) + + elif train_sampler == 'RandomSampler': + sampler = RandomSampler(data_source) + + return sampler diff --git a/strong_sort/deep/reid/torchreid/data/transforms.py b/strong_sort/deep/reid/torchreid/data/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..0c09ca0ed0a0316c3a3087f1ca137fdde0c48be1 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/data/transforms.py @@ -0,0 +1,326 @@ +from __future__ import division, print_function, absolute_import +import math +import random +from collections import deque +import torch +from PIL import Image +from torchvision.transforms import ( + Resize, Compose, ToTensor, Normalize, ColorJitter, RandomHorizontalFlip +) + + +class Random2DTranslation(object): + """Randomly translates the input image with a probability. + + Specifically, given a predefined shape (height, width), the input is first + resized with a factor of 1.125, leading to (height*1.125, width*1.125), then + a random crop is performed. Such operation is done with a probability. + + Args: + height (int): target image height. + width (int): target image width. + p (float, optional): probability that this operation takes place. + Default is 0.5. + interpolation (int, optional): desired interpolation. Default is + ``PIL.Image.BILINEAR`` + """ + + def __init__(self, height, width, p=0.5, interpolation=Image.BILINEAR): + self.height = height + self.width = width + self.p = p + self.interpolation = interpolation + + def __call__(self, img): + if random.uniform(0, 1) > self.p: + return img.resize((self.width, self.height), self.interpolation) + + new_width, new_height = int(round(self.width * 1.125) + ), int(round(self.height * 1.125)) + resized_img = img.resize((new_width, new_height), self.interpolation) + x_maxrange = new_width - self.width + y_maxrange = new_height - self.height + x1 = int(round(random.uniform(0, x_maxrange))) + y1 = int(round(random.uniform(0, y_maxrange))) + croped_img = resized_img.crop( + (x1, y1, x1 + self.width, y1 + self.height) + ) + return croped_img + + +class RandomErasing(object): + """Randomly erases an image patch. + + Origin: ``_ + + Reference: + Zhong et al. Random Erasing Data Augmentation. + + Args: + probability (float, optional): probability that this operation takes place. + Default is 0.5. + sl (float, optional): min erasing area. + sh (float, optional): max erasing area. + r1 (float, optional): min aspect ratio. + mean (list, optional): erasing value. + """ + + def __init__( + self, + probability=0.5, + sl=0.02, + sh=0.4, + r1=0.3, + mean=[0.4914, 0.4822, 0.4465] + ): + self.probability = probability + self.mean = mean + self.sl = sl + self.sh = sh + self.r1 = r1 + + def __call__(self, img): + if random.uniform(0, 1) > self.probability: + return img + + for attempt in range(100): + area = img.size()[1] * img.size()[2] + + target_area = random.uniform(self.sl, self.sh) * area + aspect_ratio = random.uniform(self.r1, 1 / self.r1) + + h = int(round(math.sqrt(target_area * aspect_ratio))) + w = int(round(math.sqrt(target_area / aspect_ratio))) + + if w < img.size()[2] and h < img.size()[1]: + x1 = random.randint(0, img.size()[1] - h) + y1 = random.randint(0, img.size()[2] - w) + if img.size()[0] == 3: + img[0, x1:x1 + h, y1:y1 + w] = self.mean[0] + img[1, x1:x1 + h, y1:y1 + w] = self.mean[1] + img[2, x1:x1 + h, y1:y1 + w] = self.mean[2] + else: + img[0, x1:x1 + h, y1:y1 + w] = self.mean[0] + return img + + return img + + +class ColorAugmentation(object): + """Randomly alters the intensities of RGB channels. + + Reference: + Krizhevsky et al. ImageNet Classification with Deep ConvolutionalNeural + Networks. NIPS 2012. + + Args: + p (float, optional): probability that this operation takes place. + Default is 0.5. + """ + + def __init__(self, p=0.5): + self.p = p + self.eig_vec = torch.Tensor( + [ + [0.4009, 0.7192, -0.5675], + [-0.8140, -0.0045, -0.5808], + [0.4203, -0.6948, -0.5836], + ] + ) + self.eig_val = torch.Tensor([[0.2175, 0.0188, 0.0045]]) + + def _check_input(self, tensor): + assert tensor.dim() == 3 and tensor.size(0) == 3 + + def __call__(self, tensor): + if random.uniform(0, 1) > self.p: + return tensor + alpha = torch.normal(mean=torch.zeros_like(self.eig_val)) * 0.1 + quatity = torch.mm(self.eig_val * alpha, self.eig_vec) + tensor = tensor + quatity.view(3, 1, 1) + return tensor + + +class RandomPatch(object): + """Random patch data augmentation. + + There is a patch pool that stores randomly extracted pathces from person images. + + For each input image, RandomPatch + 1) extracts a random patch and stores the patch in the patch pool; + 2) randomly selects a patch from the patch pool and pastes it on the + input (at random position) to simulate occlusion. + + Reference: + - Zhou et al. Omni-Scale Feature Learning for Person Re-Identification. ICCV, 2019. + - Zhou et al. Learning Generalisable Omni-Scale Representations + for Person Re-Identification. TPAMI, 2021. + """ + + def __init__( + self, + prob_happen=0.5, + pool_capacity=50000, + min_sample_size=100, + patch_min_area=0.01, + patch_max_area=0.5, + patch_min_ratio=0.1, + prob_rotate=0.5, + prob_flip_leftright=0.5, + ): + self.prob_happen = prob_happen + + self.patch_min_area = patch_min_area + self.patch_max_area = patch_max_area + self.patch_min_ratio = patch_min_ratio + + self.prob_rotate = prob_rotate + self.prob_flip_leftright = prob_flip_leftright + + self.patchpool = deque(maxlen=pool_capacity) + self.min_sample_size = min_sample_size + + def generate_wh(self, W, H): + area = W * H + for attempt in range(100): + target_area = random.uniform( + self.patch_min_area, self.patch_max_area + ) * area + aspect_ratio = random.uniform( + self.patch_min_ratio, 1. / self.patch_min_ratio + ) + h = int(round(math.sqrt(target_area * aspect_ratio))) + w = int(round(math.sqrt(target_area / aspect_ratio))) + if w < W and h < H: + return w, h + return None, None + + def transform_patch(self, patch): + if random.uniform(0, 1) > self.prob_flip_leftright: + patch = patch.transpose(Image.FLIP_LEFT_RIGHT) + if random.uniform(0, 1) > self.prob_rotate: + patch = patch.rotate(random.randint(-10, 10)) + return patch + + def __call__(self, img): + W, H = img.size # original image size + + # collect new patch + w, h = self.generate_wh(W, H) + if w is not None and h is not None: + x1 = random.randint(0, W - w) + y1 = random.randint(0, H - h) + new_patch = img.crop((x1, y1, x1 + w, y1 + h)) + self.patchpool.append(new_patch) + + if len(self.patchpool) < self.min_sample_size: + return img + + if random.uniform(0, 1) > self.prob_happen: + return img + + # paste a randomly selected patch on a random position + patch = random.sample(self.patchpool, 1)[0] + patchW, patchH = patch.size + x1 = random.randint(0, W - patchW) + y1 = random.randint(0, H - patchH) + patch = self.transform_patch(patch) + img.paste(patch, (x1, y1)) + + return img + + +def build_transforms( + height, + width, + transforms='random_flip', + norm_mean=[0.485, 0.456, 0.406], + norm_std=[0.229, 0.224, 0.225], + **kwargs +): + """Builds train and test transform functions. + + Args: + height (int): target image height. + width (int): target image width. + transforms (str or list of str, optional): transformations applied to model training. + Default is 'random_flip'. + norm_mean (list or None, optional): normalization mean values. Default is ImageNet means. + norm_std (list or None, optional): normalization standard deviation values. Default is + ImageNet standard deviation values. + """ + if transforms is None: + transforms = [] + + if isinstance(transforms, str): + transforms = [transforms] + + if not isinstance(transforms, list): + raise ValueError( + 'transforms must be a list of strings, but found to be {}'.format( + type(transforms) + ) + ) + + if len(transforms) > 0: + transforms = [t.lower() for t in transforms] + + if norm_mean is None or norm_std is None: + norm_mean = [0.485, 0.456, 0.406] # imagenet mean + norm_std = [0.229, 0.224, 0.225] # imagenet std + normalize = Normalize(mean=norm_mean, std=norm_std) + + print('Building train transforms ...') + transform_tr = [] + + print('+ resize to {}x{}'.format(height, width)) + transform_tr += [Resize((height, width))] + + if 'random_flip' in transforms: + print('+ random flip') + transform_tr += [RandomHorizontalFlip()] + + if 'random_crop' in transforms: + print( + '+ random crop (enlarge to {}x{} and ' + 'crop {}x{})'.format( + int(round(height * 1.125)), int(round(width * 1.125)), height, + width + ) + ) + transform_tr += [Random2DTranslation(height, width)] + + if 'random_patch' in transforms: + print('+ random patch') + transform_tr += [RandomPatch()] + + if 'color_jitter' in transforms: + print('+ color jitter') + transform_tr += [ + ColorJitter(brightness=0.2, contrast=0.15, saturation=0, hue=0) + ] + + print('+ to torch tensor of range [0, 1]') + transform_tr += [ToTensor()] + + print('+ normalization (mean={}, std={})'.format(norm_mean, norm_std)) + transform_tr += [normalize] + + if 'random_erase' in transforms: + print('+ random erase') + transform_tr += [RandomErasing(mean=norm_mean)] + + transform_tr = Compose(transform_tr) + + print('Building test transforms ...') + print('+ resize to {}x{}'.format(height, width)) + print('+ to torch tensor of range [0, 1]') + print('+ normalization (mean={}, std={})'.format(norm_mean, norm_std)) + + transform_te = Compose([ + Resize((height, width)), + ToTensor(), + normalize, + ]) + + return transform_tr, transform_te diff --git a/strong_sort/deep/reid/torchreid/engine/__init__.py b/strong_sort/deep/reid/torchreid/engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a39cc7f767e5350132b5e165a87624c7ca80bf80 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/engine/__init__.py @@ -0,0 +1,5 @@ +from __future__ import print_function, absolute_import + +from .image import ImageSoftmaxEngine, ImageTripletEngine +from .video import VideoSoftmaxEngine, VideoTripletEngine +from .engine import Engine diff --git a/strong_sort/deep/reid/torchreid/engine/engine.py b/strong_sort/deep/reid/torchreid/engine/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..bbc01e09ea542c4f2c08b49a78e3610627a0143a --- /dev/null +++ b/strong_sort/deep/reid/torchreid/engine/engine.py @@ -0,0 +1,478 @@ +from __future__ import division, print_function, absolute_import +import time +import numpy as np +import os.path as osp +import datetime +from collections import OrderedDict +import torch +from torch.nn import functional as F +from torch.utils.tensorboard import SummaryWriter + +from torchreid import metrics +from torchreid.utils import ( + MetricMeter, AverageMeter, re_ranking, open_all_layers, save_checkpoint, + open_specified_layers, visualize_ranked_results +) +from torchreid.losses import DeepSupervision + + +class Engine(object): + r"""A generic base Engine class for both image- and video-reid. + + Args: + datamanager (DataManager): an instance of ``torchreid.data.ImageDataManager`` + or ``torchreid.data.VideoDataManager``. + use_gpu (bool, optional): use gpu. Default is True. + """ + + def __init__(self, datamanager, use_gpu=True): + self.datamanager = datamanager + self.train_loader = self.datamanager.train_loader + self.test_loader = self.datamanager.test_loader + self.use_gpu = (torch.cuda.is_available() and use_gpu) + self.writer = None + self.epoch = 0 + + self.model = None + self.optimizer = None + self.scheduler = None + + self._models = OrderedDict() + self._optims = OrderedDict() + self._scheds = OrderedDict() + + def register_model(self, name='model', model=None, optim=None, sched=None): + if self.__dict__.get('_models') is None: + raise AttributeError( + 'Cannot assign model before super().__init__() call' + ) + + if self.__dict__.get('_optims') is None: + raise AttributeError( + 'Cannot assign optim before super().__init__() call' + ) + + if self.__dict__.get('_scheds') is None: + raise AttributeError( + 'Cannot assign sched before super().__init__() call' + ) + + self._models[name] = model + self._optims[name] = optim + self._scheds[name] = sched + + def get_model_names(self, names=None): + names_real = list(self._models.keys()) + if names is not None: + if not isinstance(names, list): + names = [names] + for name in names: + assert name in names_real + return names + else: + return names_real + + def save_model(self, epoch, rank1, save_dir, is_best=False): + names = self.get_model_names() + + for name in names: + save_checkpoint( + { + 'state_dict': self._models[name].state_dict(), + 'epoch': epoch + 1, + 'rank1': rank1, + 'optimizer': self._optims[name].state_dict(), + 'scheduler': self._scheds[name].state_dict() + }, + osp.join(save_dir, name), + is_best=is_best + ) + + def set_model_mode(self, mode='train', names=None): + assert mode in ['train', 'eval', 'test'] + names = self.get_model_names(names) + + for name in names: + if mode == 'train': + self._models[name].train() + else: + self._models[name].eval() + + def get_current_lr(self, names=None): + names = self.get_model_names(names) + name = names[0] + return self._optims[name].param_groups[-1]['lr'] + + def update_lr(self, names=None): + names = self.get_model_names(names) + + for name in names: + if self._scheds[name] is not None: + self._scheds[name].step() + + def run( + self, + save_dir='log', + max_epoch=0, + start_epoch=0, + print_freq=10, + fixbase_epoch=0, + open_layers=None, + start_eval=0, + eval_freq=-1, + test_only=False, + dist_metric='euclidean', + normalize_feature=False, + visrank=False, + visrank_topk=10, + use_metric_cuhk03=False, + ranks=[1, 5, 10, 20], + rerank=False + ): + r"""A unified pipeline for training and evaluating a model. + + Args: + save_dir (str): directory to save model. + max_epoch (int): maximum epoch. + start_epoch (int, optional): starting epoch. Default is 0. + print_freq (int, optional): print_frequency. Default is 10. + fixbase_epoch (int, optional): number of epochs to train ``open_layers`` (new layers) + while keeping base layers frozen. Default is 0. ``fixbase_epoch`` is counted + in ``max_epoch``. + open_layers (str or list, optional): layers (attribute names) open for training. + start_eval (int, optional): from which epoch to start evaluation. Default is 0. + eval_freq (int, optional): evaluation frequency. Default is -1 (meaning evaluation + is only performed at the end of training). + test_only (bool, optional): if True, only runs evaluation on test datasets. + Default is False. + dist_metric (str, optional): distance metric used to compute distance matrix + between query and gallery. Default is "euclidean". + normalize_feature (bool, optional): performs L2 normalization on feature vectors before + computing feature distance. Default is False. + visrank (bool, optional): visualizes ranked results. Default is False. It is recommended to + enable ``visrank`` when ``test_only`` is True. The ranked images will be saved to + "save_dir/visrank_dataset", e.g. "save_dir/visrank_market1501". + visrank_topk (int, optional): top-k ranked images to be visualized. Default is 10. + use_metric_cuhk03 (bool, optional): use single-gallery-shot setting for cuhk03. + Default is False. This should be enabled when using cuhk03 classic split. + ranks (list, optional): cmc ranks to be computed. Default is [1, 5, 10, 20]. + rerank (bool, optional): uses person re-ranking (by Zhong et al. CVPR'17). + Default is False. This is only enabled when test_only=True. + """ + + if visrank and not test_only: + raise ValueError( + 'visrank can be set to True only if test_only=True' + ) + + if test_only: + self.test( + dist_metric=dist_metric, + normalize_feature=normalize_feature, + visrank=visrank, + visrank_topk=visrank_topk, + save_dir=save_dir, + use_metric_cuhk03=use_metric_cuhk03, + ranks=ranks, + rerank=rerank + ) + return + + if self.writer is None: + self.writer = SummaryWriter(log_dir=save_dir) + + time_start = time.time() + self.start_epoch = start_epoch + self.max_epoch = max_epoch + print('=> Start training') + + for self.epoch in range(self.start_epoch, self.max_epoch): + self.train( + print_freq=print_freq, + fixbase_epoch=fixbase_epoch, + open_layers=open_layers + ) + + if (self.epoch + 1) >= start_eval \ + and eval_freq > 0 \ + and (self.epoch+1) % eval_freq == 0 \ + and (self.epoch + 1) != self.max_epoch: + rank1 = self.test( + dist_metric=dist_metric, + normalize_feature=normalize_feature, + visrank=visrank, + visrank_topk=visrank_topk, + save_dir=save_dir, + use_metric_cuhk03=use_metric_cuhk03, + ranks=ranks + ) + self.save_model(self.epoch, rank1, save_dir) + + if self.max_epoch > 0: + print('=> Final test') + rank1 = self.test( + dist_metric=dist_metric, + normalize_feature=normalize_feature, + visrank=visrank, + visrank_topk=visrank_topk, + save_dir=save_dir, + use_metric_cuhk03=use_metric_cuhk03, + ranks=ranks + ) + self.save_model(self.epoch, rank1, save_dir) + + elapsed = round(time.time() - time_start) + elapsed = str(datetime.timedelta(seconds=elapsed)) + print('Elapsed {}'.format(elapsed)) + if self.writer is not None: + self.writer.close() + + def train(self, print_freq=10, fixbase_epoch=0, open_layers=None): + losses = MetricMeter() + batch_time = AverageMeter() + data_time = AverageMeter() + + self.set_model_mode('train') + + self.two_stepped_transfer_learning( + self.epoch, fixbase_epoch, open_layers + ) + + self.num_batches = len(self.train_loader) + end = time.time() + for self.batch_idx, data in enumerate(self.train_loader): + data_time.update(time.time() - end) + loss_summary = self.forward_backward(data) + batch_time.update(time.time() - end) + losses.update(loss_summary) + + if (self.batch_idx + 1) % print_freq == 0: + nb_this_epoch = self.num_batches - (self.batch_idx + 1) + nb_future_epochs = ( + self.max_epoch - (self.epoch + 1) + ) * self.num_batches + eta_seconds = batch_time.avg * (nb_this_epoch+nb_future_epochs) + eta_str = str(datetime.timedelta(seconds=int(eta_seconds))) + print( + 'epoch: [{0}/{1}][{2}/{3}]\t' + 'time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' + 'data {data_time.val:.3f} ({data_time.avg:.3f})\t' + 'eta {eta}\t' + '{losses}\t' + 'lr {lr:.6f}'.format( + self.epoch + 1, + self.max_epoch, + self.batch_idx + 1, + self.num_batches, + batch_time=batch_time, + data_time=data_time, + eta=eta_str, + losses=losses, + lr=self.get_current_lr() + ) + ) + + if self.writer is not None: + n_iter = self.epoch * self.num_batches + self.batch_idx + self.writer.add_scalar('Train/time', batch_time.avg, n_iter) + self.writer.add_scalar('Train/data', data_time.avg, n_iter) + for name, meter in losses.meters.items(): + self.writer.add_scalar('Train/' + name, meter.avg, n_iter) + self.writer.add_scalar( + 'Train/lr', self.get_current_lr(), n_iter + ) + + end = time.time() + + self.update_lr() + + def forward_backward(self, data): + raise NotImplementedError + + def test( + self, + dist_metric='euclidean', + normalize_feature=False, + visrank=False, + visrank_topk=10, + save_dir='', + use_metric_cuhk03=False, + ranks=[1, 5, 10, 20], + rerank=False + ): + r"""Tests model on target datasets. + + .. note:: + + This function has been called in ``run()``. + + .. note:: + + The test pipeline implemented in this function suits both image- and + video-reid. In general, a subclass of Engine only needs to re-implement + ``extract_features()`` and ``parse_data_for_eval()`` (most of the time), + but not a must. Please refer to the source code for more details. + """ + self.set_model_mode('eval') + targets = list(self.test_loader.keys()) + + for name in targets: + domain = 'source' if name in self.datamanager.sources else 'target' + print('##### Evaluating {} ({}) #####'.format(name, domain)) + query_loader = self.test_loader[name]['query'] + gallery_loader = self.test_loader[name]['gallery'] + rank1, mAP = self._evaluate( + dataset_name=name, + query_loader=query_loader, + gallery_loader=gallery_loader, + dist_metric=dist_metric, + normalize_feature=normalize_feature, + visrank=visrank, + visrank_topk=visrank_topk, + save_dir=save_dir, + use_metric_cuhk03=use_metric_cuhk03, + ranks=ranks, + rerank=rerank + ) + + if self.writer is not None: + self.writer.add_scalar(f'Test/{name}/rank1', rank1, self.epoch) + self.writer.add_scalar(f'Test/{name}/mAP', mAP, self.epoch) + + return rank1 + + @torch.no_grad() + def _evaluate( + self, + dataset_name='', + query_loader=None, + gallery_loader=None, + dist_metric='euclidean', + normalize_feature=False, + visrank=False, + visrank_topk=10, + save_dir='', + use_metric_cuhk03=False, + ranks=[1, 5, 10, 20], + rerank=False + ): + batch_time = AverageMeter() + + def _feature_extraction(data_loader): + f_, pids_, camids_ = [], [], [] + for batch_idx, data in enumerate(data_loader): + imgs, pids, camids = self.parse_data_for_eval(data) + if self.use_gpu: + imgs = imgs.cuda() + end = time.time() + features = self.extract_features(imgs) + batch_time.update(time.time() - end) + features = features.cpu() + f_.append(features) + pids_.extend(pids.tolist()) + camids_.extend(camids.tolist()) + f_ = torch.cat(f_, 0) + pids_ = np.asarray(pids_) + camids_ = np.asarray(camids_) + return f_, pids_, camids_ + + print('Extracting features from query set ...') + qf, q_pids, q_camids = _feature_extraction(query_loader) + print('Done, obtained {}-by-{} matrix'.format(qf.size(0), qf.size(1))) + + print('Extracting features from gallery set ...') + gf, g_pids, g_camids = _feature_extraction(gallery_loader) + print('Done, obtained {}-by-{} matrix'.format(gf.size(0), gf.size(1))) + + print('Speed: {:.4f} sec/batch'.format(batch_time.avg)) + + if normalize_feature: + print('Normalzing features with L2 norm ...') + qf = F.normalize(qf, p=2, dim=1) + gf = F.normalize(gf, p=2, dim=1) + + print( + 'Computing distance matrix with metric={} ...'.format(dist_metric) + ) + distmat = metrics.compute_distance_matrix(qf, gf, dist_metric) + distmat = distmat.numpy() + + if rerank: + print('Applying person re-ranking ...') + distmat_qq = metrics.compute_distance_matrix(qf, qf, dist_metric) + distmat_gg = metrics.compute_distance_matrix(gf, gf, dist_metric) + distmat = re_ranking(distmat, distmat_qq, distmat_gg) + + print('Computing CMC and mAP ...') + cmc, mAP = metrics.evaluate_rank( + distmat, + q_pids, + g_pids, + q_camids, + g_camids, + use_metric_cuhk03=use_metric_cuhk03 + ) + + print('** Results **') + print('mAP: {:.1%}'.format(mAP)) + print('CMC curve') + for r in ranks: + print('Rank-{:<3}: {:.1%}'.format(r, cmc[r - 1])) + + if visrank: + visualize_ranked_results( + distmat, + self.datamanager.fetch_test_loaders(dataset_name), + self.datamanager.data_type, + width=self.datamanager.width, + height=self.datamanager.height, + save_dir=osp.join(save_dir, 'visrank_' + dataset_name), + topk=visrank_topk + ) + + return cmc[0], mAP + + def compute_loss(self, criterion, outputs, targets): + if isinstance(outputs, (tuple, list)): + loss = DeepSupervision(criterion, outputs, targets) + else: + loss = criterion(outputs, targets) + return loss + + def extract_features(self, input): + return self.model(input) + + def parse_data_for_train(self, data): + imgs = data['img'] + pids = data['pid'] + return imgs, pids + + def parse_data_for_eval(self, data): + imgs = data['img'] + pids = data['pid'] + camids = data['camid'] + return imgs, pids, camids + + def two_stepped_transfer_learning( + self, epoch, fixbase_epoch, open_layers, model=None + ): + """Two-stepped transfer learning. + + The idea is to freeze base layers for a certain number of epochs + and then open all layers for training. + + Reference: https://arxiv.org/abs/1611.05244 + """ + model = self.model if model is None else model + if model is None: + return + + if (epoch + 1) <= fixbase_epoch and open_layers is not None: + print( + '* Only train {} (epoch: {}/{})'.format( + open_layers, epoch + 1, fixbase_epoch + ) + ) + open_specified_layers(model, open_layers) + else: + open_all_layers(model) diff --git a/strong_sort/deep/reid/torchreid/engine/image/__init__.py b/strong_sort/deep/reid/torchreid/engine/image/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..08d313a53f99f1524f973f3d998f182c59950df1 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/engine/image/__init__.py @@ -0,0 +1,4 @@ +from __future__ import absolute_import + +from .softmax import ImageSoftmaxEngine +from .triplet import ImageTripletEngine diff --git a/strong_sort/deep/reid/torchreid/engine/image/softmax.py b/strong_sort/deep/reid/torchreid/engine/image/softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..5785d4f8c612de60b82de37dfdac2820c793545e --- /dev/null +++ b/strong_sort/deep/reid/torchreid/engine/image/softmax.py @@ -0,0 +1,97 @@ +from __future__ import division, print_function, absolute_import + +from torchreid import metrics +from torchreid.losses import CrossEntropyLoss + +from ..engine import Engine + + +class ImageSoftmaxEngine(Engine): + r"""Softmax-loss engine for image-reid. + + Args: + datamanager (DataManager): an instance of ``torchreid.data.ImageDataManager`` + or ``torchreid.data.VideoDataManager``. + model (nn.Module): model instance. + optimizer (Optimizer): an Optimizer. + scheduler (LRScheduler, optional): if None, no learning rate decay will be performed. + use_gpu (bool, optional): use gpu. Default is True. + label_smooth (bool, optional): use label smoothing regularizer. Default is True. + + Examples:: + + import torchreid + datamanager = torchreid.data.ImageDataManager( + root='path/to/reid-data', + sources='market1501', + height=256, + width=128, + combineall=False, + batch_size=32 + ) + model = torchreid.models.build_model( + name='resnet50', + num_classes=datamanager.num_train_pids, + loss='softmax' + ) + model = model.cuda() + optimizer = torchreid.optim.build_optimizer( + model, optim='adam', lr=0.0003 + ) + scheduler = torchreid.optim.build_lr_scheduler( + optimizer, + lr_scheduler='single_step', + stepsize=20 + ) + engine = torchreid.engine.ImageSoftmaxEngine( + datamanager, model, optimizer, scheduler=scheduler + ) + engine.run( + max_epoch=60, + save_dir='log/resnet50-softmax-market1501', + print_freq=10 + ) + """ + + def __init__( + self, + datamanager, + model, + optimizer, + scheduler=None, + use_gpu=True, + label_smooth=True + ): + super(ImageSoftmaxEngine, self).__init__(datamanager, use_gpu) + + self.model = model + self.optimizer = optimizer + self.scheduler = scheduler + self.register_model('model', model, optimizer, scheduler) + + self.criterion = CrossEntropyLoss( + num_classes=self.datamanager.num_train_pids, + use_gpu=self.use_gpu, + label_smooth=label_smooth + ) + + def forward_backward(self, data): + imgs, pids = self.parse_data_for_train(data) + + if self.use_gpu: + imgs = imgs.cuda() + pids = pids.cuda() + + outputs = self.model(imgs) + loss = self.compute_loss(self.criterion, outputs, pids) + + self.optimizer.zero_grad() + loss.backward() + self.optimizer.step() + + loss_summary = { + 'loss': loss.item(), + 'acc': metrics.accuracy(outputs, pids)[0].item() + } + + return loss_summary diff --git a/strong_sort/deep/reid/torchreid/engine/image/triplet.py b/strong_sort/deep/reid/torchreid/engine/image/triplet.py new file mode 100644 index 0000000000000000000000000000000000000000..cd15cfb203cbb18244b440ac7e74f253bd1db8a8 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/engine/image/triplet.py @@ -0,0 +1,122 @@ +from __future__ import division, print_function, absolute_import + +from torchreid import metrics +from torchreid.losses import TripletLoss, CrossEntropyLoss + +from ..engine import Engine + + +class ImageTripletEngine(Engine): + r"""Triplet-loss engine for image-reid. + + Args: + datamanager (DataManager): an instance of ``torchreid.data.ImageDataManager`` + or ``torchreid.data.VideoDataManager``. + model (nn.Module): model instance. + optimizer (Optimizer): an Optimizer. + margin (float, optional): margin for triplet loss. Default is 0.3. + weight_t (float, optional): weight for triplet loss. Default is 1. + weight_x (float, optional): weight for softmax loss. Default is 1. + scheduler (LRScheduler, optional): if None, no learning rate decay will be performed. + use_gpu (bool, optional): use gpu. Default is True. + label_smooth (bool, optional): use label smoothing regularizer. Default is True. + + Examples:: + + import torchreid + datamanager = torchreid.data.ImageDataManager( + root='path/to/reid-data', + sources='market1501', + height=256, + width=128, + combineall=False, + batch_size=32, + num_instances=4, + train_sampler='RandomIdentitySampler' # this is important + ) + model = torchreid.models.build_model( + name='resnet50', + num_classes=datamanager.num_train_pids, + loss='triplet' + ) + model = model.cuda() + optimizer = torchreid.optim.build_optimizer( + model, optim='adam', lr=0.0003 + ) + scheduler = torchreid.optim.build_lr_scheduler( + optimizer, + lr_scheduler='single_step', + stepsize=20 + ) + engine = torchreid.engine.ImageTripletEngine( + datamanager, model, optimizer, margin=0.3, + weight_t=0.7, weight_x=1, scheduler=scheduler + ) + engine.run( + max_epoch=60, + save_dir='log/resnet50-triplet-market1501', + print_freq=10 + ) + """ + + def __init__( + self, + datamanager, + model, + optimizer, + margin=0.3, + weight_t=1, + weight_x=1, + scheduler=None, + use_gpu=True, + label_smooth=True + ): + super(ImageTripletEngine, self).__init__(datamanager, use_gpu) + + self.model = model + self.optimizer = optimizer + self.scheduler = scheduler + self.register_model('model', model, optimizer, scheduler) + + assert weight_t >= 0 and weight_x >= 0 + assert weight_t + weight_x > 0 + self.weight_t = weight_t + self.weight_x = weight_x + + self.criterion_t = TripletLoss(margin=margin) + self.criterion_x = CrossEntropyLoss( + num_classes=self.datamanager.num_train_pids, + use_gpu=self.use_gpu, + label_smooth=label_smooth + ) + + def forward_backward(self, data): + imgs, pids = self.parse_data_for_train(data) + + if self.use_gpu: + imgs = imgs.cuda() + pids = pids.cuda() + + outputs, features = self.model(imgs) + + loss = 0 + loss_summary = {} + + if self.weight_t > 0: + loss_t = self.compute_loss(self.criterion_t, features, pids) + loss += self.weight_t * loss_t + loss_summary['loss_t'] = loss_t.item() + + if self.weight_x > 0: + loss_x = self.compute_loss(self.criterion_x, outputs, pids) + loss += self.weight_x * loss_x + loss_summary['loss_x'] = loss_x.item() + loss_summary['acc'] = metrics.accuracy(outputs, pids)[0].item() + + assert loss_summary + + self.optimizer.zero_grad() + loss.backward() + self.optimizer.step() + + return loss_summary diff --git a/strong_sort/deep/reid/torchreid/engine/video/__init__.py b/strong_sort/deep/reid/torchreid/engine/video/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b818bf4d32cbb3eba1545f1900749a2dd3636af1 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/engine/video/__init__.py @@ -0,0 +1,4 @@ +from __future__ import absolute_import + +from .softmax import VideoSoftmaxEngine +from .triplet import VideoTripletEngine diff --git a/strong_sort/deep/reid/torchreid/engine/video/softmax.py b/strong_sort/deep/reid/torchreid/engine/video/softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..fe92feba11935900f3c01e8591ce3eaa19bf6862 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/engine/video/softmax.py @@ -0,0 +1,109 @@ +from __future__ import division, print_function, absolute_import +import torch + +from torchreid.engine.image import ImageSoftmaxEngine + + +class VideoSoftmaxEngine(ImageSoftmaxEngine): + """Softmax-loss engine for video-reid. + + Args: + datamanager (DataManager): an instance of ``torchreid.data.ImageDataManager`` + or ``torchreid.data.VideoDataManager``. + model (nn.Module): model instance. + optimizer (Optimizer): an Optimizer. + scheduler (LRScheduler, optional): if None, no learning rate decay will be performed. + use_gpu (bool, optional): use gpu. Default is True. + label_smooth (bool, optional): use label smoothing regularizer. Default is True. + pooling_method (str, optional): how to pool features for a tracklet. + Default is "avg" (average). Choices are ["avg", "max"]. + + Examples:: + + import torch + import torchreid + # Each batch contains batch_size*seq_len images + datamanager = torchreid.data.VideoDataManager( + root='path/to/reid-data', + sources='mars', + height=256, + width=128, + combineall=False, + batch_size=8, # number of tracklets + seq_len=15 # number of images in each tracklet + ) + model = torchreid.models.build_model( + name='resnet50', + num_classes=datamanager.num_train_pids, + loss='softmax' + ) + model = model.cuda() + optimizer = torchreid.optim.build_optimizer( + model, optim='adam', lr=0.0003 + ) + scheduler = torchreid.optim.build_lr_scheduler( + optimizer, + lr_scheduler='single_step', + stepsize=20 + ) + engine = torchreid.engine.VideoSoftmaxEngine( + datamanager, model, optimizer, scheduler=scheduler, + pooling_method='avg' + ) + engine.run( + max_epoch=60, + save_dir='log/resnet50-softmax-mars', + print_freq=10 + ) + """ + + def __init__( + self, + datamanager, + model, + optimizer, + scheduler=None, + use_gpu=True, + label_smooth=True, + pooling_method='avg' + ): + super(VideoSoftmaxEngine, self).__init__( + datamanager, + model, + optimizer, + scheduler=scheduler, + use_gpu=use_gpu, + label_smooth=label_smooth + ) + self.pooling_method = pooling_method + + def parse_data_for_train(self, data): + imgs = data['img'] + pids = data['pid'] + if imgs.dim() == 5: + # b: batch size + # s: sqeuence length + # c: channel depth + # h: height + # w: width + b, s, c, h, w = imgs.size() + imgs = imgs.view(b * s, c, h, w) + pids = pids.view(b, 1).expand(b, s) + pids = pids.contiguous().view(b * s) + return imgs, pids + + def extract_features(self, input): + # b: batch size + # s: sqeuence length + # c: channel depth + # h: height + # w: width + b, s, c, h, w = input.size() + input = input.view(b * s, c, h, w) + features = self.model(input) + features = features.view(b, s, -1) + if self.pooling_method == 'avg': + features = torch.mean(features, 1) + else: + features = torch.max(features, 1)[0] + return features diff --git a/strong_sort/deep/reid/torchreid/engine/video/triplet.py b/strong_sort/deep/reid/torchreid/engine/video/triplet.py new file mode 100644 index 0000000000000000000000000000000000000000..b2778db9b3b1cd4c44e167735062c662884e3b52 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/engine/video/triplet.py @@ -0,0 +1,122 @@ +from __future__ import division, print_function, absolute_import +import torch + +from torchreid.engine.image import ImageTripletEngine + + +class VideoTripletEngine(ImageTripletEngine): + """Triplet-loss engine for video-reid. + + Args: + datamanager (DataManager): an instance of ``torchreid.data.ImageDataManager`` + or ``torchreid.data.VideoDataManager``. + model (nn.Module): model instance. + optimizer (Optimizer): an Optimizer. + margin (float, optional): margin for triplet loss. Default is 0.3. + weight_t (float, optional): weight for triplet loss. Default is 1. + weight_x (float, optional): weight for softmax loss. Default is 1. + scheduler (LRScheduler, optional): if None, no learning rate decay will be performed. + use_gpu (bool, optional): use gpu. Default is True. + label_smooth (bool, optional): use label smoothing regularizer. Default is True. + pooling_method (str, optional): how to pool features for a tracklet. + Default is "avg" (average). Choices are ["avg", "max"]. + + Examples:: + + import torch + import torchreid + # Each batch contains batch_size*seq_len images + # Each identity is sampled with num_instances tracklets + datamanager = torchreid.data.VideoDataManager( + root='path/to/reid-data', + sources='mars', + height=256, + width=128, + combineall=False, + num_instances=4, + train_sampler='RandomIdentitySampler' + batch_size=8, # number of tracklets + seq_len=15 # number of images in each tracklet + ) + model = torchreid.models.build_model( + name='resnet50', + num_classes=datamanager.num_train_pids, + loss='triplet' + ) + model = model.cuda() + optimizer = torchreid.optim.build_optimizer( + model, optim='adam', lr=0.0003 + ) + scheduler = torchreid.optim.build_lr_scheduler( + optimizer, + lr_scheduler='single_step', + stepsize=20 + ) + engine = torchreid.engine.VideoTripletEngine( + datamanager, model, optimizer, margin=0.3, + weight_t=0.7, weight_x=1, scheduler=scheduler, + pooling_method='avg' + ) + engine.run( + max_epoch=60, + save_dir='log/resnet50-triplet-mars', + print_freq=10 + ) + """ + + def __init__( + self, + datamanager, + model, + optimizer, + margin=0.3, + weight_t=1, + weight_x=1, + scheduler=None, + use_gpu=True, + label_smooth=True, + pooling_method='avg' + ): + super(VideoTripletEngine, self).__init__( + datamanager, + model, + optimizer, + margin=margin, + weight_t=weight_t, + weight_x=weight_x, + scheduler=scheduler, + use_gpu=use_gpu, + label_smooth=label_smooth + ) + self.pooling_method = pooling_method + + def parse_data_for_train(self, data): + imgs = data['img'] + pids = data['pid'] + if imgs.dim() == 5: + # b: batch size + # s: sqeuence length + # c: channel depth + # h: height + # w: width + b, s, c, h, w = imgs.size() + imgs = imgs.view(b * s, c, h, w) + pids = pids.view(b, 1).expand(b, s) + pids = pids.contiguous().view(b * s) + return imgs, pids + + def extract_features(self, input): + # b: batch size + # s: sqeuence length + # c: channel depth + # h: height + # w: width + b, s, c, h, w = input.size() + input = input.view(b * s, c, h, w) + features = self.model(input) + features = features.view(b, s, -1) + if self.pooling_method == 'avg': + features = torch.mean(features, 1) + else: + features = torch.max(features, 1)[0] + return features diff --git a/strong_sort/deep/reid/torchreid/losses/__init__.py b/strong_sort/deep/reid/torchreid/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..16257499c736c9f7c9ee46abd2f75c24ef10370b --- /dev/null +++ b/strong_sort/deep/reid/torchreid/losses/__init__.py @@ -0,0 +1,21 @@ +from __future__ import division, print_function, absolute_import + +from .cross_entropy_loss import CrossEntropyLoss +from .hard_mine_triplet_loss import TripletLoss + + +def DeepSupervision(criterion, xs, y): + """DeepSupervision + + Applies criterion to each element in a list. + + Args: + criterion: loss function + xs: tuple of inputs + y: ground truth + """ + loss = 0. + for x in xs: + loss += criterion(x, y) + loss /= len(xs) + return loss diff --git a/strong_sort/deep/reid/torchreid/losses/cross_entropy_loss.py b/strong_sort/deep/reid/torchreid/losses/cross_entropy_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..4cfa5d46e41b7c7d11b95a8bd62c04903981d0c0 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/losses/cross_entropy_loss.py @@ -0,0 +1,50 @@ +from __future__ import division, absolute_import +import torch +import torch.nn as nn + + +class CrossEntropyLoss(nn.Module): + r"""Cross entropy loss with label smoothing regularizer. + + Reference: + Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016. + + With label smoothing, the label :math:`y` for a class is computed by + + .. math:: + \begin{equation} + (1 - \eps) \times y + \frac{\eps}{K}, + \end{equation} + + where :math:`K` denotes the number of classes and :math:`\eps` is a weight. When + :math:`\eps = 0`, the loss function reduces to the normal cross entropy. + + Args: + num_classes (int): number of classes. + eps (float, optional): weight. Default is 0.1. + use_gpu (bool, optional): whether to use gpu devices. Default is True. + label_smooth (bool, optional): whether to apply label smoothing. Default is True. + """ + + def __init__(self, num_classes, eps=0.1, use_gpu=True, label_smooth=True): + super(CrossEntropyLoss, self).__init__() + self.num_classes = num_classes + self.eps = eps if label_smooth else 0 + self.use_gpu = use_gpu + self.logsoftmax = nn.LogSoftmax(dim=1) + + def forward(self, inputs, targets): + """ + Args: + inputs (torch.Tensor): prediction matrix (before softmax) with + shape (batch_size, num_classes). + targets (torch.LongTensor): ground truth labels with shape (batch_size). + Each position contains the label index. + """ + log_probs = self.logsoftmax(inputs) + zeros = torch.zeros(log_probs.size()) + targets = zeros.scatter_(1, targets.unsqueeze(1).data.cpu(), 1) + if self.use_gpu: + targets = targets.cuda() + targets = (1 - self.eps) * targets + self.eps / self.num_classes + return (-targets * log_probs).mean(0).sum() diff --git a/strong_sort/deep/reid/torchreid/losses/hard_mine_triplet_loss.py b/strong_sort/deep/reid/torchreid/losses/hard_mine_triplet_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..ef9019bdcc19015b690b2b4b48674edd20c5b949 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/losses/hard_mine_triplet_loss.py @@ -0,0 +1,48 @@ +from __future__ import division, absolute_import +import torch +import torch.nn as nn + + +class TripletLoss(nn.Module): + """Triplet loss with hard positive/negative mining. + + Reference: + Hermans et al. In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737. + + Imported from ``_. + + Args: + margin (float, optional): margin for triplet. Default is 0.3. + """ + + def __init__(self, margin=0.3): + super(TripletLoss, self).__init__() + self.margin = margin + self.ranking_loss = nn.MarginRankingLoss(margin=margin) + + def forward(self, inputs, targets): + """ + Args: + inputs (torch.Tensor): feature matrix with shape (batch_size, feat_dim). + targets (torch.LongTensor): ground truth labels with shape (num_classes). + """ + n = inputs.size(0) + + # Compute pairwise distance, replace by the official when merged + dist = torch.pow(inputs, 2).sum(dim=1, keepdim=True).expand(n, n) + dist = dist + dist.t() + dist.addmm_(inputs, inputs.t(), beta=1, alpha=-2) + dist = dist.clamp(min=1e-12).sqrt() # for numerical stability + + # For each anchor, find the hardest positive and negative + mask = targets.expand(n, n).eq(targets.expand(n, n).t()) + dist_ap, dist_an = [], [] + for i in range(n): + dist_ap.append(dist[i][mask[i]].max().unsqueeze(0)) + dist_an.append(dist[i][mask[i] == 0].min().unsqueeze(0)) + dist_ap = torch.cat(dist_ap) + dist_an = torch.cat(dist_an) + + # Compute ranking hinge loss + y = torch.ones_like(dist_an) + return self.ranking_loss(dist_an, dist_ap, y) diff --git a/strong_sort/deep/reid/torchreid/metrics/__init__.py b/strong_sort/deep/reid/torchreid/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5159e1e9aa07d972d2a07ef00feac341349c66b8 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/metrics/__init__.py @@ -0,0 +1,5 @@ +from __future__ import absolute_import + +from .rank import evaluate_rank +from .accuracy import accuracy +from .distance import compute_distance_matrix diff --git a/strong_sort/deep/reid/torchreid/metrics/accuracy.py b/strong_sort/deep/reid/torchreid/metrics/accuracy.py new file mode 100644 index 0000000000000000000000000000000000000000..3161f7bff08acbd8f598bc1712e693009feb60c9 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/metrics/accuracy.py @@ -0,0 +1,37 @@ +from __future__ import division, print_function, absolute_import + + +def accuracy(output, target, topk=(1, )): + """Computes the accuracy over the k top predictions for + the specified values of k. + + Args: + output (torch.Tensor): prediction matrix with shape (batch_size, num_classes). + target (torch.LongTensor): ground truth labels with shape (batch_size). + topk (tuple, optional): accuracy at top-k will be computed. For example, + topk=(1, 5) means accuracy at top-1 and top-5 will be computed. + + Returns: + list: accuracy at top-k. + + Examples:: + >>> from torchreid import metrics + >>> metrics.accuracy(output, target) + """ + maxk = max(topk) + batch_size = target.size(0) + + if isinstance(output, (tuple, list)): + output = output[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) + acc = correct_k.mul_(100.0 / batch_size) + res.append(acc) + + return res diff --git a/strong_sort/deep/reid/torchreid/metrics/distance.py b/strong_sort/deep/reid/torchreid/metrics/distance.py new file mode 100644 index 0000000000000000000000000000000000000000..f4fb38316c2af8ec13a5cf734eec64734ddf715f --- /dev/null +++ b/strong_sort/deep/reid/torchreid/metrics/distance.py @@ -0,0 +1,80 @@ +from __future__ import division, print_function, absolute_import +import torch +from torch.nn import functional as F + + +def compute_distance_matrix(input1, input2, metric='euclidean'): + """A wrapper function for computing distance matrix. + + Args: + input1 (torch.Tensor): 2-D feature matrix. + input2 (torch.Tensor): 2-D feature matrix. + metric (str, optional): "euclidean" or "cosine". + Default is "euclidean". + + Returns: + torch.Tensor: distance matrix. + + Examples:: + >>> from torchreid import metrics + >>> input1 = torch.rand(10, 2048) + >>> input2 = torch.rand(100, 2048) + >>> distmat = metrics.compute_distance_matrix(input1, input2) + >>> distmat.size() # (10, 100) + """ + # check input + assert isinstance(input1, torch.Tensor) + assert isinstance(input2, torch.Tensor) + assert input1.dim() == 2, 'Expected 2-D tensor, but got {}-D'.format( + input1.dim() + ) + assert input2.dim() == 2, 'Expected 2-D tensor, but got {}-D'.format( + input2.dim() + ) + assert input1.size(1) == input2.size(1) + + if metric == 'euclidean': + distmat = euclidean_squared_distance(input1, input2) + elif metric == 'cosine': + distmat = cosine_distance(input1, input2) + else: + raise ValueError( + 'Unknown distance metric: {}. ' + 'Please choose either "euclidean" or "cosine"'.format(metric) + ) + + return distmat + + +def euclidean_squared_distance(input1, input2): + """Computes euclidean squared distance. + + Args: + input1 (torch.Tensor): 2-D feature matrix. + input2 (torch.Tensor): 2-D feature matrix. + + Returns: + torch.Tensor: distance matrix. + """ + m, n = input1.size(0), input2.size(0) + mat1 = torch.pow(input1, 2).sum(dim=1, keepdim=True).expand(m, n) + mat2 = torch.pow(input2, 2).sum(dim=1, keepdim=True).expand(n, m).t() + distmat = mat1 + mat2 + distmat.addmm_(input1, input2.t(), beta=1, alpha=-2) + return distmat + + +def cosine_distance(input1, input2): + """Computes cosine distance. + + Args: + input1 (torch.Tensor): 2-D feature matrix. + input2 (torch.Tensor): 2-D feature matrix. + + Returns: + torch.Tensor: distance matrix. + """ + input1_normed = F.normalize(input1, p=2, dim=1) + input2_normed = F.normalize(input2, p=2, dim=1) + distmat = 1 - torch.mm(input1_normed, input2_normed.t()) + return distmat diff --git a/strong_sort/deep/reid/torchreid/metrics/rank.py b/strong_sort/deep/reid/torchreid/metrics/rank.py new file mode 100644 index 0000000000000000000000000000000000000000..bf6205b32807fcbe4ea658f28705fdc821b22feb --- /dev/null +++ b/strong_sort/deep/reid/torchreid/metrics/rank.py @@ -0,0 +1,207 @@ +from __future__ import division, print_function, absolute_import +import numpy as np +import warnings +from collections import defaultdict + +try: + from torchreid.metrics.rank_cylib.rank_cy import evaluate_cy + IS_CYTHON_AVAI = True +except ImportError: + IS_CYTHON_AVAI = False + warnings.warn( + 'Cython evaluation (very fast so highly recommended) is ' + 'unavailable, now use python evaluation.' + ) + + +def eval_cuhk03(distmat, q_pids, g_pids, q_camids, g_camids, max_rank): + """Evaluation with cuhk03 metric + Key: one image for each gallery identity is randomly sampled for each query identity. + Random sampling is performed num_repeats times. + """ + num_repeats = 10 + num_q, num_g = distmat.shape + + if num_g < max_rank: + max_rank = num_g + print( + 'Note: number of gallery samples is quite small, got {}'. + format(num_g) + ) + + indices = np.argsort(distmat, axis=1) + matches = (g_pids[indices] == q_pids[:, np.newaxis]).astype(np.int32) + + # compute cmc curve for each query + all_cmc = [] + all_AP = [] + num_valid_q = 0. # number of valid query + + for q_idx in range(num_q): + # get query pid and camid + q_pid = q_pids[q_idx] + q_camid = q_camids[q_idx] + + # remove gallery samples that have the same pid and camid with query + order = indices[q_idx] + remove = (g_pids[order] == q_pid) & (g_camids[order] == q_camid) + keep = np.invert(remove) + + # compute cmc curve + raw_cmc = matches[q_idx][ + keep] # binary vector, positions with value 1 are correct matches + if not np.any(raw_cmc): + # this condition is true when query identity does not appear in gallery + continue + + kept_g_pids = g_pids[order][keep] + g_pids_dict = defaultdict(list) + for idx, pid in enumerate(kept_g_pids): + g_pids_dict[pid].append(idx) + + cmc = 0. + for repeat_idx in range(num_repeats): + mask = np.zeros(len(raw_cmc), dtype=np.bool) + for _, idxs in g_pids_dict.items(): + # randomly sample one image for each gallery person + rnd_idx = np.random.choice(idxs) + mask[rnd_idx] = True + masked_raw_cmc = raw_cmc[mask] + _cmc = masked_raw_cmc.cumsum() + _cmc[_cmc > 1] = 1 + cmc += _cmc[:max_rank].astype(np.float32) + + cmc /= num_repeats + all_cmc.append(cmc) + # compute AP + num_rel = raw_cmc.sum() + tmp_cmc = raw_cmc.cumsum() + tmp_cmc = [x / (i+1.) for i, x in enumerate(tmp_cmc)] + tmp_cmc = np.asarray(tmp_cmc) * raw_cmc + AP = tmp_cmc.sum() / num_rel + all_AP.append(AP) + num_valid_q += 1. + + assert num_valid_q > 0, 'Error: all query identities do not appear in gallery' + + all_cmc = np.asarray(all_cmc).astype(np.float32) + all_cmc = all_cmc.sum(0) / num_valid_q + mAP = np.mean(all_AP) + + return all_cmc, mAP + + +def eval_market1501(distmat, q_pids, g_pids, q_camids, g_camids, max_rank): + """Evaluation with market1501 metric + Key: for each query identity, its gallery images from the same camera view are discarded. + """ + num_q, num_g = distmat.shape + + if num_g < max_rank: + max_rank = num_g + print( + 'Note: number of gallery samples is quite small, got {}'. + format(num_g) + ) + + indices = np.argsort(distmat, axis=1) + matches = (g_pids[indices] == q_pids[:, np.newaxis]).astype(np.int32) + + # compute cmc curve for each query + all_cmc = [] + all_AP = [] + num_valid_q = 0. # number of valid query + + for q_idx in range(num_q): + # get query pid and camid + q_pid = q_pids[q_idx] + q_camid = q_camids[q_idx] + + # remove gallery samples that have the same pid and camid with query + order = indices[q_idx] + remove = (g_pids[order] == q_pid) & (g_camids[order] == q_camid) + keep = np.invert(remove) + + # compute cmc curve + raw_cmc = matches[q_idx][ + keep] # binary vector, positions with value 1 are correct matches + if not np.any(raw_cmc): + # this condition is true when query identity does not appear in gallery + continue + + cmc = raw_cmc.cumsum() + cmc[cmc > 1] = 1 + + all_cmc.append(cmc[:max_rank]) + num_valid_q += 1. + + # compute average precision + # reference: https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision + num_rel = raw_cmc.sum() + tmp_cmc = raw_cmc.cumsum() + tmp_cmc = [x / (i+1.) for i, x in enumerate(tmp_cmc)] + tmp_cmc = np.asarray(tmp_cmc) * raw_cmc + AP = tmp_cmc.sum() / num_rel + all_AP.append(AP) + + assert num_valid_q > 0, 'Error: all query identities do not appear in gallery' + + all_cmc = np.asarray(all_cmc).astype(np.float32) + all_cmc = all_cmc.sum(0) / num_valid_q + mAP = np.mean(all_AP) + + return all_cmc, mAP + + +def evaluate_py( + distmat, q_pids, g_pids, q_camids, g_camids, max_rank, use_metric_cuhk03 +): + if use_metric_cuhk03: + return eval_cuhk03( + distmat, q_pids, g_pids, q_camids, g_camids, max_rank + ) + else: + return eval_market1501( + distmat, q_pids, g_pids, q_camids, g_camids, max_rank + ) + + +def evaluate_rank( + distmat, + q_pids, + g_pids, + q_camids, + g_camids, + max_rank=50, + use_metric_cuhk03=False, + use_cython=True +): + """Evaluates CMC rank. + + Args: + distmat (numpy.ndarray): distance matrix of shape (num_query, num_gallery). + q_pids (numpy.ndarray): 1-D array containing person identities + of each query instance. + g_pids (numpy.ndarray): 1-D array containing person identities + of each gallery instance. + q_camids (numpy.ndarray): 1-D array containing camera views under + which each query instance is captured. + g_camids (numpy.ndarray): 1-D array containing camera views under + which each gallery instance is captured. + max_rank (int, optional): maximum CMC rank to be computed. Default is 50. + use_metric_cuhk03 (bool, optional): use single-gallery-shot setting for cuhk03. + Default is False. This should be enabled when using cuhk03 classic split. + use_cython (bool, optional): use cython code for evaluation. Default is True. + This is highly recommended as the cython code can speed up the cmc computation + by more than 10x. This requires Cython to be installed. + """ + if use_cython and IS_CYTHON_AVAI: + return evaluate_cy( + distmat, q_pids, g_pids, q_camids, g_camids, max_rank, + use_metric_cuhk03 + ) + else: + return evaluate_py( + distmat, q_pids, g_pids, q_camids, g_camids, max_rank, + use_metric_cuhk03 + ) diff --git a/strong_sort/deep/reid/torchreid/metrics/rank_cylib/Makefile b/strong_sort/deep/reid/torchreid/metrics/rank_cylib/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d49e655f85f829cb8ccda5bad6fe2c65cccf2bf2 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/metrics/rank_cylib/Makefile @@ -0,0 +1,6 @@ +all: + $(PYTHON) setup.py build_ext --inplace + rm -rf build +clean: + rm -rf build + rm -f rank_cy.c *.so \ No newline at end of file diff --git a/strong_sort/deep/reid/torchreid/metrics/rank_cylib/__init__.py b/strong_sort/deep/reid/torchreid/metrics/rank_cylib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/strong_sort/deep/reid/torchreid/metrics/rank_cylib/rank_cy.pyx b/strong_sort/deep/reid/torchreid/metrics/rank_cylib/rank_cy.pyx new file mode 100644 index 0000000000000000000000000000000000000000..b4a8690e57fce4a286b49a7e822c1c6d014ba30d --- /dev/null +++ b/strong_sort/deep/reid/torchreid/metrics/rank_cylib/rank_cy.pyx @@ -0,0 +1,251 @@ +# cython: boundscheck=False, wraparound=False, nonecheck=False, cdivision=True + +from __future__ import print_function +import numpy as np +from libc.stdint cimport int64_t, uint64_t + +import cython + +cimport numpy as np + +import random +from collections import defaultdict + +""" +Compiler directives: +https://github.com/cython/cython/wiki/enhancements-compilerdirectives + +Cython tutorial: +https://cython.readthedocs.io/en/latest/src/userguide/numpy_tutorial.html + +Credit to https://github.com/luzai +""" + + +# Main interface +cpdef evaluate_cy(distmat, q_pids, g_pids, q_camids, g_camids, max_rank, use_metric_cuhk03=False): + distmat = np.asarray(distmat, dtype=np.float32) + q_pids = np.asarray(q_pids, dtype=np.int64) + g_pids = np.asarray(g_pids, dtype=np.int64) + q_camids = np.asarray(q_camids, dtype=np.int64) + g_camids = np.asarray(g_camids, dtype=np.int64) + if use_metric_cuhk03: + return eval_cuhk03_cy(distmat, q_pids, g_pids, q_camids, g_camids, max_rank) + return eval_market1501_cy(distmat, q_pids, g_pids, q_camids, g_camids, max_rank) + + +cpdef eval_cuhk03_cy(float[:,:] distmat, int64_t[:] q_pids, int64_t[:]g_pids, + int64_t[:]q_camids, int64_t[:]g_camids, int64_t max_rank): + + cdef int64_t num_q = distmat.shape[0] + cdef int64_t num_g = distmat.shape[1] + + if num_g < max_rank: + max_rank = num_g + print('Note: number of gallery samples is quite small, got {}'.format(num_g)) + + cdef: + int64_t num_repeats = 10 + int64_t[:,:] indices = np.argsort(distmat, axis=1) + int64_t[:,:] matches = (np.asarray(g_pids)[np.asarray(indices)] == np.asarray(q_pids)[:, np.newaxis]).astype(np.int64) + + float[:,:] all_cmc = np.zeros((num_q, max_rank), dtype=np.float32) + float[:] all_AP = np.zeros(num_q, dtype=np.float32) + float num_valid_q = 0. # number of valid query + + int64_t q_idx, q_pid, q_camid, g_idx + int64_t[:] order = np.zeros(num_g, dtype=np.int64) + int64_t keep + + float[:] raw_cmc = np.zeros(num_g, dtype=np.float32) # binary vector, positions with value 1 are correct matches + float[:] masked_raw_cmc = np.zeros(num_g, dtype=np.float32) + float[:] cmc, masked_cmc + int64_t num_g_real, num_g_real_masked, rank_idx, rnd_idx + uint64_t meet_condition + float AP + int64_t[:] kept_g_pids, mask + + float num_rel + float[:] tmp_cmc = np.zeros(num_g, dtype=np.float32) + float tmp_cmc_sum + + for q_idx in range(num_q): + # get query pid and camid + q_pid = q_pids[q_idx] + q_camid = q_camids[q_idx] + + # remove gallery samples that have the same pid and camid with query + for g_idx in range(num_g): + order[g_idx] = indices[q_idx, g_idx] + num_g_real = 0 + meet_condition = 0 + kept_g_pids = np.zeros(num_g, dtype=np.int64) + + for g_idx in range(num_g): + if (g_pids[order[g_idx]] != q_pid) or (g_camids[order[g_idx]] != q_camid): + raw_cmc[num_g_real] = matches[q_idx][g_idx] + kept_g_pids[num_g_real] = g_pids[order[g_idx]] + num_g_real += 1 + if matches[q_idx][g_idx] > 1e-31: + meet_condition = 1 + + if not meet_condition: + # this condition is true when query identity does not appear in gallery + continue + + # cuhk03-specific setting + g_pids_dict = defaultdict(list) # overhead! + for g_idx in range(num_g_real): + g_pids_dict[kept_g_pids[g_idx]].append(g_idx) + + cmc = np.zeros(max_rank, dtype=np.float32) + for _ in range(num_repeats): + mask = np.zeros(num_g_real, dtype=np.int64) + + for _, idxs in g_pids_dict.items(): + # randomly sample one image for each gallery person + rnd_idx = np.random.choice(idxs) + #rnd_idx = idxs[0] # use deterministic for debugging + mask[rnd_idx] = 1 + + num_g_real_masked = 0 + for g_idx in range(num_g_real): + if mask[g_idx] == 1: + masked_raw_cmc[num_g_real_masked] = raw_cmc[g_idx] + num_g_real_masked += 1 + + masked_cmc = np.zeros(num_g, dtype=np.float32) + function_cumsum(masked_raw_cmc, masked_cmc, num_g_real_masked) + for g_idx in range(num_g_real_masked): + if masked_cmc[g_idx] > 1: + masked_cmc[g_idx] = 1 + + for rank_idx in range(max_rank): + cmc[rank_idx] += masked_cmc[rank_idx] / num_repeats + + for rank_idx in range(max_rank): + all_cmc[q_idx, rank_idx] = cmc[rank_idx] + # compute average precision + # reference: https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision + function_cumsum(raw_cmc, tmp_cmc, num_g_real) + num_rel = 0 + tmp_cmc_sum = 0 + for g_idx in range(num_g_real): + tmp_cmc_sum += (tmp_cmc[g_idx] / (g_idx + 1.)) * raw_cmc[g_idx] + num_rel += raw_cmc[g_idx] + all_AP[q_idx] = tmp_cmc_sum / num_rel + num_valid_q += 1. + + assert num_valid_q > 0, 'Error: all query identities do not appear in gallery' + + # compute averaged cmc + cdef float[:] avg_cmc = np.zeros(max_rank, dtype=np.float32) + for rank_idx in range(max_rank): + for q_idx in range(num_q): + avg_cmc[rank_idx] += all_cmc[q_idx, rank_idx] + avg_cmc[rank_idx] /= num_valid_q + + cdef float mAP = 0 + for q_idx in range(num_q): + mAP += all_AP[q_idx] + mAP /= num_valid_q + + return np.asarray(avg_cmc).astype(np.float32), mAP + + +cpdef eval_market1501_cy(float[:,:] distmat, int64_t[:] q_pids, int64_t[:]g_pids, + int64_t[:]q_camids, int64_t[:]g_camids, int64_t max_rank): + + cdef int64_t num_q = distmat.shape[0] + cdef int64_t num_g = distmat.shape[1] + + if num_g < max_rank: + max_rank = num_g + print('Note: number of gallery samples is quite small, got {}'.format(num_g)) + + cdef: + int64_t[:,:] indices = np.argsort(distmat, axis=1) + int64_t[:,:] matches = (np.asarray(g_pids)[np.asarray(indices)] == np.asarray(q_pids)[:, np.newaxis]).astype(np.int64) + + float[:,:] all_cmc = np.zeros((num_q, max_rank), dtype=np.float32) + float[:] all_AP = np.zeros(num_q, dtype=np.float32) + float num_valid_q = 0. # number of valid query + + int64_t q_idx, q_pid, q_camid, g_idx + int64_t[:] order = np.zeros(num_g, dtype=np.int64) + int64_t keep + + float[:] raw_cmc = np.zeros(num_g, dtype=np.float32) # binary vector, positions with value 1 are correct matches + float[:] cmc = np.zeros(num_g, dtype=np.float32) + int64_t num_g_real, rank_idx + uint64_t meet_condition + + float num_rel + float[:] tmp_cmc = np.zeros(num_g, dtype=np.float32) + float tmp_cmc_sum + + for q_idx in range(num_q): + # get query pid and camid + q_pid = q_pids[q_idx] + q_camid = q_camids[q_idx] + + # remove gallery samples that have the same pid and camid with query + for g_idx in range(num_g): + order[g_idx] = indices[q_idx, g_idx] + num_g_real = 0 + meet_condition = 0 + + for g_idx in range(num_g): + if (g_pids[order[g_idx]] != q_pid) or (g_camids[order[g_idx]] != q_camid): + raw_cmc[num_g_real] = matches[q_idx][g_idx] + num_g_real += 1 + if matches[q_idx][g_idx] > 1e-31: + meet_condition = 1 + + if not meet_condition: + # this condition is true when query identity does not appear in gallery + continue + + # compute cmc + function_cumsum(raw_cmc, cmc, num_g_real) + for g_idx in range(num_g_real): + if cmc[g_idx] > 1: + cmc[g_idx] = 1 + + for rank_idx in range(max_rank): + all_cmc[q_idx, rank_idx] = cmc[rank_idx] + num_valid_q += 1. + + # compute average precision + # reference: https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision + function_cumsum(raw_cmc, tmp_cmc, num_g_real) + num_rel = 0 + tmp_cmc_sum = 0 + for g_idx in range(num_g_real): + tmp_cmc_sum += (tmp_cmc[g_idx] / (g_idx + 1.)) * raw_cmc[g_idx] + num_rel += raw_cmc[g_idx] + all_AP[q_idx] = tmp_cmc_sum / num_rel + + assert num_valid_q > 0, 'Error: all query identities do not appear in gallery' + + # compute averaged cmc + cdef float[:] avg_cmc = np.zeros(max_rank, dtype=np.float32) + for rank_idx in range(max_rank): + for q_idx in range(num_q): + avg_cmc[rank_idx] += all_cmc[q_idx, rank_idx] + avg_cmc[rank_idx] /= num_valid_q + + cdef float mAP = 0 + for q_idx in range(num_q): + mAP += all_AP[q_idx] + mAP /= num_valid_q + + return np.asarray(avg_cmc).astype(np.float32), mAP + + +# Compute the cumulative sum +cdef void function_cumsum(cython.numeric[:] src, cython.numeric[:] dst, int64_t n): + cdef int64_t i + dst[0] = src[0] + for i in range(1, n): + dst[i] = src[i] + dst[i - 1] \ No newline at end of file diff --git a/strong_sort/deep/reid/torchreid/metrics/rank_cylib/setup.py b/strong_sort/deep/reid/torchreid/metrics/rank_cylib/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ce2aeb7376092aa53ee32671a133bb57ee5941a2 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/metrics/rank_cylib/setup.py @@ -0,0 +1,26 @@ +import numpy as np +from distutils.core import setup +from distutils.extension import Extension +from Cython.Build import cythonize + + +def numpy_include(): + try: + numpy_include = np.get_include() + except AttributeError: + numpy_include = np.get_numpy_include() + return numpy_include + + +ext_modules = [ + Extension( + 'rank_cy', + ['rank_cy.pyx'], + include_dirs=[numpy_include()], + ) +] + +setup( + name='Cython-based reid evaluation code', + ext_modules=cythonize(ext_modules) +) diff --git a/strong_sort/deep/reid/torchreid/metrics/rank_cylib/test_cython.py b/strong_sort/deep/reid/torchreid/metrics/rank_cylib/test_cython.py new file mode 100644 index 0000000000000000000000000000000000000000..5d1175d70bbc22e8c98fa8c5f89e2f5e88dc9c0f --- /dev/null +++ b/strong_sort/deep/reid/torchreid/metrics/rank_cylib/test_cython.py @@ -0,0 +1,83 @@ +from __future__ import print_function +import sys +import numpy as np +import timeit +import os.path as osp + +from torchreid import metrics + +sys.path.insert(0, osp.dirname(osp.abspath(__file__)) + '/../../..') +""" +Test the speed of cython-based evaluation code. The speed improvements +can be much bigger when using the real reid data, which contains a larger +amount of query and gallery images. + +Note: you might encounter the following error: + 'AssertionError: Error: all query identities do not appear in gallery'. +This is normal because the inputs are random numbers. Just try again. +""" + +print('*** Compare running time ***') + +setup = ''' +import sys +import os.path as osp +import numpy as np +sys.path.insert(0, osp.dirname(osp.abspath(__file__)) + '/../../..') +from torchreid import metrics +num_q = 30 +num_g = 300 +max_rank = 5 +distmat = np.random.rand(num_q, num_g) * 20 +q_pids = np.random.randint(0, num_q, size=num_q) +g_pids = np.random.randint(0, num_g, size=num_g) +q_camids = np.random.randint(0, 5, size=num_q) +g_camids = np.random.randint(0, 5, size=num_g) +''' + +print('=> Using market1501\'s metric') +pytime = timeit.timeit( + 'metrics.evaluate_rank(distmat, q_pids, g_pids, q_camids, g_camids, max_rank, use_cython=False)', + setup=setup, + number=20 +) +cytime = timeit.timeit( + 'metrics.evaluate_rank(distmat, q_pids, g_pids, q_camids, g_camids, max_rank, use_cython=True)', + setup=setup, + number=20 +) +print('Python time: {} s'.format(pytime)) +print('Cython time: {} s'.format(cytime)) +print('Cython is {} times faster than python\n'.format(pytime / cytime)) + +print('=> Using cuhk03\'s metric') +pytime = timeit.timeit( + 'metrics.evaluate_rank(distmat, q_pids, g_pids, q_camids, g_camids, max_rank, use_metric_cuhk03=True, use_cython=False)', + setup=setup, + number=20 +) +cytime = timeit.timeit( + 'metrics.evaluate_rank(distmat, q_pids, g_pids, q_camids, g_camids, max_rank, use_metric_cuhk03=True, use_cython=True)', + setup=setup, + number=20 +) +print('Python time: {} s'.format(pytime)) +print('Cython time: {} s'.format(cytime)) +print('Cython is {} times faster than python\n'.format(pytime / cytime)) +""" +print("=> Check precision") + +num_q = 30 +num_g = 300 +max_rank = 5 +distmat = np.random.rand(num_q, num_g) * 20 +q_pids = np.random.randint(0, num_q, size=num_q) +g_pids = np.random.randint(0, num_g, size=num_g) +q_camids = np.random.randint(0, 5, size=num_q) +g_camids = np.random.randint(0, 5, size=num_g) + +cmc, mAP = evaluate(distmat, q_pids, g_pids, q_camids, g_camids, max_rank, use_cython=False) +print("Python:\nmAP = {} \ncmc = {}\n".format(mAP, cmc)) +cmc, mAP = evaluate(distmat, q_pids, g_pids, q_camids, g_camids, max_rank, use_cython=True) +print("Cython:\nmAP = {} \ncmc = {}\n".format(mAP, cmc)) +""" diff --git a/strong_sort/deep/reid/torchreid/models/__init__.py b/strong_sort/deep/reid/torchreid/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3c60ba6f59ca7fa5ff9f3c6a4dcef1357c353dde --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/__init__.py @@ -0,0 +1,122 @@ +from __future__ import absolute_import +import torch + +from .pcb import * +from .mlfn import * +from .hacnn import * +from .osnet import * +from .senet import * +from .mudeep import * +from .nasnet import * +from .resnet import * +from .densenet import * +from .xception import * +from .osnet_ain import * +from .resnetmid import * +from .shufflenet import * +from .squeezenet import * +from .inceptionv4 import * +from .mobilenetv2 import * +from .resnet_ibn_a import * +from .resnet_ibn_b import * +from .shufflenetv2 import * +from .inceptionresnetv2 import * + +__model_factory = { + # image classification models + 'resnet18': resnet18, + 'resnet34': resnet34, + 'resnet50': resnet50, + 'resnet101': resnet101, + 'resnet152': resnet152, + 'resnext50_32x4d': resnext50_32x4d, + 'resnext101_32x8d': resnext101_32x8d, + 'resnet50_fc512': resnet50_fc512, + 'se_resnet50': se_resnet50, + 'se_resnet50_fc512': se_resnet50_fc512, + 'se_resnet101': se_resnet101, + 'se_resnext50_32x4d': se_resnext50_32x4d, + 'se_resnext101_32x4d': se_resnext101_32x4d, + 'densenet121': densenet121, + 'densenet169': densenet169, + 'densenet201': densenet201, + 'densenet161': densenet161, + 'densenet121_fc512': densenet121_fc512, + 'inceptionresnetv2': inceptionresnetv2, + 'inceptionv4': inceptionv4, + 'xception': xception, + 'resnet50_ibn_a': resnet50_ibn_a, + 'resnet50_ibn_b': resnet50_ibn_b, + # lightweight models + 'nasnsetmobile': nasnetamobile, + 'mobilenetv2_x1_0': mobilenetv2_x1_0, + 'mobilenetv2_x1_4': mobilenetv2_x1_4, + 'shufflenet': shufflenet, + 'squeezenet1_0': squeezenet1_0, + 'squeezenet1_0_fc512': squeezenet1_0_fc512, + 'squeezenet1_1': squeezenet1_1, + 'shufflenet_v2_x0_5': shufflenet_v2_x0_5, + 'shufflenet_v2_x1_0': shufflenet_v2_x1_0, + 'shufflenet_v2_x1_5': shufflenet_v2_x1_5, + 'shufflenet_v2_x2_0': shufflenet_v2_x2_0, + # reid-specific models + 'mudeep': MuDeep, + 'resnet50mid': resnet50mid, + 'hacnn': HACNN, + 'pcb_p6': pcb_p6, + 'pcb_p4': pcb_p4, + 'mlfn': mlfn, + 'osnet_x1_0': osnet_x1_0, + 'osnet_x0_75': osnet_x0_75, + 'osnet_x0_5': osnet_x0_5, + 'osnet_x0_25': osnet_x0_25, + 'osnet_ibn_x1_0': osnet_ibn_x1_0, + 'osnet_ain_x1_0': osnet_ain_x1_0, + 'osnet_ain_x0_75': osnet_ain_x0_75, + 'osnet_ain_x0_5': osnet_ain_x0_5, + 'osnet_ain_x0_25': osnet_ain_x0_25 +} + + +def show_avai_models(): + """Displays available models. + + Examples:: + >>> from torchreid import models + >>> models.show_avai_models() + """ + print(list(__model_factory.keys())) + + +def build_model( + name, num_classes, loss='softmax', pretrained=True, use_gpu=True +): + """A function wrapper for building a model. + + Args: + name (str): model name. + num_classes (int): number of training identities. + loss (str, optional): loss function to optimize the model. Currently + supports "softmax" and "triplet". Default is "softmax". + pretrained (bool, optional): whether to load ImageNet-pretrained weights. + Default is True. + use_gpu (bool, optional): whether to use gpu. Default is True. + + Returns: + nn.Module + + Examples:: + >>> from torchreid import models + >>> model = models.build_model('resnet50', 751, loss='softmax') + """ + avai_models = list(__model_factory.keys()) + if name not in avai_models: + raise KeyError( + 'Unknown model: {}. Must be one of {}'.format(name, avai_models) + ) + return __model_factory[name]( + num_classes=num_classes, + loss=loss, + pretrained=pretrained, + use_gpu=use_gpu + ) diff --git a/strong_sort/deep/reid/torchreid/models/densenet.py b/strong_sort/deep/reid/torchreid/models/densenet.py new file mode 100644 index 0000000000000000000000000000000000000000..a1d9b7ef85a79cbc4c4e8a81840935531df636b8 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/densenet.py @@ -0,0 +1,380 @@ +""" +Code source: https://github.com/pytorch/vision +""" +from __future__ import division, absolute_import +import re +from collections import OrderedDict +import torch +import torch.nn as nn +from torch.nn import functional as F +from torch.utils import model_zoo + +__all__ = [ + 'densenet121', 'densenet169', 'densenet201', 'densenet161', + 'densenet121_fc512' +] + +model_urls = { + 'densenet121': + 'https://download.pytorch.org/models/densenet121-a639ec97.pth', + 'densenet169': + 'https://download.pytorch.org/models/densenet169-b2777c0a.pth', + 'densenet201': + 'https://download.pytorch.org/models/densenet201-c1103571.pth', + 'densenet161': + 'https://download.pytorch.org/models/densenet161-8d451a50.pth', +} + + +class _DenseLayer(nn.Sequential): + + def __init__(self, num_input_features, growth_rate, bn_size, drop_rate): + super(_DenseLayer, self).__init__() + self.add_module('norm1', nn.BatchNorm2d(num_input_features)), + self.add_module('relu1', nn.ReLU(inplace=True)), + self.add_module( + 'conv1', + nn.Conv2d( + num_input_features, + bn_size * growth_rate, + kernel_size=1, + stride=1, + bias=False + ) + ), + self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)), + self.add_module('relu2', nn.ReLU(inplace=True)), + self.add_module( + 'conv2', + nn.Conv2d( + bn_size * growth_rate, + growth_rate, + kernel_size=3, + stride=1, + padding=1, + bias=False + ) + ), + self.drop_rate = drop_rate + + def forward(self, x): + new_features = super(_DenseLayer, self).forward(x) + if self.drop_rate > 0: + new_features = F.dropout( + new_features, p=self.drop_rate, training=self.training + ) + return torch.cat([x, new_features], 1) + + +class _DenseBlock(nn.Sequential): + + def __init__( + self, num_layers, num_input_features, bn_size, growth_rate, drop_rate + ): + super(_DenseBlock, self).__init__() + for i in range(num_layers): + layer = _DenseLayer( + num_input_features + i*growth_rate, growth_rate, bn_size, + drop_rate + ) + self.add_module('denselayer%d' % (i+1), layer) + + +class _Transition(nn.Sequential): + + def __init__(self, num_input_features, num_output_features): + super(_Transition, self).__init__() + self.add_module('norm', nn.BatchNorm2d(num_input_features)) + self.add_module('relu', nn.ReLU(inplace=True)) + self.add_module( + 'conv', + nn.Conv2d( + num_input_features, + num_output_features, + kernel_size=1, + stride=1, + bias=False + ) + ) + self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2)) + + +class DenseNet(nn.Module): + """Densely connected network. + + Reference: + Huang et al. Densely Connected Convolutional Networks. CVPR 2017. + + Public keys: + - ``densenet121``: DenseNet121. + - ``densenet169``: DenseNet169. + - ``densenet201``: DenseNet201. + - ``densenet161``: DenseNet161. + - ``densenet121_fc512``: DenseNet121 + FC. + """ + + def __init__( + self, + num_classes, + loss, + growth_rate=32, + block_config=(6, 12, 24, 16), + num_init_features=64, + bn_size=4, + drop_rate=0, + fc_dims=None, + dropout_p=None, + **kwargs + ): + + super(DenseNet, self).__init__() + self.loss = loss + + # First convolution + self.features = nn.Sequential( + OrderedDict( + [ + ( + 'conv0', + nn.Conv2d( + 3, + num_init_features, + kernel_size=7, + stride=2, + padding=3, + bias=False + ) + ), + ('norm0', nn.BatchNorm2d(num_init_features)), + ('relu0', nn.ReLU(inplace=True)), + ( + 'pool0', + nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + ), + ] + ) + ) + + # Each denseblock + num_features = num_init_features + for i, num_layers in enumerate(block_config): + block = _DenseBlock( + num_layers=num_layers, + num_input_features=num_features, + bn_size=bn_size, + growth_rate=growth_rate, + drop_rate=drop_rate + ) + self.features.add_module('denseblock%d' % (i+1), block) + num_features = num_features + num_layers*growth_rate + if i != len(block_config) - 1: + trans = _Transition( + num_input_features=num_features, + num_output_features=num_features // 2 + ) + self.features.add_module('transition%d' % (i+1), trans) + num_features = num_features // 2 + + # Final batch norm + self.features.add_module('norm5', nn.BatchNorm2d(num_features)) + + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.feature_dim = num_features + self.fc = self._construct_fc_layer(fc_dims, num_features, dropout_p) + + # Linear layer + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self._init_params() + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + """Constructs fully connected layer. + + Args: + fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed + input_dim (int): input dimension + dropout_p (float): dropout probability, if None, dropout is unused + """ + if fc_dims is None: + self.feature_dim = input_dim + return None + + assert isinstance( + fc_dims, (list, tuple) + ), 'fc_dims must be either list or tuple, but got {}'.format( + type(fc_dims) + ) + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x): + f = self.features(x) + f = F.relu(f, inplace=True) + v = self.global_avgpool(f) + v = v.view(v.size(0), -1) + + if self.fc is not None: + v = self.fc(v) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + + # '.'s are no longer allowed in module names, but pervious _DenseLayer + # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'. + # They are also in the checkpoints in model_urls. This pattern is used + # to find such keys. + pattern = re.compile( + r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$' + ) + for key in list(pretrain_dict.keys()): + res = pattern.match(key) + if res: + new_key = res.group(1) + res.group(2) + pretrain_dict[new_key] = pretrain_dict[key] + del pretrain_dict[key] + + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +""" +Dense network configurations: +-- +densenet121: num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16) +densenet169: num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32) +densenet201: num_init_features=64, growth_rate=32, block_config=(6, 12, 48, 32) +densenet161: num_init_features=96, growth_rate=48, block_config=(6, 12, 36, 24) +""" + + +def densenet121(num_classes, loss='softmax', pretrained=True, **kwargs): + model = DenseNet( + num_classes=num_classes, + loss=loss, + num_init_features=64, + growth_rate=32, + block_config=(6, 12, 24, 16), + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['densenet121']) + return model + + +def densenet169(num_classes, loss='softmax', pretrained=True, **kwargs): + model = DenseNet( + num_classes=num_classes, + loss=loss, + num_init_features=64, + growth_rate=32, + block_config=(6, 12, 32, 32), + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['densenet169']) + return model + + +def densenet201(num_classes, loss='softmax', pretrained=True, **kwargs): + model = DenseNet( + num_classes=num_classes, + loss=loss, + num_init_features=64, + growth_rate=32, + block_config=(6, 12, 48, 32), + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['densenet201']) + return model + + +def densenet161(num_classes, loss='softmax', pretrained=True, **kwargs): + model = DenseNet( + num_classes=num_classes, + loss=loss, + num_init_features=96, + growth_rate=48, + block_config=(6, 12, 36, 24), + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['densenet161']) + return model + + +def densenet121_fc512(num_classes, loss='softmax', pretrained=True, **kwargs): + model = DenseNet( + num_classes=num_classes, + loss=loss, + num_init_features=64, + growth_rate=32, + block_config=(6, 12, 24, 16), + fc_dims=[512], + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['densenet121']) + return model diff --git a/strong_sort/deep/reid/torchreid/models/hacnn.py b/strong_sort/deep/reid/torchreid/models/hacnn.py new file mode 100644 index 0000000000000000000000000000000000000000..f21cc82f42fe181317f9a0d89cdede95699f45a9 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/hacnn.py @@ -0,0 +1,414 @@ +from __future__ import division, absolute_import +import torch +from torch import nn +from torch.nn import functional as F + +__all__ = ['HACNN'] + + +class ConvBlock(nn.Module): + """Basic convolutional block. + + convolution + batch normalization + relu. + + Args: + in_c (int): number of input channels. + out_c (int): number of output channels. + k (int or tuple): kernel size. + s (int or tuple): stride. + p (int or tuple): padding. + """ + + def __init__(self, in_c, out_c, k, s=1, p=0): + super(ConvBlock, self).__init__() + self.conv = nn.Conv2d(in_c, out_c, k, stride=s, padding=p) + self.bn = nn.BatchNorm2d(out_c) + + def forward(self, x): + return F.relu(self.bn(self.conv(x))) + + +class InceptionA(nn.Module): + + def __init__(self, in_channels, out_channels): + super(InceptionA, self).__init__() + mid_channels = out_channels // 4 + + self.stream1 = nn.Sequential( + ConvBlock(in_channels, mid_channels, 1), + ConvBlock(mid_channels, mid_channels, 3, p=1), + ) + self.stream2 = nn.Sequential( + ConvBlock(in_channels, mid_channels, 1), + ConvBlock(mid_channels, mid_channels, 3, p=1), + ) + self.stream3 = nn.Sequential( + ConvBlock(in_channels, mid_channels, 1), + ConvBlock(mid_channels, mid_channels, 3, p=1), + ) + self.stream4 = nn.Sequential( + nn.AvgPool2d(3, stride=1, padding=1), + ConvBlock(in_channels, mid_channels, 1), + ) + + def forward(self, x): + s1 = self.stream1(x) + s2 = self.stream2(x) + s3 = self.stream3(x) + s4 = self.stream4(x) + y = torch.cat([s1, s2, s3, s4], dim=1) + return y + + +class InceptionB(nn.Module): + + def __init__(self, in_channels, out_channels): + super(InceptionB, self).__init__() + mid_channels = out_channels // 4 + + self.stream1 = nn.Sequential( + ConvBlock(in_channels, mid_channels, 1), + ConvBlock(mid_channels, mid_channels, 3, s=2, p=1), + ) + self.stream2 = nn.Sequential( + ConvBlock(in_channels, mid_channels, 1), + ConvBlock(mid_channels, mid_channels, 3, p=1), + ConvBlock(mid_channels, mid_channels, 3, s=2, p=1), + ) + self.stream3 = nn.Sequential( + nn.MaxPool2d(3, stride=2, padding=1), + ConvBlock(in_channels, mid_channels * 2, 1), + ) + + def forward(self, x): + s1 = self.stream1(x) + s2 = self.stream2(x) + s3 = self.stream3(x) + y = torch.cat([s1, s2, s3], dim=1) + return y + + +class SpatialAttn(nn.Module): + """Spatial Attention (Sec. 3.1.I.1)""" + + def __init__(self): + super(SpatialAttn, self).__init__() + self.conv1 = ConvBlock(1, 1, 3, s=2, p=1) + self.conv2 = ConvBlock(1, 1, 1) + + def forward(self, x): + # global cross-channel averaging + x = x.mean(1, keepdim=True) + # 3-by-3 conv + x = self.conv1(x) + # bilinear resizing + x = F.upsample( + x, (x.size(2) * 2, x.size(3) * 2), + mode='bilinear', + align_corners=True + ) + # scaling conv + x = self.conv2(x) + return x + + +class ChannelAttn(nn.Module): + """Channel Attention (Sec. 3.1.I.2)""" + + def __init__(self, in_channels, reduction_rate=16): + super(ChannelAttn, self).__init__() + assert in_channels % reduction_rate == 0 + self.conv1 = ConvBlock(in_channels, in_channels // reduction_rate, 1) + self.conv2 = ConvBlock(in_channels // reduction_rate, in_channels, 1) + + def forward(self, x): + # squeeze operation (global average pooling) + x = F.avg_pool2d(x, x.size()[2:]) + # excitation operation (2 conv layers) + x = self.conv1(x) + x = self.conv2(x) + return x + + +class SoftAttn(nn.Module): + """Soft Attention (Sec. 3.1.I) + + Aim: Spatial Attention + Channel Attention + + Output: attention maps with shape identical to input. + """ + + def __init__(self, in_channels): + super(SoftAttn, self).__init__() + self.spatial_attn = SpatialAttn() + self.channel_attn = ChannelAttn(in_channels) + self.conv = ConvBlock(in_channels, in_channels, 1) + + def forward(self, x): + y_spatial = self.spatial_attn(x) + y_channel = self.channel_attn(x) + y = y_spatial * y_channel + y = torch.sigmoid(self.conv(y)) + return y + + +class HardAttn(nn.Module): + """Hard Attention (Sec. 3.1.II)""" + + def __init__(self, in_channels): + super(HardAttn, self).__init__() + self.fc = nn.Linear(in_channels, 4 * 2) + self.init_params() + + def init_params(self): + self.fc.weight.data.zero_() + self.fc.bias.data.copy_( + torch.tensor( + [0, -0.75, 0, -0.25, 0, 0.25, 0, 0.75], dtype=torch.float + ) + ) + + def forward(self, x): + # squeeze operation (global average pooling) + x = F.avg_pool2d(x, x.size()[2:]).view(x.size(0), x.size(1)) + # predict transformation parameters + theta = torch.tanh(self.fc(x)) + theta = theta.view(-1, 4, 2) + return theta + + +class HarmAttn(nn.Module): + """Harmonious Attention (Sec. 3.1)""" + + def __init__(self, in_channels): + super(HarmAttn, self).__init__() + self.soft_attn = SoftAttn(in_channels) + self.hard_attn = HardAttn(in_channels) + + def forward(self, x): + y_soft_attn = self.soft_attn(x) + theta = self.hard_attn(x) + return y_soft_attn, theta + + +class HACNN(nn.Module): + """Harmonious Attention Convolutional Neural Network. + + Reference: + Li et al. Harmonious Attention Network for Person Re-identification. CVPR 2018. + + Public keys: + - ``hacnn``: HACNN. + """ + + # Args: + # num_classes (int): number of classes to predict + # nchannels (list): number of channels AFTER concatenation + # feat_dim (int): feature dimension for a single stream + # learn_region (bool): whether to learn region features (i.e. local branch) + + def __init__( + self, + num_classes, + loss='softmax', + nchannels=[128, 256, 384], + feat_dim=512, + learn_region=True, + use_gpu=True, + **kwargs + ): + super(HACNN, self).__init__() + self.loss = loss + self.learn_region = learn_region + self.use_gpu = use_gpu + + self.conv = ConvBlock(3, 32, 3, s=2, p=1) + + # Construct Inception + HarmAttn blocks + # ============== Block 1 ============== + self.inception1 = nn.Sequential( + InceptionA(32, nchannels[0]), + InceptionB(nchannels[0], nchannels[0]), + ) + self.ha1 = HarmAttn(nchannels[0]) + + # ============== Block 2 ============== + self.inception2 = nn.Sequential( + InceptionA(nchannels[0], nchannels[1]), + InceptionB(nchannels[1], nchannels[1]), + ) + self.ha2 = HarmAttn(nchannels[1]) + + # ============== Block 3 ============== + self.inception3 = nn.Sequential( + InceptionA(nchannels[1], nchannels[2]), + InceptionB(nchannels[2], nchannels[2]), + ) + self.ha3 = HarmAttn(nchannels[2]) + + self.fc_global = nn.Sequential( + nn.Linear(nchannels[2], feat_dim), + nn.BatchNorm1d(feat_dim), + nn.ReLU(), + ) + self.classifier_global = nn.Linear(feat_dim, num_classes) + + if self.learn_region: + self.init_scale_factors() + self.local_conv1 = InceptionB(32, nchannels[0]) + self.local_conv2 = InceptionB(nchannels[0], nchannels[1]) + self.local_conv3 = InceptionB(nchannels[1], nchannels[2]) + self.fc_local = nn.Sequential( + nn.Linear(nchannels[2] * 4, feat_dim), + nn.BatchNorm1d(feat_dim), + nn.ReLU(), + ) + self.classifier_local = nn.Linear(feat_dim, num_classes) + self.feat_dim = feat_dim * 2 + else: + self.feat_dim = feat_dim + + def init_scale_factors(self): + # initialize scale factors (s_w, s_h) for four regions + self.scale_factors = [] + self.scale_factors.append( + torch.tensor([[1, 0], [0, 0.25]], dtype=torch.float) + ) + self.scale_factors.append( + torch.tensor([[1, 0], [0, 0.25]], dtype=torch.float) + ) + self.scale_factors.append( + torch.tensor([[1, 0], [0, 0.25]], dtype=torch.float) + ) + self.scale_factors.append( + torch.tensor([[1, 0], [0, 0.25]], dtype=torch.float) + ) + + def stn(self, x, theta): + """Performs spatial transform + + x: (batch, channel, height, width) + theta: (batch, 2, 3) + """ + grid = F.affine_grid(theta, x.size()) + x = F.grid_sample(x, grid) + return x + + def transform_theta(self, theta_i, region_idx): + """Transforms theta to include (s_w, s_h), resulting in (batch, 2, 3)""" + scale_factors = self.scale_factors[region_idx] + theta = torch.zeros(theta_i.size(0), 2, 3) + theta[:, :, :2] = scale_factors + theta[:, :, -1] = theta_i + if self.use_gpu: + theta = theta.cuda() + return theta + + def forward(self, x): + assert x.size(2) == 160 and x.size(3) == 64, \ + 'Input size does not match, expected (160, 64) but got ({}, {})'.format(x.size(2), x.size(3)) + x = self.conv(x) + + # ============== Block 1 ============== + # global branch + x1 = self.inception1(x) + x1_attn, x1_theta = self.ha1(x1) + x1_out = x1 * x1_attn + # local branch + if self.learn_region: + x1_local_list = [] + for region_idx in range(4): + x1_theta_i = x1_theta[:, region_idx, :] + x1_theta_i = self.transform_theta(x1_theta_i, region_idx) + x1_trans_i = self.stn(x, x1_theta_i) + x1_trans_i = F.upsample( + x1_trans_i, (24, 28), mode='bilinear', align_corners=True + ) + x1_local_i = self.local_conv1(x1_trans_i) + x1_local_list.append(x1_local_i) + + # ============== Block 2 ============== + # Block 2 + # global branch + x2 = self.inception2(x1_out) + x2_attn, x2_theta = self.ha2(x2) + x2_out = x2 * x2_attn + # local branch + if self.learn_region: + x2_local_list = [] + for region_idx in range(4): + x2_theta_i = x2_theta[:, region_idx, :] + x2_theta_i = self.transform_theta(x2_theta_i, region_idx) + x2_trans_i = self.stn(x1_out, x2_theta_i) + x2_trans_i = F.upsample( + x2_trans_i, (12, 14), mode='bilinear', align_corners=True + ) + x2_local_i = x2_trans_i + x1_local_list[region_idx] + x2_local_i = self.local_conv2(x2_local_i) + x2_local_list.append(x2_local_i) + + # ============== Block 3 ============== + # Block 3 + # global branch + x3 = self.inception3(x2_out) + x3_attn, x3_theta = self.ha3(x3) + x3_out = x3 * x3_attn + # local branch + if self.learn_region: + x3_local_list = [] + for region_idx in range(4): + x3_theta_i = x3_theta[:, region_idx, :] + x3_theta_i = self.transform_theta(x3_theta_i, region_idx) + x3_trans_i = self.stn(x2_out, x3_theta_i) + x3_trans_i = F.upsample( + x3_trans_i, (6, 7), mode='bilinear', align_corners=True + ) + x3_local_i = x3_trans_i + x2_local_list[region_idx] + x3_local_i = self.local_conv3(x3_local_i) + x3_local_list.append(x3_local_i) + + # ============== Feature generation ============== + # global branch + x_global = F.avg_pool2d(x3_out, + x3_out.size()[2:] + ).view(x3_out.size(0), x3_out.size(1)) + x_global = self.fc_global(x_global) + # local branch + if self.learn_region: + x_local_list = [] + for region_idx in range(4): + x_local_i = x3_local_list[region_idx] + x_local_i = F.avg_pool2d(x_local_i, + x_local_i.size()[2:] + ).view(x_local_i.size(0), -1) + x_local_list.append(x_local_i) + x_local = torch.cat(x_local_list, 1) + x_local = self.fc_local(x_local) + + if not self.training: + # l2 normalization before concatenation + if self.learn_region: + x_global = x_global / x_global.norm(p=2, dim=1, keepdim=True) + x_local = x_local / x_local.norm(p=2, dim=1, keepdim=True) + return torch.cat([x_global, x_local], 1) + else: + return x_global + + prelogits_global = self.classifier_global(x_global) + if self.learn_region: + prelogits_local = self.classifier_local(x_local) + + if self.loss == 'softmax': + if self.learn_region: + return (prelogits_global, prelogits_local) + else: + return prelogits_global + + elif self.loss == 'triplet': + if self.learn_region: + return (prelogits_global, prelogits_local), (x_global, x_local) + else: + return prelogits_global, x_global + + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) diff --git a/strong_sort/deep/reid/torchreid/models/inceptionresnetv2.py b/strong_sort/deep/reid/torchreid/models/inceptionresnetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..03e40348425a2b1bc73e6f336efae8e5525cc45c --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/inceptionresnetv2.py @@ -0,0 +1,361 @@ +""" +Code imported from https://github.com/Cadene/pretrained-models.pytorch +""" +from __future__ import division, absolute_import +import torch +import torch.nn as nn +import torch.utils.model_zoo as model_zoo + +__all__ = ['inceptionresnetv2'] + +pretrained_settings = { + 'inceptionresnetv2': { + 'imagenet': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/inceptionresnetv2-520b38e4.pth', + 'input_space': 'RGB', + 'input_size': [3, 299, 299], + 'input_range': [0, 1], + 'mean': [0.5, 0.5, 0.5], + 'std': [0.5, 0.5, 0.5], + 'num_classes': 1000 + }, + 'imagenet+background': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/inceptionresnetv2-520b38e4.pth', + 'input_space': 'RGB', + 'input_size': [3, 299, 299], + 'input_range': [0, 1], + 'mean': [0.5, 0.5, 0.5], + 'std': [0.5, 0.5, 0.5], + 'num_classes': 1001 + } + } +} + + +class BasicConv2d(nn.Module): + + def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0): + super(BasicConv2d, self).__init__() + self.conv = nn.Conv2d( + in_planes, + out_planes, + kernel_size=kernel_size, + stride=stride, + padding=padding, + bias=False + ) # verify bias false + self.bn = nn.BatchNorm2d( + out_planes, + eps=0.001, # value found in tensorflow + momentum=0.1, # default pytorch value + affine=True + ) + self.relu = nn.ReLU(inplace=False) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + +class Mixed_5b(nn.Module): + + def __init__(self): + super(Mixed_5b, self).__init__() + + self.branch0 = BasicConv2d(192, 96, kernel_size=1, stride=1) + + self.branch1 = nn.Sequential( + BasicConv2d(192, 48, kernel_size=1, stride=1), + BasicConv2d(48, 64, kernel_size=5, stride=1, padding=2) + ) + + self.branch2 = nn.Sequential( + BasicConv2d(192, 64, kernel_size=1, stride=1), + BasicConv2d(64, 96, kernel_size=3, stride=1, padding=1), + BasicConv2d(96, 96, kernel_size=3, stride=1, padding=1) + ) + + self.branch3 = nn.Sequential( + nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False), + BasicConv2d(192, 64, kernel_size=1, stride=1) + ) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + x3 = self.branch3(x) + out = torch.cat((x0, x1, x2, x3), 1) + return out + + +class Block35(nn.Module): + + def __init__(self, scale=1.0): + super(Block35, self).__init__() + + self.scale = scale + + self.branch0 = BasicConv2d(320, 32, kernel_size=1, stride=1) + + self.branch1 = nn.Sequential( + BasicConv2d(320, 32, kernel_size=1, stride=1), + BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1) + ) + + self.branch2 = nn.Sequential( + BasicConv2d(320, 32, kernel_size=1, stride=1), + BasicConv2d(32, 48, kernel_size=3, stride=1, padding=1), + BasicConv2d(48, 64, kernel_size=3, stride=1, padding=1) + ) + + self.conv2d = nn.Conv2d(128, 320, kernel_size=1, stride=1) + self.relu = nn.ReLU(inplace=False) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + out = torch.cat((x0, x1, x2), 1) + out = self.conv2d(out) + out = out * self.scale + x + out = self.relu(out) + return out + + +class Mixed_6a(nn.Module): + + def __init__(self): + super(Mixed_6a, self).__init__() + + self.branch0 = BasicConv2d(320, 384, kernel_size=3, stride=2) + + self.branch1 = nn.Sequential( + BasicConv2d(320, 256, kernel_size=1, stride=1), + BasicConv2d(256, 256, kernel_size=3, stride=1, padding=1), + BasicConv2d(256, 384, kernel_size=3, stride=2) + ) + + self.branch2 = nn.MaxPool2d(3, stride=2) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + out = torch.cat((x0, x1, x2), 1) + return out + + +class Block17(nn.Module): + + def __init__(self, scale=1.0): + super(Block17, self).__init__() + + self.scale = scale + + self.branch0 = BasicConv2d(1088, 192, kernel_size=1, stride=1) + + self.branch1 = nn.Sequential( + BasicConv2d(1088, 128, kernel_size=1, stride=1), + BasicConv2d( + 128, 160, kernel_size=(1, 7), stride=1, padding=(0, 3) + ), + BasicConv2d( + 160, 192, kernel_size=(7, 1), stride=1, padding=(3, 0) + ) + ) + + self.conv2d = nn.Conv2d(384, 1088, kernel_size=1, stride=1) + self.relu = nn.ReLU(inplace=False) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + out = torch.cat((x0, x1), 1) + out = self.conv2d(out) + out = out * self.scale + x + out = self.relu(out) + return out + + +class Mixed_7a(nn.Module): + + def __init__(self): + super(Mixed_7a, self).__init__() + + self.branch0 = nn.Sequential( + BasicConv2d(1088, 256, kernel_size=1, stride=1), + BasicConv2d(256, 384, kernel_size=3, stride=2) + ) + + self.branch1 = nn.Sequential( + BasicConv2d(1088, 256, kernel_size=1, stride=1), + BasicConv2d(256, 288, kernel_size=3, stride=2) + ) + + self.branch2 = nn.Sequential( + BasicConv2d(1088, 256, kernel_size=1, stride=1), + BasicConv2d(256, 288, kernel_size=3, stride=1, padding=1), + BasicConv2d(288, 320, kernel_size=3, stride=2) + ) + + self.branch3 = nn.MaxPool2d(3, stride=2) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + x3 = self.branch3(x) + out = torch.cat((x0, x1, x2, x3), 1) + return out + + +class Block8(nn.Module): + + def __init__(self, scale=1.0, noReLU=False): + super(Block8, self).__init__() + + self.scale = scale + self.noReLU = noReLU + + self.branch0 = BasicConv2d(2080, 192, kernel_size=1, stride=1) + + self.branch1 = nn.Sequential( + BasicConv2d(2080, 192, kernel_size=1, stride=1), + BasicConv2d( + 192, 224, kernel_size=(1, 3), stride=1, padding=(0, 1) + ), + BasicConv2d( + 224, 256, kernel_size=(3, 1), stride=1, padding=(1, 0) + ) + ) + + self.conv2d = nn.Conv2d(448, 2080, kernel_size=1, stride=1) + if not self.noReLU: + self.relu = nn.ReLU(inplace=False) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + out = torch.cat((x0, x1), 1) + out = self.conv2d(out) + out = out * self.scale + x + if not self.noReLU: + out = self.relu(out) + return out + + +# ---------------- +# Model Definition +# ---------------- +class InceptionResNetV2(nn.Module): + """Inception-ResNet-V2. + + Reference: + Szegedy et al. Inception-v4, Inception-ResNet and the Impact of Residual + Connections on Learning. AAAI 2017. + + Public keys: + - ``inceptionresnetv2``: Inception-ResNet-V2. + """ + + def __init__(self, num_classes, loss='softmax', **kwargs): + super(InceptionResNetV2, self).__init__() + self.loss = loss + + # Modules + self.conv2d_1a = BasicConv2d(3, 32, kernel_size=3, stride=2) + self.conv2d_2a = BasicConv2d(32, 32, kernel_size=3, stride=1) + self.conv2d_2b = BasicConv2d( + 32, 64, kernel_size=3, stride=1, padding=1 + ) + self.maxpool_3a = nn.MaxPool2d(3, stride=2) + self.conv2d_3b = BasicConv2d(64, 80, kernel_size=1, stride=1) + self.conv2d_4a = BasicConv2d(80, 192, kernel_size=3, stride=1) + self.maxpool_5a = nn.MaxPool2d(3, stride=2) + self.mixed_5b = Mixed_5b() + self.repeat = nn.Sequential( + Block35(scale=0.17), Block35(scale=0.17), Block35(scale=0.17), + Block35(scale=0.17), Block35(scale=0.17), Block35(scale=0.17), + Block35(scale=0.17), Block35(scale=0.17), Block35(scale=0.17), + Block35(scale=0.17) + ) + self.mixed_6a = Mixed_6a() + self.repeat_1 = nn.Sequential( + Block17(scale=0.10), Block17(scale=0.10), Block17(scale=0.10), + Block17(scale=0.10), Block17(scale=0.10), Block17(scale=0.10), + Block17(scale=0.10), Block17(scale=0.10), Block17(scale=0.10), + Block17(scale=0.10), Block17(scale=0.10), Block17(scale=0.10), + Block17(scale=0.10), Block17(scale=0.10), Block17(scale=0.10), + Block17(scale=0.10), Block17(scale=0.10), Block17(scale=0.10), + Block17(scale=0.10), Block17(scale=0.10) + ) + self.mixed_7a = Mixed_7a() + self.repeat_2 = nn.Sequential( + Block8(scale=0.20), Block8(scale=0.20), Block8(scale=0.20), + Block8(scale=0.20), Block8(scale=0.20), Block8(scale=0.20), + Block8(scale=0.20), Block8(scale=0.20), Block8(scale=0.20) + ) + + self.block8 = Block8(noReLU=True) + self.conv2d_7b = BasicConv2d(2080, 1536, kernel_size=1, stride=1) + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Linear(1536, num_classes) + + def load_imagenet_weights(self): + settings = pretrained_settings['inceptionresnetv2']['imagenet'] + pretrain_dict = model_zoo.load_url(settings['url']) + model_dict = self.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + self.load_state_dict(model_dict) + + def featuremaps(self, x): + x = self.conv2d_1a(x) + x = self.conv2d_2a(x) + x = self.conv2d_2b(x) + x = self.maxpool_3a(x) + x = self.conv2d_3b(x) + x = self.conv2d_4a(x) + x = self.maxpool_5a(x) + x = self.mixed_5b(x) + x = self.repeat(x) + x = self.mixed_6a(x) + x = self.repeat_1(x) + x = self.mixed_7a(x) + x = self.repeat_2(x) + x = self.block8(x) + x = self.conv2d_7b(x) + return x + + def forward(self, x): + f = self.featuremaps(x) + v = self.global_avgpool(f) + v = v.view(v.size(0), -1) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def inceptionresnetv2(num_classes, loss='softmax', pretrained=True, **kwargs): + model = InceptionResNetV2(num_classes=num_classes, loss=loss, **kwargs) + if pretrained: + model.load_imagenet_weights() + return model diff --git a/strong_sort/deep/reid/torchreid/models/inceptionv4.py b/strong_sort/deep/reid/torchreid/models/inceptionv4.py new file mode 100644 index 0000000000000000000000000000000000000000..b14916f140712298866c943ebdb4ebad67d72fc4 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/inceptionv4.py @@ -0,0 +1,381 @@ +from __future__ import division, absolute_import +import torch +import torch.nn as nn +import torch.utils.model_zoo as model_zoo + +__all__ = ['inceptionv4'] +""" +Code imported from https://github.com/Cadene/pretrained-models.pytorch +""" + +pretrained_settings = { + 'inceptionv4': { + 'imagenet': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/inceptionv4-8e4777a0.pth', + 'input_space': 'RGB', + 'input_size': [3, 299, 299], + 'input_range': [0, 1], + 'mean': [0.5, 0.5, 0.5], + 'std': [0.5, 0.5, 0.5], + 'num_classes': 1000 + }, + 'imagenet+background': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/inceptionv4-8e4777a0.pth', + 'input_space': 'RGB', + 'input_size': [3, 299, 299], + 'input_range': [0, 1], + 'mean': [0.5, 0.5, 0.5], + 'std': [0.5, 0.5, 0.5], + 'num_classes': 1001 + } + } +} + + +class BasicConv2d(nn.Module): + + def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0): + super(BasicConv2d, self).__init__() + self.conv = nn.Conv2d( + in_planes, + out_planes, + kernel_size=kernel_size, + stride=stride, + padding=padding, + bias=False + ) # verify bias false + self.bn = nn.BatchNorm2d( + out_planes, + eps=0.001, # value found in tensorflow + momentum=0.1, # default pytorch value + affine=True + ) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + +class Mixed_3a(nn.Module): + + def __init__(self): + super(Mixed_3a, self).__init__() + self.maxpool = nn.MaxPool2d(3, stride=2) + self.conv = BasicConv2d(64, 96, kernel_size=3, stride=2) + + def forward(self, x): + x0 = self.maxpool(x) + x1 = self.conv(x) + out = torch.cat((x0, x1), 1) + return out + + +class Mixed_4a(nn.Module): + + def __init__(self): + super(Mixed_4a, self).__init__() + + self.branch0 = nn.Sequential( + BasicConv2d(160, 64, kernel_size=1, stride=1), + BasicConv2d(64, 96, kernel_size=3, stride=1) + ) + + self.branch1 = nn.Sequential( + BasicConv2d(160, 64, kernel_size=1, stride=1), + BasicConv2d(64, 64, kernel_size=(1, 7), stride=1, padding=(0, 3)), + BasicConv2d(64, 64, kernel_size=(7, 1), stride=1, padding=(3, 0)), + BasicConv2d(64, 96, kernel_size=(3, 3), stride=1) + ) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + out = torch.cat((x0, x1), 1) + return out + + +class Mixed_5a(nn.Module): + + def __init__(self): + super(Mixed_5a, self).__init__() + self.conv = BasicConv2d(192, 192, kernel_size=3, stride=2) + self.maxpool = nn.MaxPool2d(3, stride=2) + + def forward(self, x): + x0 = self.conv(x) + x1 = self.maxpool(x) + out = torch.cat((x0, x1), 1) + return out + + +class Inception_A(nn.Module): + + def __init__(self): + super(Inception_A, self).__init__() + self.branch0 = BasicConv2d(384, 96, kernel_size=1, stride=1) + + self.branch1 = nn.Sequential( + BasicConv2d(384, 64, kernel_size=1, stride=1), + BasicConv2d(64, 96, kernel_size=3, stride=1, padding=1) + ) + + self.branch2 = nn.Sequential( + BasicConv2d(384, 64, kernel_size=1, stride=1), + BasicConv2d(64, 96, kernel_size=3, stride=1, padding=1), + BasicConv2d(96, 96, kernel_size=3, stride=1, padding=1) + ) + + self.branch3 = nn.Sequential( + nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False), + BasicConv2d(384, 96, kernel_size=1, stride=1) + ) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + x3 = self.branch3(x) + out = torch.cat((x0, x1, x2, x3), 1) + return out + + +class Reduction_A(nn.Module): + + def __init__(self): + super(Reduction_A, self).__init__() + self.branch0 = BasicConv2d(384, 384, kernel_size=3, stride=2) + + self.branch1 = nn.Sequential( + BasicConv2d(384, 192, kernel_size=1, stride=1), + BasicConv2d(192, 224, kernel_size=3, stride=1, padding=1), + BasicConv2d(224, 256, kernel_size=3, stride=2) + ) + + self.branch2 = nn.MaxPool2d(3, stride=2) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + out = torch.cat((x0, x1, x2), 1) + return out + + +class Inception_B(nn.Module): + + def __init__(self): + super(Inception_B, self).__init__() + self.branch0 = BasicConv2d(1024, 384, kernel_size=1, stride=1) + + self.branch1 = nn.Sequential( + BasicConv2d(1024, 192, kernel_size=1, stride=1), + BasicConv2d( + 192, 224, kernel_size=(1, 7), stride=1, padding=(0, 3) + ), + BasicConv2d( + 224, 256, kernel_size=(7, 1), stride=1, padding=(3, 0) + ) + ) + + self.branch2 = nn.Sequential( + BasicConv2d(1024, 192, kernel_size=1, stride=1), + BasicConv2d( + 192, 192, kernel_size=(7, 1), stride=1, padding=(3, 0) + ), + BasicConv2d( + 192, 224, kernel_size=(1, 7), stride=1, padding=(0, 3) + ), + BasicConv2d( + 224, 224, kernel_size=(7, 1), stride=1, padding=(3, 0) + ), + BasicConv2d( + 224, 256, kernel_size=(1, 7), stride=1, padding=(0, 3) + ) + ) + + self.branch3 = nn.Sequential( + nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False), + BasicConv2d(1024, 128, kernel_size=1, stride=1) + ) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + x3 = self.branch3(x) + out = torch.cat((x0, x1, x2, x3), 1) + return out + + +class Reduction_B(nn.Module): + + def __init__(self): + super(Reduction_B, self).__init__() + + self.branch0 = nn.Sequential( + BasicConv2d(1024, 192, kernel_size=1, stride=1), + BasicConv2d(192, 192, kernel_size=3, stride=2) + ) + + self.branch1 = nn.Sequential( + BasicConv2d(1024, 256, kernel_size=1, stride=1), + BasicConv2d( + 256, 256, kernel_size=(1, 7), stride=1, padding=(0, 3) + ), + BasicConv2d( + 256, 320, kernel_size=(7, 1), stride=1, padding=(3, 0) + ), BasicConv2d(320, 320, kernel_size=3, stride=2) + ) + + self.branch2 = nn.MaxPool2d(3, stride=2) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + out = torch.cat((x0, x1, x2), 1) + return out + + +class Inception_C(nn.Module): + + def __init__(self): + super(Inception_C, self).__init__() + + self.branch0 = BasicConv2d(1536, 256, kernel_size=1, stride=1) + + self.branch1_0 = BasicConv2d(1536, 384, kernel_size=1, stride=1) + self.branch1_1a = BasicConv2d( + 384, 256, kernel_size=(1, 3), stride=1, padding=(0, 1) + ) + self.branch1_1b = BasicConv2d( + 384, 256, kernel_size=(3, 1), stride=1, padding=(1, 0) + ) + + self.branch2_0 = BasicConv2d(1536, 384, kernel_size=1, stride=1) + self.branch2_1 = BasicConv2d( + 384, 448, kernel_size=(3, 1), stride=1, padding=(1, 0) + ) + self.branch2_2 = BasicConv2d( + 448, 512, kernel_size=(1, 3), stride=1, padding=(0, 1) + ) + self.branch2_3a = BasicConv2d( + 512, 256, kernel_size=(1, 3), stride=1, padding=(0, 1) + ) + self.branch2_3b = BasicConv2d( + 512, 256, kernel_size=(3, 1), stride=1, padding=(1, 0) + ) + + self.branch3 = nn.Sequential( + nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False), + BasicConv2d(1536, 256, kernel_size=1, stride=1) + ) + + def forward(self, x): + x0 = self.branch0(x) + + x1_0 = self.branch1_0(x) + x1_1a = self.branch1_1a(x1_0) + x1_1b = self.branch1_1b(x1_0) + x1 = torch.cat((x1_1a, x1_1b), 1) + + x2_0 = self.branch2_0(x) + x2_1 = self.branch2_1(x2_0) + x2_2 = self.branch2_2(x2_1) + x2_3a = self.branch2_3a(x2_2) + x2_3b = self.branch2_3b(x2_2) + x2 = torch.cat((x2_3a, x2_3b), 1) + + x3 = self.branch3(x) + + out = torch.cat((x0, x1, x2, x3), 1) + return out + + +class InceptionV4(nn.Module): + """Inception-v4. + + Reference: + Szegedy et al. Inception-v4, Inception-ResNet and the Impact of Residual + Connections on Learning. AAAI 2017. + + Public keys: + - ``inceptionv4``: InceptionV4. + """ + + def __init__(self, num_classes, loss, **kwargs): + super(InceptionV4, self).__init__() + self.loss = loss + + self.features = nn.Sequential( + BasicConv2d(3, 32, kernel_size=3, stride=2), + BasicConv2d(32, 32, kernel_size=3, stride=1), + BasicConv2d(32, 64, kernel_size=3, stride=1, padding=1), + Mixed_3a(), + Mixed_4a(), + Mixed_5a(), + Inception_A(), + Inception_A(), + Inception_A(), + Inception_A(), + Reduction_A(), # Mixed_6a + Inception_B(), + Inception_B(), + Inception_B(), + Inception_B(), + Inception_B(), + Inception_B(), + Inception_B(), + Reduction_B(), # Mixed_7a + Inception_C(), + Inception_C(), + Inception_C() + ) + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Linear(1536, num_classes) + + def forward(self, x): + f = self.features(x) + v = self.global_avgpool(f) + v = v.view(v.size(0), -1) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def inceptionv4(num_classes, loss='softmax', pretrained=True, **kwargs): + model = InceptionV4(num_classes, loss, **kwargs) + if pretrained: + model_url = pretrained_settings['inceptionv4']['imagenet']['url'] + init_pretrained_weights(model, model_url) + return model diff --git a/strong_sort/deep/reid/torchreid/models/mlfn.py b/strong_sort/deep/reid/torchreid/models/mlfn.py new file mode 100644 index 0000000000000000000000000000000000000000..ac7e126b073db6a710fc41e62624127ca91ec131 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/mlfn.py @@ -0,0 +1,269 @@ +from __future__ import division, absolute_import +import torch +import torch.utils.model_zoo as model_zoo +from torch import nn +from torch.nn import functional as F + +__all__ = ['mlfn'] + +model_urls = { + # training epoch = 5, top1 = 51.6 + 'imagenet': + 'https://mega.nz/#!YHxAhaxC!yu9E6zWl0x5zscSouTdbZu8gdFFytDdl-RAdD2DEfpk', +} + + +class MLFNBlock(nn.Module): + + def __init__( + self, in_channels, out_channels, stride, fsm_channels, groups=32 + ): + super(MLFNBlock, self).__init__() + self.groups = groups + mid_channels = out_channels // 2 + + # Factor Modules + self.fm_conv1 = nn.Conv2d(in_channels, mid_channels, 1, bias=False) + self.fm_bn1 = nn.BatchNorm2d(mid_channels) + self.fm_conv2 = nn.Conv2d( + mid_channels, + mid_channels, + 3, + stride=stride, + padding=1, + bias=False, + groups=self.groups + ) + self.fm_bn2 = nn.BatchNorm2d(mid_channels) + self.fm_conv3 = nn.Conv2d(mid_channels, out_channels, 1, bias=False) + self.fm_bn3 = nn.BatchNorm2d(out_channels) + + # Factor Selection Module + self.fsm = nn.Sequential( + nn.AdaptiveAvgPool2d(1), + nn.Conv2d(in_channels, fsm_channels[0], 1), + nn.BatchNorm2d(fsm_channels[0]), + nn.ReLU(inplace=True), + nn.Conv2d(fsm_channels[0], fsm_channels[1], 1), + nn.BatchNorm2d(fsm_channels[1]), + nn.ReLU(inplace=True), + nn.Conv2d(fsm_channels[1], self.groups, 1), + nn.BatchNorm2d(self.groups), + nn.Sigmoid(), + ) + + self.downsample = None + if in_channels != out_channels or stride > 1: + self.downsample = nn.Sequential( + nn.Conv2d( + in_channels, out_channels, 1, stride=stride, bias=False + ), + nn.BatchNorm2d(out_channels), + ) + + def forward(self, x): + residual = x + s = self.fsm(x) + + # reduce dimension + x = self.fm_conv1(x) + x = self.fm_bn1(x) + x = F.relu(x, inplace=True) + + # group convolution + x = self.fm_conv2(x) + x = self.fm_bn2(x) + x = F.relu(x, inplace=True) + + # factor selection + b, c = x.size(0), x.size(1) + n = c // self.groups + ss = s.repeat(1, n, 1, 1) # from (b, g, 1, 1) to (b, g*n=c, 1, 1) + ss = ss.view(b, n, self.groups, 1, 1) + ss = ss.permute(0, 2, 1, 3, 4).contiguous() + ss = ss.view(b, c, 1, 1) + x = ss * x + + # recover dimension + x = self.fm_conv3(x) + x = self.fm_bn3(x) + x = F.relu(x, inplace=True) + + if self.downsample is not None: + residual = self.downsample(residual) + + return F.relu(residual + x, inplace=True), s + + +class MLFN(nn.Module): + """Multi-Level Factorisation Net. + + Reference: + Chang et al. Multi-Level Factorisation Net for + Person Re-Identification. CVPR 2018. + + Public keys: + - ``mlfn``: MLFN (Multi-Level Factorisation Net). + """ + + def __init__( + self, + num_classes, + loss='softmax', + groups=32, + channels=[64, 256, 512, 1024, 2048], + embed_dim=1024, + **kwargs + ): + super(MLFN, self).__init__() + self.loss = loss + self.groups = groups + + # first convolutional layer + self.conv1 = nn.Conv2d(3, channels[0], 7, stride=2, padding=3) + self.bn1 = nn.BatchNorm2d(channels[0]) + self.maxpool = nn.MaxPool2d(3, stride=2, padding=1) + + # main body + self.feature = nn.ModuleList( + [ + # layer 1-3 + MLFNBlock(channels[0], channels[1], 1, [128, 64], self.groups), + MLFNBlock(channels[1], channels[1], 1, [128, 64], self.groups), + MLFNBlock(channels[1], channels[1], 1, [128, 64], self.groups), + # layer 4-7 + MLFNBlock( + channels[1], channels[2], 2, [256, 128], self.groups + ), + MLFNBlock( + channels[2], channels[2], 1, [256, 128], self.groups + ), + MLFNBlock( + channels[2], channels[2], 1, [256, 128], self.groups + ), + MLFNBlock( + channels[2], channels[2], 1, [256, 128], self.groups + ), + # layer 8-13 + MLFNBlock( + channels[2], channels[3], 2, [512, 128], self.groups + ), + MLFNBlock( + channels[3], channels[3], 1, [512, 128], self.groups + ), + MLFNBlock( + channels[3], channels[3], 1, [512, 128], self.groups + ), + MLFNBlock( + channels[3], channels[3], 1, [512, 128], self.groups + ), + MLFNBlock( + channels[3], channels[3], 1, [512, 128], self.groups + ), + MLFNBlock( + channels[3], channels[3], 1, [512, 128], self.groups + ), + # layer 14-16 + MLFNBlock( + channels[3], channels[4], 2, [512, 128], self.groups + ), + MLFNBlock( + channels[4], channels[4], 1, [512, 128], self.groups + ), + MLFNBlock( + channels[4], channels[4], 1, [512, 128], self.groups + ), + ] + ) + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + + # projection functions + self.fc_x = nn.Sequential( + nn.Conv2d(channels[4], embed_dim, 1, bias=False), + nn.BatchNorm2d(embed_dim), + nn.ReLU(inplace=True), + ) + self.fc_s = nn.Sequential( + nn.Conv2d(self.groups * 16, embed_dim, 1, bias=False), + nn.BatchNorm2d(embed_dim), + nn.ReLU(inplace=True), + ) + + self.classifier = nn.Linear(embed_dim, num_classes) + + self.init_params() + + def init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = F.relu(x, inplace=True) + x = self.maxpool(x) + + s_hat = [] + for block in self.feature: + x, s = block(x) + s_hat.append(s) + s_hat = torch.cat(s_hat, 1) + + x = self.global_avgpool(x) + x = self.fc_x(x) + s_hat = self.fc_s(s_hat) + + v = (x+s_hat) * 0.5 + v = v.view(v.size(0), -1) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def mlfn(num_classes, loss='softmax', pretrained=True, **kwargs): + model = MLFN(num_classes, loss, **kwargs) + if pretrained: + # init_pretrained_weights(model, model_urls['imagenet']) + import warnings + warnings.warn( + 'The imagenet pretrained weights need to be manually downloaded from {}' + .format(model_urls['imagenet']) + ) + return model diff --git a/strong_sort/deep/reid/torchreid/models/mobilenetv2.py b/strong_sort/deep/reid/torchreid/models/mobilenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..c451ef84e726ebc8d4c8e47253f335494eb801c9 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/mobilenetv2.py @@ -0,0 +1,274 @@ +from __future__ import division, absolute_import +import torch.utils.model_zoo as model_zoo +from torch import nn +from torch.nn import functional as F + +__all__ = ['mobilenetv2_x1_0', 'mobilenetv2_x1_4'] + +model_urls = { + # 1.0: top-1 71.3 + 'mobilenetv2_x1_0': + 'https://mega.nz/#!NKp2wAIA!1NH1pbNzY_M2hVk_hdsxNM1NUOWvvGPHhaNr-fASF6c', + # 1.4: top-1 73.9 + 'mobilenetv2_x1_4': + 'https://mega.nz/#!RGhgEIwS!xN2s2ZdyqI6vQ3EwgmRXLEW3khr9tpXg96G9SUJugGk', +} + + +class ConvBlock(nn.Module): + """Basic convolutional block. + + convolution (bias discarded) + batch normalization + relu6. + + Args: + in_c (int): number of input channels. + out_c (int): number of output channels. + k (int or tuple): kernel size. + s (int or tuple): stride. + p (int or tuple): padding. + g (int): number of blocked connections from input channels + to output channels (default: 1). + """ + + def __init__(self, in_c, out_c, k, s=1, p=0, g=1): + super(ConvBlock, self).__init__() + self.conv = nn.Conv2d( + in_c, out_c, k, stride=s, padding=p, bias=False, groups=g + ) + self.bn = nn.BatchNorm2d(out_c) + + def forward(self, x): + return F.relu6(self.bn(self.conv(x))) + + +class Bottleneck(nn.Module): + + def __init__(self, in_channels, out_channels, expansion_factor, stride=1): + super(Bottleneck, self).__init__() + mid_channels = in_channels * expansion_factor + self.use_residual = stride == 1 and in_channels == out_channels + self.conv1 = ConvBlock(in_channels, mid_channels, 1) + self.dwconv2 = ConvBlock( + mid_channels, mid_channels, 3, stride, 1, g=mid_channels + ) + self.conv3 = nn.Sequential( + nn.Conv2d(mid_channels, out_channels, 1, bias=False), + nn.BatchNorm2d(out_channels), + ) + + def forward(self, x): + m = self.conv1(x) + m = self.dwconv2(m) + m = self.conv3(m) + if self.use_residual: + return x + m + else: + return m + + +class MobileNetV2(nn.Module): + """MobileNetV2. + + Reference: + Sandler et al. MobileNetV2: Inverted Residuals and + Linear Bottlenecks. CVPR 2018. + + Public keys: + - ``mobilenetv2_x1_0``: MobileNetV2 x1.0. + - ``mobilenetv2_x1_4``: MobileNetV2 x1.4. + """ + + def __init__( + self, + num_classes, + width_mult=1, + loss='softmax', + fc_dims=None, + dropout_p=None, + **kwargs + ): + super(MobileNetV2, self).__init__() + self.loss = loss + self.in_channels = int(32 * width_mult) + self.feature_dim = int(1280 * width_mult) if width_mult > 1 else 1280 + + # construct layers + self.conv1 = ConvBlock(3, self.in_channels, 3, s=2, p=1) + self.conv2 = self._make_layer( + Bottleneck, 1, int(16 * width_mult), 1, 1 + ) + self.conv3 = self._make_layer( + Bottleneck, 6, int(24 * width_mult), 2, 2 + ) + self.conv4 = self._make_layer( + Bottleneck, 6, int(32 * width_mult), 3, 2 + ) + self.conv5 = self._make_layer( + Bottleneck, 6, int(64 * width_mult), 4, 2 + ) + self.conv6 = self._make_layer( + Bottleneck, 6, int(96 * width_mult), 3, 1 + ) + self.conv7 = self._make_layer( + Bottleneck, 6, int(160 * width_mult), 3, 2 + ) + self.conv8 = self._make_layer( + Bottleneck, 6, int(320 * width_mult), 1, 1 + ) + self.conv9 = ConvBlock(self.in_channels, self.feature_dim, 1) + + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.fc = self._construct_fc_layer( + fc_dims, self.feature_dim, dropout_p + ) + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self._init_params() + + def _make_layer(self, block, t, c, n, s): + # t: expansion factor + # c: output channels + # n: number of blocks + # s: stride for first layer + layers = [] + layers.append(block(self.in_channels, c, t, s)) + self.in_channels = c + for i in range(1, n): + layers.append(block(self.in_channels, c, t)) + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + """Constructs fully connected layer. + + Args: + fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed + input_dim (int): input dimension + dropout_p (float): dropout probability, if None, dropout is unused + """ + if fc_dims is None: + self.feature_dim = input_dim + return None + + assert isinstance( + fc_dims, (list, tuple) + ), 'fc_dims must be either list or tuple, but got {}'.format( + type(fc_dims) + ) + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.conv2(x) + x = self.conv3(x) + x = self.conv4(x) + x = self.conv5(x) + x = self.conv6(x) + x = self.conv7(x) + x = self.conv8(x) + x = self.conv9(x) + return x + + def forward(self, x): + f = self.featuremaps(x) + v = self.global_avgpool(f) + v = v.view(v.size(0), -1) + + if self.fc is not None: + v = self.fc(v) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def mobilenetv2_x1_0(num_classes, loss, pretrained=True, **kwargs): + model = MobileNetV2( + num_classes, + loss=loss, + width_mult=1, + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + # init_pretrained_weights(model, model_urls['mobilenetv2_x1_0']) + import warnings + warnings.warn( + 'The imagenet pretrained weights need to be manually downloaded from {}' + .format(model_urls['mobilenetv2_x1_0']) + ) + return model + + +def mobilenetv2_x1_4(num_classes, loss, pretrained=True, **kwargs): + model = MobileNetV2( + num_classes, + loss=loss, + width_mult=1.4, + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + # init_pretrained_weights(model, model_urls['mobilenetv2_x1_4']) + import warnings + warnings.warn( + 'The imagenet pretrained weights need to be manually downloaded from {}' + .format(model_urls['mobilenetv2_x1_4']) + ) + return model diff --git a/strong_sort/deep/reid/torchreid/models/mudeep.py b/strong_sort/deep/reid/torchreid/models/mudeep.py new file mode 100644 index 0000000000000000000000000000000000000000..ddbca675b69fcf38523d8687d8c7b279ededd8d1 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/mudeep.py @@ -0,0 +1,206 @@ +from __future__ import division, absolute_import +import torch +from torch import nn +from torch.nn import functional as F + +__all__ = ['MuDeep'] + + +class ConvBlock(nn.Module): + """Basic convolutional block. + + convolution + batch normalization + relu. + + Args: + in_c (int): number of input channels. + out_c (int): number of output channels. + k (int or tuple): kernel size. + s (int or tuple): stride. + p (int or tuple): padding. + """ + + def __init__(self, in_c, out_c, k, s, p): + super(ConvBlock, self).__init__() + self.conv = nn.Conv2d(in_c, out_c, k, stride=s, padding=p) + self.bn = nn.BatchNorm2d(out_c) + + def forward(self, x): + return F.relu(self.bn(self.conv(x))) + + +class ConvLayers(nn.Module): + """Preprocessing layers.""" + + def __init__(self): + super(ConvLayers, self).__init__() + self.conv1 = ConvBlock(3, 48, k=3, s=1, p=1) + self.conv2 = ConvBlock(48, 96, k=3, s=1, p=1) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + + def forward(self, x): + x = self.conv1(x) + x = self.conv2(x) + x = self.maxpool(x) + return x + + +class MultiScaleA(nn.Module): + """Multi-scale stream layer A (Sec.3.1)""" + + def __init__(self): + super(MultiScaleA, self).__init__() + self.stream1 = nn.Sequential( + ConvBlock(96, 96, k=1, s=1, p=0), + ConvBlock(96, 24, k=3, s=1, p=1), + ) + self.stream2 = nn.Sequential( + nn.AvgPool2d(kernel_size=3, stride=1, padding=1), + ConvBlock(96, 24, k=1, s=1, p=0), + ) + self.stream3 = ConvBlock(96, 24, k=1, s=1, p=0) + self.stream4 = nn.Sequential( + ConvBlock(96, 16, k=1, s=1, p=0), + ConvBlock(16, 24, k=3, s=1, p=1), + ConvBlock(24, 24, k=3, s=1, p=1), + ) + + def forward(self, x): + s1 = self.stream1(x) + s2 = self.stream2(x) + s3 = self.stream3(x) + s4 = self.stream4(x) + y = torch.cat([s1, s2, s3, s4], dim=1) + return y + + +class Reduction(nn.Module): + """Reduction layer (Sec.3.1)""" + + def __init__(self): + super(Reduction, self).__init__() + self.stream1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.stream2 = ConvBlock(96, 96, k=3, s=2, p=1) + self.stream3 = nn.Sequential( + ConvBlock(96, 48, k=1, s=1, p=0), + ConvBlock(48, 56, k=3, s=1, p=1), + ConvBlock(56, 64, k=3, s=2, p=1), + ) + + def forward(self, x): + s1 = self.stream1(x) + s2 = self.stream2(x) + s3 = self.stream3(x) + y = torch.cat([s1, s2, s3], dim=1) + return y + + +class MultiScaleB(nn.Module): + """Multi-scale stream layer B (Sec.3.1)""" + + def __init__(self): + super(MultiScaleB, self).__init__() + self.stream1 = nn.Sequential( + nn.AvgPool2d(kernel_size=3, stride=1, padding=1), + ConvBlock(256, 256, k=1, s=1, p=0), + ) + self.stream2 = nn.Sequential( + ConvBlock(256, 64, k=1, s=1, p=0), + ConvBlock(64, 128, k=(1, 3), s=1, p=(0, 1)), + ConvBlock(128, 256, k=(3, 1), s=1, p=(1, 0)), + ) + self.stream3 = ConvBlock(256, 256, k=1, s=1, p=0) + self.stream4 = nn.Sequential( + ConvBlock(256, 64, k=1, s=1, p=0), + ConvBlock(64, 64, k=(1, 3), s=1, p=(0, 1)), + ConvBlock(64, 128, k=(3, 1), s=1, p=(1, 0)), + ConvBlock(128, 128, k=(1, 3), s=1, p=(0, 1)), + ConvBlock(128, 256, k=(3, 1), s=1, p=(1, 0)), + ) + + def forward(self, x): + s1 = self.stream1(x) + s2 = self.stream2(x) + s3 = self.stream3(x) + s4 = self.stream4(x) + return s1, s2, s3, s4 + + +class Fusion(nn.Module): + """Saliency-based learning fusion layer (Sec.3.2)""" + + def __init__(self): + super(Fusion, self).__init__() + self.a1 = nn.Parameter(torch.rand(1, 256, 1, 1)) + self.a2 = nn.Parameter(torch.rand(1, 256, 1, 1)) + self.a3 = nn.Parameter(torch.rand(1, 256, 1, 1)) + self.a4 = nn.Parameter(torch.rand(1, 256, 1, 1)) + + # We add an average pooling layer to reduce the spatial dimension + # of feature maps, which differs from the original paper. + self.avgpool = nn.AvgPool2d(kernel_size=4, stride=4, padding=0) + + def forward(self, x1, x2, x3, x4): + s1 = self.a1.expand_as(x1) * x1 + s2 = self.a2.expand_as(x2) * x2 + s3 = self.a3.expand_as(x3) * x3 + s4 = self.a4.expand_as(x4) * x4 + y = self.avgpool(s1 + s2 + s3 + s4) + return y + + +class MuDeep(nn.Module): + """Multiscale deep neural network. + + Reference: + Qian et al. Multi-scale Deep Learning Architectures + for Person Re-identification. ICCV 2017. + + Public keys: + - ``mudeep``: Multiscale deep neural network. + """ + + def __init__(self, num_classes, loss='softmax', **kwargs): + super(MuDeep, self).__init__() + self.loss = loss + + self.block1 = ConvLayers() + self.block2 = MultiScaleA() + self.block3 = Reduction() + self.block4 = MultiScaleB() + self.block5 = Fusion() + + # Due to this fully connected layer, input image has to be fixed + # in shape, i.e. (3, 256, 128), such that the last convolutional feature + # maps are of shape (256, 16, 8). If input shape is changed, + # the input dimension of this layer has to be changed accordingly. + self.fc = nn.Sequential( + nn.Linear(256 * 16 * 8, 4096), + nn.BatchNorm1d(4096), + nn.ReLU(), + ) + self.classifier = nn.Linear(4096, num_classes) + self.feat_dim = 4096 + + def featuremaps(self, x): + x = self.block1(x) + x = self.block2(x) + x = self.block3(x) + x = self.block4(x) + x = self.block5(*x) + return x + + def forward(self, x): + x = self.featuremaps(x) + x = x.view(x.size(0), -1) + x = self.fc(x) + y = self.classifier(x) + + if not self.training: + return x + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, x + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) diff --git a/strong_sort/deep/reid/torchreid/models/nasnet.py b/strong_sort/deep/reid/torchreid/models/nasnet.py new file mode 100644 index 0000000000000000000000000000000000000000..b1f31def5515c3ba464c86cde471328b50c55b14 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/nasnet.py @@ -0,0 +1,1131 @@ +from __future__ import division, absolute_import +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.model_zoo as model_zoo + +__all__ = ['nasnetamobile'] +""" +NASNet Mobile +Thanks to Anastasiia (https://github.com/DagnyT) for the great help, support and motivation! + + +------------------------------------------------------------------------------------ + Architecture | Top-1 Acc | Top-5 Acc | Multiply-Adds | Params (M) +------------------------------------------------------------------------------------ +| NASNet-A (4 @ 1056) | 74.08% | 91.74% | 564 M | 5.3 | +------------------------------------------------------------------------------------ +# References: + - [Learning Transferable Architectures for Scalable Image Recognition] + (https://arxiv.org/abs/1707.07012) +""" +""" +Code imported from https://github.com/Cadene/pretrained-models.pytorch +""" + +pretrained_settings = { + 'nasnetamobile': { + 'imagenet': { + # 'url': 'https://github.com/veronikayurchuk/pretrained-models.pytorch/releases/download/v1.0/nasnetmobile-7e03cead.pth.tar', + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/nasnetamobile-7e03cead.pth', + 'input_space': 'RGB', + 'input_size': [3, 224, 224], # resize 256 + 'input_range': [0, 1], + 'mean': [0.5, 0.5, 0.5], + 'std': [0.5, 0.5, 0.5], + 'num_classes': 1000 + }, + # 'imagenet+background': { + # # 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/nasnetalarge-a1897284.pth', + # 'input_space': 'RGB', + # 'input_size': [3, 224, 224], # resize 256 + # 'input_range': [0, 1], + # 'mean': [0.5, 0.5, 0.5], + # 'std': [0.5, 0.5, 0.5], + # 'num_classes': 1001 + # } + } +} + + +class MaxPoolPad(nn.Module): + + def __init__(self): + super(MaxPoolPad, self).__init__() + self.pad = nn.ZeroPad2d((1, 0, 1, 0)) + self.pool = nn.MaxPool2d(3, stride=2, padding=1) + + def forward(self, x): + x = self.pad(x) + x = self.pool(x) + x = x[:, :, 1:, 1:].contiguous() + return x + + +class AvgPoolPad(nn.Module): + + def __init__(self, stride=2, padding=1): + super(AvgPoolPad, self).__init__() + self.pad = nn.ZeroPad2d((1, 0, 1, 0)) + self.pool = nn.AvgPool2d( + 3, stride=stride, padding=padding, count_include_pad=False + ) + + def forward(self, x): + x = self.pad(x) + x = self.pool(x) + x = x[:, :, 1:, 1:].contiguous() + return x + + +class SeparableConv2d(nn.Module): + + def __init__( + self, + in_channels, + out_channels, + dw_kernel, + dw_stride, + dw_padding, + bias=False + ): + super(SeparableConv2d, self).__init__() + self.depthwise_conv2d = nn.Conv2d( + in_channels, + in_channels, + dw_kernel, + stride=dw_stride, + padding=dw_padding, + bias=bias, + groups=in_channels + ) + self.pointwise_conv2d = nn.Conv2d( + in_channels, out_channels, 1, stride=1, bias=bias + ) + + def forward(self, x): + x = self.depthwise_conv2d(x) + x = self.pointwise_conv2d(x) + return x + + +class BranchSeparables(nn.Module): + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + name=None, + bias=False + ): + super(BranchSeparables, self).__init__() + self.relu = nn.ReLU() + self.separable_1 = SeparableConv2d( + in_channels, in_channels, kernel_size, stride, padding, bias=bias + ) + self.bn_sep_1 = nn.BatchNorm2d( + in_channels, eps=0.001, momentum=0.1, affine=True + ) + self.relu1 = nn.ReLU() + self.separable_2 = SeparableConv2d( + in_channels, out_channels, kernel_size, 1, padding, bias=bias + ) + self.bn_sep_2 = nn.BatchNorm2d( + out_channels, eps=0.001, momentum=0.1, affine=True + ) + self.name = name + + def forward(self, x): + x = self.relu(x) + if self.name == 'specific': + x = nn.ZeroPad2d((1, 0, 1, 0))(x) + x = self.separable_1(x) + if self.name == 'specific': + x = x[:, :, 1:, 1:].contiguous() + + x = self.bn_sep_1(x) + x = self.relu1(x) + x = self.separable_2(x) + x = self.bn_sep_2(x) + return x + + +class BranchSeparablesStem(nn.Module): + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + bias=False + ): + super(BranchSeparablesStem, self).__init__() + self.relu = nn.ReLU() + self.separable_1 = SeparableConv2d( + in_channels, out_channels, kernel_size, stride, padding, bias=bias + ) + self.bn_sep_1 = nn.BatchNorm2d( + out_channels, eps=0.001, momentum=0.1, affine=True + ) + self.relu1 = nn.ReLU() + self.separable_2 = SeparableConv2d( + out_channels, out_channels, kernel_size, 1, padding, bias=bias + ) + self.bn_sep_2 = nn.BatchNorm2d( + out_channels, eps=0.001, momentum=0.1, affine=True + ) + + def forward(self, x): + x = self.relu(x) + x = self.separable_1(x) + x = self.bn_sep_1(x) + x = self.relu1(x) + x = self.separable_2(x) + x = self.bn_sep_2(x) + return x + + +class BranchSeparablesReduction(BranchSeparables): + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + z_padding=1, + bias=False + ): + BranchSeparables.__init__( + self, in_channels, out_channels, kernel_size, stride, padding, bias + ) + self.padding = nn.ZeroPad2d((z_padding, 0, z_padding, 0)) + + def forward(self, x): + x = self.relu(x) + x = self.padding(x) + x = self.separable_1(x) + x = x[:, :, 1:, 1:].contiguous() + x = self.bn_sep_1(x) + x = self.relu1(x) + x = self.separable_2(x) + x = self.bn_sep_2(x) + return x + + +class CellStem0(nn.Module): + + def __init__(self, stem_filters, num_filters=42): + super(CellStem0, self).__init__() + self.num_filters = num_filters + self.stem_filters = stem_filters + self.conv_1x1 = nn.Sequential() + self.conv_1x1.add_module('relu', nn.ReLU()) + self.conv_1x1.add_module( + 'conv', + nn.Conv2d( + self.stem_filters, self.num_filters, 1, stride=1, bias=False + ) + ) + self.conv_1x1.add_module( + 'bn', + nn.BatchNorm2d( + self.num_filters, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.comb_iter_0_left = BranchSeparables( + self.num_filters, self.num_filters, 5, 2, 2 + ) + self.comb_iter_0_right = BranchSeparablesStem( + self.stem_filters, self.num_filters, 7, 2, 3, bias=False + ) + + self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1) + self.comb_iter_1_right = BranchSeparablesStem( + self.stem_filters, self.num_filters, 7, 2, 3, bias=False + ) + + self.comb_iter_2_left = nn.AvgPool2d( + 3, stride=2, padding=1, count_include_pad=False + ) + self.comb_iter_2_right = BranchSeparablesStem( + self.stem_filters, self.num_filters, 5, 2, 2, bias=False + ) + + self.comb_iter_3_right = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + + self.comb_iter_4_left = BranchSeparables( + self.num_filters, self.num_filters, 3, 1, 1, bias=False + ) + self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1) + + def forward(self, x): + x1 = self.conv_1x1(x) + + x_comb_iter_0_left = self.comb_iter_0_left(x1) + x_comb_iter_0_right = self.comb_iter_0_right(x) + x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right + + x_comb_iter_1_left = self.comb_iter_1_left(x1) + x_comb_iter_1_right = self.comb_iter_1_right(x) + x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right + + x_comb_iter_2_left = self.comb_iter_2_left(x1) + x_comb_iter_2_right = self.comb_iter_2_right(x) + x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right + + x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0) + x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1 + + x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0) + x_comb_iter_4_right = self.comb_iter_4_right(x1) + x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right + + x_out = torch.cat( + [x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1 + ) + return x_out + + +class CellStem1(nn.Module): + + def __init__(self, stem_filters, num_filters): + super(CellStem1, self).__init__() + self.num_filters = num_filters + self.stem_filters = stem_filters + self.conv_1x1 = nn.Sequential() + self.conv_1x1.add_module('relu', nn.ReLU()) + self.conv_1x1.add_module( + 'conv', + nn.Conv2d( + 2 * self.num_filters, + self.num_filters, + 1, + stride=1, + bias=False + ) + ) + self.conv_1x1.add_module( + 'bn', + nn.BatchNorm2d( + self.num_filters, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.relu = nn.ReLU() + self.path_1 = nn.Sequential() + self.path_1.add_module( + 'avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False) + ) + self.path_1.add_module( + 'conv', + nn.Conv2d( + self.stem_filters, + self.num_filters // 2, + 1, + stride=1, + bias=False + ) + ) + self.path_2 = nn.ModuleList() + self.path_2.add_module('pad', nn.ZeroPad2d((0, 1, 0, 1))) + self.path_2.add_module( + 'avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False) + ) + self.path_2.add_module( + 'conv', + nn.Conv2d( + self.stem_filters, + self.num_filters // 2, + 1, + stride=1, + bias=False + ) + ) + + self.final_path_bn = nn.BatchNorm2d( + self.num_filters, eps=0.001, momentum=0.1, affine=True + ) + + self.comb_iter_0_left = BranchSeparables( + self.num_filters, + self.num_filters, + 5, + 2, + 2, + name='specific', + bias=False + ) + self.comb_iter_0_right = BranchSeparables( + self.num_filters, + self.num_filters, + 7, + 2, + 3, + name='specific', + bias=False + ) + + # self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1) + self.comb_iter_1_left = MaxPoolPad() + self.comb_iter_1_right = BranchSeparables( + self.num_filters, + self.num_filters, + 7, + 2, + 3, + name='specific', + bias=False + ) + + # self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False) + self.comb_iter_2_left = AvgPoolPad() + self.comb_iter_2_right = BranchSeparables( + self.num_filters, + self.num_filters, + 5, + 2, + 2, + name='specific', + bias=False + ) + + self.comb_iter_3_right = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + + self.comb_iter_4_left = BranchSeparables( + self.num_filters, + self.num_filters, + 3, + 1, + 1, + name='specific', + bias=False + ) + # self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1) + self.comb_iter_4_right = MaxPoolPad() + + def forward(self, x_conv0, x_stem_0): + x_left = self.conv_1x1(x_stem_0) + + x_relu = self.relu(x_conv0) + # path 1 + x_path1 = self.path_1(x_relu) + # path 2 + x_path2 = self.path_2.pad(x_relu) + x_path2 = x_path2[:, :, 1:, 1:] + x_path2 = self.path_2.avgpool(x_path2) + x_path2 = self.path_2.conv(x_path2) + # final path + x_right = self.final_path_bn(torch.cat([x_path1, x_path2], 1)) + + x_comb_iter_0_left = self.comb_iter_0_left(x_left) + x_comb_iter_0_right = self.comb_iter_0_right(x_right) + x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right + + x_comb_iter_1_left = self.comb_iter_1_left(x_left) + x_comb_iter_1_right = self.comb_iter_1_right(x_right) + x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right + + x_comb_iter_2_left = self.comb_iter_2_left(x_left) + x_comb_iter_2_right = self.comb_iter_2_right(x_right) + x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right + + x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0) + x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1 + + x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0) + x_comb_iter_4_right = self.comb_iter_4_right(x_left) + x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right + + x_out = torch.cat( + [x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1 + ) + return x_out + + +class FirstCell(nn.Module): + + def __init__( + self, in_channels_left, out_channels_left, in_channels_right, + out_channels_right + ): + super(FirstCell, self).__init__() + self.conv_1x1 = nn.Sequential() + self.conv_1x1.add_module('relu', nn.ReLU()) + self.conv_1x1.add_module( + 'conv', + nn.Conv2d( + in_channels_right, out_channels_right, 1, stride=1, bias=False + ) + ) + self.conv_1x1.add_module( + 'bn', + nn.BatchNorm2d( + out_channels_right, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.relu = nn.ReLU() + self.path_1 = nn.Sequential() + self.path_1.add_module( + 'avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False) + ) + self.path_1.add_module( + 'conv', + nn.Conv2d( + in_channels_left, out_channels_left, 1, stride=1, bias=False + ) + ) + self.path_2 = nn.ModuleList() + self.path_2.add_module('pad', nn.ZeroPad2d((0, 1, 0, 1))) + self.path_2.add_module( + 'avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False) + ) + self.path_2.add_module( + 'conv', + nn.Conv2d( + in_channels_left, out_channels_left, 1, stride=1, bias=False + ) + ) + + self.final_path_bn = nn.BatchNorm2d( + out_channels_left * 2, eps=0.001, momentum=0.1, affine=True + ) + + self.comb_iter_0_left = BranchSeparables( + out_channels_right, out_channels_right, 5, 1, 2, bias=False + ) + self.comb_iter_0_right = BranchSeparables( + out_channels_right, out_channels_right, 3, 1, 1, bias=False + ) + + self.comb_iter_1_left = BranchSeparables( + out_channels_right, out_channels_right, 5, 1, 2, bias=False + ) + self.comb_iter_1_right = BranchSeparables( + out_channels_right, out_channels_right, 3, 1, 1, bias=False + ) + + self.comb_iter_2_left = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + + self.comb_iter_3_left = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + self.comb_iter_3_right = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + + self.comb_iter_4_left = BranchSeparables( + out_channels_right, out_channels_right, 3, 1, 1, bias=False + ) + + def forward(self, x, x_prev): + x_relu = self.relu(x_prev) + # path 1 + x_path1 = self.path_1(x_relu) + # path 2 + x_path2 = self.path_2.pad(x_relu) + x_path2 = x_path2[:, :, 1:, 1:] + x_path2 = self.path_2.avgpool(x_path2) + x_path2 = self.path_2.conv(x_path2) + # final path + x_left = self.final_path_bn(torch.cat([x_path1, x_path2], 1)) + + x_right = self.conv_1x1(x) + + x_comb_iter_0_left = self.comb_iter_0_left(x_right) + x_comb_iter_0_right = self.comb_iter_0_right(x_left) + x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right + + x_comb_iter_1_left = self.comb_iter_1_left(x_left) + x_comb_iter_1_right = self.comb_iter_1_right(x_left) + x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right + + x_comb_iter_2_left = self.comb_iter_2_left(x_right) + x_comb_iter_2 = x_comb_iter_2_left + x_left + + x_comb_iter_3_left = self.comb_iter_3_left(x_left) + x_comb_iter_3_right = self.comb_iter_3_right(x_left) + x_comb_iter_3 = x_comb_iter_3_left + x_comb_iter_3_right + + x_comb_iter_4_left = self.comb_iter_4_left(x_right) + x_comb_iter_4 = x_comb_iter_4_left + x_right + + x_out = torch.cat( + [ + x_left, x_comb_iter_0, x_comb_iter_1, x_comb_iter_2, + x_comb_iter_3, x_comb_iter_4 + ], 1 + ) + return x_out + + +class NormalCell(nn.Module): + + def __init__( + self, in_channels_left, out_channels_left, in_channels_right, + out_channels_right + ): + super(NormalCell, self).__init__() + self.conv_prev_1x1 = nn.Sequential() + self.conv_prev_1x1.add_module('relu', nn.ReLU()) + self.conv_prev_1x1.add_module( + 'conv', + nn.Conv2d( + in_channels_left, out_channels_left, 1, stride=1, bias=False + ) + ) + self.conv_prev_1x1.add_module( + 'bn', + nn.BatchNorm2d( + out_channels_left, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.conv_1x1 = nn.Sequential() + self.conv_1x1.add_module('relu', nn.ReLU()) + self.conv_1x1.add_module( + 'conv', + nn.Conv2d( + in_channels_right, out_channels_right, 1, stride=1, bias=False + ) + ) + self.conv_1x1.add_module( + 'bn', + nn.BatchNorm2d( + out_channels_right, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.comb_iter_0_left = BranchSeparables( + out_channels_right, out_channels_right, 5, 1, 2, bias=False + ) + self.comb_iter_0_right = BranchSeparables( + out_channels_left, out_channels_left, 3, 1, 1, bias=False + ) + + self.comb_iter_1_left = BranchSeparables( + out_channels_left, out_channels_left, 5, 1, 2, bias=False + ) + self.comb_iter_1_right = BranchSeparables( + out_channels_left, out_channels_left, 3, 1, 1, bias=False + ) + + self.comb_iter_2_left = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + + self.comb_iter_3_left = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + self.comb_iter_3_right = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + + self.comb_iter_4_left = BranchSeparables( + out_channels_right, out_channels_right, 3, 1, 1, bias=False + ) + + def forward(self, x, x_prev): + x_left = self.conv_prev_1x1(x_prev) + x_right = self.conv_1x1(x) + + x_comb_iter_0_left = self.comb_iter_0_left(x_right) + x_comb_iter_0_right = self.comb_iter_0_right(x_left) + x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right + + x_comb_iter_1_left = self.comb_iter_1_left(x_left) + x_comb_iter_1_right = self.comb_iter_1_right(x_left) + x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right + + x_comb_iter_2_left = self.comb_iter_2_left(x_right) + x_comb_iter_2 = x_comb_iter_2_left + x_left + + x_comb_iter_3_left = self.comb_iter_3_left(x_left) + x_comb_iter_3_right = self.comb_iter_3_right(x_left) + x_comb_iter_3 = x_comb_iter_3_left + x_comb_iter_3_right + + x_comb_iter_4_left = self.comb_iter_4_left(x_right) + x_comb_iter_4 = x_comb_iter_4_left + x_right + + x_out = torch.cat( + [ + x_left, x_comb_iter_0, x_comb_iter_1, x_comb_iter_2, + x_comb_iter_3, x_comb_iter_4 + ], 1 + ) + return x_out + + +class ReductionCell0(nn.Module): + + def __init__( + self, in_channels_left, out_channels_left, in_channels_right, + out_channels_right + ): + super(ReductionCell0, self).__init__() + self.conv_prev_1x1 = nn.Sequential() + self.conv_prev_1x1.add_module('relu', nn.ReLU()) + self.conv_prev_1x1.add_module( + 'conv', + nn.Conv2d( + in_channels_left, out_channels_left, 1, stride=1, bias=False + ) + ) + self.conv_prev_1x1.add_module( + 'bn', + nn.BatchNorm2d( + out_channels_left, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.conv_1x1 = nn.Sequential() + self.conv_1x1.add_module('relu', nn.ReLU()) + self.conv_1x1.add_module( + 'conv', + nn.Conv2d( + in_channels_right, out_channels_right, 1, stride=1, bias=False + ) + ) + self.conv_1x1.add_module( + 'bn', + nn.BatchNorm2d( + out_channels_right, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.comb_iter_0_left = BranchSeparablesReduction( + out_channels_right, out_channels_right, 5, 2, 2, bias=False + ) + self.comb_iter_0_right = BranchSeparablesReduction( + out_channels_right, out_channels_right, 7, 2, 3, bias=False + ) + + self.comb_iter_1_left = MaxPoolPad() + self.comb_iter_1_right = BranchSeparablesReduction( + out_channels_right, out_channels_right, 7, 2, 3, bias=False + ) + + self.comb_iter_2_left = AvgPoolPad() + self.comb_iter_2_right = BranchSeparablesReduction( + out_channels_right, out_channels_right, 5, 2, 2, bias=False + ) + + self.comb_iter_3_right = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + + self.comb_iter_4_left = BranchSeparablesReduction( + out_channels_right, out_channels_right, 3, 1, 1, bias=False + ) + self.comb_iter_4_right = MaxPoolPad() + + def forward(self, x, x_prev): + x_left = self.conv_prev_1x1(x_prev) + x_right = self.conv_1x1(x) + + x_comb_iter_0_left = self.comb_iter_0_left(x_right) + x_comb_iter_0_right = self.comb_iter_0_right(x_left) + x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right + + x_comb_iter_1_left = self.comb_iter_1_left(x_right) + x_comb_iter_1_right = self.comb_iter_1_right(x_left) + x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right + + x_comb_iter_2_left = self.comb_iter_2_left(x_right) + x_comb_iter_2_right = self.comb_iter_2_right(x_left) + x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right + + x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0) + x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1 + + x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0) + x_comb_iter_4_right = self.comb_iter_4_right(x_right) + x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right + + x_out = torch.cat( + [x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1 + ) + return x_out + + +class ReductionCell1(nn.Module): + + def __init__( + self, in_channels_left, out_channels_left, in_channels_right, + out_channels_right + ): + super(ReductionCell1, self).__init__() + self.conv_prev_1x1 = nn.Sequential() + self.conv_prev_1x1.add_module('relu', nn.ReLU()) + self.conv_prev_1x1.add_module( + 'conv', + nn.Conv2d( + in_channels_left, out_channels_left, 1, stride=1, bias=False + ) + ) + self.conv_prev_1x1.add_module( + 'bn', + nn.BatchNorm2d( + out_channels_left, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.conv_1x1 = nn.Sequential() + self.conv_1x1.add_module('relu', nn.ReLU()) + self.conv_1x1.add_module( + 'conv', + nn.Conv2d( + in_channels_right, out_channels_right, 1, stride=1, bias=False + ) + ) + self.conv_1x1.add_module( + 'bn', + nn.BatchNorm2d( + out_channels_right, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.comb_iter_0_left = BranchSeparables( + out_channels_right, + out_channels_right, + 5, + 2, + 2, + name='specific', + bias=False + ) + self.comb_iter_0_right = BranchSeparables( + out_channels_right, + out_channels_right, + 7, + 2, + 3, + name='specific', + bias=False + ) + + # self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1) + self.comb_iter_1_left = MaxPoolPad() + self.comb_iter_1_right = BranchSeparables( + out_channels_right, + out_channels_right, + 7, + 2, + 3, + name='specific', + bias=False + ) + + # self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False) + self.comb_iter_2_left = AvgPoolPad() + self.comb_iter_2_right = BranchSeparables( + out_channels_right, + out_channels_right, + 5, + 2, + 2, + name='specific', + bias=False + ) + + self.comb_iter_3_right = nn.AvgPool2d( + 3, stride=1, padding=1, count_include_pad=False + ) + + self.comb_iter_4_left = BranchSeparables( + out_channels_right, + out_channels_right, + 3, + 1, + 1, + name='specific', + bias=False + ) + # self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1) + self.comb_iter_4_right = MaxPoolPad() + + def forward(self, x, x_prev): + x_left = self.conv_prev_1x1(x_prev) + x_right = self.conv_1x1(x) + + x_comb_iter_0_left = self.comb_iter_0_left(x_right) + x_comb_iter_0_right = self.comb_iter_0_right(x_left) + x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right + + x_comb_iter_1_left = self.comb_iter_1_left(x_right) + x_comb_iter_1_right = self.comb_iter_1_right(x_left) + x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right + + x_comb_iter_2_left = self.comb_iter_2_left(x_right) + x_comb_iter_2_right = self.comb_iter_2_right(x_left) + x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right + + x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0) + x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1 + + x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0) + x_comb_iter_4_right = self.comb_iter_4_right(x_right) + x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right + + x_out = torch.cat( + [x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1 + ) + return x_out + + +class NASNetAMobile(nn.Module): + """Neural Architecture Search (NAS). + + Reference: + Zoph et al. Learning Transferable Architectures + for Scalable Image Recognition. CVPR 2018. + + Public keys: + - ``nasnetamobile``: NASNet-A Mobile. + """ + + def __init__( + self, + num_classes, + loss, + stem_filters=32, + penultimate_filters=1056, + filters_multiplier=2, + **kwargs + ): + super(NASNetAMobile, self).__init__() + self.stem_filters = stem_filters + self.penultimate_filters = penultimate_filters + self.filters_multiplier = filters_multiplier + self.loss = loss + + filters = self.penultimate_filters // 24 + # 24 is default value for the architecture + + self.conv0 = nn.Sequential() + self.conv0.add_module( + 'conv', + nn.Conv2d( + in_channels=3, + out_channels=self.stem_filters, + kernel_size=3, + padding=0, + stride=2, + bias=False + ) + ) + self.conv0.add_module( + 'bn', + nn.BatchNorm2d( + self.stem_filters, eps=0.001, momentum=0.1, affine=True + ) + ) + + self.cell_stem_0 = CellStem0( + self.stem_filters, num_filters=filters // (filters_multiplier**2) + ) + self.cell_stem_1 = CellStem1( + self.stem_filters, num_filters=filters // filters_multiplier + ) + + self.cell_0 = FirstCell( + in_channels_left=filters, + out_channels_left=filters // 2, # 1, 0.5 + in_channels_right=2 * filters, + out_channels_right=filters + ) # 2, 1 + self.cell_1 = NormalCell( + in_channels_left=2 * filters, + out_channels_left=filters, # 2, 1 + in_channels_right=6 * filters, + out_channels_right=filters + ) # 6, 1 + self.cell_2 = NormalCell( + in_channels_left=6 * filters, + out_channels_left=filters, # 6, 1 + in_channels_right=6 * filters, + out_channels_right=filters + ) # 6, 1 + self.cell_3 = NormalCell( + in_channels_left=6 * filters, + out_channels_left=filters, # 6, 1 + in_channels_right=6 * filters, + out_channels_right=filters + ) # 6, 1 + + self.reduction_cell_0 = ReductionCell0( + in_channels_left=6 * filters, + out_channels_left=2 * filters, # 6, 2 + in_channels_right=6 * filters, + out_channels_right=2 * filters + ) # 6, 2 + + self.cell_6 = FirstCell( + in_channels_left=6 * filters, + out_channels_left=filters, # 6, 1 + in_channels_right=8 * filters, + out_channels_right=2 * filters + ) # 8, 2 + self.cell_7 = NormalCell( + in_channels_left=8 * filters, + out_channels_left=2 * filters, # 8, 2 + in_channels_right=12 * filters, + out_channels_right=2 * filters + ) # 12, 2 + self.cell_8 = NormalCell( + in_channels_left=12 * filters, + out_channels_left=2 * filters, # 12, 2 + in_channels_right=12 * filters, + out_channels_right=2 * filters + ) # 12, 2 + self.cell_9 = NormalCell( + in_channels_left=12 * filters, + out_channels_left=2 * filters, # 12, 2 + in_channels_right=12 * filters, + out_channels_right=2 * filters + ) # 12, 2 + + self.reduction_cell_1 = ReductionCell1( + in_channels_left=12 * filters, + out_channels_left=4 * filters, # 12, 4 + in_channels_right=12 * filters, + out_channels_right=4 * filters + ) # 12, 4 + + self.cell_12 = FirstCell( + in_channels_left=12 * filters, + out_channels_left=2 * filters, # 12, 2 + in_channels_right=16 * filters, + out_channels_right=4 * filters + ) # 16, 4 + self.cell_13 = NormalCell( + in_channels_left=16 * filters, + out_channels_left=4 * filters, # 16, 4 + in_channels_right=24 * filters, + out_channels_right=4 * filters + ) # 24, 4 + self.cell_14 = NormalCell( + in_channels_left=24 * filters, + out_channels_left=4 * filters, # 24, 4 + in_channels_right=24 * filters, + out_channels_right=4 * filters + ) # 24, 4 + self.cell_15 = NormalCell( + in_channels_left=24 * filters, + out_channels_left=4 * filters, # 24, 4 + in_channels_right=24 * filters, + out_channels_right=4 * filters + ) # 24, 4 + + self.relu = nn.ReLU() + self.dropout = nn.Dropout() + self.classifier = nn.Linear(24 * filters, num_classes) + + self._init_params() + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def features(self, input): + x_conv0 = self.conv0(input) + x_stem_0 = self.cell_stem_0(x_conv0) + x_stem_1 = self.cell_stem_1(x_conv0, x_stem_0) + + x_cell_0 = self.cell_0(x_stem_1, x_stem_0) + x_cell_1 = self.cell_1(x_cell_0, x_stem_1) + x_cell_2 = self.cell_2(x_cell_1, x_cell_0) + x_cell_3 = self.cell_3(x_cell_2, x_cell_1) + + x_reduction_cell_0 = self.reduction_cell_0(x_cell_3, x_cell_2) + + x_cell_6 = self.cell_6(x_reduction_cell_0, x_cell_3) + x_cell_7 = self.cell_7(x_cell_6, x_reduction_cell_0) + x_cell_8 = self.cell_8(x_cell_7, x_cell_6) + x_cell_9 = self.cell_9(x_cell_8, x_cell_7) + + x_reduction_cell_1 = self.reduction_cell_1(x_cell_9, x_cell_8) + + x_cell_12 = self.cell_12(x_reduction_cell_1, x_cell_9) + x_cell_13 = self.cell_13(x_cell_12, x_reduction_cell_1) + x_cell_14 = self.cell_14(x_cell_13, x_cell_12) + x_cell_15 = self.cell_15(x_cell_14, x_cell_13) + + x_cell_15 = self.relu(x_cell_15) + x_cell_15 = F.avg_pool2d( + x_cell_15, + x_cell_15.size()[2:] + ) # global average pool + x_cell_15 = x_cell_15.view(x_cell_15.size(0), -1) + x_cell_15 = self.dropout(x_cell_15) + + return x_cell_15 + + def forward(self, input): + v = self.features(input) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def nasnetamobile(num_classes, loss='softmax', pretrained=True, **kwargs): + model = NASNetAMobile(num_classes, loss, **kwargs) + if pretrained: + model_url = pretrained_settings['nasnetamobile']['imagenet']['url'] + init_pretrained_weights(model, model_url) + return model diff --git a/strong_sort/deep/reid/torchreid/models/osnet.py b/strong_sort/deep/reid/torchreid/models/osnet.py new file mode 100644 index 0000000000000000000000000000000000000000..b77388f13289f050da2bf2bdebd40ab4fce6f976 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/osnet.py @@ -0,0 +1,598 @@ +from __future__ import division, absolute_import +import warnings +import torch +from torch import nn +from torch.nn import functional as F + +__all__ = [ + 'osnet_x1_0', 'osnet_x0_75', 'osnet_x0_5', 'osnet_x0_25', 'osnet_ibn_x1_0' +] + +pretrained_urls = { + 'osnet_x1_0': + 'https://drive.google.com/uc?id=1LaG1EJpHrxdAxKnSCJ_i0u-nbxSAeiFY', + 'osnet_x0_75': + 'https://drive.google.com/uc?id=1uwA9fElHOk3ZogwbeY5GkLI6QPTX70Hq', + 'osnet_x0_5': + 'https://drive.google.com/uc?id=16DGLbZukvVYgINws8u8deSaOqjybZ83i', + 'osnet_x0_25': + 'https://drive.google.com/uc?id=1rb8UN5ZzPKRc_xvtHlyDh-cSz88YX9hs', + 'osnet_ibn_x1_0': + 'https://drive.google.com/uc?id=1sr90V6irlYYDd4_4ISU2iruoRG8J__6l' +} + + +########## +# Basic layers +########## +class ConvLayer(nn.Module): + """Convolution layer (conv + bn + relu).""" + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + groups=1, + IN=False + ): + super(ConvLayer, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + bias=False, + groups=groups + ) + if IN: + self.bn = nn.InstanceNorm2d(out_channels, affine=True) + else: + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + +class Conv1x1(nn.Module): + """1x1 convolution + bn + relu.""" + + def __init__(self, in_channels, out_channels, stride=1, groups=1): + super(Conv1x1, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 1, + stride=stride, + padding=0, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + +class Conv1x1Linear(nn.Module): + """1x1 convolution + bn (w/o non-linearity).""" + + def __init__(self, in_channels, out_channels, stride=1): + super(Conv1x1Linear, self).__init__() + self.conv = nn.Conv2d( + in_channels, out_channels, 1, stride=stride, padding=0, bias=False + ) + self.bn = nn.BatchNorm2d(out_channels) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return x + + +class Conv3x3(nn.Module): + """3x3 convolution + bn + relu.""" + + def __init__(self, in_channels, out_channels, stride=1, groups=1): + super(Conv3x3, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 3, + stride=stride, + padding=1, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + +class LightConv3x3(nn.Module): + """Lightweight 3x3 convolution. + + 1x1 (linear) + dw 3x3 (nonlinear). + """ + + def __init__(self, in_channels, out_channels): + super(LightConv3x3, self).__init__() + self.conv1 = nn.Conv2d( + in_channels, out_channels, 1, stride=1, padding=0, bias=False + ) + self.conv2 = nn.Conv2d( + out_channels, + out_channels, + 3, + stride=1, + padding=1, + bias=False, + groups=out_channels + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.conv1(x) + x = self.conv2(x) + x = self.bn(x) + x = self.relu(x) + return x + + +########## +# Building blocks for omni-scale feature learning +########## +class ChannelGate(nn.Module): + """A mini-network that generates channel-wise gates conditioned on input tensor.""" + + def __init__( + self, + in_channels, + num_gates=None, + return_gates=False, + gate_activation='sigmoid', + reduction=16, + layer_norm=False + ): + super(ChannelGate, self).__init__() + if num_gates is None: + num_gates = in_channels + self.return_gates = return_gates + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.fc1 = nn.Conv2d( + in_channels, + in_channels // reduction, + kernel_size=1, + bias=True, + padding=0 + ) + self.norm1 = None + if layer_norm: + self.norm1 = nn.LayerNorm((in_channels // reduction, 1, 1)) + self.relu = nn.ReLU(inplace=True) + self.fc2 = nn.Conv2d( + in_channels // reduction, + num_gates, + kernel_size=1, + bias=True, + padding=0 + ) + if gate_activation == 'sigmoid': + self.gate_activation = nn.Sigmoid() + elif gate_activation == 'relu': + self.gate_activation = nn.ReLU(inplace=True) + elif gate_activation == 'linear': + self.gate_activation = None + else: + raise RuntimeError( + "Unknown gate activation: {}".format(gate_activation) + ) + + def forward(self, x): + input = x + x = self.global_avgpool(x) + x = self.fc1(x) + if self.norm1 is not None: + x = self.norm1(x) + x = self.relu(x) + x = self.fc2(x) + if self.gate_activation is not None: + x = self.gate_activation(x) + if self.return_gates: + return x + return input * x + + +class OSBlock(nn.Module): + """Omni-scale feature learning block.""" + + def __init__( + self, + in_channels, + out_channels, + IN=False, + bottleneck_reduction=4, + **kwargs + ): + super(OSBlock, self).__init__() + mid_channels = out_channels // bottleneck_reduction + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2a = LightConv3x3(mid_channels, mid_channels) + self.conv2b = nn.Sequential( + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + ) + self.conv2c = nn.Sequential( + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + ) + self.conv2d = nn.Sequential( + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + LightConv3x3(mid_channels, mid_channels), + ) + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + self.IN = None + if IN: + self.IN = nn.InstanceNorm2d(out_channels, affine=True) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2a = self.conv2a(x1) + x2b = self.conv2b(x1) + x2c = self.conv2c(x1) + x2d = self.conv2d(x1) + x2 = self.gate(x2a) + self.gate(x2b) + self.gate(x2c) + self.gate(x2d) + x3 = self.conv3(x2) + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + if self.IN is not None: + out = self.IN(out) + return F.relu(out) + + +########## +# Network architecture +########## +class OSNet(nn.Module): + """Omni-Scale Network. + + Reference: + - Zhou et al. Omni-Scale Feature Learning for Person Re-Identification. ICCV, 2019. + - Zhou et al. Learning Generalisable Omni-Scale Representations + for Person Re-Identification. TPAMI, 2021. + """ + + def __init__( + self, + num_classes, + blocks, + layers, + channels, + feature_dim=512, + loss='softmax', + IN=False, + **kwargs + ): + super(OSNet, self).__init__() + num_blocks = len(blocks) + assert num_blocks == len(layers) + assert num_blocks == len(channels) - 1 + self.loss = loss + self.feature_dim = feature_dim + + # convolutional backbone + self.conv1 = ConvLayer(3, channels[0], 7, stride=2, padding=3, IN=IN) + self.maxpool = nn.MaxPool2d(3, stride=2, padding=1) + self.conv2 = self._make_layer( + blocks[0], + layers[0], + channels[0], + channels[1], + reduce_spatial_size=True, + IN=IN + ) + self.conv3 = self._make_layer( + blocks[1], + layers[1], + channels[1], + channels[2], + reduce_spatial_size=True + ) + self.conv4 = self._make_layer( + blocks[2], + layers[2], + channels[2], + channels[3], + reduce_spatial_size=False + ) + self.conv5 = Conv1x1(channels[3], channels[3]) + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + # fully connected layer + self.fc = self._construct_fc_layer( + self.feature_dim, channels[3], dropout_p=None + ) + # identity classification layer + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self._init_params() + + def _make_layer( + self, + block, + layer, + in_channels, + out_channels, + reduce_spatial_size, + IN=False + ): + layers = [] + + layers.append(block(in_channels, out_channels, IN=IN)) + for i in range(1, layer): + layers.append(block(out_channels, out_channels, IN=IN)) + + if reduce_spatial_size: + layers.append( + nn.Sequential( + Conv1x1(out_channels, out_channels), + nn.AvgPool2d(2, stride=2) + ) + ) + + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + if fc_dims is None or fc_dims < 0: + self.feature_dim = input_dim + return None + + if isinstance(fc_dims, int): + fc_dims = [fc_dims] + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.maxpool(x) + x = self.conv2(x) + x = self.conv3(x) + x = self.conv4(x) + x = self.conv5(x) + return x + + def forward(self, x, return_featuremaps=False): + x = self.featuremaps(x) + if return_featuremaps: + return x + v = self.global_avgpool(x) + v = v.view(v.size(0), -1) + if self.fc is not None: + v = self.fc(v) + if not self.training: + return v + y = self.classifier(v) + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) + + +def init_pretrained_weights(model, key=''): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + import os + import errno + import gdown + from collections import OrderedDict + + def _get_torch_home(): + ENV_TORCH_HOME = 'TORCH_HOME' + ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME' + DEFAULT_CACHE_DIR = '~/.cache' + torch_home = os.path.expanduser( + os.getenv( + ENV_TORCH_HOME, + os.path.join( + os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'torch' + ) + ) + ) + return torch_home + + torch_home = _get_torch_home() + model_dir = os.path.join(torch_home, 'checkpoints') + try: + os.makedirs(model_dir) + except OSError as e: + if e.errno == errno.EEXIST: + # Directory already exists, ignore. + pass + else: + # Unexpected OSError, re-raise. + raise + filename = key + '_imagenet.pth' + cached_file = os.path.join(model_dir, filename) + + if not os.path.exists(cached_file): + gdown.download(pretrained_urls[key], cached_file, quiet=False) + + state_dict = torch.load(cached_file) + model_dict = model.state_dict() + new_state_dict = OrderedDict() + matched_layers, discarded_layers = [], [] + + for k, v in state_dict.items(): + if k.startswith('module.'): + k = k[7:] # discard module. + + if k in model_dict and model_dict[k].size() == v.size(): + new_state_dict[k] = v + matched_layers.append(k) + else: + discarded_layers.append(k) + + model_dict.update(new_state_dict) + model.load_state_dict(model_dict) + + if len(matched_layers) == 0: + warnings.warn( + 'The pretrained weights from "{}" cannot be loaded, ' + 'please check the key names manually ' + '(** ignored and continue **)'.format(cached_file) + ) + else: + print( + 'Successfully loaded imagenet pretrained weights from "{}"'. + format(cached_file) + ) + if len(discarded_layers) > 0: + print( + '** The following layers are discarded ' + 'due to unmatched keys or layer size: {}'. + format(discarded_layers) + ) + + +########## +# Instantiation +########## +def osnet_x1_0(num_classes=1000, pretrained=True, loss='softmax', **kwargs): + # standard size (width x1.0) + model = OSNet( + num_classes, + blocks=[OSBlock, OSBlock, OSBlock], + layers=[2, 2, 2], + channels=[64, 256, 384, 512], + loss=loss, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, key='osnet_x1_0') + return model + + +def osnet_x0_75(num_classes=1000, pretrained=True, loss='softmax', **kwargs): + # medium size (width x0.75) + model = OSNet( + num_classes, + blocks=[OSBlock, OSBlock, OSBlock], + layers=[2, 2, 2], + channels=[48, 192, 288, 384], + loss=loss, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, key='osnet_x0_75') + return model + + +def osnet_x0_5(num_classes=1000, pretrained=True, loss='softmax', **kwargs): + # tiny size (width x0.5) + model = OSNet( + num_classes, + blocks=[OSBlock, OSBlock, OSBlock], + layers=[2, 2, 2], + channels=[32, 128, 192, 256], + loss=loss, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, key='osnet_x0_5') + return model + + +def osnet_x0_25(num_classes=1000, pretrained=True, loss='softmax', **kwargs): + # very tiny size (width x0.25) + model = OSNet( + num_classes, + blocks=[OSBlock, OSBlock, OSBlock], + layers=[2, 2, 2], + channels=[16, 64, 96, 128], + loss=loss, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, key='osnet_x0_25') + return model + + +def osnet_ibn_x1_0( + num_classes=1000, pretrained=True, loss='softmax', **kwargs +): + # standard size (width x1.0) + IBN layer + # Ref: Pan et al. Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net. ECCV, 2018. + model = OSNet( + num_classes, + blocks=[OSBlock, OSBlock, OSBlock], + layers=[2, 2, 2], + channels=[64, 256, 384, 512], + loss=loss, + IN=True, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, key='osnet_ibn_x1_0') + return model diff --git a/strong_sort/deep/reid/torchreid/models/osnet_ain.py b/strong_sort/deep/reid/torchreid/models/osnet_ain.py new file mode 100644 index 0000000000000000000000000000000000000000..3f9f7bd0704502401d499fd2bfdb802522b99efe --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/osnet_ain.py @@ -0,0 +1,609 @@ +from __future__ import division, absolute_import +import warnings +import torch +from torch import nn +from torch.nn import functional as F + +__all__ = [ + 'osnet_ain_x1_0', 'osnet_ain_x0_75', 'osnet_ain_x0_5', 'osnet_ain_x0_25' +] + +pretrained_urls = { + 'osnet_ain_x1_0': + 'https://drive.google.com/uc?id=1-CaioD9NaqbHK_kzSMW8VE4_3KcsRjEo', + 'osnet_ain_x0_75': + 'https://drive.google.com/uc?id=1apy0hpsMypqstfencdH-jKIUEFOW4xoM', + 'osnet_ain_x0_5': + 'https://drive.google.com/uc?id=1KusKvEYyKGDTUBVRxRiz55G31wkihB6l', + 'osnet_ain_x0_25': + 'https://drive.google.com/uc?id=1SxQt2AvmEcgWNhaRb2xC4rP6ZwVDP0Wt' +} + + +########## +# Basic layers +########## +class ConvLayer(nn.Module): + """Convolution layer (conv + bn + relu).""" + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + groups=1, + IN=False + ): + super(ConvLayer, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + bias=False, + groups=groups + ) + if IN: + self.bn = nn.InstanceNorm2d(out_channels, affine=True) + else: + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU() + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return self.relu(x) + + +class Conv1x1(nn.Module): + """1x1 convolution + bn + relu.""" + + def __init__(self, in_channels, out_channels, stride=1, groups=1): + super(Conv1x1, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 1, + stride=stride, + padding=0, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU() + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return self.relu(x) + + +class Conv1x1Linear(nn.Module): + """1x1 convolution + bn (w/o non-linearity).""" + + def __init__(self, in_channels, out_channels, stride=1, bn=True): + super(Conv1x1Linear, self).__init__() + self.conv = nn.Conv2d( + in_channels, out_channels, 1, stride=stride, padding=0, bias=False + ) + self.bn = None + if bn: + self.bn = nn.BatchNorm2d(out_channels) + + def forward(self, x): + x = self.conv(x) + if self.bn is not None: + x = self.bn(x) + return x + + +class Conv3x3(nn.Module): + """3x3 convolution + bn + relu.""" + + def __init__(self, in_channels, out_channels, stride=1, groups=1): + super(Conv3x3, self).__init__() + self.conv = nn.Conv2d( + in_channels, + out_channels, + 3, + stride=stride, + padding=1, + bias=False, + groups=groups + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU() + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return self.relu(x) + + +class LightConv3x3(nn.Module): + """Lightweight 3x3 convolution. + + 1x1 (linear) + dw 3x3 (nonlinear). + """ + + def __init__(self, in_channels, out_channels): + super(LightConv3x3, self).__init__() + self.conv1 = nn.Conv2d( + in_channels, out_channels, 1, stride=1, padding=0, bias=False + ) + self.conv2 = nn.Conv2d( + out_channels, + out_channels, + 3, + stride=1, + padding=1, + bias=False, + groups=out_channels + ) + self.bn = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU() + + def forward(self, x): + x = self.conv1(x) + x = self.conv2(x) + x = self.bn(x) + return self.relu(x) + + +class LightConvStream(nn.Module): + """Lightweight convolution stream.""" + + def __init__(self, in_channels, out_channels, depth): + super(LightConvStream, self).__init__() + assert depth >= 1, 'depth must be equal to or larger than 1, but got {}'.format( + depth + ) + layers = [] + layers += [LightConv3x3(in_channels, out_channels)] + for i in range(depth - 1): + layers += [LightConv3x3(out_channels, out_channels)] + self.layers = nn.Sequential(*layers) + + def forward(self, x): + return self.layers(x) + + +########## +# Building blocks for omni-scale feature learning +########## +class ChannelGate(nn.Module): + """A mini-network that generates channel-wise gates conditioned on input tensor.""" + + def __init__( + self, + in_channels, + num_gates=None, + return_gates=False, + gate_activation='sigmoid', + reduction=16, + layer_norm=False + ): + super(ChannelGate, self).__init__() + if num_gates is None: + num_gates = in_channels + self.return_gates = return_gates + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.fc1 = nn.Conv2d( + in_channels, + in_channels // reduction, + kernel_size=1, + bias=True, + padding=0 + ) + self.norm1 = None + if layer_norm: + self.norm1 = nn.LayerNorm((in_channels // reduction, 1, 1)) + self.relu = nn.ReLU() + self.fc2 = nn.Conv2d( + in_channels // reduction, + num_gates, + kernel_size=1, + bias=True, + padding=0 + ) + if gate_activation == 'sigmoid': + self.gate_activation = nn.Sigmoid() + elif gate_activation == 'relu': + self.gate_activation = nn.ReLU() + elif gate_activation == 'linear': + self.gate_activation = None + else: + raise RuntimeError( + "Unknown gate activation: {}".format(gate_activation) + ) + + def forward(self, x): + input = x + x = self.global_avgpool(x) + x = self.fc1(x) + if self.norm1 is not None: + x = self.norm1(x) + x = self.relu(x) + x = self.fc2(x) + if self.gate_activation is not None: + x = self.gate_activation(x) + if self.return_gates: + return x + return input * x + + +class OSBlock(nn.Module): + """Omni-scale feature learning block.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlock, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + return F.relu(out) + + +class OSBlockINin(nn.Module): + """Omni-scale feature learning block with instance normalization.""" + + def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): + super(OSBlockINin, self).__init__() + assert T >= 1 + assert out_channels >= reduction and out_channels % reduction == 0 + mid_channels = out_channels // reduction + + self.conv1 = Conv1x1(in_channels, mid_channels) + self.conv2 = nn.ModuleList() + for t in range(1, T + 1): + self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] + self.gate = ChannelGate(mid_channels) + self.conv3 = Conv1x1Linear(mid_channels, out_channels, bn=False) + self.downsample = None + if in_channels != out_channels: + self.downsample = Conv1x1Linear(in_channels, out_channels) + self.IN = nn.InstanceNorm2d(out_channels, affine=True) + + def forward(self, x): + identity = x + x1 = self.conv1(x) + x2 = 0 + for conv2_t in self.conv2: + x2_t = conv2_t(x1) + x2 = x2 + self.gate(x2_t) + x3 = self.conv3(x2) + x3 = self.IN(x3) # IN inside residual + if self.downsample is not None: + identity = self.downsample(identity) + out = x3 + identity + return F.relu(out) + + +########## +# Network architecture +########## +class OSNet(nn.Module): + """Omni-Scale Network. + + Reference: + - Zhou et al. Omni-Scale Feature Learning for Person Re-Identification. ICCV, 2019. + - Zhou et al. Learning Generalisable Omni-Scale Representations + for Person Re-Identification. TPAMI, 2021. + """ + + def __init__( + self, + num_classes, + blocks, + layers, + channels, + feature_dim=512, + loss='softmax', + conv1_IN=False, + **kwargs + ): + super(OSNet, self).__init__() + num_blocks = len(blocks) + assert num_blocks == len(layers) + assert num_blocks == len(channels) - 1 + self.loss = loss + self.feature_dim = feature_dim + + # convolutional backbone + self.conv1 = ConvLayer( + 3, channels[0], 7, stride=2, padding=3, IN=conv1_IN + ) + self.maxpool = nn.MaxPool2d(3, stride=2, padding=1) + self.conv2 = self._make_layer( + blocks[0], layers[0], channels[0], channels[1] + ) + self.pool2 = nn.Sequential( + Conv1x1(channels[1], channels[1]), nn.AvgPool2d(2, stride=2) + ) + self.conv3 = self._make_layer( + blocks[1], layers[1], channels[1], channels[2] + ) + self.pool3 = nn.Sequential( + Conv1x1(channels[2], channels[2]), nn.AvgPool2d(2, stride=2) + ) + self.conv4 = self._make_layer( + blocks[2], layers[2], channels[2], channels[3] + ) + self.conv5 = Conv1x1(channels[3], channels[3]) + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + # fully connected layer + self.fc = self._construct_fc_layer( + self.feature_dim, channels[3], dropout_p=None + ) + # identity classification layer + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self._init_params() + + def _make_layer(self, blocks, layer, in_channels, out_channels): + layers = [] + layers += [blocks[0](in_channels, out_channels)] + for i in range(1, len(blocks)): + layers += [blocks[i](out_channels, out_channels)] + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + if fc_dims is None or fc_dims < 0: + self.feature_dim = input_dim + return None + + if isinstance(fc_dims, int): + fc_dims = [fc_dims] + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU()) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.InstanceNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.maxpool(x) + x = self.conv2(x) + x = self.pool2(x) + x = self.conv3(x) + x = self.pool3(x) + x = self.conv4(x) + x = self.conv5(x) + return x + + def forward(self, x, return_featuremaps=False): + x = self.featuremaps(x) + if return_featuremaps: + return x + v = self.global_avgpool(x) + v = v.view(v.size(0), -1) + if self.fc is not None: + v = self.fc(v) + if not self.training: + return v + y = self.classifier(v) + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) + + +def init_pretrained_weights(model, key=''): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + import os + import errno + import gdown + from collections import OrderedDict + + def _get_torch_home(): + ENV_TORCH_HOME = 'TORCH_HOME' + ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME' + DEFAULT_CACHE_DIR = '~/.cache' + torch_home = os.path.expanduser( + os.getenv( + ENV_TORCH_HOME, + os.path.join( + os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'torch' + ) + ) + ) + return torch_home + + torch_home = _get_torch_home() + model_dir = os.path.join(torch_home, 'checkpoints') + try: + os.makedirs(model_dir) + except OSError as e: + if e.errno == errno.EEXIST: + # Directory already exists, ignore. + pass + else: + # Unexpected OSError, re-raise. + raise + filename = key + '_imagenet.pth' + cached_file = os.path.join(model_dir, filename) + + if not os.path.exists(cached_file): + gdown.download(pretrained_urls[key], cached_file, quiet=False) + + state_dict = torch.load(cached_file) + model_dict = model.state_dict() + new_state_dict = OrderedDict() + matched_layers, discarded_layers = [], [] + + for k, v in state_dict.items(): + if k.startswith('module.'): + k = k[7:] # discard module. + + if k in model_dict and model_dict[k].size() == v.size(): + new_state_dict[k] = v + matched_layers.append(k) + else: + discarded_layers.append(k) + + model_dict.update(new_state_dict) + model.load_state_dict(model_dict) + + if len(matched_layers) == 0: + warnings.warn( + 'The pretrained weights from "{}" cannot be loaded, ' + 'please check the key names manually ' + '(** ignored and continue **)'.format(cached_file) + ) + else: + print( + 'Successfully loaded imagenet pretrained weights from "{}"'. + format(cached_file) + ) + if len(discarded_layers) > 0: + print( + '** The following layers are discarded ' + 'due to unmatched keys or layer size: {}'. + format(discarded_layers) + ) + + +########## +# Instantiation +########## +def osnet_ain_x1_0( + num_classes=1000, pretrained=True, loss='softmax', **kwargs +): + model = OSNet( + num_classes, + blocks=[ + [OSBlockINin, OSBlockINin], [OSBlock, OSBlockINin], + [OSBlockINin, OSBlock] + ], + layers=[2, 2, 2], + channels=[64, 256, 384, 512], + loss=loss, + conv1_IN=True, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, key='osnet_ain_x1_0') + return model + + +def osnet_ain_x0_75( + num_classes=1000, pretrained=True, loss='softmax', **kwargs +): + model = OSNet( + num_classes, + blocks=[ + [OSBlockINin, OSBlockINin], [OSBlock, OSBlockINin], + [OSBlockINin, OSBlock] + ], + layers=[2, 2, 2], + channels=[48, 192, 288, 384], + loss=loss, + conv1_IN=True, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, key='osnet_ain_x0_75') + return model + + +def osnet_ain_x0_5( + num_classes=1000, pretrained=True, loss='softmax', **kwargs +): + model = OSNet( + num_classes, + blocks=[ + [OSBlockINin, OSBlockINin], [OSBlock, OSBlockINin], + [OSBlockINin, OSBlock] + ], + layers=[2, 2, 2], + channels=[32, 128, 192, 256], + loss=loss, + conv1_IN=True, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, key='osnet_ain_x0_5') + return model + + +def osnet_ain_x0_25( + num_classes=1000, pretrained=True, loss='softmax', **kwargs +): + model = OSNet( + num_classes, + blocks=[ + [OSBlockINin, OSBlockINin], [OSBlock, OSBlockINin], + [OSBlockINin, OSBlock] + ], + layers=[2, 2, 2], + channels=[16, 64, 96, 128], + loss=loss, + conv1_IN=True, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, key='osnet_ain_x0_25') + return model diff --git a/strong_sort/deep/reid/torchreid/models/pcb.py b/strong_sort/deep/reid/torchreid/models/pcb.py new file mode 100644 index 0000000000000000000000000000000000000000..92c74148763a600ed331bb0e361588fbf3b09189 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/pcb.py @@ -0,0 +1,314 @@ +from __future__ import division, absolute_import +import torch.utils.model_zoo as model_zoo +from torch import nn +from torch.nn import functional as F + +__all__ = ['pcb_p6', 'pcb_p4'] + +model_urls = { + 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', + 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', + 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', + 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', + 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', +} + + +def conv3x3(in_planes, out_planes, stride=1): + """3x3 convolution with padding""" + return nn.Conv2d( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=1, + bias=False + ) + + +class BasicBlock(nn.Module): + expansion = 1 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(BasicBlock, self).__init__() + self.conv1 = conv3x3(inplanes, planes, stride) + self.bn1 = nn.BatchNorm2d(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes) + self.bn2 = nn.BatchNorm2d(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(Bottleneck, self).__init__() + self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.conv2 = nn.Conv2d( + planes, + planes, + kernel_size=3, + stride=stride, + padding=1, + bias=False + ) + self.bn2 = nn.BatchNorm2d(planes) + self.conv3 = nn.Conv2d( + planes, planes * self.expansion, kernel_size=1, bias=False + ) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class DimReduceLayer(nn.Module): + + def __init__(self, in_channels, out_channels, nonlinear): + super(DimReduceLayer, self).__init__() + layers = [] + layers.append( + nn.Conv2d( + in_channels, out_channels, 1, stride=1, padding=0, bias=False + ) + ) + layers.append(nn.BatchNorm2d(out_channels)) + + if nonlinear == 'relu': + layers.append(nn.ReLU(inplace=True)) + elif nonlinear == 'leakyrelu': + layers.append(nn.LeakyReLU(0.1)) + + self.layers = nn.Sequential(*layers) + + def forward(self, x): + return self.layers(x) + + +class PCB(nn.Module): + """Part-based Convolutional Baseline. + + Reference: + Sun et al. Beyond Part Models: Person Retrieval with Refined + Part Pooling (and A Strong Convolutional Baseline). ECCV 2018. + + Public keys: + - ``pcb_p4``: PCB with 4-part strips. + - ``pcb_p6``: PCB with 6-part strips. + """ + + def __init__( + self, + num_classes, + loss, + block, + layers, + parts=6, + reduced_dim=256, + nonlinear='relu', + **kwargs + ): + self.inplanes = 64 + super(PCB, self).__init__() + self.loss = loss + self.parts = parts + self.feature_dim = 512 * block.expansion + + # backbone network + self.conv1 = nn.Conv2d( + 3, 64, kernel_size=7, stride=2, padding=3, bias=False + ) + self.bn1 = nn.BatchNorm2d(64) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(block, 64, layers[0]) + self.layer2 = self._make_layer(block, 128, layers[1], stride=2) + self.layer3 = self._make_layer(block, 256, layers[2], stride=2) + self.layer4 = self._make_layer(block, 512, layers[3], stride=1) + + # pcb layers + self.parts_avgpool = nn.AdaptiveAvgPool2d((self.parts, 1)) + self.dropout = nn.Dropout(p=0.5) + self.conv5 = DimReduceLayer( + 512 * block.expansion, reduced_dim, nonlinear=nonlinear + ) + self.feature_dim = reduced_dim + self.classifier = nn.ModuleList( + [ + nn.Linear(self.feature_dim, num_classes) + for _ in range(self.parts) + ] + ) + + self._init_params() + + def _make_layer(self, block, planes, blocks, stride=1): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2d( + self.inplanes, + planes * block.expansion, + kernel_size=1, + stride=stride, + bias=False + ), + nn.BatchNorm2d(planes * block.expansion), + ) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + return x + + def forward(self, x): + f = self.featuremaps(x) + v_g = self.parts_avgpool(f) + + if not self.training: + v_g = F.normalize(v_g, p=2, dim=1) + return v_g.view(v_g.size(0), -1) + + v_g = self.dropout(v_g) + v_h = self.conv5(v_g) + + y = [] + for i in range(self.parts): + v_h_i = v_h[:, :, i, :] + v_h_i = v_h_i.view(v_h_i.size(0), -1) + y_i = self.classifier[i](v_h_i) + y.append(y_i) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + v_g = F.normalize(v_g, p=2, dim=1) + return y, v_g.view(v_g.size(0), -1) + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def pcb_p6(num_classes, loss='softmax', pretrained=True, **kwargs): + model = PCB( + num_classes=num_classes, + loss=loss, + block=Bottleneck, + layers=[3, 4, 6, 3], + last_stride=1, + parts=6, + reduced_dim=256, + nonlinear='relu', + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet50']) + return model + + +def pcb_p4(num_classes, loss='softmax', pretrained=True, **kwargs): + model = PCB( + num_classes=num_classes, + loss=loss, + block=Bottleneck, + layers=[3, 4, 6, 3], + last_stride=1, + parts=4, + reduced_dim=256, + nonlinear='relu', + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet50']) + return model diff --git a/strong_sort/deep/reid/torchreid/models/resnet.py b/strong_sort/deep/reid/torchreid/models/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..63d7f43ff43373d28c45de3930da0bdbee817b61 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/resnet.py @@ -0,0 +1,530 @@ +""" +Code source: https://github.com/pytorch/vision +""" +from __future__ import division, absolute_import +import torch.utils.model_zoo as model_zoo +from torch import nn + +__all__ = [ + 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', + 'resnext50_32x4d', 'resnext101_32x8d', 'resnet50_fc512' +] + +model_urls = { + 'resnet18': + 'https://download.pytorch.org/models/resnet18-5c106cde.pth', + 'resnet34': + 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', + 'resnet50': + 'https://download.pytorch.org/models/resnet50-19c8e357.pth', + 'resnet101': + 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', + 'resnet152': + 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', + 'resnext50_32x4d': + 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth', + 'resnext101_32x8d': + 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth', +} + + +def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): + """3x3 convolution with padding""" + return nn.Conv2d( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=dilation, + groups=groups, + bias=False, + dilation=dilation + ) + + +def conv1x1(in_planes, out_planes, stride=1): + """1x1 convolution""" + return nn.Conv2d( + in_planes, out_planes, kernel_size=1, stride=stride, bias=False + ) + + +class BasicBlock(nn.Module): + expansion = 1 + + def __init__( + self, + inplanes, + planes, + stride=1, + downsample=None, + groups=1, + base_width=64, + dilation=1, + norm_layer=None + ): + super(BasicBlock, self).__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2d + if groups != 1 or base_width != 64: + raise ValueError( + 'BasicBlock only supports groups=1 and base_width=64' + ) + if dilation > 1: + raise NotImplementedError( + "Dilation > 1 not supported in BasicBlock" + ) + # Both self.conv1 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv3x3(inplanes, planes, stride) + self.bn1 = norm_layer(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes) + self.bn2 = norm_layer(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__( + self, + inplanes, + planes, + stride=1, + downsample=None, + groups=1, + base_width=64, + dilation=1, + norm_layer=None + ): + super(Bottleneck, self).__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2d + width = int(planes * (base_width/64.)) * groups + # Both self.conv2 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv1x1(inplanes, width) + self.bn1 = norm_layer(width) + self.conv2 = conv3x3(width, width, stride, groups, dilation) + self.bn2 = norm_layer(width) + self.conv3 = conv1x1(width, planes * self.expansion) + self.bn3 = norm_layer(planes * self.expansion) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + + return out + + +class ResNet(nn.Module): + """Residual network. + + Reference: + - He et al. Deep Residual Learning for Image Recognition. CVPR 2016. + - Xie et al. Aggregated Residual Transformations for Deep Neural Networks. CVPR 2017. + + Public keys: + - ``resnet18``: ResNet18. + - ``resnet34``: ResNet34. + - ``resnet50``: ResNet50. + - ``resnet101``: ResNet101. + - ``resnet152``: ResNet152. + - ``resnext50_32x4d``: ResNeXt50. + - ``resnext101_32x8d``: ResNeXt101. + - ``resnet50_fc512``: ResNet50 + FC. + """ + + def __init__( + self, + num_classes, + loss, + block, + layers, + zero_init_residual=False, + groups=1, + width_per_group=64, + replace_stride_with_dilation=None, + norm_layer=None, + last_stride=2, + fc_dims=None, + dropout_p=None, + **kwargs + ): + super(ResNet, self).__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2d + self._norm_layer = norm_layer + self.loss = loss + self.feature_dim = 512 * block.expansion + self.inplanes = 64 + self.dilation = 1 + if replace_stride_with_dilation is None: + # each element in the tuple indicates if we should replace + # the 2x2 stride with a dilated convolution instead + replace_stride_with_dilation = [False, False, False] + if len(replace_stride_with_dilation) != 3: + raise ValueError( + "replace_stride_with_dilation should be None " + "or a 3-element tuple, got {}". + format(replace_stride_with_dilation) + ) + self.groups = groups + self.base_width = width_per_group + self.conv1 = nn.Conv2d( + 3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False + ) + self.bn1 = norm_layer(self.inplanes) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(block, 64, layers[0]) + self.layer2 = self._make_layer( + block, + 128, + layers[1], + stride=2, + dilate=replace_stride_with_dilation[0] + ) + self.layer3 = self._make_layer( + block, + 256, + layers[2], + stride=2, + dilate=replace_stride_with_dilation[1] + ) + self.layer4 = self._make_layer( + block, + 512, + layers[3], + stride=last_stride, + dilate=replace_stride_with_dilation[2] + ) + self.global_avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.fc = self._construct_fc_layer( + fc_dims, 512 * block.expansion, dropout_p + ) + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self._init_params() + + # Zero-initialize the last BN in each residual branch, + # so that the residual branch starts with zeros, and each residual block behaves like an identity. + # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 + if zero_init_residual: + for m in self.modules(): + if isinstance(m, Bottleneck): + nn.init.constant_(m.bn3.weight, 0) + elif isinstance(m, BasicBlock): + nn.init.constant_(m.bn2.weight, 0) + + def _make_layer(self, block, planes, blocks, stride=1, dilate=False): + norm_layer = self._norm_layer + downsample = None + previous_dilation = self.dilation + if dilate: + self.dilation *= stride + stride = 1 + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + conv1x1(self.inplanes, planes * block.expansion, stride), + norm_layer(planes * block.expansion), + ) + + layers = [] + layers.append( + block( + self.inplanes, planes, stride, downsample, self.groups, + self.base_width, previous_dilation, norm_layer + ) + ) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append( + block( + self.inplanes, + planes, + groups=self.groups, + base_width=self.base_width, + dilation=self.dilation, + norm_layer=norm_layer + ) + ) + + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + """Constructs fully connected layer + + Args: + fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed + input_dim (int): input dimension + dropout_p (float): dropout probability, if None, dropout is unused + """ + if fc_dims is None: + self.feature_dim = input_dim + return None + + assert isinstance( + fc_dims, (list, tuple) + ), 'fc_dims must be either list or tuple, but got {}'.format( + type(fc_dims) + ) + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + return x + + def forward(self, x): + f = self.featuremaps(x) + v = self.global_avgpool(f) + v = v.view(v.size(0), -1) + + if self.fc is not None: + v = self.fc(v) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +"""ResNet""" + + +def resnet18(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ResNet( + num_classes=num_classes, + loss=loss, + block=BasicBlock, + layers=[2, 2, 2, 2], + last_stride=2, + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet18']) + return model + + +def resnet34(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ResNet( + num_classes=num_classes, + loss=loss, + block=BasicBlock, + layers=[3, 4, 6, 3], + last_stride=2, + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet34']) + return model + + +def resnet50(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ResNet( + num_classes=num_classes, + loss=loss, + block=Bottleneck, + layers=[3, 4, 6, 3], + last_stride=2, + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet50']) + return model + + +def resnet101(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ResNet( + num_classes=num_classes, + loss=loss, + block=Bottleneck, + layers=[3, 4, 23, 3], + last_stride=2, + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet101']) + return model + + +def resnet152(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ResNet( + num_classes=num_classes, + loss=loss, + block=Bottleneck, + layers=[3, 8, 36, 3], + last_stride=2, + fc_dims=None, + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet152']) + return model + + +"""ResNeXt""" + + +def resnext50_32x4d(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ResNet( + num_classes=num_classes, + loss=loss, + block=Bottleneck, + layers=[3, 4, 6, 3], + last_stride=2, + fc_dims=None, + dropout_p=None, + groups=32, + width_per_group=4, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnext50_32x4d']) + return model + + +def resnext101_32x8d(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ResNet( + num_classes=num_classes, + loss=loss, + block=Bottleneck, + layers=[3, 4, 23, 3], + last_stride=2, + fc_dims=None, + dropout_p=None, + groups=32, + width_per_group=8, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnext101_32x8d']) + return model + + +""" +ResNet + FC +""" + + +def resnet50_fc512(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ResNet( + num_classes=num_classes, + loss=loss, + block=Bottleneck, + layers=[3, 4, 6, 3], + last_stride=1, + fc_dims=[512], + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet50']) + return model diff --git a/strong_sort/deep/reid/torchreid/models/resnet_ibn_a.py b/strong_sort/deep/reid/torchreid/models/resnet_ibn_a.py new file mode 100644 index 0000000000000000000000000000000000000000..d198e7c9e361c40d25bc7eb1f352b971596ee124 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/resnet_ibn_a.py @@ -0,0 +1,289 @@ +""" +Credit to https://github.com/XingangPan/IBN-Net. +""" +from __future__ import division, absolute_import +import math +import torch +import torch.nn as nn +import torch.utils.model_zoo as model_zoo + +__all__ = ['resnet50_ibn_a'] + +model_urls = { + 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', + 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', + 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', +} + + +def conv3x3(in_planes, out_planes, stride=1): + "3x3 convolution with padding" + return nn.Conv2d( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=1, + bias=False + ) + + +class BasicBlock(nn.Module): + expansion = 1 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(BasicBlock, self).__init__() + self.conv1 = conv3x3(inplanes, planes, stride) + self.bn1 = nn.BatchNorm2d(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes) + self.bn2 = nn.BatchNorm2d(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class IBN(nn.Module): + + def __init__(self, planes): + super(IBN, self).__init__() + half1 = int(planes / 2) + self.half = half1 + half2 = planes - half1 + self.IN = nn.InstanceNorm2d(half1, affine=True) + self.BN = nn.BatchNorm2d(half2) + + def forward(self, x): + split = torch.split(x, self.half, 1) + out1 = self.IN(split[0].contiguous()) + out2 = self.BN(split[1].contiguous()) + out = torch.cat((out1, out2), 1) + return out + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, ibn=False, stride=1, downsample=None): + super(Bottleneck, self).__init__() + self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) + if ibn: + self.bn1 = IBN(planes) + else: + self.bn1 = nn.BatchNorm2d(planes) + self.conv2 = nn.Conv2d( + planes, + planes, + kernel_size=3, + stride=stride, + padding=1, + bias=False + ) + self.bn2 = nn.BatchNorm2d(planes) + self.conv3 = nn.Conv2d( + planes, planes * self.expansion, kernel_size=1, bias=False + ) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class ResNet(nn.Module): + """Residual network + IBN layer. + + Reference: + - He et al. Deep Residual Learning for Image Recognition. CVPR 2016. + - Pan et al. Two at Once: Enhancing Learning and Generalization + Capacities via IBN-Net. ECCV 2018. + """ + + def __init__( + self, + block, + layers, + num_classes=1000, + loss='softmax', + fc_dims=None, + dropout_p=None, + **kwargs + ): + scale = 64 + self.inplanes = scale + super(ResNet, self).__init__() + self.loss = loss + self.feature_dim = scale * 8 * block.expansion + + self.conv1 = nn.Conv2d( + 3, scale, kernel_size=7, stride=2, padding=3, bias=False + ) + self.bn1 = nn.BatchNorm2d(scale) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(block, scale, layers[0]) + self.layer2 = self._make_layer(block, scale * 2, layers[1], stride=2) + self.layer3 = self._make_layer(block, scale * 4, layers[2], stride=2) + self.layer4 = self._make_layer(block, scale * 8, layers[3], stride=2) + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.fc = self._construct_fc_layer( + fc_dims, scale * 8 * block.expansion, dropout_p + ) + self.classifier = nn.Linear(self.feature_dim, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + m.weight.data.normal_(0, math.sqrt(2. / n)) + elif isinstance(m, nn.BatchNorm2d): + m.weight.data.fill_(1) + m.bias.data.zero_() + elif isinstance(m, nn.InstanceNorm2d): + m.weight.data.fill_(1) + m.bias.data.zero_() + + def _make_layer(self, block, planes, blocks, stride=1): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2d( + self.inplanes, + planes * block.expansion, + kernel_size=1, + stride=stride, + bias=False + ), + nn.BatchNorm2d(planes * block.expansion), + ) + + layers = [] + ibn = True + if planes == 512: + ibn = False + layers.append(block(self.inplanes, planes, ibn, stride, downsample)) + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes, ibn)) + + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + """Constructs fully connected layer + + Args: + fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed + input_dim (int): input dimension + dropout_p (float): dropout probability, if None, dropout is unused + """ + if fc_dims is None: + self.feature_dim = input_dim + return None + + assert isinstance( + fc_dims, (list, tuple) + ), 'fc_dims must be either list or tuple, but got {}'.format( + type(fc_dims) + ) + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + return x + + def forward(self, x): + f = self.featuremaps(x) + v = self.avgpool(f) + v = v.view(v.size(0), -1) + if self.fc is not None: + v = self.fc(v) + if not self.training: + return v + y = self.classifier(v) + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def resnet50_ibn_a(num_classes, loss='softmax', pretrained=False, **kwargs): + model = ResNet( + Bottleneck, [3, 4, 6, 3], num_classes=num_classes, loss=loss, **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet50']) + return model diff --git a/strong_sort/deep/reid/torchreid/models/resnet_ibn_b.py b/strong_sort/deep/reid/torchreid/models/resnet_ibn_b.py new file mode 100644 index 0000000000000000000000000000000000000000..9881cc7d64e97a74bab35e6145197d6d740689ad --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/resnet_ibn_b.py @@ -0,0 +1,274 @@ +""" +Credit to https://github.com/XingangPan/IBN-Net. +""" +from __future__ import division, absolute_import +import math +import torch.nn as nn +import torch.utils.model_zoo as model_zoo + +__all__ = ['resnet50_ibn_b'] + +model_urls = { + 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', + 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', + 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', +} + + +def conv3x3(in_planes, out_planes, stride=1): + "3x3 convolution with padding" + return nn.Conv2d( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=1, + bias=False + ) + + +class BasicBlock(nn.Module): + expansion = 1 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(BasicBlock, self).__init__() + self.conv1 = conv3x3(inplanes, planes, stride) + self.bn1 = nn.BatchNorm2d(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes) + self.bn2 = nn.BatchNorm2d(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1, downsample=None, IN=False): + super(Bottleneck, self).__init__() + self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.conv2 = nn.Conv2d( + planes, + planes, + kernel_size=3, + stride=stride, + padding=1, + bias=False + ) + self.bn2 = nn.BatchNorm2d(planes) + self.conv3 = nn.Conv2d( + planes, planes * self.expansion, kernel_size=1, bias=False + ) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.IN = None + if IN: + self.IN = nn.InstanceNorm2d(planes * 4, affine=True) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + if self.IN is not None: + out = self.IN(out) + out = self.relu(out) + + return out + + +class ResNet(nn.Module): + """Residual network + IBN layer. + + Reference: + - He et al. Deep Residual Learning for Image Recognition. CVPR 2016. + - Pan et al. Two at Once: Enhancing Learning and Generalization + Capacities via IBN-Net. ECCV 2018. + """ + + def __init__( + self, + block, + layers, + num_classes=1000, + loss='softmax', + fc_dims=None, + dropout_p=None, + **kwargs + ): + scale = 64 + self.inplanes = scale + super(ResNet, self).__init__() + self.loss = loss + self.feature_dim = scale * 8 * block.expansion + + self.conv1 = nn.Conv2d( + 3, scale, kernel_size=7, stride=2, padding=3, bias=False + ) + self.bn1 = nn.InstanceNorm2d(scale, affine=True) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer( + block, scale, layers[0], stride=1, IN=True + ) + self.layer2 = self._make_layer( + block, scale * 2, layers[1], stride=2, IN=True + ) + self.layer3 = self._make_layer(block, scale * 4, layers[2], stride=2) + self.layer4 = self._make_layer(block, scale * 8, layers[3], stride=2) + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.fc = self._construct_fc_layer( + fc_dims, scale * 8 * block.expansion, dropout_p + ) + self.classifier = nn.Linear(self.feature_dim, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + m.weight.data.normal_(0, math.sqrt(2. / n)) + elif isinstance(m, nn.BatchNorm2d): + m.weight.data.fill_(1) + m.bias.data.zero_() + elif isinstance(m, nn.InstanceNorm2d): + m.weight.data.fill_(1) + m.bias.data.zero_() + + def _make_layer(self, block, planes, blocks, stride=1, IN=False): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2d( + self.inplanes, + planes * block.expansion, + kernel_size=1, + stride=stride, + bias=False + ), + nn.BatchNorm2d(planes * block.expansion), + ) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for i in range(1, blocks - 1): + layers.append(block(self.inplanes, planes)) + layers.append(block(self.inplanes, planes, IN=IN)) + + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + """Constructs fully connected layer + + Args: + fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed + input_dim (int): input dimension + dropout_p (float): dropout probability, if None, dropout is unused + """ + if fc_dims is None: + self.feature_dim = input_dim + return None + + assert isinstance( + fc_dims, (list, tuple) + ), 'fc_dims must be either list or tuple, but got {}'.format( + type(fc_dims) + ) + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + return x + + def forward(self, x): + f = self.featuremaps(x) + v = self.avgpool(f) + v = v.view(v.size(0), -1) + if self.fc is not None: + v = self.fc(v) + if not self.training: + return v + y = self.classifier(v) + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def resnet50_ibn_b(num_classes, loss='softmax', pretrained=False, **kwargs): + model = ResNet( + Bottleneck, [3, 4, 6, 3], num_classes=num_classes, loss=loss, **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet50']) + return model diff --git a/strong_sort/deep/reid/torchreid/models/resnetmid.py b/strong_sort/deep/reid/torchreid/models/resnetmid.py new file mode 100644 index 0000000000000000000000000000000000000000..017f6c62653535a7b04566227d893cb4dfa2a34c --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/resnetmid.py @@ -0,0 +1,307 @@ +from __future__ import division, absolute_import +import torch +import torch.utils.model_zoo as model_zoo +from torch import nn + +__all__ = ['resnet50mid'] + +model_urls = { + 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', + 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', + 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', + 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', + 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', +} + + +def conv3x3(in_planes, out_planes, stride=1): + """3x3 convolution with padding""" + return nn.Conv2d( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=1, + bias=False + ) + + +class BasicBlock(nn.Module): + expansion = 1 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(BasicBlock, self).__init__() + self.conv1 = conv3x3(inplanes, planes, stride) + self.bn1 = nn.BatchNorm2d(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes) + self.bn2 = nn.BatchNorm2d(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(Bottleneck, self).__init__() + self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.conv2 = nn.Conv2d( + planes, + planes, + kernel_size=3, + stride=stride, + padding=1, + bias=False + ) + self.bn2 = nn.BatchNorm2d(planes) + self.conv3 = nn.Conv2d( + planes, planes * self.expansion, kernel_size=1, bias=False + ) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class ResNetMid(nn.Module): + """Residual network + mid-level features. + + Reference: + Yu et al. The Devil is in the Middle: Exploiting Mid-level Representations for + Cross-Domain Instance Matching. arXiv:1711.08106. + + Public keys: + - ``resnet50mid``: ResNet50 + mid-level feature fusion. + """ + + def __init__( + self, + num_classes, + loss, + block, + layers, + last_stride=2, + fc_dims=None, + **kwargs + ): + self.inplanes = 64 + super(ResNetMid, self).__init__() + self.loss = loss + self.feature_dim = 512 * block.expansion + + # backbone network + self.conv1 = nn.Conv2d( + 3, 64, kernel_size=7, stride=2, padding=3, bias=False + ) + self.bn1 = nn.BatchNorm2d(64) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(block, 64, layers[0]) + self.layer2 = self._make_layer(block, 128, layers[1], stride=2) + self.layer3 = self._make_layer(block, 256, layers[2], stride=2) + self.layer4 = self._make_layer( + block, 512, layers[3], stride=last_stride + ) + + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + assert fc_dims is not None + self.fc_fusion = self._construct_fc_layer( + fc_dims, 512 * block.expansion * 2 + ) + self.feature_dim += 512 * block.expansion + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self._init_params() + + def _make_layer(self, block, planes, blocks, stride=1): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2d( + self.inplanes, + planes * block.expansion, + kernel_size=1, + stride=stride, + bias=False + ), + nn.BatchNorm2d(planes * block.expansion), + ) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + """Constructs fully connected layer + + Args: + fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed + input_dim (int): input dimension + dropout_p (float): dropout probability, if None, dropout is unused + """ + if fc_dims is None: + self.feature_dim = input_dim + return None + + assert isinstance( + fc_dims, (list, tuple) + ), 'fc_dims must be either list or tuple, but got {}'.format( + type(fc_dims) + ) + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x4a = self.layer4[0](x) + x4b = self.layer4[1](x4a) + x4c = self.layer4[2](x4b) + return x4a, x4b, x4c + + def forward(self, x): + x4a, x4b, x4c = self.featuremaps(x) + + v4a = self.global_avgpool(x4a) + v4b = self.global_avgpool(x4b) + v4c = self.global_avgpool(x4c) + v4ab = torch.cat([v4a, v4b], 1) + v4ab = v4ab.view(v4ab.size(0), -1) + v4ab = self.fc_fusion(v4ab) + v4c = v4c.view(v4c.size(0), -1) + v = torch.cat([v4ab, v4c], 1) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +""" +Residual network configurations: +-- +resnet18: block=BasicBlock, layers=[2, 2, 2, 2] +resnet34: block=BasicBlock, layers=[3, 4, 6, 3] +resnet50: block=Bottleneck, layers=[3, 4, 6, 3] +resnet101: block=Bottleneck, layers=[3, 4, 23, 3] +resnet152: block=Bottleneck, layers=[3, 8, 36, 3] +""" + + +def resnet50mid(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ResNetMid( + num_classes=num_classes, + loss=loss, + block=Bottleneck, + layers=[3, 4, 6, 3], + last_stride=2, + fc_dims=[1024], + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['resnet50']) + return model diff --git a/strong_sort/deep/reid/torchreid/models/senet.py b/strong_sort/deep/reid/torchreid/models/senet.py new file mode 100644 index 0000000000000000000000000000000000000000..baaf9b0acbe8577bd5e574de47d3f9ef935946db --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/senet.py @@ -0,0 +1,688 @@ +from __future__ import division, absolute_import +import math +from collections import OrderedDict +import torch.nn as nn +from torch.utils import model_zoo + +__all__ = [ + 'senet154', 'se_resnet50', 'se_resnet101', 'se_resnet152', + 'se_resnext50_32x4d', 'se_resnext101_32x4d', 'se_resnet50_fc512' +] +""" +Code imported from https://github.com/Cadene/pretrained-models.pytorch +""" + +pretrained_settings = { + 'senet154': { + 'imagenet': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/senet154-c7b49a05.pth', + 'input_space': 'RGB', + 'input_size': [3, 224, 224], + 'input_range': [0, 1], + 'mean': [0.485, 0.456, 0.406], + 'std': [0.229, 0.224, 0.225], + 'num_classes': 1000 + } + }, + 'se_resnet50': { + 'imagenet': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnet50-ce0d4300.pth', + 'input_space': 'RGB', + 'input_size': [3, 224, 224], + 'input_range': [0, 1], + 'mean': [0.485, 0.456, 0.406], + 'std': [0.229, 0.224, 0.225], + 'num_classes': 1000 + } + }, + 'se_resnet101': { + 'imagenet': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnet101-7e38fcc6.pth', + 'input_space': 'RGB', + 'input_size': [3, 224, 224], + 'input_range': [0, 1], + 'mean': [0.485, 0.456, 0.406], + 'std': [0.229, 0.224, 0.225], + 'num_classes': 1000 + } + }, + 'se_resnet152': { + 'imagenet': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnet152-d17c99b7.pth', + 'input_space': 'RGB', + 'input_size': [3, 224, 224], + 'input_range': [0, 1], + 'mean': [0.485, 0.456, 0.406], + 'std': [0.229, 0.224, 0.225], + 'num_classes': 1000 + } + }, + 'se_resnext50_32x4d': { + 'imagenet': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnext50_32x4d-a260b3a4.pth', + 'input_space': 'RGB', + 'input_size': [3, 224, 224], + 'input_range': [0, 1], + 'mean': [0.485, 0.456, 0.406], + 'std': [0.229, 0.224, 0.225], + 'num_classes': 1000 + } + }, + 'se_resnext101_32x4d': { + 'imagenet': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnext101_32x4d-3b2fe3d8.pth', + 'input_space': 'RGB', + 'input_size': [3, 224, 224], + 'input_range': [0, 1], + 'mean': [0.485, 0.456, 0.406], + 'std': [0.229, 0.224, 0.225], + 'num_classes': 1000 + } + }, +} + + +class SEModule(nn.Module): + + def __init__(self, channels, reduction): + super(SEModule, self).__init__() + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.fc1 = nn.Conv2d( + channels, channels // reduction, kernel_size=1, padding=0 + ) + self.relu = nn.ReLU(inplace=True) + self.fc2 = nn.Conv2d( + channels // reduction, channels, kernel_size=1, padding=0 + ) + self.sigmoid = nn.Sigmoid() + + def forward(self, x): + module_input = x + x = self.avg_pool(x) + x = self.fc1(x) + x = self.relu(x) + x = self.fc2(x) + x = self.sigmoid(x) + return module_input * x + + +class Bottleneck(nn.Module): + """ + Base class for bottlenecks that implements `forward()` method. + """ + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out = self.se_module(out) + residual + out = self.relu(out) + + return out + + +class SEBottleneck(Bottleneck): + """ + Bottleneck for SENet154. + """ + expansion = 4 + + def __init__( + self, inplanes, planes, groups, reduction, stride=1, downsample=None + ): + super(SEBottleneck, self).__init__() + self.conv1 = nn.Conv2d(inplanes, planes * 2, kernel_size=1, bias=False) + self.bn1 = nn.BatchNorm2d(planes * 2) + self.conv2 = nn.Conv2d( + planes * 2, + planes * 4, + kernel_size=3, + stride=stride, + padding=1, + groups=groups, + bias=False + ) + self.bn2 = nn.BatchNorm2d(planes * 4) + self.conv3 = nn.Conv2d( + planes * 4, planes * 4, kernel_size=1, bias=False + ) + self.bn3 = nn.BatchNorm2d(planes * 4) + self.relu = nn.ReLU(inplace=True) + self.se_module = SEModule(planes * 4, reduction=reduction) + self.downsample = downsample + self.stride = stride + + +class SEResNetBottleneck(Bottleneck): + """ + ResNet bottleneck with a Squeeze-and-Excitation module. It follows Caffe + implementation and uses `stride=stride` in `conv1` and not in `conv2` + (the latter is used in the torchvision implementation of ResNet). + """ + expansion = 4 + + def __init__( + self, inplanes, planes, groups, reduction, stride=1, downsample=None + ): + super(SEResNetBottleneck, self).__init__() + self.conv1 = nn.Conv2d( + inplanes, planes, kernel_size=1, bias=False, stride=stride + ) + self.bn1 = nn.BatchNorm2d(planes) + self.conv2 = nn.Conv2d( + planes, + planes, + kernel_size=3, + padding=1, + groups=groups, + bias=False + ) + self.bn2 = nn.BatchNorm2d(planes) + self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * 4) + self.relu = nn.ReLU(inplace=True) + self.se_module = SEModule(planes * 4, reduction=reduction) + self.downsample = downsample + self.stride = stride + + +class SEResNeXtBottleneck(Bottleneck): + """ResNeXt bottleneck type C with a Squeeze-and-Excitation module""" + expansion = 4 + + def __init__( + self, + inplanes, + planes, + groups, + reduction, + stride=1, + downsample=None, + base_width=4 + ): + super(SEResNeXtBottleneck, self).__init__() + width = int(math.floor(planes * (base_width/64.)) * groups) + self.conv1 = nn.Conv2d( + inplanes, width, kernel_size=1, bias=False, stride=1 + ) + self.bn1 = nn.BatchNorm2d(width) + self.conv2 = nn.Conv2d( + width, + width, + kernel_size=3, + stride=stride, + padding=1, + groups=groups, + bias=False + ) + self.bn2 = nn.BatchNorm2d(width) + self.conv3 = nn.Conv2d(width, planes * 4, kernel_size=1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * 4) + self.relu = nn.ReLU(inplace=True) + self.se_module = SEModule(planes * 4, reduction=reduction) + self.downsample = downsample + self.stride = stride + + +class SENet(nn.Module): + """Squeeze-and-excitation network. + + Reference: + Hu et al. Squeeze-and-Excitation Networks. CVPR 2018. + + Public keys: + - ``senet154``: SENet154. + - ``se_resnet50``: ResNet50 + SE. + - ``se_resnet101``: ResNet101 + SE. + - ``se_resnet152``: ResNet152 + SE. + - ``se_resnext50_32x4d``: ResNeXt50 (groups=32, width=4) + SE. + - ``se_resnext101_32x4d``: ResNeXt101 (groups=32, width=4) + SE. + - ``se_resnet50_fc512``: (ResNet50 + SE) + FC. + """ + + def __init__( + self, + num_classes, + loss, + block, + layers, + groups, + reduction, + dropout_p=0.2, + inplanes=128, + input_3x3=True, + downsample_kernel_size=3, + downsample_padding=1, + last_stride=2, + fc_dims=None, + **kwargs + ): + """ + Parameters + ---------- + block (nn.Module): Bottleneck class. + - For SENet154: SEBottleneck + - For SE-ResNet models: SEResNetBottleneck + - For SE-ResNeXt models: SEResNeXtBottleneck + layers (list of ints): Number of residual blocks for 4 layers of the + network (layer1...layer4). + groups (int): Number of groups for the 3x3 convolution in each + bottleneck block. + - For SENet154: 64 + - For SE-ResNet models: 1 + - For SE-ResNeXt models: 32 + reduction (int): Reduction ratio for Squeeze-and-Excitation modules. + - For all models: 16 + dropout_p (float or None): Drop probability for the Dropout layer. + If `None` the Dropout layer is not used. + - For SENet154: 0.2 + - For SE-ResNet models: None + - For SE-ResNeXt models: None + inplanes (int): Number of input channels for layer1. + - For SENet154: 128 + - For SE-ResNet models: 64 + - For SE-ResNeXt models: 64 + input_3x3 (bool): If `True`, use three 3x3 convolutions instead of + a single 7x7 convolution in layer0. + - For SENet154: True + - For SE-ResNet models: False + - For SE-ResNeXt models: False + downsample_kernel_size (int): Kernel size for downsampling convolutions + in layer2, layer3 and layer4. + - For SENet154: 3 + - For SE-ResNet models: 1 + - For SE-ResNeXt models: 1 + downsample_padding (int): Padding for downsampling convolutions in + layer2, layer3 and layer4. + - For SENet154: 1 + - For SE-ResNet models: 0 + - For SE-ResNeXt models: 0 + num_classes (int): Number of outputs in `classifier` layer. + """ + super(SENet, self).__init__() + self.inplanes = inplanes + self.loss = loss + + if input_3x3: + layer0_modules = [ + ( + 'conv1', + nn.Conv2d(3, 64, 3, stride=2, padding=1, bias=False) + ), + ('bn1', nn.BatchNorm2d(64)), + ('relu1', nn.ReLU(inplace=True)), + ( + 'conv2', + nn.Conv2d(64, 64, 3, stride=1, padding=1, bias=False) + ), + ('bn2', nn.BatchNorm2d(64)), + ('relu2', nn.ReLU(inplace=True)), + ( + 'conv3', + nn.Conv2d( + 64, inplanes, 3, stride=1, padding=1, bias=False + ) + ), + ('bn3', nn.BatchNorm2d(inplanes)), + ('relu3', nn.ReLU(inplace=True)), + ] + else: + layer0_modules = [ + ( + 'conv1', + nn.Conv2d( + 3, + inplanes, + kernel_size=7, + stride=2, + padding=3, + bias=False + ) + ), + ('bn1', nn.BatchNorm2d(inplanes)), + ('relu1', nn.ReLU(inplace=True)), + ] + # To preserve compatibility with Caffe weights `ceil_mode=True` + # is used instead of `padding=1`. + layer0_modules.append( + ('pool', nn.MaxPool2d(3, stride=2, ceil_mode=True)) + ) + self.layer0 = nn.Sequential(OrderedDict(layer0_modules)) + self.layer1 = self._make_layer( + block, + planes=64, + blocks=layers[0], + groups=groups, + reduction=reduction, + downsample_kernel_size=1, + downsample_padding=0 + ) + self.layer2 = self._make_layer( + block, + planes=128, + blocks=layers[1], + stride=2, + groups=groups, + reduction=reduction, + downsample_kernel_size=downsample_kernel_size, + downsample_padding=downsample_padding + ) + self.layer3 = self._make_layer( + block, + planes=256, + blocks=layers[2], + stride=2, + groups=groups, + reduction=reduction, + downsample_kernel_size=downsample_kernel_size, + downsample_padding=downsample_padding + ) + self.layer4 = self._make_layer( + block, + planes=512, + blocks=layers[3], + stride=last_stride, + groups=groups, + reduction=reduction, + downsample_kernel_size=downsample_kernel_size, + downsample_padding=downsample_padding + ) + + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.fc = self._construct_fc_layer( + fc_dims, 512 * block.expansion, dropout_p + ) + self.classifier = nn.Linear(self.feature_dim, num_classes) + + def _make_layer( + self, + block, + planes, + blocks, + groups, + reduction, + stride=1, + downsample_kernel_size=1, + downsample_padding=0 + ): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2d( + self.inplanes, + planes * block.expansion, + kernel_size=downsample_kernel_size, + stride=stride, + padding=downsample_padding, + bias=False + ), + nn.BatchNorm2d(planes * block.expansion), + ) + + layers = [] + layers.append( + block( + self.inplanes, planes, groups, reduction, stride, downsample + ) + ) + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes, groups, reduction)) + + return nn.Sequential(*layers) + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + """ + Construct fully connected layer + + - fc_dims (list or tuple): dimensions of fc layers, if None, + no fc layers are constructed + - input_dim (int): input dimension + - dropout_p (float): dropout probability, if None, dropout is unused + """ + if fc_dims is None: + self.feature_dim = input_dim + return None + + assert isinstance( + fc_dims, (list, tuple) + ), 'fc_dims must be either list or tuple, but got {}'.format( + type(fc_dims) + ) + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def featuremaps(self, x): + x = self.layer0(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + return x + + def forward(self, x): + f = self.featuremaps(x) + v = self.global_avgpool(f) + v = v.view(v.size(0), -1) + + if self.fc is not None: + v = self.fc(v) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def senet154(num_classes, loss='softmax', pretrained=True, **kwargs): + model = SENet( + num_classes=num_classes, + loss=loss, + block=SEBottleneck, + layers=[3, 8, 36, 3], + groups=64, + reduction=16, + dropout_p=0.2, + last_stride=2, + fc_dims=None, + **kwargs + ) + if pretrained: + model_url = pretrained_settings['senet154']['imagenet']['url'] + init_pretrained_weights(model, model_url) + return model + + +def se_resnet50(num_classes, loss='softmax', pretrained=True, **kwargs): + model = SENet( + num_classes=num_classes, + loss=loss, + block=SEResNetBottleneck, + layers=[3, 4, 6, 3], + groups=1, + reduction=16, + dropout_p=None, + inplanes=64, + input_3x3=False, + downsample_kernel_size=1, + downsample_padding=0, + last_stride=2, + fc_dims=None, + **kwargs + ) + if pretrained: + model_url = pretrained_settings['se_resnet50']['imagenet']['url'] + init_pretrained_weights(model, model_url) + return model + + +def se_resnet50_fc512(num_classes, loss='softmax', pretrained=True, **kwargs): + model = SENet( + num_classes=num_classes, + loss=loss, + block=SEResNetBottleneck, + layers=[3, 4, 6, 3], + groups=1, + reduction=16, + dropout_p=None, + inplanes=64, + input_3x3=False, + downsample_kernel_size=1, + downsample_padding=0, + last_stride=1, + fc_dims=[512], + **kwargs + ) + if pretrained: + model_url = pretrained_settings['se_resnet50']['imagenet']['url'] + init_pretrained_weights(model, model_url) + return model + + +def se_resnet101(num_classes, loss='softmax', pretrained=True, **kwargs): + model = SENet( + num_classes=num_classes, + loss=loss, + block=SEResNetBottleneck, + layers=[3, 4, 23, 3], + groups=1, + reduction=16, + dropout_p=None, + inplanes=64, + input_3x3=False, + downsample_kernel_size=1, + downsample_padding=0, + last_stride=2, + fc_dims=None, + **kwargs + ) + if pretrained: + model_url = pretrained_settings['se_resnet101']['imagenet']['url'] + init_pretrained_weights(model, model_url) + return model + + +def se_resnet152(num_classes, loss='softmax', pretrained=True, **kwargs): + model = SENet( + num_classes=num_classes, + loss=loss, + block=SEResNetBottleneck, + layers=[3, 8, 36, 3], + groups=1, + reduction=16, + dropout_p=None, + inplanes=64, + input_3x3=False, + downsample_kernel_size=1, + downsample_padding=0, + last_stride=2, + fc_dims=None, + **kwargs + ) + if pretrained: + model_url = pretrained_settings['se_resnet152']['imagenet']['url'] + init_pretrained_weights(model, model_url) + return model + + +def se_resnext50_32x4d(num_classes, loss='softmax', pretrained=True, **kwargs): + model = SENet( + num_classes=num_classes, + loss=loss, + block=SEResNeXtBottleneck, + layers=[3, 4, 6, 3], + groups=32, + reduction=16, + dropout_p=None, + inplanes=64, + input_3x3=False, + downsample_kernel_size=1, + downsample_padding=0, + last_stride=2, + fc_dims=None, + **kwargs + ) + if pretrained: + model_url = pretrained_settings['se_resnext50_32x4d']['imagenet']['url' + ] + init_pretrained_weights(model, model_url) + return model + + +def se_resnext101_32x4d( + num_classes, loss='softmax', pretrained=True, **kwargs +): + model = SENet( + num_classes=num_classes, + loss=loss, + block=SEResNeXtBottleneck, + layers=[3, 4, 23, 3], + groups=32, + reduction=16, + dropout_p=None, + inplanes=64, + input_3x3=False, + downsample_kernel_size=1, + downsample_padding=0, + last_stride=2, + fc_dims=None, + **kwargs + ) + if pretrained: + model_url = pretrained_settings['se_resnext101_32x4d']['imagenet'][ + 'url'] + init_pretrained_weights(model, model_url) + return model diff --git a/strong_sort/deep/reid/torchreid/models/shufflenet.py b/strong_sort/deep/reid/torchreid/models/shufflenet.py new file mode 100644 index 0000000000000000000000000000000000000000..bc4d34f1c4a631aa981cfb1797b036f23aed4503 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/shufflenet.py @@ -0,0 +1,198 @@ +from __future__ import division, absolute_import +import torch +import torch.utils.model_zoo as model_zoo +from torch import nn +from torch.nn import functional as F + +__all__ = ['shufflenet'] + +model_urls = { + # training epoch = 90, top1 = 61.8 + 'imagenet': + 'https://mega.nz/#!RDpUlQCY!tr_5xBEkelzDjveIYBBcGcovNCOrgfiJO9kiidz9fZM', +} + + +class ChannelShuffle(nn.Module): + + def __init__(self, num_groups): + super(ChannelShuffle, self).__init__() + self.g = num_groups + + def forward(self, x): + b, c, h, w = x.size() + n = c // self.g + # reshape + x = x.view(b, self.g, n, h, w) + # transpose + x = x.permute(0, 2, 1, 3, 4).contiguous() + # flatten + x = x.view(b, c, h, w) + return x + + +class Bottleneck(nn.Module): + + def __init__( + self, + in_channels, + out_channels, + stride, + num_groups, + group_conv1x1=True + ): + super(Bottleneck, self).__init__() + assert stride in [1, 2], 'Warning: stride must be either 1 or 2' + self.stride = stride + mid_channels = out_channels // 4 + if stride == 2: + out_channels -= in_channels + # group conv is not applied to first conv1x1 at stage 2 + num_groups_conv1x1 = num_groups if group_conv1x1 else 1 + self.conv1 = nn.Conv2d( + in_channels, + mid_channels, + 1, + groups=num_groups_conv1x1, + bias=False + ) + self.bn1 = nn.BatchNorm2d(mid_channels) + self.shuffle1 = ChannelShuffle(num_groups) + self.conv2 = nn.Conv2d( + mid_channels, + mid_channels, + 3, + stride=stride, + padding=1, + groups=mid_channels, + bias=False + ) + self.bn2 = nn.BatchNorm2d(mid_channels) + self.conv3 = nn.Conv2d( + mid_channels, out_channels, 1, groups=num_groups, bias=False + ) + self.bn3 = nn.BatchNorm2d(out_channels) + if stride == 2: + self.shortcut = nn.AvgPool2d(3, stride=2, padding=1) + + def forward(self, x): + out = F.relu(self.bn1(self.conv1(x))) + out = self.shuffle1(out) + out = self.bn2(self.conv2(out)) + out = self.bn3(self.conv3(out)) + if self.stride == 2: + res = self.shortcut(x) + out = F.relu(torch.cat([res, out], 1)) + else: + out = F.relu(x + out) + return out + + +# configuration of (num_groups: #out_channels) based on Table 1 in the paper +cfg = { + 1: [144, 288, 576], + 2: [200, 400, 800], + 3: [240, 480, 960], + 4: [272, 544, 1088], + 8: [384, 768, 1536], +} + + +class ShuffleNet(nn.Module): + """ShuffleNet. + + Reference: + Zhang et al. ShuffleNet: An Extremely Efficient Convolutional Neural + Network for Mobile Devices. CVPR 2018. + + Public keys: + - ``shufflenet``: ShuffleNet (groups=3). + """ + + def __init__(self, num_classes, loss='softmax', num_groups=3, **kwargs): + super(ShuffleNet, self).__init__() + self.loss = loss + + self.conv1 = nn.Sequential( + nn.Conv2d(3, 24, 3, stride=2, padding=1, bias=False), + nn.BatchNorm2d(24), + nn.ReLU(), + nn.MaxPool2d(3, stride=2, padding=1), + ) + + self.stage2 = nn.Sequential( + Bottleneck( + 24, cfg[num_groups][0], 2, num_groups, group_conv1x1=False + ), + Bottleneck(cfg[num_groups][0], cfg[num_groups][0], 1, num_groups), + Bottleneck(cfg[num_groups][0], cfg[num_groups][0], 1, num_groups), + Bottleneck(cfg[num_groups][0], cfg[num_groups][0], 1, num_groups), + ) + + self.stage3 = nn.Sequential( + Bottleneck(cfg[num_groups][0], cfg[num_groups][1], 2, num_groups), + Bottleneck(cfg[num_groups][1], cfg[num_groups][1], 1, num_groups), + Bottleneck(cfg[num_groups][1], cfg[num_groups][1], 1, num_groups), + Bottleneck(cfg[num_groups][1], cfg[num_groups][1], 1, num_groups), + Bottleneck(cfg[num_groups][1], cfg[num_groups][1], 1, num_groups), + Bottleneck(cfg[num_groups][1], cfg[num_groups][1], 1, num_groups), + Bottleneck(cfg[num_groups][1], cfg[num_groups][1], 1, num_groups), + Bottleneck(cfg[num_groups][1], cfg[num_groups][1], 1, num_groups), + ) + + self.stage4 = nn.Sequential( + Bottleneck(cfg[num_groups][1], cfg[num_groups][2], 2, num_groups), + Bottleneck(cfg[num_groups][2], cfg[num_groups][2], 1, num_groups), + Bottleneck(cfg[num_groups][2], cfg[num_groups][2], 1, num_groups), + Bottleneck(cfg[num_groups][2], cfg[num_groups][2], 1, num_groups), + ) + + self.classifier = nn.Linear(cfg[num_groups][2], num_classes) + self.feat_dim = cfg[num_groups][2] + + def forward(self, x): + x = self.conv1(x) + x = self.stage2(x) + x = self.stage3(x) + x = self.stage4(x) + x = F.avg_pool2d(x, x.size()[2:]).view(x.size(0), -1) + + if not self.training: + return x + + y = self.classifier(x) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, x + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def shufflenet(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ShuffleNet(num_classes, loss, **kwargs) + if pretrained: + # init_pretrained_weights(model, model_urls['imagenet']) + import warnings + warnings.warn( + 'The imagenet pretrained weights need to be manually downloaded from {}' + .format(model_urls['imagenet']) + ) + return model diff --git a/strong_sort/deep/reid/torchreid/models/shufflenetv2.py b/strong_sort/deep/reid/torchreid/models/shufflenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff879e8d731b4cb16a77cfa6892035656405f71 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/shufflenetv2.py @@ -0,0 +1,262 @@ +""" +Code source: https://github.com/pytorch/vision +""" +from __future__ import division, absolute_import +import torch +import torch.utils.model_zoo as model_zoo +from torch import nn + +__all__ = [ + 'shufflenet_v2_x0_5', 'shufflenet_v2_x1_0', 'shufflenet_v2_x1_5', + 'shufflenet_v2_x2_0' +] + +model_urls = { + 'shufflenetv2_x0.5': + 'https://download.pytorch.org/models/shufflenetv2_x0.5-f707e7126e.pth', + 'shufflenetv2_x1.0': + 'https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth', + 'shufflenetv2_x1.5': None, + 'shufflenetv2_x2.0': None, +} + + +def channel_shuffle(x, groups): + batchsize, num_channels, height, width = x.data.size() + channels_per_group = num_channels // groups + + # reshape + x = x.view(batchsize, groups, channels_per_group, height, width) + + x = torch.transpose(x, 1, 2).contiguous() + + # flatten + x = x.view(batchsize, -1, height, width) + + return x + + +class InvertedResidual(nn.Module): + + def __init__(self, inp, oup, stride): + super(InvertedResidual, self).__init__() + + if not (1 <= stride <= 3): + raise ValueError('illegal stride value') + self.stride = stride + + branch_features = oup // 2 + assert (self.stride != 1) or (inp == branch_features << 1) + + if self.stride > 1: + self.branch1 = nn.Sequential( + self.depthwise_conv( + inp, inp, kernel_size=3, stride=self.stride, padding=1 + ), + nn.BatchNorm2d(inp), + nn.Conv2d( + inp, + branch_features, + kernel_size=1, + stride=1, + padding=0, + bias=False + ), + nn.BatchNorm2d(branch_features), + nn.ReLU(inplace=True), + ) + + self.branch2 = nn.Sequential( + nn.Conv2d( + inp if (self.stride > 1) else branch_features, + branch_features, + kernel_size=1, + stride=1, + padding=0, + bias=False + ), + nn.BatchNorm2d(branch_features), + nn.ReLU(inplace=True), + self.depthwise_conv( + branch_features, + branch_features, + kernel_size=3, + stride=self.stride, + padding=1 + ), + nn.BatchNorm2d(branch_features), + nn.Conv2d( + branch_features, + branch_features, + kernel_size=1, + stride=1, + padding=0, + bias=False + ), + nn.BatchNorm2d(branch_features), + nn.ReLU(inplace=True), + ) + + @staticmethod + def depthwise_conv(i, o, kernel_size, stride=1, padding=0, bias=False): + return nn.Conv2d( + i, o, kernel_size, stride, padding, bias=bias, groups=i + ) + + def forward(self, x): + if self.stride == 1: + x1, x2 = x.chunk(2, dim=1) + out = torch.cat((x1, self.branch2(x2)), dim=1) + else: + out = torch.cat((self.branch1(x), self.branch2(x)), dim=1) + + out = channel_shuffle(out, 2) + + return out + + +class ShuffleNetV2(nn.Module): + """ShuffleNetV2. + + Reference: + Ma et al. ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design. ECCV 2018. + + Public keys: + - ``shufflenet_v2_x0_5``: ShuffleNetV2 x0.5. + - ``shufflenet_v2_x1_0``: ShuffleNetV2 x1.0. + - ``shufflenet_v2_x1_5``: ShuffleNetV2 x1.5. + - ``shufflenet_v2_x2_0``: ShuffleNetV2 x2.0. + """ + + def __init__( + self, num_classes, loss, stages_repeats, stages_out_channels, **kwargs + ): + super(ShuffleNetV2, self).__init__() + self.loss = loss + + if len(stages_repeats) != 3: + raise ValueError( + 'expected stages_repeats as list of 3 positive ints' + ) + if len(stages_out_channels) != 5: + raise ValueError( + 'expected stages_out_channels as list of 5 positive ints' + ) + self._stage_out_channels = stages_out_channels + + input_channels = 3 + output_channels = self._stage_out_channels[0] + self.conv1 = nn.Sequential( + nn.Conv2d(input_channels, output_channels, 3, 2, 1, bias=False), + nn.BatchNorm2d(output_channels), + nn.ReLU(inplace=True), + ) + input_channels = output_channels + + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + + stage_names = ['stage{}'.format(i) for i in [2, 3, 4]] + for name, repeats, output_channels in zip( + stage_names, stages_repeats, self._stage_out_channels[1:] + ): + seq = [InvertedResidual(input_channels, output_channels, 2)] + for i in range(repeats - 1): + seq.append( + InvertedResidual(output_channels, output_channels, 1) + ) + setattr(self, name, nn.Sequential(*seq)) + input_channels = output_channels + + output_channels = self._stage_out_channels[-1] + self.conv5 = nn.Sequential( + nn.Conv2d(input_channels, output_channels, 1, 1, 0, bias=False), + nn.BatchNorm2d(output_channels), + nn.ReLU(inplace=True), + ) + self.global_avgpool = nn.AdaptiveAvgPool2d((1, 1)) + + self.classifier = nn.Linear(output_channels, num_classes) + + def featuremaps(self, x): + x = self.conv1(x) + x = self.maxpool(x) + x = self.stage2(x) + x = self.stage3(x) + x = self.stage4(x) + x = self.conv5(x) + return x + + def forward(self, x): + f = self.featuremaps(x) + v = self.global_avgpool(f) + v = v.view(v.size(0), -1) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError("Unsupported loss: {}".format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + if model_url is None: + import warnings + warnings.warn( + 'ImageNet pretrained weights are unavailable for this model' + ) + return + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def shufflenet_v2_x0_5(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ShuffleNetV2( + num_classes, loss, [4, 8, 4], [24, 48, 96, 192, 1024], **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['shufflenetv2_x0.5']) + return model + + +def shufflenet_v2_x1_0(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ShuffleNetV2( + num_classes, loss, [4, 8, 4], [24, 116, 232, 464, 1024], **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['shufflenetv2_x1.0']) + return model + + +def shufflenet_v2_x1_5(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ShuffleNetV2( + num_classes, loss, [4, 8, 4], [24, 176, 352, 704, 1024], **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['shufflenetv2_x1.5']) + return model + + +def shufflenet_v2_x2_0(num_classes, loss='softmax', pretrained=True, **kwargs): + model = ShuffleNetV2( + num_classes, loss, [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['shufflenetv2_x2.0']) + return model diff --git a/strong_sort/deep/reid/torchreid/models/squeezenet.py b/strong_sort/deep/reid/torchreid/models/squeezenet.py new file mode 100644 index 0000000000000000000000000000000000000000..83e8dc9fc46b4e76304bf1b681a14ce5b865b993 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/squeezenet.py @@ -0,0 +1,236 @@ +""" +Code source: https://github.com/pytorch/vision +""" +from __future__ import division, absolute_import +import torch +import torch.nn as nn +import torch.utils.model_zoo as model_zoo + +__all__ = ['squeezenet1_0', 'squeezenet1_1', 'squeezenet1_0_fc512'] + +model_urls = { + 'squeezenet1_0': + 'https://download.pytorch.org/models/squeezenet1_0-a815701f.pth', + 'squeezenet1_1': + 'https://download.pytorch.org/models/squeezenet1_1-f364aa15.pth', +} + + +class Fire(nn.Module): + + def __init__( + self, inplanes, squeeze_planes, expand1x1_planes, expand3x3_planes + ): + super(Fire, self).__init__() + self.inplanes = inplanes + self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1) + self.squeeze_activation = nn.ReLU(inplace=True) + self.expand1x1 = nn.Conv2d( + squeeze_planes, expand1x1_planes, kernel_size=1 + ) + self.expand1x1_activation = nn.ReLU(inplace=True) + self.expand3x3 = nn.Conv2d( + squeeze_planes, expand3x3_planes, kernel_size=3, padding=1 + ) + self.expand3x3_activation = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.squeeze_activation(self.squeeze(x)) + return torch.cat( + [ + self.expand1x1_activation(self.expand1x1(x)), + self.expand3x3_activation(self.expand3x3(x)) + ], 1 + ) + + +class SqueezeNet(nn.Module): + """SqueezeNet. + + Reference: + Iandola et al. SqueezeNet: AlexNet-level accuracy with 50x fewer parameters + and< 0.5 MB model size. arXiv:1602.07360. + + Public keys: + - ``squeezenet1_0``: SqueezeNet (version=1.0). + - ``squeezenet1_1``: SqueezeNet (version=1.1). + - ``squeezenet1_0_fc512``: SqueezeNet (version=1.0) + FC. + """ + + def __init__( + self, + num_classes, + loss, + version=1.0, + fc_dims=None, + dropout_p=None, + **kwargs + ): + super(SqueezeNet, self).__init__() + self.loss = loss + self.feature_dim = 512 + + if version not in [1.0, 1.1]: + raise ValueError( + 'Unsupported SqueezeNet version {version}:' + '1.0 or 1.1 expected'.format(version=version) + ) + + if version == 1.0: + self.features = nn.Sequential( + nn.Conv2d(3, 96, kernel_size=7, stride=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(96, 16, 64, 64), + Fire(128, 16, 64, 64), + Fire(128, 32, 128, 128), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(256, 32, 128, 128), + Fire(256, 48, 192, 192), + Fire(384, 48, 192, 192), + Fire(384, 64, 256, 256), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(512, 64, 256, 256), + ) + else: + self.features = nn.Sequential( + nn.Conv2d(3, 64, kernel_size=3, stride=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(64, 16, 64, 64), + Fire(128, 16, 64, 64), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(128, 32, 128, 128), + Fire(256, 32, 128, 128), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(256, 48, 192, 192), + Fire(384, 48, 192, 192), + Fire(384, 64, 256, 256), + Fire(512, 64, 256, 256), + ) + + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.fc = self._construct_fc_layer(fc_dims, 512, dropout_p) + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self._init_params() + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + """Constructs fully connected layer + + Args: + fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed + input_dim (int): input dimension + dropout_p (float): dropout probability, if None, dropout is unused + """ + if fc_dims is None: + self.feature_dim = input_dim + return None + + assert isinstance( + fc_dims, (list, tuple) + ), 'fc_dims must be either list or tuple, but got {}'.format( + type(fc_dims) + ) + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x): + f = self.features(x) + v = self.global_avgpool(f) + v = v.view(v.size(0), -1) + + if self.fc is not None: + v = self.fc(v) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initializes model with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url, map_location=None) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def squeezenet1_0(num_classes, loss='softmax', pretrained=True, **kwargs): + model = SqueezeNet( + num_classes, loss, version=1.0, fc_dims=None, dropout_p=None, **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['squeezenet1_0']) + return model + + +def squeezenet1_0_fc512( + num_classes, loss='softmax', pretrained=True, **kwargs +): + model = SqueezeNet( + num_classes, + loss, + version=1.0, + fc_dims=[512], + dropout_p=None, + **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['squeezenet1_0']) + return model + + +def squeezenet1_1(num_classes, loss='softmax', pretrained=True, **kwargs): + model = SqueezeNet( + num_classes, loss, version=1.1, fc_dims=None, dropout_p=None, **kwargs + ) + if pretrained: + init_pretrained_weights(model, model_urls['squeezenet1_1']) + return model diff --git a/strong_sort/deep/reid/torchreid/models/xception.py b/strong_sort/deep/reid/torchreid/models/xception.py new file mode 100644 index 0000000000000000000000000000000000000000..43db4ab53283daf1267f2f4cc5f7d778daf4076a --- /dev/null +++ b/strong_sort/deep/reid/torchreid/models/xception.py @@ -0,0 +1,344 @@ +from __future__ import division, absolute_import +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.model_zoo as model_zoo + +__all__ = ['xception'] + +pretrained_settings = { + 'xception': { + 'imagenet': { + 'url': + 'http://data.lip6.fr/cadene/pretrainedmodels/xception-43020ad28.pth', + 'input_space': 'RGB', + 'input_size': [3, 299, 299], + 'input_range': [0, 1], + 'mean': [0.5, 0.5, 0.5], + 'std': [0.5, 0.5, 0.5], + 'num_classes': 1000, + 'scale': + 0.8975 # The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299 + } + } +} + + +class SeparableConv2d(nn.Module): + + def __init__( + self, + in_channels, + out_channels, + kernel_size=1, + stride=1, + padding=0, + dilation=1, + bias=False + ): + super(SeparableConv2d, self).__init__() + + self.conv1 = nn.Conv2d( + in_channels, + in_channels, + kernel_size, + stride, + padding, + dilation, + groups=in_channels, + bias=bias + ) + self.pointwise = nn.Conv2d( + in_channels, out_channels, 1, 1, 0, 1, 1, bias=bias + ) + + def forward(self, x): + x = self.conv1(x) + x = self.pointwise(x) + return x + + +class Block(nn.Module): + + def __init__( + self, + in_filters, + out_filters, + reps, + strides=1, + start_with_relu=True, + grow_first=True + ): + super(Block, self).__init__() + + if out_filters != in_filters or strides != 1: + self.skip = nn.Conv2d( + in_filters, out_filters, 1, stride=strides, bias=False + ) + self.skipbn = nn.BatchNorm2d(out_filters) + else: + self.skip = None + + self.relu = nn.ReLU(inplace=True) + rep = [] + + filters = in_filters + if grow_first: + rep.append(self.relu) + rep.append( + SeparableConv2d( + in_filters, + out_filters, + 3, + stride=1, + padding=1, + bias=False + ) + ) + rep.append(nn.BatchNorm2d(out_filters)) + filters = out_filters + + for i in range(reps - 1): + rep.append(self.relu) + rep.append( + SeparableConv2d( + filters, filters, 3, stride=1, padding=1, bias=False + ) + ) + rep.append(nn.BatchNorm2d(filters)) + + if not grow_first: + rep.append(self.relu) + rep.append( + SeparableConv2d( + in_filters, + out_filters, + 3, + stride=1, + padding=1, + bias=False + ) + ) + rep.append(nn.BatchNorm2d(out_filters)) + + if not start_with_relu: + rep = rep[1:] + else: + rep[0] = nn.ReLU(inplace=False) + + if strides != 1: + rep.append(nn.MaxPool2d(3, strides, 1)) + self.rep = nn.Sequential(*rep) + + def forward(self, inp): + x = self.rep(inp) + + if self.skip is not None: + skip = self.skip(inp) + skip = self.skipbn(skip) + else: + skip = inp + + x += skip + return x + + +class Xception(nn.Module): + """Xception. + + Reference: + Chollet. Xception: Deep Learning with Depthwise + Separable Convolutions. CVPR 2017. + + Public keys: + - ``xception``: Xception. + """ + + def __init__( + self, num_classes, loss, fc_dims=None, dropout_p=None, **kwargs + ): + super(Xception, self).__init__() + self.loss = loss + + self.conv1 = nn.Conv2d(3, 32, 3, 2, 0, bias=False) + self.bn1 = nn.BatchNorm2d(32) + + self.conv2 = nn.Conv2d(32, 64, 3, bias=False) + self.bn2 = nn.BatchNorm2d(64) + + self.block1 = Block( + 64, 128, 2, 2, start_with_relu=False, grow_first=True + ) + self.block2 = Block( + 128, 256, 2, 2, start_with_relu=True, grow_first=True + ) + self.block3 = Block( + 256, 728, 2, 2, start_with_relu=True, grow_first=True + ) + + self.block4 = Block( + 728, 728, 3, 1, start_with_relu=True, grow_first=True + ) + self.block5 = Block( + 728, 728, 3, 1, start_with_relu=True, grow_first=True + ) + self.block6 = Block( + 728, 728, 3, 1, start_with_relu=True, grow_first=True + ) + self.block7 = Block( + 728, 728, 3, 1, start_with_relu=True, grow_first=True + ) + + self.block8 = Block( + 728, 728, 3, 1, start_with_relu=True, grow_first=True + ) + self.block9 = Block( + 728, 728, 3, 1, start_with_relu=True, grow_first=True + ) + self.block10 = Block( + 728, 728, 3, 1, start_with_relu=True, grow_first=True + ) + self.block11 = Block( + 728, 728, 3, 1, start_with_relu=True, grow_first=True + ) + + self.block12 = Block( + 728, 1024, 2, 2, start_with_relu=True, grow_first=False + ) + + self.conv3 = SeparableConv2d(1024, 1536, 3, 1, 1) + self.bn3 = nn.BatchNorm2d(1536) + + self.conv4 = SeparableConv2d(1536, 2048, 3, 1, 1) + self.bn4 = nn.BatchNorm2d(2048) + + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.feature_dim = 2048 + self.fc = self._construct_fc_layer(fc_dims, 2048, dropout_p) + self.classifier = nn.Linear(self.feature_dim, num_classes) + + self._init_params() + + def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): + """Constructs fully connected layer. + + Args: + fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed + input_dim (int): input dimension + dropout_p (float): dropout probability, if None, dropout is unused + """ + if fc_dims is None: + self.feature_dim = input_dim + return None + + assert isinstance( + fc_dims, (list, tuple) + ), 'fc_dims must be either list or tuple, but got {}'.format( + type(fc_dims) + ) + + layers = [] + for dim in fc_dims: + layers.append(nn.Linear(input_dim, dim)) + layers.append(nn.BatchNorm1d(dim)) + layers.append(nn.ReLU(inplace=True)) + if dropout_p is not None: + layers.append(nn.Dropout(p=dropout_p)) + input_dim = dim + + self.feature_dim = fc_dims[-1] + + return nn.Sequential(*layers) + + def _init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu' + ) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm1d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def featuremaps(self, input): + x = self.conv1(input) + x = self.bn1(x) + x = F.relu(x, inplace=True) + + x = self.conv2(x) + x = self.bn2(x) + x = F.relu(x, inplace=True) + + x = self.block1(x) + x = self.block2(x) + x = self.block3(x) + x = self.block4(x) + x = self.block5(x) + x = self.block6(x) + x = self.block7(x) + x = self.block8(x) + x = self.block9(x) + x = self.block10(x) + x = self.block11(x) + x = self.block12(x) + + x = self.conv3(x) + x = self.bn3(x) + x = F.relu(x, inplace=True) + + x = self.conv4(x) + x = self.bn4(x) + x = F.relu(x, inplace=True) + return x + + def forward(self, x): + f = self.featuremaps(x) + v = self.global_avgpool(f) + v = v.view(v.size(0), -1) + + if self.fc is not None: + v = self.fc(v) + + if not self.training: + return v + + y = self.classifier(v) + + if self.loss == 'softmax': + return y + elif self.loss == 'triplet': + return y, v + else: + raise KeyError('Unsupported loss: {}'.format(self.loss)) + + +def init_pretrained_weights(model, model_url): + """Initialize models with pretrained weights. + + Layers that don't match with pretrained layers in name or size are kept unchanged. + """ + pretrain_dict = model_zoo.load_url(model_url) + model_dict = model.state_dict() + pretrain_dict = { + k: v + for k, v in pretrain_dict.items() + if k in model_dict and model_dict[k].size() == v.size() + } + model_dict.update(pretrain_dict) + model.load_state_dict(model_dict) + + +def xception(num_classes, loss='softmax', pretrained=True, **kwargs): + model = Xception(num_classes, loss, fc_dims=None, dropout_p=None, **kwargs) + if pretrained: + model_url = pretrained_settings['xception']['imagenet']['url'] + init_pretrained_weights(model, model_url) + return model diff --git a/strong_sort/deep/reid/torchreid/optim/__init__.py b/strong_sort/deep/reid/torchreid/optim/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1813e465741cf723c570f9dccf221bd186172dd4 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/optim/__init__.py @@ -0,0 +1,4 @@ +from __future__ import absolute_import + +from .optimizer import build_optimizer +from .lr_scheduler import build_lr_scheduler diff --git a/strong_sort/deep/reid/torchreid/optim/lr_scheduler.py b/strong_sort/deep/reid/torchreid/optim/lr_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..d60bd1dc237372b068f80d6867d4ca3b1709ad07 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/optim/lr_scheduler.py @@ -0,0 +1,68 @@ +from __future__ import print_function, absolute_import +import torch + +AVAI_SCH = ['single_step', 'multi_step', 'cosine'] + + +def build_lr_scheduler( + optimizer, lr_scheduler='single_step', stepsize=1, gamma=0.1, max_epoch=1 +): + """A function wrapper for building a learning rate scheduler. + + Args: + optimizer (Optimizer): an Optimizer. + lr_scheduler (str, optional): learning rate scheduler method. Default is single_step. + stepsize (int or list, optional): step size to decay learning rate. When ``lr_scheduler`` + is "single_step", ``stepsize`` should be an integer. When ``lr_scheduler`` is + "multi_step", ``stepsize`` is a list. Default is 1. + gamma (float, optional): decay rate. Default is 0.1. + max_epoch (int, optional): maximum epoch (for cosine annealing). Default is 1. + + Examples:: + >>> # Decay learning rate by every 20 epochs. + >>> scheduler = torchreid.optim.build_lr_scheduler( + >>> optimizer, lr_scheduler='single_step', stepsize=20 + >>> ) + >>> # Decay learning rate at 30, 50 and 55 epochs. + >>> scheduler = torchreid.optim.build_lr_scheduler( + >>> optimizer, lr_scheduler='multi_step', stepsize=[30, 50, 55] + >>> ) + """ + if lr_scheduler not in AVAI_SCH: + raise ValueError( + 'Unsupported scheduler: {}. Must be one of {}'.format( + lr_scheduler, AVAI_SCH + ) + ) + + if lr_scheduler == 'single_step': + if isinstance(stepsize, list): + stepsize = stepsize[-1] + + if not isinstance(stepsize, int): + raise TypeError( + 'For single_step lr_scheduler, stepsize must ' + 'be an integer, but got {}'.format(type(stepsize)) + ) + + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=stepsize, gamma=gamma + ) + + elif lr_scheduler == 'multi_step': + if not isinstance(stepsize, list): + raise TypeError( + 'For multi_step lr_scheduler, stepsize must ' + 'be a list, but got {}'.format(type(stepsize)) + ) + + scheduler = torch.optim.lr_scheduler.MultiStepLR( + optimizer, milestones=stepsize, gamma=gamma + ) + + elif lr_scheduler == 'cosine': + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, float(max_epoch) + ) + + return scheduler diff --git a/strong_sort/deep/reid/torchreid/optim/optimizer.py b/strong_sort/deep/reid/torchreid/optim/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..f57b03a0537b9596c3e072eeb8800cd6e54051ca --- /dev/null +++ b/strong_sort/deep/reid/torchreid/optim/optimizer.py @@ -0,0 +1,157 @@ +from __future__ import print_function, absolute_import +import warnings +import torch +import torch.nn as nn + +from .radam import RAdam + +AVAI_OPTIMS = ['adam', 'amsgrad', 'sgd', 'rmsprop', 'radam'] + + +def build_optimizer( + model, + optim='adam', + lr=0.0003, + weight_decay=5e-04, + momentum=0.9, + sgd_dampening=0, + sgd_nesterov=False, + rmsprop_alpha=0.99, + adam_beta1=0.9, + adam_beta2=0.99, + staged_lr=False, + new_layers='', + base_lr_mult=0.1 +): + """A function wrapper for building an optimizer. + + Args: + model (nn.Module): model. + optim (str, optional): optimizer. Default is "adam". + lr (float, optional): learning rate. Default is 0.0003. + weight_decay (float, optional): weight decay (L2 penalty). Default is 5e-04. + momentum (float, optional): momentum factor in sgd. Default is 0.9, + sgd_dampening (float, optional): dampening for momentum. Default is 0. + sgd_nesterov (bool, optional): enables Nesterov momentum. Default is False. + rmsprop_alpha (float, optional): smoothing constant for rmsprop. Default is 0.99. + adam_beta1 (float, optional): beta-1 value in adam. Default is 0.9. + adam_beta2 (float, optional): beta-2 value in adam. Default is 0.99, + staged_lr (bool, optional): uses different learning rates for base and new layers. Base + layers are pretrained layers while new layers are randomly initialized, e.g. the + identity classification layer. Enabling ``staged_lr`` can allow the base layers to + be trained with a smaller learning rate determined by ``base_lr_mult``, while the new + layers will take the ``lr``. Default is False. + new_layers (str or list): attribute names in ``model``. Default is empty. + base_lr_mult (float, optional): learning rate multiplier for base layers. Default is 0.1. + + Examples:: + >>> # A normal optimizer can be built by + >>> optimizer = torchreid.optim.build_optimizer(model, optim='sgd', lr=0.01) + >>> # If you want to use a smaller learning rate for pretrained layers + >>> # and the attribute name for the randomly initialized layer is 'classifier', + >>> # you can do + >>> optimizer = torchreid.optim.build_optimizer( + >>> model, optim='sgd', lr=0.01, staged_lr=True, + >>> new_layers='classifier', base_lr_mult=0.1 + >>> ) + >>> # Now the `classifier` has learning rate 0.01 but the base layers + >>> # have learning rate 0.01 * 0.1. + >>> # new_layers can also take multiple attribute names. Say the new layers + >>> # are 'fc' and 'classifier', you can do + >>> optimizer = torchreid.optim.build_optimizer( + >>> model, optim='sgd', lr=0.01, staged_lr=True, + >>> new_layers=['fc', 'classifier'], base_lr_mult=0.1 + >>> ) + """ + if optim not in AVAI_OPTIMS: + raise ValueError( + 'Unsupported optim: {}. Must be one of {}'.format( + optim, AVAI_OPTIMS + ) + ) + + if not isinstance(model, nn.Module): + raise TypeError( + 'model given to build_optimizer must be an instance of nn.Module' + ) + + if staged_lr: + if isinstance(new_layers, str): + if new_layers is None: + warnings.warn( + 'new_layers is empty, therefore, staged_lr is useless' + ) + new_layers = [new_layers] + + if isinstance(model, nn.DataParallel): + model = model.module + + base_params = [] + base_layers = [] + new_params = [] + + for name, module in model.named_children(): + if name in new_layers: + new_params += [p for p in module.parameters()] + else: + base_params += [p for p in module.parameters()] + base_layers.append(name) + + param_groups = [ + { + 'params': base_params, + 'lr': lr * base_lr_mult + }, + { + 'params': new_params + }, + ] + + else: + param_groups = model.parameters() + + if optim == 'adam': + optimizer = torch.optim.Adam( + param_groups, + lr=lr, + weight_decay=weight_decay, + betas=(adam_beta1, adam_beta2), + ) + + elif optim == 'amsgrad': + optimizer = torch.optim.Adam( + param_groups, + lr=lr, + weight_decay=weight_decay, + betas=(adam_beta1, adam_beta2), + amsgrad=True, + ) + + elif optim == 'sgd': + optimizer = torch.optim.SGD( + param_groups, + lr=lr, + momentum=momentum, + weight_decay=weight_decay, + dampening=sgd_dampening, + nesterov=sgd_nesterov, + ) + + elif optim == 'rmsprop': + optimizer = torch.optim.RMSprop( + param_groups, + lr=lr, + momentum=momentum, + weight_decay=weight_decay, + alpha=rmsprop_alpha, + ) + + elif optim == 'radam': + optimizer = RAdam( + param_groups, + lr=lr, + weight_decay=weight_decay, + betas=(adam_beta1, adam_beta2) + ) + + return optimizer diff --git a/strong_sort/deep/reid/torchreid/optim/radam.py b/strong_sort/deep/reid/torchreid/optim/radam.py new file mode 100644 index 0000000000000000000000000000000000000000..f066c573f8b650a6162f0b54a1c2c100b2679f3b --- /dev/null +++ b/strong_sort/deep/reid/torchreid/optim/radam.py @@ -0,0 +1,330 @@ +""" +Imported from: https://github.com/LiyuanLucasLiu/RAdam + +Paper: https://arxiv.org/abs/1908.03265 + +@article{liu2019radam, + title={On the Variance of the Adaptive Learning Rate and Beyond}, + author={Liu, Liyuan and Jiang, Haoming and He, Pengcheng and Chen, Weizhu and Liu, Xiaodong and Gao, Jianfeng and Han, Jiawei}, + journal={arXiv preprint arXiv:1908.03265}, + year={2019} +} +""" +from __future__ import print_function, absolute_import +import math +import torch +from torch.optim.optimizer import Optimizer + + +class RAdam(Optimizer): + + def __init__( + self, + params, + lr=1e-3, + betas=(0.9, 0.999), + eps=1e-8, + weight_decay=0, + degenerated_to_sgd=True + ): + if not 0.0 <= lr: + raise ValueError("Invalid learning rate: {}".format(lr)) + if not 0.0 <= eps: + raise ValueError("Invalid epsilon value: {}".format(eps)) + if not 0.0 <= betas[0] < 1.0: + raise ValueError( + "Invalid beta parameter at index 0: {}".format(betas[0]) + ) + if not 0.0 <= betas[1] < 1.0: + raise ValueError( + "Invalid beta parameter at index 1: {}".format(betas[1]) + ) + + self.degenerated_to_sgd = degenerated_to_sgd + defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) + self.buffer = [[None, None, None] for ind in range(10)] + super(RAdam, self).__init__(params, defaults) + + def __setstate__(self, state): + super(RAdam, self).__setstate__(state) + + def step(self, closure=None): + + loss = None + if closure is not None: + loss = closure() + + for group in self.param_groups: + + for p in group['params']: + if p.grad is None: + continue + grad = p.grad.data.float() + if grad.is_sparse: + raise RuntimeError( + 'RAdam does not support sparse gradients' + ) + + p_data_fp32 = p.data.float() + + state = self.state[p] + + if len(state) == 0: + state['step'] = 0 + state['exp_avg'] = torch.zeros_like(p_data_fp32) + state['exp_avg_sq'] = torch.zeros_like(p_data_fp32) + else: + state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32) + state['exp_avg_sq'] = state['exp_avg_sq'].type_as( + p_data_fp32 + ) + + exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] + beta1, beta2 = group['betas'] + + exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) + exp_avg.mul_(beta1).add_(1 - beta1, grad) + + state['step'] += 1 + buffered = self.buffer[int(state['step'] % 10)] + if state['step'] == buffered[0]: + N_sma, step_size = buffered[1], buffered[2] + else: + buffered[0] = state['step'] + beta2_t = beta2**state['step'] + N_sma_max = 2 / (1-beta2) - 1 + N_sma = N_sma_max - 2 * state['step' + ] * beta2_t / (1-beta2_t) + buffered[1] = N_sma + + # more conservative since it's an approximated value + if N_sma >= 5: + step_size = math.sqrt( + (1-beta2_t) * (N_sma-4) / (N_sma_max-4) * + (N_sma-2) / N_sma * N_sma_max / (N_sma_max-2) + ) / (1 - beta1**state['step']) + elif self.degenerated_to_sgd: + step_size = 1.0 / (1 - beta1**state['step']) + else: + step_size = -1 + buffered[2] = step_size + + # more conservative since it's an approximated value + if N_sma >= 5: + if group['weight_decay'] != 0: + p_data_fp32.add_( + -group['weight_decay'] * group['lr'], p_data_fp32 + ) + denom = exp_avg_sq.sqrt().add_(group['eps']) + p_data_fp32.addcdiv_( + -step_size * group['lr'], exp_avg, denom + ) + p.data.copy_(p_data_fp32) + elif step_size > 0: + if group['weight_decay'] != 0: + p_data_fp32.add_( + -group['weight_decay'] * group['lr'], p_data_fp32 + ) + p_data_fp32.add_(-step_size * group['lr'], exp_avg) + p.data.copy_(p_data_fp32) + + return loss + + +class PlainRAdam(Optimizer): + + def __init__( + self, + params, + lr=1e-3, + betas=(0.9, 0.999), + eps=1e-8, + weight_decay=0, + degenerated_to_sgd=True + ): + if not 0.0 <= lr: + raise ValueError("Invalid learning rate: {}".format(lr)) + if not 0.0 <= eps: + raise ValueError("Invalid epsilon value: {}".format(eps)) + if not 0.0 <= betas[0] < 1.0: + raise ValueError( + "Invalid beta parameter at index 0: {}".format(betas[0]) + ) + if not 0.0 <= betas[1] < 1.0: + raise ValueError( + "Invalid beta parameter at index 1: {}".format(betas[1]) + ) + + self.degenerated_to_sgd = degenerated_to_sgd + defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) + + super(PlainRAdam, self).__init__(params, defaults) + + def __setstate__(self, state): + super(PlainRAdam, self).__setstate__(state) + + def step(self, closure=None): + + loss = None + if closure is not None: + loss = closure() + + for group in self.param_groups: + + for p in group['params']: + if p.grad is None: + continue + grad = p.grad.data.float() + if grad.is_sparse: + raise RuntimeError( + 'RAdam does not support sparse gradients' + ) + + p_data_fp32 = p.data.float() + + state = self.state[p] + + if len(state) == 0: + state['step'] = 0 + state['exp_avg'] = torch.zeros_like(p_data_fp32) + state['exp_avg_sq'] = torch.zeros_like(p_data_fp32) + else: + state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32) + state['exp_avg_sq'] = state['exp_avg_sq'].type_as( + p_data_fp32 + ) + + exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] + beta1, beta2 = group['betas'] + + exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) + exp_avg.mul_(beta1).add_(1 - beta1, grad) + + state['step'] += 1 + beta2_t = beta2**state['step'] + N_sma_max = 2 / (1-beta2) - 1 + N_sma = N_sma_max - 2 * state['step'] * beta2_t / (1-beta2_t) + + # more conservative since it's an approximated value + if N_sma >= 5: + if group['weight_decay'] != 0: + p_data_fp32.add_( + -group['weight_decay'] * group['lr'], p_data_fp32 + ) + step_size = group['lr'] * math.sqrt( + (1-beta2_t) * (N_sma-4) / (N_sma_max-4) * + (N_sma-2) / N_sma * N_sma_max / (N_sma_max-2) + ) / (1 - beta1**state['step']) + denom = exp_avg_sq.sqrt().add_(group['eps']) + p_data_fp32.addcdiv_(-step_size, exp_avg, denom) + p.data.copy_(p_data_fp32) + elif self.degenerated_to_sgd: + if group['weight_decay'] != 0: + p_data_fp32.add_( + -group['weight_decay'] * group['lr'], p_data_fp32 + ) + step_size = group['lr'] / (1 - beta1**state['step']) + p_data_fp32.add_(-step_size, exp_avg) + p.data.copy_(p_data_fp32) + + return loss + + +class AdamW(Optimizer): + + def __init__( + self, + params, + lr=1e-3, + betas=(0.9, 0.999), + eps=1e-8, + weight_decay=0, + warmup=0 + ): + if not 0.0 <= lr: + raise ValueError("Invalid learning rate: {}".format(lr)) + if not 0.0 <= eps: + raise ValueError("Invalid epsilon value: {}".format(eps)) + if not 0.0 <= betas[0] < 1.0: + raise ValueError( + "Invalid beta parameter at index 0: {}".format(betas[0]) + ) + if not 0.0 <= betas[1] < 1.0: + raise ValueError( + "Invalid beta parameter at index 1: {}".format(betas[1]) + ) + + defaults = dict( + lr=lr, + betas=betas, + eps=eps, + weight_decay=weight_decay, + warmup=warmup + ) + super(AdamW, self).__init__(params, defaults) + + def __setstate__(self, state): + super(AdamW, self).__setstate__(state) + + def step(self, closure=None): + loss = None + if closure is not None: + loss = closure() + + for group in self.param_groups: + + for p in group['params']: + if p.grad is None: + continue + grad = p.grad.data.float() + if grad.is_sparse: + raise RuntimeError( + 'Adam does not support sparse gradients, please consider SparseAdam instead' + ) + + p_data_fp32 = p.data.float() + + state = self.state[p] + + if len(state) == 0: + state['step'] = 0 + state['exp_avg'] = torch.zeros_like(p_data_fp32) + state['exp_avg_sq'] = torch.zeros_like(p_data_fp32) + else: + state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32) + state['exp_avg_sq'] = state['exp_avg_sq'].type_as( + p_data_fp32 + ) + + exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] + beta1, beta2 = group['betas'] + + state['step'] += 1 + + exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) + exp_avg.mul_(beta1).add_(1 - beta1, grad) + + denom = exp_avg_sq.sqrt().add_(group['eps']) + bias_correction1 = 1 - beta1**state['step'] + bias_correction2 = 1 - beta2**state['step'] + + if group['warmup'] > state['step']: + scheduled_lr = 1e-8 + state['step'] * group['lr'] / group[ + 'warmup'] + else: + scheduled_lr = group['lr'] + + step_size = scheduled_lr * math.sqrt( + bias_correction2 + ) / bias_correction1 + + if group['weight_decay'] != 0: + p_data_fp32.add_( + -group['weight_decay'] * scheduled_lr, p_data_fp32 + ) + + p_data_fp32.addcdiv_(-step_size, exp_avg, denom) + + p.data.copy_(p_data_fp32) + + return loss diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/README.md b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/README.md new file mode 100644 index 0000000000000000000000000000000000000000..349a9ef637309852f0628151f010058bf4f1a4cc --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/README.md @@ -0,0 +1,37 @@ +# Understanding Image Retrieval Re-Ranking: A Graph Neural Network Perspective + +[[Paper]](https://arxiv.org/abs/2012.07620v2) + +On the Market-1501 dataset, we accelerate the re-ranking processing from **89.2s** to **9.4ms** with one K40m GPU, facilitating the real-time post-processing. +Similarly, we observe that our method achieves comparable or even better retrieval results on the other four image retrieval benchmarks, +i.e., VeRi-776, Oxford-5k, Paris-6k and University-1652, with limited time cost. + +## Prerequisites + +The code was mainly developed and tested with python 3.7, PyTorch 1.4.1, CUDA 10.2, and CentOS release 6.10. + +The code has been included in `/extension`. To compile it: + +```shell +cd extension +sh make.sh +``` + +## Demo + +The demo script `main.py` provides the gnn re-ranking method using the prepared feature. + +```shell +python main.py --data_path PATH_TO_DATA --k1 26 --k2 7 +``` + +## Citation +```bibtex +@article{zhang2020understanding, + title={Understanding Image Retrieval Re-Ranking: A Graph Neural Network Perspective}, + author={Xuanmeng Zhang, Minyue Jiang, Zhedong Zheng, Xiao Tan, Errui Ding, Yi Yang}, + journal={arXiv preprint arXiv:2012.07620}, + year={2020} +} +``` + diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/adjacency_matrix/build_adjacency_matrix.cpp b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/adjacency_matrix/build_adjacency_matrix.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c496041e37e525af728794f11627a7e0027a267 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/adjacency_matrix/build_adjacency_matrix.cpp @@ -0,0 +1,19 @@ +#include +#include +#include + +at::Tensor build_adjacency_matrix_forward(torch::Tensor initial_rank); + + +#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") +#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) + +at::Tensor build_adjacency_matrix(at::Tensor initial_rank) { + CHECK_INPUT(initial_rank); + return build_adjacency_matrix_forward(initial_rank); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward", &build_adjacency_matrix, "build_adjacency_matrix (CUDA)"); +} diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/adjacency_matrix/build_adjacency_matrix_kernel.cu b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/adjacency_matrix/build_adjacency_matrix_kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..4973ddefeaa4253291bb9d34fbbbb50a46c32b8a --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/adjacency_matrix/build_adjacency_matrix_kernel.cu @@ -0,0 +1,31 @@ +#include + +#include +#include +#include + +#define CUDA_1D_KERNEL_LOOP(i, n) for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += blockDim.x * gridDim.x) + + +__global__ void build_adjacency_matrix_kernel(float* initial_rank, float* A, const int total_num, const int topk, const int nthreads, const int all_num) { + int index = blockIdx.x * blockDim.x + threadIdx.x; + int stride = blockDim.x * gridDim.x; + for (int i = index; i < all_num; i += stride) { + int ii = i / topk; + A[ii * total_num + int(initial_rank[i])] = float(1.0); + } +} + +at::Tensor build_adjacency_matrix_forward(at::Tensor initial_rank) { + const auto total_num = initial_rank.size(0); + const auto topk = initial_rank.size(1); + const auto all_num = total_num * topk; + auto A = torch::zeros({total_num, total_num}, at::device(initial_rank.device()).dtype(at::ScalarType::Float)); + + const int threads = 1024; + const int blocks = (all_num + threads - 1) / threads; + + build_adjacency_matrix_kernel<<>>(initial_rank.data_ptr(), A.data_ptr(), total_num, topk, threads, all_num); + return A; + +} diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/adjacency_matrix/setup.py b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/adjacency_matrix/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..abd3e3a4e1fbd1db7b4bdd1d080d48381082c60a --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/adjacency_matrix/setup.py @@ -0,0 +1,36 @@ +""" + Understanding Image Retrieval Re-Ranking: A Graph Neural Network Perspective + + Xuanmeng Zhang, Minyue Jiang, Zhedong Zheng, Xiao Tan, Errui Ding, Yi Yang + + Project Page : https://github.com/Xuanmeng-Zhang/gnn-re-ranking + + Paper: https://arxiv.org/abs/2012.07620v2 + + ====================================================================== + + On the Market-1501 dataset, we accelerate the re-ranking processing from 89.2s to 9.4ms + with one K40m GPU, facilitating the real-time post-processing. Similarly, we observe + that our method achieves comparable or even better retrieval results on the other four + image retrieval benchmarks, i.e., VeRi-776, Oxford-5k, Paris-6k and University-1652, + with limited time cost. +""" + +from setuptools import Extension, setup +import torch +import torch.nn as nn +from torch.autograd import Function +from torch.utils.cpp_extension import CUDAExtension, BuildExtension + +setup( + name='build_adjacency_matrix', + ext_modules=[ + CUDAExtension( + 'build_adjacency_matrix', [ + 'build_adjacency_matrix.cpp', + 'build_adjacency_matrix_kernel.cu', + ] + ), + ], + cmdclass={'build_ext': BuildExtension} +) diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/make.sh b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/make.sh new file mode 100644 index 0000000000000000000000000000000000000000..f0197ff9c964cfa7b6496a29b8411da01d323568 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/make.sh @@ -0,0 +1,4 @@ +cd adjacency_matrix +python setup.py install +cd ../propagation +python setup.py install \ No newline at end of file diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/propagation/gnn_propagate.cpp b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/propagation/gnn_propagate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..10a939ffe7fb0ed73dd450d6bfc667132448dfca --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/propagation/gnn_propagate.cpp @@ -0,0 +1,21 @@ +#include +#include +#include + +at::Tensor gnn_propagate_forward(at::Tensor A, at::Tensor initial_rank, at::Tensor S); + + +#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") +#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) + +at::Tensor gnn_propagate(at::Tensor A ,at::Tensor initial_rank, at::Tensor S) { + CHECK_INPUT(A); + CHECK_INPUT(initial_rank); + CHECK_INPUT(S); + return gnn_propagate_forward(A, initial_rank, S); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward", &gnn_propagate, "gnn propagate (CUDA)"); +} \ No newline at end of file diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/propagation/gnn_propagate_kernel.cu b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/propagation/gnn_propagate_kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..8bdebf1666e16f3fbdd294d374e6438e667f96a1 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/propagation/gnn_propagate_kernel.cu @@ -0,0 +1,36 @@ +#include + +#include +#include +#include +#include + +__global__ void gnn_propagate_forward_kernel(float* initial_rank, float* A, float* A_qe, float* S, const int sample_num, const int topk, const int total_num) { + int index = blockIdx.x * blockDim.x + threadIdx.x; + int stride = blockDim.x * gridDim.x; + for (int i = index; i < total_num; i += stride) { + int fea = i % sample_num; + int sample_index = i / sample_num; + float sum = 0.0; + for (int j = 0; j < topk ; j++) { + int topk_fea_index = int(initial_rank[sample_index*topk+j]) * sample_num + fea; + sum += A[ topk_fea_index] * S[sample_index*topk+j]; + } + A_qe[i] = sum; + } +} + +at::Tensor gnn_propagate_forward(at::Tensor A, at::Tensor initial_rank, at::Tensor S) { + const auto sample_num = A.size(0); + const auto topk = initial_rank.size(1); + + const auto total_num = sample_num * sample_num ; + auto A_qe = torch::zeros({sample_num, sample_num}, at::device(initial_rank.device()).dtype(at::ScalarType::Float)); + + const int threads = 1024; + const int blocks = (total_num + threads - 1) / threads; + + gnn_propagate_forward_kernel<<>>(initial_rank.data_ptr(), A.data_ptr(), A_qe.data_ptr(), S.data_ptr(), sample_num, topk, total_num); + return A_qe; + +} \ No newline at end of file diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/propagation/setup.py b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/propagation/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..1f7b43b42150dd8bf7ea839c51b2d8be29263310 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/extension/propagation/setup.py @@ -0,0 +1,36 @@ +""" + Understanding Image Retrieval Re-Ranking: A Graph Neural Network Perspective + + Xuanmeng Zhang, Minyue Jiang, Zhedong Zheng, Xiao Tan, Errui Ding, Yi Yang + + Project Page : https://github.com/Xuanmeng-Zhang/gnn-re-ranking + + Paper: https://arxiv.org/abs/2012.07620v2 + + ====================================================================== + + On the Market-1501 dataset, we accelerate the re-ranking processing from 89.2s to 9.4ms + with one K40m GPU, facilitating the real-time post-processing. Similarly, we observe + that our method achieves comparable or even better retrieval results on the other four + image retrieval benchmarks, i.e., VeRi-776, Oxford-5k, Paris-6k and University-1652, + with limited time cost. +""" + +from setuptools import Extension, setup +import torch +import torch.nn as nn +from torch.autograd import Function +from torch.utils.cpp_extension import CUDAExtension, BuildExtension + +setup( + name='gnn_propagate', + ext_modules=[ + CUDAExtension( + 'gnn_propagate', [ + 'gnn_propagate.cpp', + 'gnn_propagate_kernel.cu', + ] + ), + ], + cmdclass={'build_ext': BuildExtension} +) diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/gnn_reranking.py b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/gnn_reranking.py new file mode 100644 index 0000000000000000000000000000000000000000..2c8cc53b91d4e2a384881825839b44910556ee11 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/gnn_reranking.py @@ -0,0 +1,59 @@ +""" + Understanding Image Retrieval Re-Ranking: A Graph Neural Network Perspective + + Xuanmeng Zhang, Minyue Jiang, Zhedong Zheng, Xiao Tan, Errui Ding, Yi Yang + + Project Page : https://github.com/Xuanmeng-Zhang/gnn-re-ranking + + Paper: https://arxiv.org/abs/2012.07620v2 + + ====================================================================== + + On the Market-1501 dataset, we accelerate the re-ranking processing from 89.2s to 9.4ms + with one K40m GPU, facilitating the real-time post-processing. Similarly, we observe + that our method achieves comparable or even better retrieval results on the other four + image retrieval benchmarks, i.e., VeRi-776, Oxford-5k, Paris-6k and University-1652, + with limited time cost. +""" + +import numpy as np +import torch + +import gnn_propagate +import build_adjacency_matrix +from utils import * + + +def gnn_reranking(X_q, X_g, k1, k2): + query_num, gallery_num = X_q.shape[0], X_g.shape[0] + + X_u = torch.cat((X_q, X_g), axis=0) + original_score = torch.mm(X_u, X_u.t()) + del X_u, X_q, X_g + + # initial ranking list + S, initial_rank = original_score.topk( + k=k1, dim=-1, largest=True, sorted=True + ) + + # stage 1 + A = build_adjacency_matrix.forward(initial_rank.float()) + S = S * S + + # stage 2 + if k2 != 1: + for i in range(2): + A = A + A.T + A = gnn_propagate.forward( + A, initial_rank[:, :k2].contiguous().float(), + S[:, :k2].contiguous().float() + ) + A_norm = torch.norm(A, p=2, dim=1, keepdim=True) + A = A.div(A_norm.expand_as(A)) + + cosine_similarity = torch.mm(A[:query_num, ], A[query_num:, ].t()) + del A, S + + L = torch.sort(-cosine_similarity, dim=1)[1] + L = L.data.cpu().numpy() + return L diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/main.py b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/main.py new file mode 100644 index 0000000000000000000000000000000000000000..53ef6ac570194a136023c8b602759bc3792691db --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/main.py @@ -0,0 +1,72 @@ +""" + Understanding Image Retrieval Re-Ranking: A Graph Neural Network Perspective + + Xuanmeng Zhang, Minyue Jiang, Zhedong Zheng, Xiao Tan, Errui Ding, Yi Yang + + Project Page : https://github.com/Xuanmeng-Zhang/gnn-re-ranking + + Paper: https://arxiv.org/abs/2012.07620v2 + + ====================================================================== + + On the Market-1501 dataset, we accelerate the re-ranking processing from 89.2s to 9.4ms + with one K40m GPU, facilitating the real-time post-processing. Similarly, we observe + that our method achieves comparable or even better retrieval results on the other four + image retrieval benchmarks, i.e., VeRi-776, Oxford-5k, Paris-6k and University-1652, + with limited time cost. +""" + +import os +import numpy as np +import argparse +import torch + +from utils import * +from gnn_reranking import * + +parser = argparse.ArgumentParser(description='Reranking_is_GNN') +parser.add_argument( + '--data_path', + type=str, + default='../xm_rerank_gpu_2/features/market_88_test.pkl', + help='path to dataset' +) +parser.add_argument( + '--k1', + type=int, + default=26, # Market-1501 + # default=60, # Veri-776 + help='parameter k1' +) +parser.add_argument( + '--k2', + type=int, + default=7, # Market-1501 + # default=10, # Veri-776 + help='parameter k2' +) + +args = parser.parse_args() + + +def main(): + data = load_pickle(args.data_path) + + query_cam = data['query_cam'] + query_label = data['query_label'] + gallery_cam = data['gallery_cam'] + gallery_label = data['gallery_label'] + + gallery_feature = torch.FloatTensor(data['gallery_f']) + query_feature = torch.FloatTensor(data['query_f']) + query_feature = query_feature.cuda() + gallery_feature = gallery_feature.cuda() + + indices = gnn_reranking(query_feature, gallery_feature, args.k1, args.k2) + evaluate_ranking_list( + indices, query_label, query_cam, gallery_label, gallery_cam + ) + + +if __name__ == '__main__': + main() diff --git a/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/utils.py b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1ed9f88a3c53a1c8ceb14c0cf3959f332fe271 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/GPU-Re-Ranking/utils.py @@ -0,0 +1,137 @@ +""" + Understanding Image Retrieval Re-Ranking: A Graph Neural Network Perspective + + Xuanmeng Zhang, Minyue Jiang, Zhedong Zheng, Xiao Tan, Errui Ding, Yi Yang + + Project Page : https://github.com/Xuanmeng-Zhang/gnn-re-ranking + + Paper: https://arxiv.org/abs/2012.07620v2 + + ====================================================================== + + On the Market-1501 dataset, we accelerate the re-ranking processing from 89.2s to 9.4ms + with one K40m GPU, facilitating the real-time post-processing. Similarly, we observe + that our method achieves comparable or even better retrieval results on the other four + image retrieval benchmarks, i.e., VeRi-776, Oxford-5k, Paris-6k and University-1652, + with limited time cost. +""" + +import os +import numpy as np +import pickle +import torch + + +def load_pickle(pickle_path): + with open(pickle_path, 'rb') as f: + data = pickle.load(f) + return data + + +def save_pickle(pickle_path, data): + with open(pickle_path, 'wb') as f: + pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL) + + +def pairwise_squared_distance(x): + ''' + x : (n_samples, n_points, dims) + return : (n_samples, n_points, n_points) + ''' + x2s = (x * x).sum(-1, keepdim=True) + return x2s + x2s.transpose(-1, -2) - 2 * x @ x.transpose(-1, -2) + + +def pairwise_distance(x, y): + m, n = x.size(0), y.size(0) + + x = x.view(m, -1) + y = y.view(n, -1) + + dist = torch.pow(x, 2).sum( + dim=1, keepdim=True + ).expand(m, n) + torch.pow(y, 2).sum( + dim=1, keepdim=True + ).expand(n, m).t() + dist.addmm_(1, -2, x, y.t()) + + return dist + + +def cosine_similarity(x, y): + m, n = x.size(0), y.size(0) + + x = x.view(m, -1) + y = y.view(n, -1) + + y = y.t() + score = torch.mm(x, y) + + return score + + +def evaluate_ranking_list( + indices, query_label, query_cam, gallery_label, gallery_cam +): + CMC = np.zeros((len(gallery_label)), dtype=np.int) + ap = 0.0 + + for i in range(len(query_label)): + ap_tmp, CMC_tmp = evaluate( + indices[i], query_label[i], query_cam[i], gallery_label, + gallery_cam + ) + if CMC_tmp[0] == -1: + continue + CMC = CMC + CMC_tmp + ap += ap_tmp + + CMC = CMC.astype(np.float32) + CMC = CMC / len(query_label) #average CMC + print( + 'Rank@1:%f Rank@5:%f Rank@10:%f mAP:%f' % + (CMC[0], CMC[4], CMC[9], ap / len(query_label)) + ) + + +def evaluate(index, ql, qc, gl, gc): + query_index = np.argwhere(gl == ql) + camera_index = np.argwhere(gc == qc) + + good_index = np.setdiff1d(query_index, camera_index, assume_unique=True) + junk_index1 = np.argwhere(gl == -1) + junk_index2 = np.intersect1d(query_index, camera_index) + junk_index = np.append(junk_index2, junk_index1) #.flatten()) + + CMC_tmp = compute_mAP(index, good_index, junk_index) + return CMC_tmp + + +def compute_mAP(index, good_index, junk_index): + ap = 0 + cmc = np.zeros((len(index)), dtype=np.int) + if good_index.size == 0: # if empty + cmc[0] = -1 + return ap, cmc + + # remove junk_index + mask = np.in1d(index, junk_index, invert=True) + index = index[mask] + + # find good_index index + ngood = len(good_index) + mask = np.in1d(index, good_index) + rows_good = np.argwhere(mask == True) + rows_good = rows_good.flatten() + + cmc[rows_good[0]:] = 1 + for i in range(ngood): + d_recall = 1.0 / ngood + precision = (i+1) * 1.0 / (rows_good[i] + 1) + if rows_good[i] != 0: + old_precision = i * 1.0 / rows_good[i] + else: + old_precision = 1.0 + ap = ap + d_recall * (old_precision+precision) / 2 + + return ap, cmc diff --git a/strong_sort/deep/reid/torchreid/utils/__init__.py b/strong_sort/deep/reid/torchreid/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..50167c3f05779b327f88e0450048730a1224e473 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/__init__.py @@ -0,0 +1,10 @@ +from __future__ import absolute_import + +from .tools import * +from .rerank import re_ranking +from .loggers import * +from .avgmeter import * +from .reidtools import * +from .torchtools import * +from .model_complexity import compute_model_complexity +from .feature_extractor import FeatureExtractor diff --git a/strong_sort/deep/reid/torchreid/utils/avgmeter.py b/strong_sort/deep/reid/torchreid/utils/avgmeter.py new file mode 100644 index 0000000000000000000000000000000000000000..b62d26d4ec7d8cbe8d21a209f9af53ff16b1cc7d --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/avgmeter.py @@ -0,0 +1,73 @@ +from __future__ import division, absolute_import +from collections import defaultdict +import torch + +__all__ = ['AverageMeter', 'MetricMeter'] + + +class AverageMeter(object): + """Computes and stores the average and current value. + + Examples:: + >>> # Initialize a meter to record loss + >>> losses = AverageMeter() + >>> # Update meter after every minibatch update + >>> losses.update(loss_value, batch_size) + """ + + 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 + + +class MetricMeter(object): + """A collection of metrics. + + Source: https://github.com/KaiyangZhou/Dassl.pytorch + + Examples:: + >>> # 1. Create an instance of MetricMeter + >>> metric = MetricMeter() + >>> # 2. Update using a dictionary as input + >>> input_dict = {'loss_1': value_1, 'loss_2': value_2} + >>> metric.update(input_dict) + >>> # 3. Convert to string and print + >>> print(str(metric)) + """ + + def __init__(self, delimiter='\t'): + self.meters = defaultdict(AverageMeter) + self.delimiter = delimiter + + def update(self, input_dict): + if input_dict is None: + return + + if not isinstance(input_dict, dict): + raise TypeError( + 'Input to MetricMeter.update() must be a dictionary' + ) + + for k, v in input_dict.items(): + if isinstance(v, torch.Tensor): + v = v.item() + self.meters[k].update(v) + + def __str__(self): + output_str = [] + for name, meter in self.meters.items(): + output_str.append( + '{} {:.4f} ({:.4f})'.format(name, meter.val, meter.avg) + ) + return self.delimiter.join(output_str) diff --git a/strong_sort/deep/reid/torchreid/utils/feature_extractor.py b/strong_sort/deep/reid/torchreid/utils/feature_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..83635fd3fe3419d54fbe1d0c6e9b7114deb8bdf5 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/feature_extractor.py @@ -0,0 +1,152 @@ +from __future__ import absolute_import +import numpy as np +import torch +import torchvision.transforms as T +from PIL import Image + +from torchreid.utils import ( + check_isfile, load_pretrained_weights, compute_model_complexity +) +from torchreid.models import build_model + + +class FeatureExtractor(object): + """A simple API for feature extraction. + + FeatureExtractor can be used like a python function, which + accepts input of the following types: + - a list of strings (image paths) + - a list of numpy.ndarray each with shape (H, W, C) + - a single string (image path) + - a single numpy.ndarray with shape (H, W, C) + - a torch.Tensor with shape (B, C, H, W) or (C, H, W) + + Returned is a torch tensor with shape (B, D) where D is the + feature dimension. + + Args: + model_name (str): model name. + model_path (str): path to model weights. + image_size (sequence or int): image height and width. + pixel_mean (list): pixel mean for normalization. + pixel_std (list): pixel std for normalization. + pixel_norm (bool): whether to normalize pixels. + device (str): 'cpu' or 'cuda' (could be specific gpu devices). + verbose (bool): show model details. + + Examples:: + + from torchreid.utils import FeatureExtractor + + extractor = FeatureExtractor( + model_name='osnet_x1_0', + model_path='a/b/c/model.pth.tar', + device='cuda' + ) + + image_list = [ + 'a/b/c/image001.jpg', + 'a/b/c/image002.jpg', + 'a/b/c/image003.jpg', + 'a/b/c/image004.jpg', + 'a/b/c/image005.jpg' + ] + + features = extractor(image_list) + print(features.shape) # output (5, 512) + """ + + def __init__( + self, + model_name='', + model_path='', + image_size=(256, 128), + pixel_mean=[0.485, 0.456, 0.406], + pixel_std=[0.229, 0.224, 0.225], + pixel_norm=True, + device='cuda', + verbose=True + ): + # Build model + model = build_model( + model_name, + num_classes=1, + pretrained=not (model_path and check_isfile(model_path)), + use_gpu=device.startswith('cuda') + ) + model.eval() + + if verbose: + num_params, flops = compute_model_complexity( + model, (1, 3, image_size[0], image_size[1]) + ) + print('Model: {}'.format(model_name)) + print('- params: {:,}'.format(num_params)) + print('- flops: {:,}'.format(flops)) + + if model_path and check_isfile(model_path): + load_pretrained_weights(model, model_path) + + # Build transform functions + transforms = [] + transforms += [T.Resize(image_size)] + transforms += [T.ToTensor()] + if pixel_norm: + transforms += [T.Normalize(mean=pixel_mean, std=pixel_std)] + preprocess = T.Compose(transforms) + + to_pil = T.ToPILImage() + + device = torch.device(device) + model.to(device) + + # Class attributes + self.model = model + self.preprocess = preprocess + self.to_pil = to_pil + self.device = device + + def __call__(self, input): + if isinstance(input, list): + images = [] + + for element in input: + if isinstance(element, str): + image = Image.open(element).convert('RGB') + + elif isinstance(element, np.ndarray): + image = self.to_pil(element) + + else: + raise TypeError( + 'Type of each element must belong to [str | numpy.ndarray]' + ) + + image = self.preprocess(image) + images.append(image) + + images = torch.stack(images, dim=0) + images = images.to(self.device) + + elif isinstance(input, str): + image = Image.open(input).convert('RGB') + image = self.preprocess(image) + images = image.unsqueeze(0).to(self.device) + + elif isinstance(input, np.ndarray): + image = self.to_pil(input) + image = self.preprocess(image) + images = image.unsqueeze(0).to(self.device) + + elif isinstance(input, torch.Tensor): + if input.dim() == 3: + input = input.unsqueeze(0) + images = input.to(self.device) + + else: + raise NotImplementedError + + with torch.no_grad(): + features = self.model(images) + + return features diff --git a/strong_sort/deep/reid/torchreid/utils/loggers.py b/strong_sort/deep/reid/torchreid/utils/loggers.py new file mode 100644 index 0000000000000000000000000000000000000000..f7fae3c57b300b76afd8e5a485439aee9fefdbbe --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/loggers.py @@ -0,0 +1,146 @@ +from __future__ import absolute_import +import os +import sys +import os.path as osp + +from .tools import mkdir_if_missing + +__all__ = ['Logger', 'RankLogger'] + + +class Logger(object): + """Writes console output to external text file. + + Imported from ``_ + + Args: + fpath (str): directory to save logging file. + + Examples:: + >>> import sys + >>> import os + >>> import os.path as osp + >>> from torchreid.utils import Logger + >>> save_dir = 'log/resnet50-softmax-market1501' + >>> log_name = 'train.log' + >>> sys.stdout = Logger(osp.join(args.save_dir, log_name)) + """ + + def __init__(self, fpath=None): + self.console = sys.stdout + self.file = None + if fpath is not None: + mkdir_if_missing(osp.dirname(fpath)) + self.file = open(fpath, 'w') + + def __del__(self): + self.close() + + def __enter__(self): + pass + + def __exit__(self, *args): + self.close() + + def write(self, msg): + self.console.write(msg) + if self.file is not None: + self.file.write(msg) + + def flush(self): + self.console.flush() + if self.file is not None: + self.file.flush() + os.fsync(self.file.fileno()) + + def close(self): + self.console.close() + if self.file is not None: + self.file.close() + + +class RankLogger(object): + """Records the rank1 matching accuracy obtained for each + test dataset at specified evaluation steps and provides a function + to show the summarized results, which are convenient for analysis. + + Args: + sources (str or list): source dataset name(s). + targets (str or list): target dataset name(s). + + Examples:: + >>> from torchreid.utils import RankLogger + >>> s = 'market1501' + >>> t = 'market1501' + >>> ranklogger = RankLogger(s, t) + >>> ranklogger.write(t, 10, 0.5) + >>> ranklogger.write(t, 20, 0.7) + >>> ranklogger.write(t, 30, 0.9) + >>> ranklogger.show_summary() + >>> # You will see: + >>> # => Show performance summary + >>> # market1501 (source) + >>> # - epoch 10 rank1 50.0% + >>> # - epoch 20 rank1 70.0% + >>> # - epoch 30 rank1 90.0% + >>> # If there are multiple test datasets + >>> t = ['market1501', 'dukemtmcreid'] + >>> ranklogger = RankLogger(s, t) + >>> ranklogger.write(t[0], 10, 0.5) + >>> ranklogger.write(t[0], 20, 0.7) + >>> ranklogger.write(t[0], 30, 0.9) + >>> ranklogger.write(t[1], 10, 0.1) + >>> ranklogger.write(t[1], 20, 0.2) + >>> ranklogger.write(t[1], 30, 0.3) + >>> ranklogger.show_summary() + >>> # You can see: + >>> # => Show performance summary + >>> # market1501 (source) + >>> # - epoch 10 rank1 50.0% + >>> # - epoch 20 rank1 70.0% + >>> # - epoch 30 rank1 90.0% + >>> # dukemtmcreid (target) + >>> # - epoch 10 rank1 10.0% + >>> # - epoch 20 rank1 20.0% + >>> # - epoch 30 rank1 30.0% + """ + + def __init__(self, sources, targets): + self.sources = sources + self.targets = targets + + if isinstance(self.sources, str): + self.sources = [self.sources] + + if isinstance(self.targets, str): + self.targets = [self.targets] + + self.logger = { + name: { + 'epoch': [], + 'rank1': [] + } + for name in self.targets + } + + def write(self, name, epoch, rank1): + """Writes result. + + Args: + name (str): dataset name. + epoch (int): current epoch. + rank1 (float): rank1 result. + """ + self.logger[name]['epoch'].append(epoch) + self.logger[name]['rank1'].append(rank1) + + def show_summary(self): + """Shows saved results.""" + print('=> Show performance summary') + for name in self.targets: + from_where = 'source' if name in self.sources else 'target' + print('{} ({})'.format(name, from_where)) + for epoch, rank1 in zip( + self.logger[name]['epoch'], self.logger[name]['rank1'] + ): + print('- epoch {}\t rank1 {:.1%}'.format(epoch, rank1)) diff --git a/strong_sort/deep/reid/torchreid/utils/model_complexity.py b/strong_sort/deep/reid/torchreid/utils/model_complexity.py new file mode 100644 index 0000000000000000000000000000000000000000..7d1dc1ed13ba747b510030a5690b81cd0d570822 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/model_complexity.py @@ -0,0 +1,363 @@ +from __future__ import division, print_function, absolute_import +import math +import numpy as np +from itertools import repeat +from collections import namedtuple, defaultdict +import torch + +__all__ = ['compute_model_complexity'] +""" +Utility +""" + + +def _ntuple(n): + + def parse(x): + if isinstance(x, int): + return tuple(repeat(x, n)) + return x + + return parse + + +_single = _ntuple(1) +_pair = _ntuple(2) +_triple = _ntuple(3) +""" +Convolution +""" + + +def hook_convNd(m, x, y): + k = torch.prod(torch.Tensor(m.kernel_size)).item() + cin = m.in_channels + flops_per_ele = k * cin # + (k*cin-1) + if m.bias is not None: + flops_per_ele += 1 + flops = flops_per_ele * y.numel() / m.groups + return int(flops) + + +""" +Pooling +""" + + +def hook_maxpool1d(m, x, y): + flops_per_ele = m.kernel_size - 1 + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_maxpool2d(m, x, y): + k = _pair(m.kernel_size) + k = torch.prod(torch.Tensor(k)).item() + # ops: compare + flops_per_ele = k - 1 + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_maxpool3d(m, x, y): + k = _triple(m.kernel_size) + k = torch.prod(torch.Tensor(k)).item() + flops_per_ele = k - 1 + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_avgpool1d(m, x, y): + flops_per_ele = m.kernel_size + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_avgpool2d(m, x, y): + k = _pair(m.kernel_size) + k = torch.prod(torch.Tensor(k)).item() + flops_per_ele = k + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_avgpool3d(m, x, y): + k = _triple(m.kernel_size) + k = torch.prod(torch.Tensor(k)).item() + flops_per_ele = k + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_adapmaxpool1d(m, x, y): + x = x[0] + out_size = m.output_size + k = math.ceil(x.size(2) / out_size) + flops_per_ele = k - 1 + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_adapmaxpool2d(m, x, y): + x = x[0] + out_size = _pair(m.output_size) + k = torch.Tensor(list(x.size()[2:])) / torch.Tensor(out_size) + k = torch.prod(torch.ceil(k)).item() + flops_per_ele = k - 1 + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_adapmaxpool3d(m, x, y): + x = x[0] + out_size = _triple(m.output_size) + k = torch.Tensor(list(x.size()[2:])) / torch.Tensor(out_size) + k = torch.prod(torch.ceil(k)).item() + flops_per_ele = k - 1 + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_adapavgpool1d(m, x, y): + x = x[0] + out_size = m.output_size + k = math.ceil(x.size(2) / out_size) + flops_per_ele = k + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_adapavgpool2d(m, x, y): + x = x[0] + out_size = _pair(m.output_size) + k = torch.Tensor(list(x.size()[2:])) / torch.Tensor(out_size) + k = torch.prod(torch.ceil(k)).item() + flops_per_ele = k + flops = flops_per_ele * y.numel() + return int(flops) + + +def hook_adapavgpool3d(m, x, y): + x = x[0] + out_size = _triple(m.output_size) + k = torch.Tensor(list(x.size()[2:])) / torch.Tensor(out_size) + k = torch.prod(torch.ceil(k)).item() + flops_per_ele = k + flops = flops_per_ele * y.numel() + return int(flops) + + +""" +Non-linear activations +""" + + +def hook_relu(m, x, y): + # eq: max(0, x) + num_ele = y.numel() + return int(num_ele) + + +def hook_leakyrelu(m, x, y): + # eq: max(0, x) + negative_slope*min(0, x) + num_ele = y.numel() + flops = 3 * num_ele + return int(flops) + + +""" +Normalization +""" + + +def hook_batchnormNd(m, x, y): + num_ele = y.numel() + flops = 2 * num_ele # mean and std + if m.affine: + flops += 2 * num_ele # gamma and beta + return int(flops) + + +def hook_instancenormNd(m, x, y): + return hook_batchnormNd(m, x, y) + + +def hook_groupnorm(m, x, y): + return hook_batchnormNd(m, x, y) + + +def hook_layernorm(m, x, y): + num_ele = y.numel() + flops = 2 * num_ele # mean and std + if m.elementwise_affine: + flops += 2 * num_ele # gamma and beta + return int(flops) + + +""" +Linear +""" + + +def hook_linear(m, x, y): + flops_per_ele = m.in_features # + (m.in_features-1) + if m.bias is not None: + flops_per_ele += 1 + flops = flops_per_ele * y.numel() + return int(flops) + + +__generic_flops_counter = { + # Convolution + 'Conv1d': hook_convNd, + 'Conv2d': hook_convNd, + 'Conv3d': hook_convNd, + # Pooling + 'MaxPool1d': hook_maxpool1d, + 'MaxPool2d': hook_maxpool2d, + 'MaxPool3d': hook_maxpool3d, + 'AvgPool1d': hook_avgpool1d, + 'AvgPool2d': hook_avgpool2d, + 'AvgPool3d': hook_avgpool3d, + 'AdaptiveMaxPool1d': hook_adapmaxpool1d, + 'AdaptiveMaxPool2d': hook_adapmaxpool2d, + 'AdaptiveMaxPool3d': hook_adapmaxpool3d, + 'AdaptiveAvgPool1d': hook_adapavgpool1d, + 'AdaptiveAvgPool2d': hook_adapavgpool2d, + 'AdaptiveAvgPool3d': hook_adapavgpool3d, + # Non-linear activations + 'ReLU': hook_relu, + 'ReLU6': hook_relu, + 'LeakyReLU': hook_leakyrelu, + # Normalization + 'BatchNorm1d': hook_batchnormNd, + 'BatchNorm2d': hook_batchnormNd, + 'BatchNorm3d': hook_batchnormNd, + 'InstanceNorm1d': hook_instancenormNd, + 'InstanceNorm2d': hook_instancenormNd, + 'InstanceNorm3d': hook_instancenormNd, + 'GroupNorm': hook_groupnorm, + 'LayerNorm': hook_layernorm, + # Linear + 'Linear': hook_linear, +} + +__conv_linear_flops_counter = { + # Convolution + 'Conv1d': hook_convNd, + 'Conv2d': hook_convNd, + 'Conv3d': hook_convNd, + # Linear + 'Linear': hook_linear, +} + + +def _get_flops_counter(only_conv_linear): + if only_conv_linear: + return __conv_linear_flops_counter + return __generic_flops_counter + + +def compute_model_complexity( + model, input_size, verbose=False, only_conv_linear=True +): + """Returns number of parameters and FLOPs. + + .. note:: + (1) this function only provides an estimate of the theoretical time complexity + rather than the actual running time which depends on implementations and hardware, + and (2) the FLOPs is only counted for layers that are used at test time. This means + that redundant layers such as person ID classification layer will be ignored as it + is discarded when doing feature extraction. Note that the inference graph depends on + how you construct the computations in ``forward()``. + + Args: + model (nn.Module): network model. + input_size (tuple): input size, e.g. (1, 3, 256, 128). + verbose (bool, optional): shows detailed complexity of + each module. Default is False. + only_conv_linear (bool, optional): only considers convolution + and linear layers when counting flops. Default is True. + If set to False, flops of all layers will be counted. + + Examples:: + >>> from torchreid import models, utils + >>> model = models.build_model(name='resnet50', num_classes=1000) + >>> num_params, flops = utils.compute_model_complexity(model, (1, 3, 256, 128), verbose=True) + """ + registered_handles = [] + layer_list = [] + layer = namedtuple('layer', ['class_name', 'params', 'flops']) + + def _add_hooks(m): + + def _has_submodule(m): + return len(list(m.children())) > 0 + + def _hook(m, x, y): + params = sum(p.numel() for p in m.parameters()) + class_name = str(m.__class__.__name__) + flops_counter = _get_flops_counter(only_conv_linear) + if class_name in flops_counter: + flops = flops_counter[class_name](m, x, y) + else: + flops = 0 + layer_list.append( + layer(class_name=class_name, params=params, flops=flops) + ) + + # only consider the very basic nn layer + if _has_submodule(m): + return + + handle = m.register_forward_hook(_hook) + registered_handles.append(handle) + + default_train_mode = model.training + + model.eval().apply(_add_hooks) + input = torch.rand(input_size) + if next(model.parameters()).is_cuda: + input = input.cuda() + model(input) # forward + + for handle in registered_handles: + handle.remove() + + model.train(default_train_mode) + + if verbose: + per_module_params = defaultdict(list) + per_module_flops = defaultdict(list) + + total_params, total_flops = 0, 0 + + for layer in layer_list: + total_params += layer.params + total_flops += layer.flops + if verbose: + per_module_params[layer.class_name].append(layer.params) + per_module_flops[layer.class_name].append(layer.flops) + + if verbose: + num_udscore = 55 + print(' {}'.format('-' * num_udscore)) + print(' Model complexity with input size {}'.format(input_size)) + print(' {}'.format('-' * num_udscore)) + for class_name in per_module_params: + params = int(np.sum(per_module_params[class_name])) + flops = int(np.sum(per_module_flops[class_name])) + print( + ' {} (params={:,}, flops={:,})'.format( + class_name, params, flops + ) + ) + print(' {}'.format('-' * num_udscore)) + print( + ' Total (params={:,}, flops={:,})'.format( + total_params, total_flops + ) + ) + print(' {}'.format('-' * num_udscore)) + + return total_params, total_flops diff --git a/strong_sort/deep/reid/torchreid/utils/reidtools.py b/strong_sort/deep/reid/torchreid/utils/reidtools.py new file mode 100644 index 0000000000000000000000000000000000000000..acb87602ba905062424a9ebbe524f9cad83384e3 --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/reidtools.py @@ -0,0 +1,154 @@ +from __future__ import print_function, absolute_import +import numpy as np +import shutil +import os.path as osp +import cv2 + +from .tools import mkdir_if_missing + +__all__ = ['visualize_ranked_results'] + +GRID_SPACING = 10 +QUERY_EXTRA_SPACING = 90 +BW = 5 # border width +GREEN = (0, 255, 0) +RED = (0, 0, 255) + + +def visualize_ranked_results( + distmat, dataset, data_type, width=128, height=256, save_dir='', topk=10 +): + """Visualizes ranked results. + + Supports both image-reid and video-reid. + + For image-reid, ranks will be plotted in a single figure. For video-reid, ranks will be + saved in folders each containing a tracklet. + + Args: + distmat (numpy.ndarray): distance matrix of shape (num_query, num_gallery). + dataset (tuple): a 2-tuple containing (query, gallery), each of which contains + tuples of (img_path(s), pid, camid, dsetid). + data_type (str): "image" or "video". + width (int, optional): resized image width. Default is 128. + height (int, optional): resized image height. Default is 256. + save_dir (str): directory to save output images. + topk (int, optional): denoting top-k images in the rank list to be visualized. + Default is 10. + """ + num_q, num_g = distmat.shape + mkdir_if_missing(save_dir) + + print('# query: {}\n# gallery {}'.format(num_q, num_g)) + print('Visualizing top-{} ranks ...'.format(topk)) + + query, gallery = dataset + assert num_q == len(query) + assert num_g == len(gallery) + + indices = np.argsort(distmat, axis=1) + + def _cp_img_to(src, dst, rank, prefix, matched=False): + """ + Args: + src: image path or tuple (for vidreid) + dst: target directory + rank: int, denoting ranked position, starting from 1 + prefix: string + matched: bool + """ + if isinstance(src, (tuple, list)): + if prefix == 'gallery': + suffix = 'TRUE' if matched else 'FALSE' + dst = osp.join( + dst, prefix + '_top' + str(rank).zfill(3) + ) + '_' + suffix + else: + dst = osp.join(dst, prefix + '_top' + str(rank).zfill(3)) + mkdir_if_missing(dst) + for img_path in src: + shutil.copy(img_path, dst) + else: + dst = osp.join( + dst, prefix + '_top' + str(rank).zfill(3) + '_name_' + + osp.basename(src) + ) + shutil.copy(src, dst) + + for q_idx in range(num_q): + qimg_path, qpid, qcamid = query[q_idx][:3] + qimg_path_name = qimg_path[0] if isinstance( + qimg_path, (tuple, list) + ) else qimg_path + + if data_type == 'image': + qimg = cv2.imread(qimg_path) + qimg = cv2.resize(qimg, (width, height)) + qimg = cv2.copyMakeBorder( + qimg, BW, BW, BW, BW, cv2.BORDER_CONSTANT, value=(0, 0, 0) + ) + # resize twice to ensure that the border width is consistent across images + qimg = cv2.resize(qimg, (width, height)) + num_cols = topk + 1 + grid_img = 255 * np.ones( + ( + height, + num_cols*width + topk*GRID_SPACING + QUERY_EXTRA_SPACING, 3 + ), + dtype=np.uint8 + ) + grid_img[:, :width, :] = qimg + else: + qdir = osp.join( + save_dir, osp.basename(osp.splitext(qimg_path_name)[0]) + ) + mkdir_if_missing(qdir) + _cp_img_to(qimg_path, qdir, rank=0, prefix='query') + + rank_idx = 1 + for g_idx in indices[q_idx, :]: + gimg_path, gpid, gcamid = gallery[g_idx][:3] + invalid = (qpid == gpid) & (qcamid == gcamid) + + if not invalid: + matched = gpid == qpid + if data_type == 'image': + border_color = GREEN if matched else RED + gimg = cv2.imread(gimg_path) + gimg = cv2.resize(gimg, (width, height)) + gimg = cv2.copyMakeBorder( + gimg, + BW, + BW, + BW, + BW, + cv2.BORDER_CONSTANT, + value=border_color + ) + gimg = cv2.resize(gimg, (width, height)) + start = rank_idx*width + rank_idx*GRID_SPACING + QUERY_EXTRA_SPACING + end = ( + rank_idx+1 + ) * width + rank_idx*GRID_SPACING + QUERY_EXTRA_SPACING + grid_img[:, start:end, :] = gimg + else: + _cp_img_to( + gimg_path, + qdir, + rank=rank_idx, + prefix='gallery', + matched=matched + ) + + rank_idx += 1 + if rank_idx > topk: + break + + if data_type == 'image': + imname = osp.basename(osp.splitext(qimg_path_name)[0]) + cv2.imwrite(osp.join(save_dir, imname + '.jpg'), grid_img) + + if (q_idx+1) % 100 == 0: + print('- done {}/{}'.format(q_idx + 1, num_q)) + + print('Done. Images have been saved to "{}" ...'.format(save_dir)) diff --git a/strong_sort/deep/reid/torchreid/utils/rerank.py b/strong_sort/deep/reid/torchreid/utils/rerank.py new file mode 100644 index 0000000000000000000000000000000000000000..efadf5afe26ec057bd66e161a34dea637849e7ab --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/rerank.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python2/python3 +# -*- coding: utf-8 -*- +""" +Source: https://github.com/zhunzhong07/person-re-ranking + +Created on Mon Jun 26 14:46:56 2017 +@author: luohao +Modified by Houjing Huang, 2017-12-22. +- This version accepts distance matrix instead of raw features. +- The difference of `/` division between python 2 and 3 is handled. +- numpy.float16 is replaced by numpy.float32 for numerical precision. + +CVPR2017 paper:Zhong Z, Zheng L, Cao D, et al. Re-ranking Person Re-identification with k-reciprocal Encoding[J]. 2017. +url:http://openaccess.thecvf.com/content_cvpr_2017/papers/Zhong_Re-Ranking_Person_Re-Identification_CVPR_2017_paper.pdf +Matlab version: https://github.com/zhunzhong07/person-re-ranking + +API +q_g_dist: query-gallery distance matrix, numpy array, shape [num_query, num_gallery] +q_q_dist: query-query distance matrix, numpy array, shape [num_query, num_query] +g_g_dist: gallery-gallery distance matrix, numpy array, shape [num_gallery, num_gallery] +k1, k2, lambda_value: parameters, the original paper is (k1=20, k2=6, lambda_value=0.3) +Returns: + final_dist: re-ranked distance, numpy array, shape [num_query, num_gallery] +""" +from __future__ import division, print_function, absolute_import +import numpy as np + +__all__ = ['re_ranking'] + + +def re_ranking(q_g_dist, q_q_dist, g_g_dist, k1=20, k2=6, lambda_value=0.3): + + # The following naming, e.g. gallery_num, is different from outer scope. + # Don't care about it. + + original_dist = np.concatenate( + [ + np.concatenate([q_q_dist, q_g_dist], axis=1), + np.concatenate([q_g_dist.T, g_g_dist], axis=1) + ], + axis=0 + ) + original_dist = np.power(original_dist, 2).astype(np.float32) + original_dist = np.transpose( + 1. * original_dist / np.max(original_dist, axis=0) + ) + V = np.zeros_like(original_dist).astype(np.float32) + initial_rank = np.argsort(original_dist).astype(np.int32) + + query_num = q_g_dist.shape[0] + gallery_num = q_g_dist.shape[0] + q_g_dist.shape[1] + all_num = gallery_num + + for i in range(all_num): + # k-reciprocal neighbors + forward_k_neigh_index = initial_rank[i, :k1 + 1] + backward_k_neigh_index = initial_rank[forward_k_neigh_index, :k1 + 1] + fi = np.where(backward_k_neigh_index == i)[0] + k_reciprocal_index = forward_k_neigh_index[fi] + k_reciprocal_expansion_index = k_reciprocal_index + for j in range(len(k_reciprocal_index)): + candidate = k_reciprocal_index[j] + candidate_forward_k_neigh_index = initial_rank[ + candidate, :int(np.around(k1 / 2.)) + 1] + candidate_backward_k_neigh_index = initial_rank[ + candidate_forward_k_neigh_index, :int(np.around(k1 / 2.)) + 1] + fi_candidate = np.where( + candidate_backward_k_neigh_index == candidate + )[0] + candidate_k_reciprocal_index = candidate_forward_k_neigh_index[ + fi_candidate] + if len( + np. + intersect1d(candidate_k_reciprocal_index, k_reciprocal_index) + ) > 2. / 3 * len(candidate_k_reciprocal_index): + k_reciprocal_expansion_index = np.append( + k_reciprocal_expansion_index, candidate_k_reciprocal_index + ) + + k_reciprocal_expansion_index = np.unique(k_reciprocal_expansion_index) + weight = np.exp(-original_dist[i, k_reciprocal_expansion_index]) + V[i, k_reciprocal_expansion_index] = 1. * weight / np.sum(weight) + original_dist = original_dist[:query_num, ] + if k2 != 1: + V_qe = np.zeros_like(V, dtype=np.float32) + for i in range(all_num): + V_qe[i, :] = np.mean(V[initial_rank[i, :k2], :], axis=0) + V = V_qe + del V_qe + del initial_rank + invIndex = [] + for i in range(gallery_num): + invIndex.append(np.where(V[:, i] != 0)[0]) + + jaccard_dist = np.zeros_like(original_dist, dtype=np.float32) + + for i in range(query_num): + temp_min = np.zeros(shape=[1, gallery_num], dtype=np.float32) + indNonZero = np.where(V[i, :] != 0)[0] + indImages = [] + indImages = [invIndex[ind] for ind in indNonZero] + for j in range(len(indNonZero)): + temp_min[0, indImages[j]] = temp_min[0, indImages[j]] + np.minimum( + V[i, indNonZero[j]], V[indImages[j], indNonZero[j]] + ) + jaccard_dist[i] = 1 - temp_min / (2.-temp_min) + + final_dist = jaccard_dist * (1-lambda_value) + original_dist*lambda_value + del original_dist + del V + del jaccard_dist + final_dist = final_dist[:query_num, query_num:] + return final_dist diff --git a/strong_sort/deep/reid/torchreid/utils/tools.py b/strong_sort/deep/reid/torchreid/utils/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..518fa18863b460bf25051cc06e4cfea8fa00bbef --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/tools.py @@ -0,0 +1,143 @@ +from __future__ import division, print_function, absolute_import +import os +import sys +import json +import time +import errno +import numpy as np +import random +import os.path as osp +import warnings +import PIL +import torch +from PIL import Image + +__all__ = [ + 'mkdir_if_missing', 'check_isfile', 'read_json', 'write_json', + 'set_random_seed', 'download_url', 'read_image', 'collect_env_info', + 'listdir_nohidden' +] + + +def mkdir_if_missing(dirname): + """Creates dirname if it is missing.""" + if not osp.exists(dirname): + try: + os.makedirs(dirname) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + +def check_isfile(fpath): + """Checks if the given path is a file. + + Args: + fpath (str): file path. + + Returns: + bool + """ + isfile = osp.isfile(fpath) + if not isfile: + warnings.warn('No file found at "{}"'.format(fpath)) + return isfile + + +def read_json(fpath): + """Reads json file from a path.""" + with open(fpath, 'r') as f: + obj = json.load(f) + return obj + + +def write_json(obj, fpath): + """Writes to a json file.""" + mkdir_if_missing(osp.dirname(fpath)) + with open(fpath, 'w') as f: + json.dump(obj, f, indent=4, separators=(',', ': ')) + + +def set_random_seed(seed): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +def download_url(url, dst): + """Downloads file from a url to a destination. + + Args: + url (str): url to download file. + dst (str): destination path. + """ + from six.moves import urllib + print('* url="{}"'.format(url)) + print('* destination="{}"'.format(dst)) + + def _reporthook(count, block_size, total_size): + global start_time + if count == 0: + start_time = time.time() + return + duration = time.time() - start_time + progress_size = int(count * block_size) + speed = int(progress_size / (1024*duration)) + percent = int(count * block_size * 100 / total_size) + sys.stdout.write( + '\r...%d%%, %d MB, %d KB/s, %d seconds passed' % + (percent, progress_size / (1024*1024), speed, duration) + ) + sys.stdout.flush() + + urllib.request.urlretrieve(url, dst, _reporthook) + sys.stdout.write('\n') + + +def read_image(path): + """Reads image from path using ``PIL.Image``. + + Args: + path (str): path to an image. + + Returns: + PIL image + """ + got_img = False + if not osp.exists(path): + raise IOError('"{}" does not exist'.format(path)) + while not got_img: + try: + img = Image.open(path).convert('RGB') + got_img = True + except IOError: + print( + 'IOError incurred when reading "{}". Will redo. Don\'t worry. Just chill.' + .format(path) + ) + return img + + +def collect_env_info(): + """Returns env info as a string. + + Code source: github.com/facebookresearch/maskrcnn-benchmark + """ + from torch.utils.collect_env import get_pretty_env_info + env_str = get_pretty_env_info() + env_str += '\n Pillow ({})'.format(PIL.__version__) + return env_str + + +def listdir_nohidden(path, sort=False): + """List non-hidden items in a directory. + + Args: + path (str): directory path. + sort (bool): sort the items. + """ + items = [f for f in os.listdir(path) if not f.startswith('.')] + if sort: + items.sort() + return items diff --git a/strong_sort/deep/reid/torchreid/utils/torchtools.py b/strong_sort/deep/reid/torchreid/utils/torchtools.py new file mode 100644 index 0000000000000000000000000000000000000000..e854278d90106e64c0f0822b2fa699da05221f7c --- /dev/null +++ b/strong_sort/deep/reid/torchreid/utils/torchtools.py @@ -0,0 +1,312 @@ +from __future__ import division, print_function, absolute_import +import pickle +import shutil +import os.path as osp +import warnings +from functools import partial +from collections import OrderedDict +import torch +import torch.nn as nn + +from .tools import mkdir_if_missing + +__all__ = [ + 'save_checkpoint', 'load_checkpoint', 'resume_from_checkpoint', + 'open_all_layers', 'open_specified_layers', 'count_num_param', + 'load_pretrained_weights' +] + + +def save_checkpoint( + state, save_dir, is_best=False, remove_module_from_keys=False +): + r"""Saves checkpoint. + + Args: + state (dict): dictionary. + save_dir (str): directory to save checkpoint. + is_best (bool, optional): if True, this checkpoint will be copied and named + ``model-best.pth.tar``. Default is False. + remove_module_from_keys (bool, optional): whether to remove "module." + from layer names. Default is False. + + Examples:: + >>> state = { + >>> 'state_dict': model.state_dict(), + >>> 'epoch': 10, + >>> 'rank1': 0.5, + >>> 'optimizer': optimizer.state_dict() + >>> } + >>> save_checkpoint(state, 'log/my_model') + """ + mkdir_if_missing(save_dir) + if remove_module_from_keys: + # remove 'module.' in state_dict's keys + state_dict = state['state_dict'] + new_state_dict = OrderedDict() + for k, v in state_dict.items(): + if k.startswith('module.'): + k = k[7:] + new_state_dict[k] = v + state['state_dict'] = new_state_dict + # save + epoch = state['epoch'] + fpath = osp.join(save_dir, 'model.pth.tar-' + str(epoch)) + torch.save(state, fpath) + print('Checkpoint saved to "{}"'.format(fpath)) + if is_best: + shutil.copy(fpath, osp.join(osp.dirname(fpath), 'model-best.pth.tar')) + + +def load_checkpoint(fpath): + r"""Loads checkpoint. + + ``UnicodeDecodeError`` can be well handled, which means + python2-saved files can be read from python3. + + Args: + fpath (str): path to checkpoint. + + Returns: + dict + + Examples:: + >>> from torchreid.utils import load_checkpoint + >>> fpath = 'log/my_model/model.pth.tar-10' + >>> checkpoint = load_checkpoint(fpath) + """ + if fpath is None: + raise ValueError('File path is None') + fpath = osp.abspath(osp.expanduser(fpath)) + if not osp.exists(fpath): + raise FileNotFoundError('File is not found at "{}"'.format(fpath)) + map_location = None if torch.cuda.is_available() else 'cpu' + try: + checkpoint = torch.load(fpath, map_location=map_location) + except UnicodeDecodeError: + pickle.load = partial(pickle.load, encoding="latin1") + pickle.Unpickler = partial(pickle.Unpickler, encoding="latin1") + checkpoint = torch.load( + fpath, pickle_module=pickle, map_location=map_location + ) + except Exception: + print('Unable to load checkpoint from "{}"'.format(fpath)) + raise + return checkpoint + + +def resume_from_checkpoint(fpath, model, optimizer=None, scheduler=None): + r"""Resumes training from a checkpoint. + + This will load (1) model weights and (2) ``state_dict`` + of optimizer if ``optimizer`` is not None. + + Args: + fpath (str): path to checkpoint. + model (nn.Module): model. + optimizer (Optimizer, optional): an Optimizer. + scheduler (LRScheduler, optional): an LRScheduler. + + Returns: + int: start_epoch. + + Examples:: + >>> from torchreid.utils import resume_from_checkpoint + >>> fpath = 'log/my_model/model.pth.tar-10' + >>> start_epoch = resume_from_checkpoint( + >>> fpath, model, optimizer, scheduler + >>> ) + """ + print('Loading checkpoint from "{}"'.format(fpath)) + checkpoint = load_checkpoint(fpath) + model.load_state_dict(checkpoint['state_dict']) + print('Loaded model weights') + if optimizer is not None and 'optimizer' in checkpoint.keys(): + optimizer.load_state_dict(checkpoint['optimizer']) + print('Loaded optimizer') + if scheduler is not None and 'scheduler' in checkpoint.keys(): + scheduler.load_state_dict(checkpoint['scheduler']) + print('Loaded scheduler') + start_epoch = checkpoint['epoch'] + print('Last epoch = {}'.format(start_epoch)) + if 'rank1' in checkpoint.keys(): + print('Last rank1 = {:.1%}'.format(checkpoint['rank1'])) + return start_epoch + + +def adjust_learning_rate( + optimizer, + base_lr, + epoch, + stepsize=20, + gamma=0.1, + linear_decay=False, + final_lr=0, + max_epoch=100 +): + r"""Adjusts learning rate. + + Deprecated. + """ + if linear_decay: + # linearly decay learning rate from base_lr to final_lr + frac_done = epoch / max_epoch + lr = frac_done*final_lr + (1.-frac_done) * base_lr + else: + # decay learning rate by gamma for every stepsize + lr = base_lr * (gamma**(epoch // stepsize)) + + for param_group in optimizer.param_groups: + param_group['lr'] = lr + + +def set_bn_to_eval(m): + r"""Sets BatchNorm layers to eval mode.""" + # 1. no update for running mean and var + # 2. scale and shift parameters are still trainable + classname = m.__class__.__name__ + if classname.find('BatchNorm') != -1: + m.eval() + + +def open_all_layers(model): + r"""Opens all layers in model for training. + + Examples:: + >>> from torchreid.utils import open_all_layers + >>> open_all_layers(model) + """ + model.train() + for p in model.parameters(): + p.requires_grad = True + + +def open_specified_layers(model, open_layers): + r"""Opens specified layers in model for training while keeping + other layers frozen. + + Args: + model (nn.Module): neural net model. + open_layers (str or list): layers open for training. + + Examples:: + >>> from torchreid.utils import open_specified_layers + >>> # Only model.classifier will be updated. + >>> open_layers = 'classifier' + >>> open_specified_layers(model, open_layers) + >>> # Only model.fc and model.classifier will be updated. + >>> open_layers = ['fc', 'classifier'] + >>> open_specified_layers(model, open_layers) + """ + if isinstance(model, nn.DataParallel): + model = model.module + + if isinstance(open_layers, str): + open_layers = [open_layers] + + for layer in open_layers: + assert hasattr( + model, layer + ), '"{}" is not an attribute of the model, please provide the correct name'.format( + layer + ) + + for name, module in model.named_children(): + if name in open_layers: + module.train() + for p in module.parameters(): + p.requires_grad = True + else: + module.eval() + for p in module.parameters(): + p.requires_grad = False + + +def count_num_param(model): + r"""Counts number of parameters in a model while ignoring ``self.classifier``. + + Args: + model (nn.Module): network model. + + Examples:: + >>> from torchreid.utils import count_num_param + >>> model_size = count_num_param(model) + + .. warning:: + + This method is deprecated in favor of + ``torchreid.utils.compute_model_complexity``. + """ + warnings.warn( + 'This method is deprecated and will be removed in the future.' + ) + + num_param = sum(p.numel() for p in model.parameters()) + + if isinstance(model, nn.DataParallel): + model = model.module + + if hasattr(model, + 'classifier') and isinstance(model.classifier, nn.Module): + # we ignore the classifier because it is unused at test time + num_param -= sum(p.numel() for p in model.classifier.parameters()) + + return num_param + + +def load_pretrained_weights(model, weight_path): + r"""Loads pretrianed weights to model. + + Features:: + - Incompatible layers (unmatched in name or size) will be ignored. + - Can automatically deal with keys containing "module.". + + Args: + model (nn.Module): network model. + weight_path (str): path to pretrained weights. + + Examples:: + >>> from torchreid.utils import load_pretrained_weights + >>> weight_path = 'log/my_model/model-best.pth.tar' + >>> load_pretrained_weights(model, weight_path) + """ + checkpoint = load_checkpoint(weight_path) + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + + model_dict = model.state_dict() + new_state_dict = OrderedDict() + matched_layers, discarded_layers = [], [] + + for k, v in state_dict.items(): + if k.startswith('module.'): + k = k[7:] # discard module. + + if k in model_dict and model_dict[k].size() == v.size(): + new_state_dict[k] = v + matched_layers.append(k) + else: + discarded_layers.append(k) + + model_dict.update(new_state_dict) + model.load_state_dict(model_dict) + + if len(matched_layers) == 0: + warnings.warn( + 'The pretrained weights "{}" cannot be loaded, ' + 'please check the key names manually ' + '(** ignored and continue **)'.format(weight_path) + ) + else: + print( + 'Successfully loaded pretrained weights from "{}"'. + format(weight_path) + ) + if len(discarded_layers) > 0: + print( + '** The following layers are discarded ' + 'due to unmatched keys or layer size: {}'. + format(discarded_layers) + ) diff --git a/strong_sort/deep/reid_model_factory.py b/strong_sort/deep/reid_model_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..cf64fb07d80178fc9b402ac7fb1db6a71fe124b8 --- /dev/null +++ b/strong_sort/deep/reid_model_factory.py @@ -0,0 +1,125 @@ +__model_types = [ + 'resnet50', 'mlfn', 'hacnn', 'mobilenetv2_x1_0', 'mobilenetv2_x1_4', + 'osnet_x1_0', 'osnet_x0_75', 'osnet_x0_5', 'osnet_x0_25', + 'osnet_ibn_x1_0', 'osnet_ain_x1_0'] + +__trained_urls = { + + # market1501 models ######################################################## + 'resnet50_market1501.pt': + 'https://drive.google.com/uc?id=1dUUZ4rHDWohmsQXCRe2C_HbYkzz94iBV', + 'resnet50_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=17ymnLglnc64NRvGOitY3BqMRS9UWd1wg', + 'resnet50_msmt17.pt': + 'https://drive.google.com/uc?id=1ep7RypVDOthCRIAqDnn4_N-UhkkFHJsj', + + 'resnet50_fc512_market1501.pt': + 'https://drive.google.com/uc?id=1kv8l5laX_YCdIGVCetjlNdzKIA3NvsSt', + 'resnet50_fc512_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=13QN8Mp3XH81GK4BPGXobKHKyTGH50Rtx', + 'resnet50_fc512_msmt17.pt': + 'https://drive.google.com/uc?id=1fDJLcz4O5wxNSUvImIIjoaIF9u1Rwaud', + + 'mlfn_market1501.pt': + 'https://drive.google.com/uc?id=1wXcvhA_b1kpDfrt9s2Pma-MHxtj9pmvS', + 'mlfn_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=1rExgrTNb0VCIcOnXfMsbwSUW1h2L1Bum', + 'mlfn_msmt17.pt': + 'https://drive.google.com/uc?id=18JzsZlJb3Wm7irCbZbZ07TN4IFKvR6p-', + + 'hacnn_market1501.pt': + 'https://drive.google.com/uc?id=1LRKIQduThwGxMDQMiVkTScBwR7WidmYF', + 'hacnn_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=1zNm6tP4ozFUCUQ7Sv1Z98EAJWXJEhtYH', + 'hacnn_msmt17.pt': + 'https://drive.google.com/uc?id=1MsKRtPM5WJ3_Tk2xC0aGOO7pM3VaFDNZ', + + 'mobilenetv2_x1_0_market1501.pt': + 'https://drive.google.com/uc?id=18DgHC2ZJkjekVoqBWszD8_Xiikz-fewp', + 'mobilenetv2_x1_0_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=1q1WU2FETRJ3BXcpVtfJUuqq4z3psetds', + 'mobilenetv2_x1_0_msmt17.pt': + 'https://drive.google.com/uc?id=1j50Hv14NOUAg7ZeB3frzfX-WYLi7SrhZ', + + 'mobilenetv2_x1_4_market1501.pt': + 'https://drive.google.com/uc?id=1t6JCqphJG-fwwPVkRLmGGyEBhGOf2GO5', + 'mobilenetv2_x1_4_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=12uD5FeVqLg9-AFDju2L7SQxjmPb4zpBN', + 'mobilenetv2_x1_4_msmt17.pt': + 'https://drive.google.com/uc?id=1ZY5P2Zgm-3RbDpbXM0kIBMPvspeNIbXz', + + 'osnet_x1_0_market1501.pt': + 'https://drive.google.com/uc?id=1vduhq5DpN2q1g4fYEZfPI17MJeh9qyrA', + 'osnet_x1_0_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=1QZO_4sNf4hdOKKKzKc-TZU9WW1v6zQbq', + 'osnet_x1_0_msmt17.pt': + 'https://drive.google.com/uc?id=112EMUfBPYeYg70w-syK6V6Mx8-Qb9Q1M', + + 'osnet_x0_75_market1501.pt': + 'https://drive.google.com/uc?id=1ozRaDSQw_EQ8_93OUmjDbvLXw9TnfPer', + 'osnet_x0_75_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=1IE3KRaTPp4OUa6PGTFL_d5_KQSJbP0Or', + 'osnet_x0_75_msmt17.pt': + 'https://drive.google.com/uc?id=1QEGO6WnJ-BmUzVPd3q9NoaO_GsPNlmWc', + + 'osnet_x0_5_market1501.pt': + 'https://drive.google.com/uc?id=1PLB9rgqrUM7blWrg4QlprCuPT7ILYGKT', + 'osnet_x0_5_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=1KoUVqmiST175hnkALg9XuTi1oYpqcyTu', + 'osnet_x0_5_msmt17.pt': + 'https://drive.google.com/uc?id=1UT3AxIaDvS2PdxzZmbkLmjtiqq7AIKCv', + + 'osnet_x0_25_market1501.pt': + 'https://drive.google.com/uc?id=1z1UghYvOTtjx7kEoRfmqSMu-z62J6MAj', + 'osnet_x0_25_dukemtmcreid.pt': + 'https://drive.google.com/uc?id=1eumrtiXT4NOspjyEV4j8cHmlOaaCGk5l', + 'osnet_x0_25_msmt17.pt': + 'https://drive.google.com/uc?id=1sSwXSUlj4_tHZequ_iZ8w_Jh0VaRQMqF', + + ####### market1501 models ################################################## + 'resnet50_msmt17.pt': + 'https://drive.google.com/uc?id=1yiBteqgIZoOeywE8AhGmEQl7FTVwrQmf', + 'osnet_x1_0_msmt17.pt': + 'https://drive.google.com/uc?id=1IosIFlLiulGIjwW3H8uMRmx3MzPwf86x', + 'osnet_x0_75_msmt17.pt': + 'https://drive.google.com/uc?id=1fhjSS_7SUGCioIf2SWXaRGPqIY9j7-uw', + + 'osnet_x0_5_msmt17.pt': + 'https://drive.google.com/uc?id=1DHgmb6XV4fwG3n-CnCM0zdL9nMsZ9_RF', + 'osnet_x0_25_msmt17.pt': + 'https://drive.google.com/uc?id=1Kkx2zW89jq_NETu4u42CFZTMVD5Hwm6e', + 'osnet_ibn_x1_0_msmt17.pt': + 'https://drive.google.com/uc?id=1q3Sj2ii34NlfxA4LvmHdWO_75NDRmECJ', + 'osnet_ain_x1_0_msmt17.pt': + 'https://drive.google.com/uc?id=1SigwBE6mPdqiJMqhuIY4aqC7--5CsMal', +} + + +def show_downloadeable_models(): + print('\nAvailable .pt ReID models for automatic download') + print(list(__trained_urls.keys())) + + +def get_model_url(model): + model = str(model).rsplit('/', 1)[-1] + if model in __trained_urls: + return __trained_urls[model] + else: + None + + +def is_model_in_model_types(model): + model = str(model).rsplit('/', 1)[-1].split('.')[0] + if model in __model_types: + return True + else: + return False + + +def get_model_name(model): + model = str(model).rsplit('/', 1)[-1].split('.')[0] + for x in __model_types: + if x in model: + return x + return None + diff --git a/strong_sort/reid_multibackend.py b/strong_sort/reid_multibackend.py new file mode 100644 index 0000000000000000000000000000000000000000..2f2bdd8c0000c9ec8feaaf5beb3175670cddc9c1 --- /dev/null +++ b/strong_sort/reid_multibackend.py @@ -0,0 +1,181 @@ +import torch.nn as nn +import torch +from pathlib import Path +import numpy as np +import torchvision.transforms as transforms +import cv2 +import pandas as pd +import gdown +from os.path import exists as file_exists +from .deep.reid_model_factory import show_downloadeable_models, get_model_url, get_model_name + +from torchreid.reid.utils import FeatureExtractor +from torchreid.reid.utils.tools import download_url + + +def check_suffix(file='yolov5s.pt', suffix=('.pt',), msg=''): + # Check file(s) for acceptable suffix + if file and suffix: + if isinstance(suffix, str): + suffix = [suffix] + for f in file if isinstance(file, (list, tuple)) else [file]: + s = Path(f).suffix.lower() # file suffix + if len(s): + assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}" + + +class ReIDDetectMultiBackend(nn.Module): + # ReID models MultiBackend class for python inference on various backends + def __init__(self, weights='osnet_x0_25_msmt17.pt', device=torch.device('cpu'), fp16=False): + super().__init__() + w = str(weights[0] if isinstance(weights, list) else weights) + self.pt, self.jit, self.onnx, self.xml, self.engine, self.coreml, \ + self.saved_model, self.pb, self.tflite, self.edgetpu, self.tfjs = self.model_type(w) # get backend + + if self.pt: # PyTorch + model_name = get_model_name(weights) + model_url = get_model_url(weights) + + if not file_exists(weights) and model_url is not None: + gdown.download(model_url, str(weights), quiet=False) + elif file_exists(weights): + pass + elif model_url is None: + print('No URL associated to the chosen DeepSort weights. Choose between:') + show_downloadeable_models() + exit() + + self.extractor = FeatureExtractor( + # get rid of dataset information DeepSort model name + model_name=model_name, + model_path=weights, + device=str(device) + ) + self.extractor.model.half() if fp16 else self.extractor.model.float() + elif self.onnx: # ONNX Runtime + # LOGGER.info(f'Loading {w} for ONNX Runtime inference...') + cuda = torch.cuda.is_available() + #check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime')) + import onnxruntime + providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider'] + self.session = onnxruntime.InferenceSession(w, providers=providers) + + elif self.tflite: + try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu + from tflite_runtime.interpreter import Interpreter, load_delegate + except ImportError: + import tensorflow as tf + Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate, + self.interpreter = tf.lite.Interpreter(model_path=weights) + self.interpreter.allocate_tensors() + # Get input and output tensors. + self.input_details = self.interpreter.get_input_details() + self.output_details = self.interpreter.get_output_details() + + # Test model on random input data. + input_data = np.array(np.random.random_sample((1,256,128,3)), dtype=np.float32) + self.interpreter.set_tensor(self.input_details[0]['index'], input_data) + + self.interpreter.invoke() + + # The function `get_tensor()` returns a copy of the tensor data. + output_data = self.interpreter.get_tensor(self.output_details[0]['index']) + print(output_data.shape) + else: + print('This model framework is not supported yet!') + exit() + + pixel_mean=[0.485, 0.456, 0.406] + pixel_std=[0.229, 0.224, 0.225] + self.norm = transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize(pixel_mean, pixel_std), + ]) + self.size = (256, 128) + self.fp16 = fp16 + self.device = device + + def export_formats(self): + # YOLOv5 export formats + x = [ + ['PyTorch', '-', '.pt', True, True], + ['TorchScript', 'torchscript', '.torchscript', True, True], + ['ONNX', 'onnx', '.onnx', True, True], + ['OpenVINO', 'openvino', '_openvino_model', True, False], + ['TensorRT', 'engine', '.engine', False, True], + ['CoreML', 'coreml', '.mlmodel', True, False], + ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True], + ['TensorFlow GraphDef', 'pb', '.pb', True, True], + ['TensorFlow Lite', 'tflite', '.tflite', True, False], + ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False, False], + ['TensorFlow.js', 'tfjs', '_web_model', False, False],] + return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU']) + + + def model_type(self, p='path/to/model.pt'): + # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx + + suffixes = list(self.export_formats().Suffix) + ['.xml'] # export suffixes + check_suffix(p, suffixes) # checks + p = Path(p).name # eliminate trailing separators + pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, xml2 = (s in p for s in suffixes) + xml |= xml2 # *_openvino_model or *.xml + tflite &= not edgetpu # *.tflite + return pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs + + def warmup(self, imgsz=(1, 256, 128, 3)): + # Warmup model by running inference once + warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb + if any(warmup_types) and self.device.type != 'cpu': + im = torch.zeros(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input + im = im.cpu().numpy() + print(im.shape) + for _ in range(2 if self.jit else 1): # + self.forward(im) # warmup + + def preprocess(self, im_crops): + def _resize(im, size): + return cv2.resize(im.astype(np.float32), size) + + im = torch.cat([self.norm(_resize(im, self.size)).unsqueeze(0) for im in im_crops], dim=0).float() + im = im.float().to(device=self.device) + return im + + def forward(self, im_batch): + im_batch = self.preprocess(im_batch) + b, ch, h, w = im_batch.shape # batch, channel, height, width + features = [] + for i in range(0, im_batch.shape[0]): + im = im_batch[i, :, :, :].unsqueeze(0) + if self.fp16 and im.dtype != torch.float16: + im = im.half() # to FP16 + if self.pt: # PyTorch + y = self.extractor.model(im)[0] + elif self.jit: # TorchScript + y = self.model(im)[0] + elif self.onnx: # ONNX Runtime + im = im.permute(0, 1, 3, 2).cpu().numpy() # torch to numpy # torch to numpy + y = self.session.run([self.session.get_outputs()[0].name], {self.session.get_inputs()[0].name: im})[0] + elif self.xml: # OpenVINO + im = im.cpu().numpy() # FP32 + y = self.executable_network([im])[self.output_layer] + else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU) + im = im.permute(0, 3, 2, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3) + input, output = self.input_details[0], self.output_details[0] + int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model + if int8: + scale, zero_point = input['quantization'] + im = (im / scale + zero_point).astype(np.uint8) # de-scale + self.interpreter.set_tensor(input['index'], im) + self.interpreter.invoke() + y = torch.tensor(self.interpreter.get_tensor(output['index'])) + if int8: + scale, zero_point = output['quantization'] + y = (y.astype(np.float32) - zero_point) * scale # re-scale + + if isinstance(y, np.ndarray): + y = torch.tensor(y, device=self.device) + features.append(y.squeeze()) + + + return features \ No newline at end of file diff --git a/strong_sort/sort/__init__.py b/strong_sort/sort/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/strong_sort/sort/detection.py b/strong_sort/sort/detection.py new file mode 100644 index 0000000000000000000000000000000000000000..1a018853dcb384d528787715fde416711619208f --- /dev/null +++ b/strong_sort/sort/detection.py @@ -0,0 +1,49 @@ +# vim: expandtab:ts=4:sw=4 +import numpy as np + + +class Detection(object): + """ + This class represents a bounding box detection in a single image. + + Parameters + ---------- + tlwh : array_like + Bounding box in format `(x, y, w, h)`. + confidence : float + Detector confidence score. + feature : array_like + A feature vector that describes the object contained in this image. + + Attributes + ---------- + tlwh : ndarray + Bounding box in format `(top left x, top left y, width, height)`. + confidence : ndarray + Detector confidence score. + feature : ndarray | NoneType + A feature vector that describes the object contained in this image. + + """ + + def __init__(self, tlwh, confidence, feature): + self.tlwh = np.asarray(tlwh, dtype=np.float32) + self.confidence = float(confidence) + self.feature = np.asarray(feature.cpu(), dtype=np.float32) + + def to_tlbr(self): + """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., + `(top left, bottom right)`. + """ + ret = self.tlwh.copy() + ret[2:] += ret[:2] + return ret + + def to_xyah(self): + """Convert bounding box to format `(center x, center y, aspect ratio, + height)`, where the aspect ratio is `width / height`. + """ + ret = self.tlwh.copy() + ret[:2] += ret[2:] / 2 + ret[2] /= ret[3] + return ret diff --git a/strong_sort/sort/iou_matching.py b/strong_sort/sort/iou_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..62d5a3f63b70db5e322b6f8766444dd824c010ae --- /dev/null +++ b/strong_sort/sort/iou_matching.py @@ -0,0 +1,82 @@ +# vim: expandtab:ts=4:sw=4 +from __future__ import absolute_import +import numpy as np +from . import linear_assignment + + +def iou(bbox, candidates): + """Computer intersection over union. + + Parameters + ---------- + bbox : ndarray + A bounding box in format `(top left x, top left y, width, height)`. + candidates : ndarray + A matrix of candidate bounding boxes (one per row) in the same format + as `bbox`. + + Returns + ------- + ndarray + The intersection over union in [0, 1] between the `bbox` and each + candidate. A higher score means a larger fraction of the `bbox` is + occluded by the candidate. + + """ + bbox_tl, bbox_br = bbox[:2], bbox[:2] + bbox[2:] + candidates_tl = candidates[:, :2] + candidates_br = candidates[:, :2] + candidates[:, 2:] + + tl = np.c_[np.maximum(bbox_tl[0], candidates_tl[:, 0])[:, np.newaxis], + np.maximum(bbox_tl[1], candidates_tl[:, 1])[:, np.newaxis]] + br = np.c_[np.minimum(bbox_br[0], candidates_br[:, 0])[:, np.newaxis], + np.minimum(bbox_br[1], candidates_br[:, 1])[:, np.newaxis]] + wh = np.maximum(0., br - tl) + + area_intersection = wh.prod(axis=1) + area_bbox = bbox[2:].prod() + area_candidates = candidates[:, 2:].prod(axis=1) + return area_intersection / (area_bbox + area_candidates - area_intersection) + + +def iou_cost(tracks, detections, track_indices=None, + detection_indices=None): + """An intersection over union distance metric. + + Parameters + ---------- + tracks : List[deep_sort.track.Track] + A list of tracks. + detections : List[deep_sort.detection.Detection] + A list of detections. + track_indices : Optional[List[int]] + A list of indices to tracks that should be matched. Defaults to + all `tracks`. + detection_indices : Optional[List[int]] + A list of indices to detections that should be matched. Defaults + to all `detections`. + + Returns + ------- + ndarray + Returns a cost matrix of shape + len(track_indices), len(detection_indices) where entry (i, j) is + `1 - iou(tracks[track_indices[i]], detections[detection_indices[j]])`. + + """ + if track_indices is None: + track_indices = np.arange(len(tracks)) + if detection_indices is None: + detection_indices = np.arange(len(detections)) + + cost_matrix = np.zeros((len(track_indices), len(detection_indices))) + for row, track_idx in enumerate(track_indices): + if tracks[track_idx].time_since_update > 1: + cost_matrix[row, :] = linear_assignment.INFTY_COST + continue + + bbox = tracks[track_idx].to_tlwh() + candidates = np.asarray( + [detections[i].tlwh for i in detection_indices]) + cost_matrix[row, :] = 1. - iou(bbox, candidates) + return cost_matrix diff --git a/strong_sort/sort/kalman_filter.py b/strong_sort/sort/kalman_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..87c48d7e332bef5f8feab8abf7936409abbf5d03 --- /dev/null +++ b/strong_sort/sort/kalman_filter.py @@ -0,0 +1,214 @@ +# vim: expandtab:ts=4:sw=4 +import numpy as np +import scipy.linalg +""" +Table for the 0.95 quantile of the chi-square distribution with N degrees of +freedom (contains values for N=1, ..., 9). Taken from MATLAB/Octave's chi2inv +function and used as Mahalanobis gating threshold. +""" +chi2inv95 = { + 1: 3.8415, + 2: 5.9915, + 3: 7.8147, + 4: 9.4877, + 5: 11.070, + 6: 12.592, + 7: 14.067, + 8: 15.507, + 9: 16.919} + + +class KalmanFilter(object): + """ + A simple Kalman filter for tracking bounding boxes in image space. + The 8-dimensional state space + x, y, a, h, vx, vy, va, vh + contains the bounding box center position (x, y), aspect ratio a, height h, + and their respective velocities. + Object motion follows a constant velocity model. The bounding box location + (x, y, a, h) is taken as direct observation of the state space (linear + observation model). + """ + + def __init__(self): + ndim, dt = 4, 1. + + # Create Kalman filter model matrices. + self._motion_mat = np.eye(2 * ndim, 2 * ndim) + for i in range(ndim): + self._motion_mat[i, ndim + i] = dt + + self._update_mat = np.eye(ndim, 2 * ndim) + + # Motion and observation uncertainty are chosen relative to the current + # state estimate. These weights control the amount of uncertainty in + # the model. This is a bit hacky. + self._std_weight_position = 1. / 20 + self._std_weight_velocity = 1. / 160 + + def initiate(self, measurement): + """Create track from unassociated measurement. + Parameters + ---------- + measurement : ndarray + Bounding box coordinates (x, y, a, h) with center position (x, y), + aspect ratio a, and height h. + Returns + ------- + (ndarray, ndarray) + Returns the mean vector (8 dimensional) and covariance matrix (8x8 + dimensional) of the new track. Unobserved velocities are initialized + to 0 mean. + """ + mean_pos = measurement + mean_vel = np.zeros_like(mean_pos) + mean = np.r_[mean_pos, mean_vel] + + std = [ + 2 * self._std_weight_position * measurement[0], # the center point x + 2 * self._std_weight_position * measurement[1], # the center point y + 1 * measurement[2], # the ratio of width/height + 2 * self._std_weight_position * measurement[3], # the height + 10 * self._std_weight_velocity * measurement[0], + 10 * self._std_weight_velocity * measurement[1], + 0.1 * measurement[2], + 10 * self._std_weight_velocity * measurement[3]] + covariance = np.diag(np.square(std)) + return mean, covariance + + def predict(self, mean, covariance): + """Run Kalman filter prediction step. + Parameters + ---------- + mean : ndarray + The 8 dimensional mean vector of the object state at the previous + time step. + covariance : ndarray + The 8x8 dimensional covariance matrix of the object state at the + previous time step. + Returns + ------- + (ndarray, ndarray) + Returns the mean vector and covariance matrix of the predicted + state. Unobserved velocities are initialized to 0 mean. + """ + std_pos = [ + self._std_weight_position * mean[0], + self._std_weight_position * mean[1], + 1 * mean[2], + self._std_weight_position * mean[3]] + std_vel = [ + self._std_weight_velocity * mean[0], + self._std_weight_velocity * mean[1], + 0.1 * mean[2], + self._std_weight_velocity * mean[3]] + motion_cov = np.diag(np.square(np.r_[std_pos, std_vel])) + + mean = np.dot(self._motion_mat, mean) + covariance = np.linalg.multi_dot(( + self._motion_mat, covariance, self._motion_mat.T)) + motion_cov + + return mean, covariance + + def project(self, mean, covariance, confidence=.0): + """Project state distribution to measurement space. + Parameters + ---------- + mean : ndarray + The state's mean vector (8 dimensional array). + covariance : ndarray + The state's covariance matrix (8x8 dimensional). + confidence: (dyh) 检测框置信度 + Returns + ------- + (ndarray, ndarray) + Returns the projected mean and covariance matrix of the given state + estimate. + """ + std = [ + self._std_weight_position * mean[3], + self._std_weight_position * mean[3], + 1e-1, + self._std_weight_position * mean[3]] + + + std = [(1 - confidence) * x for x in std] + + innovation_cov = np.diag(np.square(std)) + + mean = np.dot(self._update_mat, mean) + covariance = np.linalg.multi_dot(( + self._update_mat, covariance, self._update_mat.T)) + return mean, covariance + innovation_cov + + def update(self, mean, covariance, measurement, confidence=.0): + """Run Kalman filter correction step. + Parameters + ---------- + mean : ndarray + The predicted state's mean vector (8 dimensional). + covariance : ndarray + The state's covariance matrix (8x8 dimensional). + measurement : ndarray + The 4 dimensional measurement vector (x, y, a, h), where (x, y) + is the center position, a the aspect ratio, and h the height of the + bounding box. + confidence: (dyh)检测框置信度 + Returns + ------- + (ndarray, ndarray) + Returns the measurement-corrected state distribution. + """ + projected_mean, projected_cov = self.project(mean, covariance, confidence) + + chol_factor, lower = scipy.linalg.cho_factor( + projected_cov, lower=True, check_finite=False) + kalman_gain = scipy.linalg.cho_solve( + (chol_factor, lower), np.dot(covariance, self._update_mat.T).T, + check_finite=False).T + innovation = measurement - projected_mean + + new_mean = mean + np.dot(innovation, kalman_gain.T) + new_covariance = covariance - np.linalg.multi_dot(( + kalman_gain, projected_cov, kalman_gain.T)) + return new_mean, new_covariance + + def gating_distance(self, mean, covariance, measurements, + only_position=False): + """Compute gating distance between state distribution and measurements. + A suitable distance threshold can be obtained from `chi2inv95`. If + `only_position` is False, the chi-square distribution has 4 degrees of + freedom, otherwise 2. + Parameters + ---------- + mean : ndarray + Mean vector over the state distribution (8 dimensional). + covariance : ndarray + Covariance of the state distribution (8x8 dimensional). + measurements : ndarray + An Nx4 dimensional matrix of N measurements, each in + format (x, y, a, h) where (x, y) is the bounding box center + position, a the aspect ratio, and h the height. + only_position : Optional[bool] + If True, distance computation is done with respect to the bounding + box center position only. + Returns + ------- + ndarray + Returns an array of length N, where the i-th element contains the + squared Mahalanobis distance between (mean, covariance) and + `measurements[i]`. + """ + mean, covariance = self.project(mean, covariance) + + if only_position: + mean, covariance = mean[:2], covariance[:2, :2] + measurements = measurements[:, :2] + + cholesky_factor = np.linalg.cholesky(covariance) + d = measurements - mean + z = scipy.linalg.solve_triangular( + cholesky_factor, d.T, lower=True, check_finite=False, + overwrite_b=True) + squared_maha = np.sum(z * z, axis=0) + return squared_maha \ No newline at end of file diff --git a/strong_sort/sort/linear_assignment.py b/strong_sort/sort/linear_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..924895fd3a0b8243a6eb691624883feccaa937cc --- /dev/null +++ b/strong_sort/sort/linear_assignment.py @@ -0,0 +1,174 @@ +# vim: expandtab:ts=4:sw=4 +from __future__ import absolute_import +import numpy as np +from scipy.optimize import linear_sum_assignment +from . import kalman_filter + + +INFTY_COST = 1e+5 + + +def min_cost_matching( + distance_metric, max_distance, tracks, detections, track_indices=None, + detection_indices=None): + """Solve linear assignment problem. + Parameters + ---------- + distance_metric : Callable[List[Track], List[Detection], List[int], List[int]) -> ndarray + The distance metric is given a list of tracks and detections as well as + a list of N track indices and M detection indices. The metric should + return the NxM dimensional cost matrix, where element (i, j) is the + association cost between the i-th track in the given track indices and + the j-th detection in the given detection_indices. + max_distance : float + Gating threshold. Associations with cost larger than this value are + disregarded. + tracks : List[track.Track] + A list of predicted tracks at the current time step. + detections : List[detection.Detection] + A list of detections at the current time step. + track_indices : List[int] + List of track indices that maps rows in `cost_matrix` to tracks in + `tracks` (see description above). + detection_indices : List[int] + List of detection indices that maps columns in `cost_matrix` to + detections in `detections` (see description above). + Returns + ------- + (List[(int, int)], List[int], List[int]) + Returns a tuple with the following three entries: + * A list of matched track and detection indices. + * A list of unmatched track indices. + * A list of unmatched detection indices. + """ + if track_indices is None: + track_indices = np.arange(len(tracks)) + if detection_indices is None: + detection_indices = np.arange(len(detections)) + + if len(detection_indices) == 0 or len(track_indices) == 0: + return [], track_indices, detection_indices # Nothing to match. + + cost_matrix = distance_metric( + tracks, detections, track_indices, detection_indices) + cost_matrix[cost_matrix > max_distance] = max_distance + 1e-5 + row_indices, col_indices = linear_sum_assignment(cost_matrix) + + matches, unmatched_tracks, unmatched_detections = [], [], [] + for col, detection_idx in enumerate(detection_indices): + if col not in col_indices: + unmatched_detections.append(detection_idx) + for row, track_idx in enumerate(track_indices): + if row not in row_indices: + unmatched_tracks.append(track_idx) + for row, col in zip(row_indices, col_indices): + track_idx = track_indices[row] + detection_idx = detection_indices[col] + if cost_matrix[row, col] > max_distance: + unmatched_tracks.append(track_idx) + unmatched_detections.append(detection_idx) + else: + matches.append((track_idx, detection_idx)) + return matches, unmatched_tracks, unmatched_detections + + +def matching_cascade( + distance_metric, max_distance, cascade_depth, tracks, detections, + track_indices=None, detection_indices=None): + """Run matching cascade. + Parameters + ---------- + distance_metric : Callable[List[Track], List[Detection], List[int], List[int]) -> ndarray + The distance metric is given a list of tracks and detections as well as + a list of N track indices and M detection indices. The metric should + return the NxM dimensional cost matrix, where element (i, j) is the + association cost between the i-th track in the given track indices and + the j-th detection in the given detection indices. + max_distance : float + Gating threshold. Associations with cost larger than this value are + disregarded. + cascade_depth: int + The cascade depth, should be se to the maximum track age. + tracks : List[track.Track] + A list of predicted tracks at the current time step. + detections : List[detection.Detection] + A list of detections at the current time step. + track_indices : Optional[List[int]] + List of track indices that maps rows in `cost_matrix` to tracks in + `tracks` (see description above). Defaults to all tracks. + detection_indices : Optional[List[int]] + List of detection indices that maps columns in `cost_matrix` to + detections in `detections` (see description above). Defaults to all + detections. + Returns + ------- + (List[(int, int)], List[int], List[int]) + Returns a tuple with the following three entries: + * A list of matched track and detection indices. + * A list of unmatched track indices. + * A list of unmatched detection indices. + """ + if track_indices is None: + track_indices = list(range(len(tracks))) + if detection_indices is None: + detection_indices = list(range(len(detections))) + + unmatched_detections = detection_indices + matches = [] + track_indices_l = [ + k for k in track_indices + # if tracks[k].time_since_update == 1 + level + ] + matches_l, _, unmatched_detections = \ + min_cost_matching( + distance_metric, max_distance, tracks, detections, + track_indices_l, unmatched_detections) + matches += matches_l + unmatched_tracks = list(set(track_indices) - set(k for k, _ in matches)) + return matches, unmatched_tracks, unmatched_detections + + +def gate_cost_matrix( + cost_matrix, tracks, detections, track_indices, detection_indices, + gated_cost=INFTY_COST, only_position=False): + """Invalidate infeasible entries in cost matrix based on the state + distributions obtained by Kalman filtering. + Parameters + ---------- + kf : The Kalman filter. + cost_matrix : ndarray + The NxM dimensional cost matrix, where N is the number of track indices + and M is the number of detection indices, such that entry (i, j) is the + association cost between `tracks[track_indices[i]]` and + `detections[detection_indices[j]]`. + tracks : List[track.Track] + A list of predicted tracks at the current time step. + detections : List[detection.Detection] + A list of detections at the current time step. + track_indices : List[int] + List of track indices that maps rows in `cost_matrix` to tracks in + `tracks` (see description above). + detection_indices : List[int] + List of detection indices that maps columns in `cost_matrix` to + detections in `detections` (see description above). + gated_cost : Optional[float] + Entries in the cost matrix corresponding to infeasible associations are + set this value. Defaults to a very large value. + only_position : Optional[bool] + If True, only the x, y position of the state distribution is considered + during gating. Defaults to False. + Returns + ------- + ndarray + Returns the modified cost matrix. + """ + gating_dim = 2 if only_position else 4 + gating_threshold = kalman_filter.chi2inv95[gating_dim] + measurements = np.asarray( + [detections[i].to_xyah() for i in detection_indices]) + for row, track_idx in enumerate(track_indices): + track = tracks[track_idx] + gating_distance = track.kf.gating_distance(track.mean, track.covariance, measurements, only_position) + cost_matrix[row, gating_distance > gating_threshold] = gated_cost + cost_matrix[row] = 0.995 * cost_matrix[row] + (1 - 0.995) * gating_distance + return cost_matrix \ No newline at end of file diff --git a/strong_sort/sort/nn_matching.py b/strong_sort/sort/nn_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..461c36d8de2b9b183cfa18c2c9f53e10c6f13a1e --- /dev/null +++ b/strong_sort/sort/nn_matching.py @@ -0,0 +1,164 @@ +# vim: expandtab:ts=4:sw=4 +import numpy as np +import sys +import torch +sys.path.append('strong_sort/deep/reid') +from torchreid.reid.metrics.distance import compute_distance_matrix + + +def _pdist(a, b): + """Compute pair-wise squared distance between points in `a` and `b`. + Parameters + ---------- + a : array_like + An NxM matrix of N samples of dimensionality M. + b : array_like + An LxM matrix of L samples of dimensionality M. + Returns + ------- + ndarray + Returns a matrix of size len(a), len(b) such that eleement (i, j) + contains the squared distance between `a[i]` and `b[j]`. + """ + a, b = np.asarray(a), np.asarray(b) + if len(a) == 0 or len(b) == 0: + return np.zeros((len(a), len(b))) + a2, b2 = np.square(a).sum(axis=1), np.square(b).sum(axis=1) + r2 = -2. * np.dot(a, b.T) + a2[:, None] + b2[None, :] + r2 = np.clip(r2, 0., float(np.inf)) + return r2 + + +def _cosine_distance(a, b, data_is_normalized=False): + """Compute pair-wise cosine distance between points in `a` and `b`. + Parameters + ---------- + a : array_like + An NxM matrix of N samples of dimensionality M. + b : array_like + An LxM matrix of L samples of dimensionality M. + data_is_normalized : Optional[bool] + If True, assumes rows in a and b are unit length vectors. + Otherwise, a and b are explicitly normalized to lenght 1. + Returns + ------- + ndarray + Returns a matrix of size len(a), len(b) such that eleement (i, j) + contains the squared distance between `a[i]` and `b[j]`. + """ + if not data_is_normalized: + a = np.asarray(a) / np.linalg.norm(a, axis=1, keepdims=True) + b = np.asarray(b) / np.linalg.norm(b, axis=1, keepdims=True) + return 1. - np.dot(a, b.T) + + +def _nn_euclidean_distance(x, y): + """ Helper function for nearest neighbor distance metric (Euclidean). + Parameters + ---------- + x : ndarray + A matrix of N row-vectors (sample points). + y : ndarray + A matrix of M row-vectors (query points). + Returns + ------- + ndarray + A vector of length M that contains for each entry in `y` the + smallest Euclidean distance to a sample in `x`. + """ + x_ = torch.from_numpy(np.asarray(x) / np.linalg.norm(x, axis=1, keepdims=True)) + y_ = torch.from_numpy(np.asarray(y) / np.linalg.norm(y, axis=1, keepdims=True)) + distances = compute_distance_matrix(x_, y_, metric='euclidean') + return np.maximum(0.0, torch.min(distances, axis=0)[0].numpy()) + + +def _nn_cosine_distance(x, y): + """ Helper function for nearest neighbor distance metric (cosine). + Parameters + ---------- + x : ndarray + A matrix of N row-vectors (sample points). + y : ndarray + A matrix of M row-vectors (query points). + Returns + ------- + ndarray + A vector of length M that contains for each entry in `y` the + smallest cosine distance to a sample in `x`. + """ + x_ = torch.from_numpy(np.asarray(x)) + y_ = torch.from_numpy(np.asarray(y)) + distances = compute_distance_matrix(x_, y_, metric='cosine') + distances = distances.cpu().detach().numpy() + return distances.min(axis=0) + + +class NearestNeighborDistanceMetric(object): + """ + A nearest neighbor distance metric that, for each target, returns + the closest distance to any sample that has been observed so far. + Parameters + ---------- + metric : str + Either "euclidean" or "cosine". + matching_threshold: float + The matching threshold. Samples with larger distance are considered an + invalid match. + budget : Optional[int] + If not None, fix samples per class to at most this number. Removes + the oldest samples when the budget is reached. + Attributes + ---------- + samples : Dict[int -> List[ndarray]] + A dictionary that maps from target identities to the list of samples + that have been observed so far. + """ + + def __init__(self, metric, matching_threshold, budget=None): + if metric == "euclidean": + self._metric = _nn_euclidean_distance + elif metric == "cosine": + self._metric = _nn_cosine_distance + else: + raise ValueError( + "Invalid metric; must be either 'euclidean' or 'cosine'") + self.matching_threshold = matching_threshold + self.budget = budget + self.samples = {} + + def partial_fit(self, features, targets, active_targets): + """Update the distance metric with new data. + Parameters + ---------- + features : ndarray + An NxM matrix of N features of dimensionality M. + targets : ndarray + An integer array of associated target identities. + active_targets : List[int] + A list of targets that are currently present in the scene. + """ + for feature, target in zip(features, targets): + self.samples.setdefault(target, []).append(feature) + if self.budget is not None: + self.samples[target] = self.samples[target][-self.budget:] + self.samples = {k: self.samples[k] for k in active_targets} + + def distance(self, features, targets): + """Compute distance between features and targets. + Parameters + ---------- + features : ndarray + An NxM matrix of N features of dimensionality M. + targets : List[int] + A list of targets to match the given `features` against. + Returns + ------- + ndarray + Returns a cost matrix of shape len(targets), len(features), where + element (i, j) contains the closest squared distance between + `targets[i]` and `features[j]`. + """ + cost_matrix = np.zeros((len(targets), len(features))) + for i, target in enumerate(targets): + cost_matrix[i, :] = self._metric(self.samples[target], features) + return cost_matrix \ No newline at end of file diff --git a/strong_sort/sort/preprocessing.py b/strong_sort/sort/preprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..5493b127f602dec398efac4269c00d31a3650ce9 --- /dev/null +++ b/strong_sort/sort/preprocessing.py @@ -0,0 +1,73 @@ +# vim: expandtab:ts=4:sw=4 +import numpy as np +import cv2 + + +def non_max_suppression(boxes, max_bbox_overlap, scores=None): + """Suppress overlapping detections. + + Original code from [1]_ has been adapted to include confidence score. + + .. [1] http://www.pyimagesearch.com/2015/02/16/ + faster-non-maximum-suppression-python/ + + Examples + -------- + + >>> boxes = [d.roi for d in detections] + >>> scores = [d.confidence for d in detections] + >>> indices = non_max_suppression(boxes, max_bbox_overlap, scores) + >>> detections = [detections[i] for i in indices] + + Parameters + ---------- + boxes : ndarray + Array of ROIs (x, y, width, height). + max_bbox_overlap : float + ROIs that overlap more than this values are suppressed. + scores : Optional[array_like] + Detector confidence score. + + Returns + ------- + List[int] + Returns indices of detections that have survived non-maxima suppression. + + """ + if len(boxes) == 0: + return [] + + boxes = boxes.astype(np.float) + pick = [] + + x1 = boxes[:, 0] + y1 = boxes[:, 1] + x2 = boxes[:, 2] + boxes[:, 0] + y2 = boxes[:, 3] + boxes[:, 1] + + area = (x2 - x1 + 1) * (y2 - y1 + 1) + if scores is not None: + idxs = np.argsort(scores) + else: + idxs = np.argsort(y2) + + while len(idxs) > 0: + last = len(idxs) - 1 + i = idxs[last] + pick.append(i) + + xx1 = np.maximum(x1[i], x1[idxs[:last]]) + yy1 = np.maximum(y1[i], y1[idxs[:last]]) + xx2 = np.minimum(x2[i], x2[idxs[:last]]) + yy2 = np.minimum(y2[i], y2[idxs[:last]]) + + w = np.maximum(0, xx2 - xx1 + 1) + h = np.maximum(0, yy2 - yy1 + 1) + + overlap = (w * h) / area[idxs[:last]] + + idxs = np.delete( + idxs, np.concatenate( + ([last], np.where(overlap > max_bbox_overlap)[0]))) + + return pick diff --git a/strong_sort/sort/track.py b/strong_sort/sort/track.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3d0e152c39e18caa2d8a7174fc2189a3366b56 --- /dev/null +++ b/strong_sort/sort/track.py @@ -0,0 +1,305 @@ +# vim: expandtab:ts=4:sw=4 +import cv2 +import numpy as np +from strong_sort.sort.kalman_filter import KalmanFilter + + +class TrackState: + """ + Enumeration type for the single target track state. Newly created tracks are + classified as `tentative` until enough evidence has been collected. Then, + the track state is changed to `confirmed`. Tracks that are no longer alive + are classified as `deleted` to mark them for removal from the set of active + tracks. + + """ + + Tentative = 1 + Confirmed = 2 + Deleted = 3 + + +class Track: + """ + A single target track with state space `(x, y, a, h)` and associated + velocities, where `(x, y)` is the center of the bounding box, `a` is the + aspect ratio and `h` is the height. + + Parameters + ---------- + mean : ndarray + Mean vector of the initial state distribution. + covariance : ndarray + Covariance matrix of the initial state distribution. + track_id : int + A unique track identifier. + n_init : int + Number of consecutive detections before the track is confirmed. The + track state is set to `Deleted` if a miss occurs within the first + `n_init` frames. + max_age : int + The maximum number of consecutive misses before the track state is + set to `Deleted`. + feature : Optional[ndarray] + Feature vector of the detection this track originates from. If not None, + this feature is added to the `features` cache. + + Attributes + ---------- + mean : ndarray + Mean vector of the initial state distribution. + covariance : ndarray + Covariance matrix of the initial state distribution. + track_id : int + A unique track identifier. + hits : int + Total number of measurement updates. + age : int + Total number of frames since first occurance. + time_since_update : int + Total number of frames since last measurement update. + state : TrackState + The current track state. + features : List[ndarray] + A cache of features. On each measurement update, the associated feature + vector is added to this list. + + """ + + def __init__(self, detection, track_id, class_id, conf, n_init, max_age, ema_alpha, + feature=None): + self.track_id = track_id + self.class_id = int(class_id) + self.hits = 1 + self.age = 1 + self.time_since_update = 0 + self.ema_alpha = ema_alpha + + self.state = TrackState.Tentative + self.features = [] + if feature is not None: + feature /= np.linalg.norm(feature) + self.features.append(feature) + + self.conf = conf + self._n_init = n_init + self._max_age = max_age + + self.kf = KalmanFilter() + self.mean, self.covariance = self.kf.initiate(detection) + + def to_tlwh(self): + """Get current position in bounding box format `(top left x, top left y, + width, height)`. + + Returns + ------- + ndarray + The bounding box. + + """ + ret = self.mean[:4].copy() + ret[2] *= ret[3] + ret[:2] -= ret[2:] / 2 + return ret + + def to_tlbr(self): + """Get kf estimated current position in bounding box format `(min x, miny, max x, + max y)`. + + Returns + ------- + ndarray + The predicted kf bounding box. + + """ + ret = self.to_tlwh() + ret[2:] = ret[:2] + ret[2:] + return ret + + + def ECC(self, src, dst, warp_mode = cv2.MOTION_EUCLIDEAN, eps = 1e-5, + max_iter = 100, scale = 0.1, align = False): + """Compute the warp matrix from src to dst. + Parameters + ---------- + src : ndarray + An NxM matrix of source img(BGR or Gray), it must be the same format as dst. + dst : ndarray + An NxM matrix of target img(BGR or Gray). + warp_mode: flags of opencv + translation: cv2.MOTION_TRANSLATION + rotated and shifted: cv2.MOTION_EUCLIDEAN + affine(shift,rotated,shear): cv2.MOTION_AFFINE + homography(3d): cv2.MOTION_HOMOGRAPHY + eps: float + the threshold of the increment in the correlation coefficient between two iterations + max_iter: int + the number of iterations. + scale: float or [int, int] + scale_ratio: float + scale_size: [W, H] + align: bool + whether to warp affine or perspective transforms to the source image + Returns + ------- + warp matrix : ndarray + Returns the warp matrix from src to dst. + if motion models is homography, the warp matrix will be 3x3, otherwise 2x3 + src_aligned: ndarray + aligned source image of gray + """ + + # skip if current and previous frame are not initialized (1st inference) + if (src.any() or dst.any() is None): + return None, None + # skip if current and previous fames are not the same size + elif (src.shape != dst.shape): + return None, None + + # BGR2GRAY + if src.ndim == 3: + # Convert images to grayscale + src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) + dst = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY) + + # make the imgs smaller to speed up + if scale is not None: + if isinstance(scale, float) or isinstance(scale, int): + if scale != 1: + src_r = cv2.resize(src, (0, 0), fx = scale, fy = scale,interpolation = cv2.INTER_LINEAR) + dst_r = cv2.resize(dst, (0, 0), fx = scale, fy = scale,interpolation = cv2.INTER_LINEAR) + scale = [scale, scale] + else: + src_r, dst_r = src, dst + scale = None + else: + if scale[0] != src.shape[1] and scale[1] != src.shape[0]: + src_r = cv2.resize(src, (scale[0], scale[1]), interpolation = cv2.INTER_LINEAR) + dst_r = cv2.resize(dst, (scale[0], scale[1]), interpolation=cv2.INTER_LINEAR) + scale = [scale[0] / src.shape[1], scale[1] / src.shape[0]] + else: + src_r, dst_r = src, dst + scale = None + else: + src_r, dst_r = src, dst + + # Define 2x3 or 3x3 matrices and initialize the matrix to identity + if warp_mode == cv2.MOTION_HOMOGRAPHY : + warp_matrix = np.eye(3, 3, dtype=np.float32) + else : + warp_matrix = np.eye(2, 3, dtype=np.float32) + + # Define termination criteria + criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, max_iter, eps) + + # Run the ECC algorithm. The results are stored in warp_matrix. + try: + (cc, warp_matrix) = cv2.findTransformECC (src_r, dst_r, warp_matrix, warp_mode, criteria, None, 1) + except cv2.error as e: + return None, None + + + if scale is not None: + warp_matrix[0, 2] = warp_matrix[0, 2] / scale[0] + warp_matrix[1, 2] = warp_matrix[1, 2] / scale[1] + + if align: + sz = src.shape + if warp_mode == cv2.MOTION_HOMOGRAPHY: + # Use warpPerspective for Homography + src_aligned = cv2.warpPerspective(src, warp_matrix, (sz[1],sz[0]), flags=cv2.INTER_LINEAR) + else : + # Use warpAffine for Translation, Euclidean and Affine + src_aligned = cv2.warpAffine(src, warp_matrix, (sz[1],sz[0]), flags=cv2.INTER_LINEAR) + return warp_matrix, src_aligned + else: + return warp_matrix, None + + + def get_matrix(self, matrix): + eye = np.eye(3) + dist = np.linalg.norm(eye - matrix) + if dist < 100: + return matrix + else: + return eye + + def camera_update(self, previous_frame, next_frame): + warp_matrix, src_aligned = self.ECC(previous_frame, next_frame) + if warp_matrix is None and src_aligned is None: + return + [a,b] = warp_matrix + warp_matrix=np.array([a,b,[0,0,1]]) + warp_matrix = warp_matrix.tolist() + matrix = self.get_matrix(warp_matrix) + + x1, y1, x2, y2 = self.to_tlbr() + x1_, y1_, _ = matrix @ np.array([x1, y1, 1]).T + x2_, y2_, _ = matrix @ np.array([x2, y2, 1]).T + w, h = x2_ - x1_, y2_ - y1_ + cx, cy = x1_ + w / 2, y1_ + h / 2 + self.mean[:4] = [cx, cy, w / h, h] + + + def increment_age(self): + self.age += 1 + self.time_since_update += 1 + + def predict(self, kf): + """Propagate the state distribution to the current time step using a + Kalman filter prediction step. + + Parameters + ---------- + kf : kalman_filter.KalmanFilter + The Kalman filter. + + """ + self.mean, self.covariance = self.kf.predict(self.mean, self.covariance) + self.age += 1 + self.time_since_update += 1 + + def update(self, detection, class_id, conf): + """Perform Kalman filter measurement update step and update the feature + cache. + Parameters + ---------- + detection : Detection + The associated detection. + """ + self.conf = conf + self.class_id = class_id.int() + self.mean, self.covariance = self.kf.update(self.mean, self.covariance, detection.to_xyah(), detection.confidence) + + feature = detection.feature / np.linalg.norm(detection.feature) + + smooth_feat = self.ema_alpha * self.features[-1] + (1 - self.ema_alpha) * feature + smooth_feat /= np.linalg.norm(smooth_feat) + self.features = [smooth_feat] + + self.hits += 1 + self.time_since_update = 0 + if self.state == TrackState.Tentative and self.hits >= self._n_init: + self.state = TrackState.Confirmed + + def mark_missed(self): + """Mark this track as missed (no association at the current time step). + """ + if self.state == TrackState.Tentative: + self.state = TrackState.Deleted + elif self.time_since_update > self._max_age: + self.state = TrackState.Deleted + + def is_tentative(self): + """Returns True if this track is tentative (unconfirmed). + """ + return self.state == TrackState.Tentative + + def is_confirmed(self): + """Returns True if this track is confirmed.""" + return self.state == TrackState.Confirmed + + def is_deleted(self): + """Returns True if this track is dead and should be deleted.""" + return self.state == TrackState.Deleted diff --git a/strong_sort/sort/tracker.py b/strong_sort/sort/tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..e0bcce6c7b48e4535f21710abf226c107d5a0f99 --- /dev/null +++ b/strong_sort/sort/tracker.py @@ -0,0 +1,177 @@ +# vim: expandtab:ts=4:sw=4 +from __future__ import absolute_import +import numpy as np +from . import kalman_filter +from . import linear_assignment +from . import iou_matching +from .track import Track + + +class Tracker: + """ + This is the multi-target tracker. + Parameters + ---------- + metric : nn_matching.NearestNeighborDistanceMetric + A distance metric for measurement-to-track association. + max_age : int + Maximum number of missed misses before a track is deleted. + n_init : int + Number of consecutive detections before the track is confirmed. The + track state is set to `Deleted` if a miss occurs within the first + `n_init` frames. + Attributes + ---------- + metric : nn_matching.NearestNeighborDistanceMetric + The distance metric used for measurement to track association. + max_age : int + Maximum number of missed misses before a track is deleted. + n_init : int + Number of frames that a track remains in initialization phase. + kf : kalman_filter.KalmanFilter + A Kalman filter to filter target trajectories in image space. + tracks : List[Track] + The list of active tracks at the current time step. + """ + GATING_THRESHOLD = np.sqrt(kalman_filter.chi2inv95[4]) + + def __init__(self, metric, max_iou_distance=0.9, max_age=30, n_init=3, _lambda=0, ema_alpha=0.9, mc_lambda=0.995): + self.metric = metric + self.max_iou_distance = max_iou_distance + self.max_age = max_age + self.n_init = n_init + self._lambda = _lambda + self.ema_alpha = ema_alpha + self.mc_lambda = mc_lambda + + self.kf = kalman_filter.KalmanFilter() + self.tracks = [] + self._next_id = 1 + + def predict(self): + """Propagate track state distributions one time step forward. + + This function should be called once every time step, before `update`. + """ + for track in self.tracks: + track.predict(self.kf) + + def increment_ages(self): + for track in self.tracks: + track.increment_age() + track.mark_missed() + + def camera_update(self, previous_img, current_img): + for track in self.tracks: + track.camera_update(previous_img, current_img) + + def update(self, detections, classes, confidences): + """Perform measurement update and track management. + + Parameters + ---------- + detections : List[deep_sort.detection.Detection] + A list of detections at the current time step. + + """ + # Run matching cascade. + matches, unmatched_tracks, unmatched_detections = \ + self._match(detections) + + # Update track set. + for track_idx, detection_idx in matches: + self.tracks[track_idx].update( + detections[detection_idx], classes[detection_idx], confidences[detection_idx]) + for track_idx in unmatched_tracks: + self.tracks[track_idx].mark_missed() + for detection_idx in unmatched_detections: + self._initiate_track(detections[detection_idx], classes[detection_idx].item(), confidences[detection_idx].item()) + self.tracks = [t for t in self.tracks if not t.is_deleted()] + + # Update distance metric. + active_targets = [t.track_id for t in self.tracks if t.is_confirmed()] + features, targets = [], [] + for track in self.tracks: + if not track.is_confirmed(): + continue + features += track.features + targets += [track.track_id for _ in track.features] + self.metric.partial_fit(np.asarray(features), np.asarray(targets), active_targets) + + def _full_cost_metric(self, tracks, dets, track_indices, detection_indices): + """ + This implements the full lambda-based cost-metric. However, in doing so, it disregards + the possibility to gate the position only which is provided by + linear_assignment.gate_cost_matrix(). Instead, I gate by everything. + Note that the Mahalanobis distance is itself an unnormalised metric. Given the cosine + distance being normalised, we employ a quick and dirty normalisation based on the + threshold: that is, we divide the positional-cost by the gating threshold, thus ensuring + that the valid values range 0-1. + Note also that the authors work with the squared distance. I also sqrt this, so that it + is more intuitive in terms of values. + """ + # Compute First the Position-based Cost Matrix + pos_cost = np.empty([len(track_indices), len(detection_indices)]) + msrs = np.asarray([dets[i].to_xyah() for i in detection_indices]) + for row, track_idx in enumerate(track_indices): + pos_cost[row, :] = np.sqrt( + self.kf.gating_distance( + tracks[track_idx].mean, tracks[track_idx].covariance, msrs, False + ) + ) / self.GATING_THRESHOLD + pos_gate = pos_cost > 1.0 + # Now Compute the Appearance-based Cost Matrix + app_cost = self.metric.distance( + np.array([dets[i].feature for i in detection_indices]), + np.array([tracks[i].track_id for i in track_indices]), + ) + app_gate = app_cost > self.metric.matching_threshold + # Now combine and threshold + cost_matrix = self._lambda * pos_cost + (1 - self._lambda) * app_cost + cost_matrix[np.logical_or(pos_gate, app_gate)] = linear_assignment.INFTY_COST + # Return Matrix + return cost_matrix + + def _match(self, detections): + + def gated_metric(tracks, dets, track_indices, detection_indices): + features = np.array([dets[i].feature for i in detection_indices]) + targets = np.array([tracks[i].track_id for i in track_indices]) + cost_matrix = self.metric.distance(features, targets) + cost_matrix = linear_assignment.gate_cost_matrix(cost_matrix, tracks, dets, track_indices, detection_indices) + + return cost_matrix + + # Split track set into confirmed and unconfirmed tracks. + confirmed_tracks = [ + i for i, t in enumerate(self.tracks) if t.is_confirmed()] + unconfirmed_tracks = [ + i for i, t in enumerate(self.tracks) if not t.is_confirmed()] + + # Associate confirmed tracks using appearance features. + matches_a, unmatched_tracks_a, unmatched_detections = \ + linear_assignment.matching_cascade( + gated_metric, self.metric.matching_threshold, self.max_age, + self.tracks, detections, confirmed_tracks) + + # Associate remaining tracks together with unconfirmed tracks using IOU. + iou_track_candidates = unconfirmed_tracks + [ + k for k in unmatched_tracks_a if + self.tracks[k].time_since_update == 1] + unmatched_tracks_a = [ + k for k in unmatched_tracks_a if + self.tracks[k].time_since_update != 1] + matches_b, unmatched_tracks_b, unmatched_detections = \ + linear_assignment.min_cost_matching( + iou_matching.iou_cost, self.max_iou_distance, self.tracks, + detections, iou_track_candidates, unmatched_detections) + + matches = matches_a + matches_b + unmatched_tracks = list(set(unmatched_tracks_a + unmatched_tracks_b)) + return matches, unmatched_tracks, unmatched_detections + + def _initiate_track(self, detection, class_id, conf): + self.tracks.append(Track( + detection.to_xyah(), self._next_id, class_id, conf, self.n_init, self.max_age, self.ema_alpha, + detection.feature)) + self._next_id += 1 diff --git a/strong_sort/strong_sort.py b/strong_sort/strong_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..349e867022f09bfb8bc0990d3814a6995205d153 --- /dev/null +++ b/strong_sort/strong_sort.py @@ -0,0 +1,134 @@ +import numpy as np +import torch +import sys +import cv2 +import gdown +from os.path import exists as file_exists, join +import torchvision.transforms as transforms + +from .sort.nn_matching import NearestNeighborDistanceMetric +from .sort.detection import Detection +from .sort.tracker import Tracker +# from .deep.reid_model_factory import show_downloadeable_models, get_model_url, get_model_name + +from torchreid.reid.utils import FeatureExtractor +from torchreid.reid.utils.tools import download_url +from .reid_multibackend import ReIDDetectMultiBackend + +__all__ = ['StrongSORT'] + + +class StrongSORT(object): + def __init__(self, + model_weights, + device, + fp16, + max_dist=0.2, + max_iou_distance=0.7, + max_age=70, n_init=3, + nn_budget=100, + mc_lambda=0.995, + ema_alpha=0.9 + ): + + self.model = ReIDDetectMultiBackend(weights=model_weights, device=device, fp16=fp16) + + self.max_dist = max_dist + metric = NearestNeighborDistanceMetric( + "cosine", self.max_dist, nn_budget) + self.tracker = Tracker( + metric, max_iou_distance=max_iou_distance, max_age=max_age, n_init=n_init) + + def update(self, bbox_xywh, confidences, classes, ori_img): + self.height, self.width = ori_img.shape[:2] + # generate detections + features = self._get_features(bbox_xywh, ori_img) + bbox_tlwh = self._xywh_to_tlwh(bbox_xywh) + detections = [Detection(bbox_tlwh[i], conf, features[i]) for i, conf in enumerate( + confidences)] + + # run on non-maximum supression + boxes = np.array([d.tlwh for d in detections]) + scores = np.array([d.confidence for d in detections]) + + + # update tracker + self.tracker.predict() + self.tracker.update(detections, classes, confidences) + + # output bbox identities + outputs = [] + for track in self.tracker.tracks: + if not track.is_confirmed() or track.time_since_update > 1: + continue + + box = track.to_tlwh() + x1, y1, x2, y2 = self._tlwh_to_xyxy(box) + + track_id = track.track_id + class_id = track.class_id + conf = track.conf + outputs.append(np.array([x1, y1, x2, y2, track_id, class_id, conf])) + if len(outputs) > 0: + outputs = np.stack(outputs, axis=0) + return outputs + + """ + TODO: + Convert bbox from xc_yc_w_h to xtl_ytl_w_h + Thanks JieChen91@github.com for reporting this bug! + """ + @staticmethod + def _xywh_to_tlwh(bbox_xywh): + if isinstance(bbox_xywh, np.ndarray): + bbox_tlwh = bbox_xywh.copy() + elif isinstance(bbox_xywh, torch.Tensor): + bbox_tlwh = bbox_xywh.clone() + bbox_tlwh[:, 0] = bbox_xywh[:, 0] - bbox_xywh[:, 2] / 2. + bbox_tlwh[:, 1] = bbox_xywh[:, 1] - bbox_xywh[:, 3] / 2. + return bbox_tlwh + + def _xywh_to_xyxy(self, bbox_xywh): + x, y, w, h = bbox_xywh + x1 = max(int(x - w / 2), 0) + x2 = min(int(x + w / 2), self.width - 1) + y1 = max(int(y - h / 2), 0) + y2 = min(int(y + h / 2), self.height - 1) + return x1, y1, x2, y2 + + def _tlwh_to_xyxy(self, bbox_tlwh): + """ + TODO: + Convert bbox from xtl_ytl_w_h to xc_yc_w_h + Thanks JieChen91@github.com for reporting this bug! + """ + x, y, w, h = bbox_tlwh + x1 = max(int(x), 0) + x2 = min(int(x+w), self.width - 1) + y1 = max(int(y), 0) + y2 = min(int(y+h), self.height - 1) + return x1, y1, x2, y2 + + def increment_ages(self): + self.tracker.increment_ages() + + def _xyxy_to_tlwh(self, bbox_xyxy): + x1, y1, x2, y2 = bbox_xyxy + + t = x1 + l = y1 + w = int(x2 - x1) + h = int(y2 - y1) + return t, l, w, h + + def _get_features(self, bbox_xywh, ori_img): + im_crops = [] + for box in bbox_xywh: + x1, y1, x2, y2 = self._xywh_to_xyxy(box) + im = ori_img[y1:y2, x1:x2] + im_crops.append(im) + if im_crops: + features = self.model(im_crops) + else: + features = np.array([]) + return features diff --git a/strong_sort/utils/__init__.py b/strong_sort/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/strong_sort/utils/asserts.py b/strong_sort/utils/asserts.py new file mode 100644 index 0000000000000000000000000000000000000000..59a73cc04025762d6490fcd2945a747d963def32 --- /dev/null +++ b/strong_sort/utils/asserts.py @@ -0,0 +1,13 @@ +from os import environ + + +def assert_in(file, files_to_check): + if file not in files_to_check: + raise AssertionError("{} does not exist in the list".format(str(file))) + return True + + +def assert_in_env(check_list: list): + for item in check_list: + assert_in(item, environ.keys()) + return True diff --git a/strong_sort/utils/draw.py b/strong_sort/utils/draw.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7cb537978e86805d5d9789785a8afe67df9030 --- /dev/null +++ b/strong_sort/utils/draw.py @@ -0,0 +1,36 @@ +import numpy as np +import cv2 + +palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) + + +def compute_color_for_labels(label): + """ + Simple function that adds fixed color depending on the class + """ + color = [int((p * (label ** 2 - label + 1)) % 255) for p in palette] + return tuple(color) + + +def draw_boxes(img, bbox, identities=None, offset=(0,0)): + for i,box in enumerate(bbox): + x1,y1,x2,y2 = [int(i) for i in box] + x1 += offset[0] + x2 += offset[0] + y1 += offset[1] + y2 += offset[1] + # box text and bar + id = int(identities[i]) if identities is not None else 0 + color = compute_color_for_labels(id) + label = '{}{:d}'.format("", id) + t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 2 , 2)[0] + cv2.rectangle(img,(x1, y1),(x2,y2),color,3) + cv2.rectangle(img,(x1, y1),(x1+t_size[0]+3,y1+t_size[1]+4), color,-1) + cv2.putText(img,label,(x1,y1+t_size[1]+4), cv2.FONT_HERSHEY_PLAIN, 2, [255,255,255], 2) + return img + + + +if __name__ == '__main__': + for i in range(82): + print(compute_color_for_labels(i)) diff --git a/strong_sort/utils/evaluation.py b/strong_sort/utils/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..100179407181933d59809b25400d115cfa789867 --- /dev/null +++ b/strong_sort/utils/evaluation.py @@ -0,0 +1,103 @@ +import os +import numpy as np +import copy +import motmetrics as mm +mm.lap.default_solver = 'lap' +from utils.io import read_results, unzip_objs + + +class Evaluator(object): + + def __init__(self, data_root, seq_name, data_type): + self.data_root = data_root + self.seq_name = seq_name + self.data_type = data_type + + self.load_annotations() + self.reset_accumulator() + + def load_annotations(self): + assert self.data_type == 'mot' + + gt_filename = os.path.join(self.data_root, self.seq_name, 'gt', 'gt.txt') + self.gt_frame_dict = read_results(gt_filename, self.data_type, is_gt=True) + self.gt_ignore_frame_dict = read_results(gt_filename, self.data_type, is_ignore=True) + + def reset_accumulator(self): + self.acc = mm.MOTAccumulator(auto_id=True) + + def eval_frame(self, frame_id, trk_tlwhs, trk_ids, rtn_events=False): + # results + trk_tlwhs = np.copy(trk_tlwhs) + trk_ids = np.copy(trk_ids) + + # gts + gt_objs = self.gt_frame_dict.get(frame_id, []) + gt_tlwhs, gt_ids = unzip_objs(gt_objs)[:2] + + # ignore boxes + ignore_objs = self.gt_ignore_frame_dict.get(frame_id, []) + ignore_tlwhs = unzip_objs(ignore_objs)[0] + + + # remove ignored results + keep = np.ones(len(trk_tlwhs), dtype=bool) + iou_distance = mm.distances.iou_matrix(ignore_tlwhs, trk_tlwhs, max_iou=0.5) + if len(iou_distance) > 0: + match_is, match_js = mm.lap.linear_sum_assignment(iou_distance) + match_is, match_js = map(lambda a: np.asarray(a, dtype=int), [match_is, match_js]) + match_ious = iou_distance[match_is, match_js] + + match_js = np.asarray(match_js, dtype=int) + match_js = match_js[np.logical_not(np.isnan(match_ious))] + keep[match_js] = False + trk_tlwhs = trk_tlwhs[keep] + trk_ids = trk_ids[keep] + + # get distance matrix + iou_distance = mm.distances.iou_matrix(gt_tlwhs, trk_tlwhs, max_iou=0.5) + + # acc + self.acc.update(gt_ids, trk_ids, iou_distance) + + if rtn_events and iou_distance.size > 0 and hasattr(self.acc, 'last_mot_events'): + events = self.acc.last_mot_events # only supported by https://github.com/longcw/py-motmetrics + else: + events = None + return events + + def eval_file(self, filename): + self.reset_accumulator() + + result_frame_dict = read_results(filename, self.data_type, is_gt=False) + frames = sorted(list(set(self.gt_frame_dict.keys()) | set(result_frame_dict.keys()))) + for frame_id in frames: + trk_objs = result_frame_dict.get(frame_id, []) + trk_tlwhs, trk_ids = unzip_objs(trk_objs)[:2] + self.eval_frame(frame_id, trk_tlwhs, trk_ids, rtn_events=False) + + return self.acc + + @staticmethod + def get_summary(accs, names, metrics=('mota', 'num_switches', 'idp', 'idr', 'idf1', 'precision', 'recall')): + names = copy.deepcopy(names) + if metrics is None: + metrics = mm.metrics.motchallenge_metrics + metrics = copy.deepcopy(metrics) + + mh = mm.metrics.create() + summary = mh.compute_many( + accs, + metrics=metrics, + names=names, + generate_overall=True + ) + + return summary + + @staticmethod + def save_summary(summary, filename): + import pandas as pd + writer = pd.ExcelWriter(filename) + summary.to_excel(writer) + writer.save() diff --git a/strong_sort/utils/io.py b/strong_sort/utils/io.py new file mode 100644 index 0000000000000000000000000000000000000000..2dc9afd24019cd930eef6c21ab9f579313dd3b3a --- /dev/null +++ b/strong_sort/utils/io.py @@ -0,0 +1,133 @@ +import os +from typing import Dict +import numpy as np + +# from utils.log import get_logger + + +def write_results(filename, results, data_type): + if data_type == 'mot': + save_format = '{frame},{id},{x1},{y1},{w},{h},-1,-1,-1,-1\n' + elif data_type == 'kitti': + save_format = '{frame} {id} pedestrian 0 0 -10 {x1} {y1} {x2} {y2} -10 -10 -10 -1000 -1000 -1000 -10\n' + else: + raise ValueError(data_type) + + with open(filename, 'w') as f: + for frame_id, tlwhs, track_ids in results: + if data_type == 'kitti': + frame_id -= 1 + for tlwh, track_id in zip(tlwhs, track_ids): + if track_id < 0: + continue + x1, y1, w, h = tlwh + x2, y2 = x1 + w, y1 + h + line = save_format.format(frame=frame_id, id=track_id, x1=x1, y1=y1, x2=x2, y2=y2, w=w, h=h) + f.write(line) + + +# def write_results(filename, results_dict: Dict, data_type: str): +# if not filename: +# return +# path = os.path.dirname(filename) +# if not os.path.exists(path): +# os.makedirs(path) + +# if data_type in ('mot', 'mcmot', 'lab'): +# save_format = '{frame},{id},{x1},{y1},{w},{h},1,-1,-1,-1\n' +# elif data_type == 'kitti': +# save_format = '{frame} {id} pedestrian -1 -1 -10 {x1} {y1} {x2} {y2} -1 -1 -1 -1000 -1000 -1000 -10 {score}\n' +# else: +# raise ValueError(data_type) + +# with open(filename, 'w') as f: +# for frame_id, frame_data in results_dict.items(): +# if data_type == 'kitti': +# frame_id -= 1 +# for tlwh, track_id in frame_data: +# if track_id < 0: +# continue +# x1, y1, w, h = tlwh +# x2, y2 = x1 + w, y1 + h +# line = save_format.format(frame=frame_id, id=track_id, x1=x1, y1=y1, x2=x2, y2=y2, w=w, h=h, score=1.0) +# f.write(line) +# logger.info('Save results to {}'.format(filename)) + + +def read_results(filename, data_type: str, is_gt=False, is_ignore=False): + if data_type in ('mot', 'lab'): + read_fun = read_mot_results + else: + raise ValueError('Unknown data type: {}'.format(data_type)) + + return read_fun(filename, is_gt, is_ignore) + + +""" +labels={'ped', ... % 1 +'person_on_vhcl', ... % 2 +'car', ... % 3 +'bicycle', ... % 4 +'mbike', ... % 5 +'non_mot_vhcl', ... % 6 +'static_person', ... % 7 +'distractor', ... % 8 +'occluder', ... % 9 +'occluder_on_grnd', ... %10 +'occluder_full', ... % 11 +'reflection', ... % 12 +'crowd' ... % 13 +}; +""" + + +def read_mot_results(filename, is_gt, is_ignore): + valid_labels = {1} + ignore_labels = {2, 7, 8, 12} + results_dict = dict() + if os.path.isfile(filename): + with open(filename, 'r') as f: + for line in f.readlines(): + linelist = line.split(',') + if len(linelist) < 7: + continue + fid = int(linelist[0]) + if fid < 1: + continue + results_dict.setdefault(fid, list()) + + if is_gt: + if 'MOT16-' in filename or 'MOT17-' in filename: + label = int(float(linelist[7])) + mark = int(float(linelist[6])) + if mark == 0 or label not in valid_labels: + continue + score = 1 + elif is_ignore: + if 'MOT16-' in filename or 'MOT17-' in filename: + label = int(float(linelist[7])) + vis_ratio = float(linelist[8]) + if label not in ignore_labels and vis_ratio >= 0: + continue + else: + continue + score = 1 + else: + score = float(linelist[6]) + + tlwh = tuple(map(float, linelist[2:6])) + target_id = int(linelist[1]) + + results_dict[fid].append((tlwh, target_id, score)) + + return results_dict + + +def unzip_objs(objs): + if len(objs) > 0: + tlwhs, ids, scores = zip(*objs) + else: + tlwhs, ids, scores = [], [], [] + tlwhs = np.asarray(tlwhs, dtype=float).reshape(-1, 4) + + return tlwhs, ids, scores \ No newline at end of file diff --git a/strong_sort/utils/json_logger.py b/strong_sort/utils/json_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..0afd0b45df736866c49473db78286685d77660ac --- /dev/null +++ b/strong_sort/utils/json_logger.py @@ -0,0 +1,383 @@ +""" +References: + https://medium.com/analytics-vidhya/creating-a-custom-logging-mechanism-for-real-time-object-detection-using-tdd-4ca2cfcd0a2f +""" +import json +from os import makedirs +from os.path import exists, join +from datetime import datetime + + +class JsonMeta(object): + HOURS = 3 + MINUTES = 59 + SECONDS = 59 + PATH_TO_SAVE = 'LOGS' + DEFAULT_FILE_NAME = 'remaining' + + +class BaseJsonLogger(object): + """ + This is the base class that returns __dict__ of its own + it also returns the dicts of objects in the attributes that are list instances + + """ + + def dic(self): + # returns dicts of objects + out = {} + for k, v in self.__dict__.items(): + if hasattr(v, 'dic'): + out[k] = v.dic() + elif isinstance(v, list): + out[k] = self.list(v) + else: + out[k] = v + return out + + @staticmethod + def list(values): + # applies the dic method on items in the list + return [v.dic() if hasattr(v, 'dic') else v for v in values] + + +class Label(BaseJsonLogger): + """ + For each bounding box there are various categories with confidences. Label class keeps track of that information. + """ + + def __init__(self, category: str, confidence: float): + self.category = category + self.confidence = confidence + + +class Bbox(BaseJsonLogger): + """ + This module stores the information for each frame and use them in JsonParser + Attributes: + labels (list): List of label module. + top (int): + left (int): + width (int): + height (int): + + Args: + bbox_id (float): + top (int): + left (int): + width (int): + height (int): + + References: + Check Label module for better understanding. + + + """ + + def __init__(self, bbox_id, top, left, width, height): + self.labels = [] + self.bbox_id = bbox_id + self.top = top + self.left = left + self.width = width + self.height = height + + def add_label(self, category, confidence): + # adds category and confidence only if top_k is not exceeded. + self.labels.append(Label(category, confidence)) + + def labels_full(self, value): + return len(self.labels) == value + + +class Frame(BaseJsonLogger): + """ + This module stores the information for each frame and use them in JsonParser + Attributes: + timestamp (float): The elapsed time of captured frame + frame_id (int): The frame number of the captured video + bboxes (list of Bbox objects): Stores the list of bbox objects. + + References: + Check Bbox class for better information + + Args: + timestamp (float): + frame_id (int): + + """ + + def __init__(self, frame_id: int, timestamp: float = None): + self.frame_id = frame_id + self.timestamp = timestamp + self.bboxes = [] + + def add_bbox(self, bbox_id: int, top: int, left: int, width: int, height: int): + bboxes_ids = [bbox.bbox_id for bbox in self.bboxes] + if bbox_id not in bboxes_ids: + self.bboxes.append(Bbox(bbox_id, top, left, width, height)) + else: + raise ValueError("Frame with id: {} already has a Bbox with id: {}".format(self.frame_id, bbox_id)) + + def add_label_to_bbox(self, bbox_id: int, category: str, confidence: float): + bboxes = {bbox.id: bbox for bbox in self.bboxes} + if bbox_id in bboxes.keys(): + res = bboxes.get(bbox_id) + res.add_label(category, confidence) + else: + raise ValueError('the bbox with id: {} does not exists!'.format(bbox_id)) + + +class BboxToJsonLogger(BaseJsonLogger): + """ + ُ This module is designed to automate the task of logging jsons. An example json is used + to show the contents of json file shortly + Example: + { + "video_details": { + "frame_width": 1920, + "frame_height": 1080, + "frame_rate": 20, + "video_name": "/home/gpu/codes/MSD/pedestrian_2/project/public/camera1.avi" + }, + "frames": [ + { + "frame_id": 329, + "timestamp": 3365.1254 + "bboxes": [ + { + "labels": [ + { + "category": "pedestrian", + "confidence": 0.9 + } + ], + "bbox_id": 0, + "top": 1257, + "left": 138, + "width": 68, + "height": 109 + } + ] + }], + + Attributes: + frames (dict): It's a dictionary that maps each frame_id to json attributes. + video_details (dict): information about video file. + top_k_labels (int): shows the allowed number of labels + start_time (datetime object): we use it to automate the json output by time. + + Args: + top_k_labels (int): shows the allowed number of labels + + """ + + def __init__(self, top_k_labels: int = 1): + self.frames = {} + self.video_details = self.video_details = dict(frame_width=None, frame_height=None, frame_rate=None, + video_name=None) + self.top_k_labels = top_k_labels + self.start_time = datetime.now() + + def set_top_k(self, value): + self.top_k_labels = value + + def frame_exists(self, frame_id: int) -> bool: + """ + Args: + frame_id (int): + + Returns: + bool: true if frame_id is recognized + """ + return frame_id in self.frames.keys() + + def add_frame(self, frame_id: int, timestamp: float = None) -> None: + """ + Args: + frame_id (int): + timestamp (float): opencv captured frame time property + + Raises: + ValueError: if frame_id would not exist in class frames attribute + + Returns: + None + + """ + if not self.frame_exists(frame_id): + self.frames[frame_id] = Frame(frame_id, timestamp) + else: + raise ValueError("Frame id: {} already exists".format(frame_id)) + + def bbox_exists(self, frame_id: int, bbox_id: int) -> bool: + """ + Args: + frame_id: + bbox_id: + + Returns: + bool: if bbox exists in frame bboxes list + """ + bboxes = [] + if self.frame_exists(frame_id=frame_id): + bboxes = [bbox.bbox_id for bbox in self.frames[frame_id].bboxes] + return bbox_id in bboxes + + def find_bbox(self, frame_id: int, bbox_id: int): + """ + + Args: + frame_id: + bbox_id: + + Returns: + bbox_id (int): + + Raises: + ValueError: if bbox_id does not exist in the bbox list of specific frame. + """ + if not self.bbox_exists(frame_id, bbox_id): + raise ValueError("frame with id: {} does not contain bbox with id: {}".format(frame_id, bbox_id)) + bboxes = {bbox.bbox_id: bbox for bbox in self.frames[frame_id].bboxes} + return bboxes.get(bbox_id) + + def add_bbox_to_frame(self, frame_id: int, bbox_id: int, top: int, left: int, width: int, height: int) -> None: + """ + + Args: + frame_id (int): + bbox_id (int): + top (int): + left (int): + width (int): + height (int): + + Returns: + None + + Raises: + ValueError: if bbox_id already exist in frame information with frame_id + ValueError: if frame_id does not exist in frames attribute + """ + if self.frame_exists(frame_id): + frame = self.frames[frame_id] + if not self.bbox_exists(frame_id, bbox_id): + frame.add_bbox(bbox_id, top, left, width, height) + else: + raise ValueError( + "frame with frame_id: {} already contains the bbox with id: {} ".format(frame_id, bbox_id)) + else: + raise ValueError("frame with frame_id: {} does not exist".format(frame_id)) + + def add_label_to_bbox(self, frame_id: int, bbox_id: int, category: str, confidence: float): + """ + Args: + frame_id: + bbox_id: + category: + confidence: the confidence value returned from yolo detection + + Returns: + None + + Raises: + ValueError: if labels quota (top_k_labels) exceeds. + """ + bbox = self.find_bbox(frame_id, bbox_id) + if not bbox.labels_full(self.top_k_labels): + bbox.add_label(category, confidence) + else: + raise ValueError("labels in frame_id: {}, bbox_id: {} is fulled".format(frame_id, bbox_id)) + + def add_video_details(self, frame_width: int = None, frame_height: int = None, frame_rate: int = None, + video_name: str = None): + self.video_details['frame_width'] = frame_width + self.video_details['frame_height'] = frame_height + self.video_details['frame_rate'] = frame_rate + self.video_details['video_name'] = video_name + + def output(self): + output = {'video_details': self.video_details} + result = list(self.frames.values()) + output['frames'] = [item.dic() for item in result] + return output + + def json_output(self, output_name): + """ + Args: + output_name: + + Returns: + None + + Notes: + It creates the json output with `output_name` name. + """ + if not output_name.endswith('.json'): + output_name += '.json' + with open(output_name, 'w') as file: + json.dump(self.output(), file) + file.close() + + def set_start(self): + self.start_time = datetime.now() + + def schedule_output_by_time(self, output_dir=JsonMeta.PATH_TO_SAVE, hours: int = 0, minutes: int = 0, + seconds: int = 60) -> None: + """ + Notes: + Creates folder and then periodically stores the jsons on that address. + + Args: + output_dir (str): the directory where output files will be stored + hours (int): + minutes (int): + seconds (int): + + Returns: + None + + """ + end = datetime.now() + interval = 0 + interval += abs(min([hours, JsonMeta.HOURS]) * 3600) + interval += abs(min([minutes, JsonMeta.MINUTES]) * 60) + interval += abs(min([seconds, JsonMeta.SECONDS])) + diff = (end - self.start_time).seconds + + if diff > interval: + output_name = self.start_time.strftime('%Y-%m-%d %H-%M-%S') + '.json' + if not exists(output_dir): + makedirs(output_dir) + output = join(output_dir, output_name) + self.json_output(output_name=output) + self.frames = {} + self.start_time = datetime.now() + + def schedule_output_by_frames(self, frames_quota, frame_counter, output_dir=JsonMeta.PATH_TO_SAVE): + """ + saves as the number of frames quota increases higher. + :param frames_quota: + :param frame_counter: + :param output_dir: + :return: + """ + pass + + def flush(self, output_dir): + """ + Notes: + We use this function to output jsons whenever possible. + like the time that we exit the while loop of opencv. + + Args: + output_dir: + + Returns: + None + + """ + filename = self.start_time.strftime('%Y-%m-%d %H-%M-%S') + '-remaining.json' + output = join(output_dir, filename) + self.json_output(output_name=output) diff --git a/strong_sort/utils/log.py b/strong_sort/utils/log.py new file mode 100644 index 0000000000000000000000000000000000000000..0d48757dca88f35e9ea2cd1ca16e41bac9976a45 --- /dev/null +++ b/strong_sort/utils/log.py @@ -0,0 +1,17 @@ +import logging + + +def get_logger(name='root'): + formatter = logging.Formatter( + # fmt='%(asctime)s [%(levelname)s]: %(filename)s(%(funcName)s:%(lineno)s) >> %(message)s') + fmt='%(asctime)s [%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') + + handler = logging.StreamHandler() + handler.setFormatter(formatter) + + logger = logging.getLogger(name) + logger.setLevel(logging.INFO) + logger.addHandler(handler) + return logger + + diff --git a/strong_sort/utils/parser.py b/strong_sort/utils/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..c29ed84479c6a7b8bc7148f3aac8941c7b261c3d --- /dev/null +++ b/strong_sort/utils/parser.py @@ -0,0 +1,41 @@ +import os +import yaml +from easydict import EasyDict as edict + + +class YamlParser(edict): + """ + This is yaml parser based on EasyDict. + """ + + def __init__(self, cfg_dict=None, config_file=None): + if cfg_dict is None: + cfg_dict = {} + + if config_file is not None: + assert(os.path.isfile(config_file)) + with open(config_file, 'r') as fo: + yaml_ = yaml.load(fo.read(), Loader=yaml.FullLoader) + cfg_dict.update(yaml_) + + super(YamlParser, self).__init__(cfg_dict) + + def merge_from_file(self, config_file): + with open(config_file, 'r') as fo: + yaml_ = yaml.load(fo.read(), Loader=yaml.FullLoader) + self.update(yaml_) + + def merge_from_dict(self, config_dict): + self.update(config_dict) + + +def get_config(config_file=None): + return YamlParser(config_file=config_file) + + +if __name__ == "__main__": + cfg = YamlParser(config_file="../configs/yolov3.yaml") + cfg.merge_from_file("../configs/strong_sort.yaml") + + import ipdb + ipdb.set_trace() diff --git a/strong_sort/utils/tools.py b/strong_sort/utils/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..965fb69c2df41510fd740a4ab57d8fc7b81012de --- /dev/null +++ b/strong_sort/utils/tools.py @@ -0,0 +1,39 @@ +from functools import wraps +from time import time + + +def is_video(ext: str): + """ + Returns true if ext exists in + allowed_exts for video files. + + Args: + ext: + + Returns: + + """ + + allowed_exts = ('.mp4', '.webm', '.ogg', '.avi', '.wmv', '.mkv', '.3gp') + return any((ext.endswith(x) for x in allowed_exts)) + + +def tik_tok(func): + """ + keep track of time for each process. + Args: + func: + + Returns: + + """ + @wraps(func) + def _time_it(*args, **kwargs): + start = time() + try: + return func(*args, **kwargs) + finally: + end_ = time() + print("time: {:.03f}s, fps: {:.03f}".format(end_ - start, 1 / (end_ - start))) + + return _time_it