|
| 1 | +import numpy as np |
| 2 | +import torch |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +import cv2 |
| 5 | +import torch.utils.benchmark as benchmark |
| 6 | + |
| 7 | +from torch._inductor import config as inductorconfig |
| 8 | +inductorconfig.triton.unique_kernel_names = True |
| 9 | +inductorconfig.coordinate_descent_tuning = True |
| 10 | +inductorconfig.coordinate_descent_check_all_directions = True |
| 11 | + |
| 12 | +def profiler_runner(path, fn, *args, **kwargs): |
| 13 | + with torch.profiler.profile( |
| 14 | + activities=[torch.profiler.ProfilerActivity.CPU, |
| 15 | + torch.profiler.ProfilerActivity.CUDA], |
| 16 | + record_shapes=True) as prof: |
| 17 | + result = fn(*args, **kwargs) |
| 18 | + print(f"Saving trace under {path}") |
| 19 | + prof.export_chrome_trace(path) |
| 20 | + return result |
| 21 | + |
| 22 | +def show_anns(anns): |
| 23 | + if len(anns) == 0: |
| 24 | + return |
| 25 | + sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True) |
| 26 | + ax = plt.gca() |
| 27 | + ax.set_autoscale_on(False) |
| 28 | + |
| 29 | + img = np.ones((sorted_anns[0]['segmentation'].shape[0], sorted_anns[0]['segmentation'].shape[1], 4)) |
| 30 | + img[:,:,3] = 0 |
| 31 | + ms = [] |
| 32 | + for ann in sorted_anns: |
| 33 | + m = ann['segmentation'] |
| 34 | + ms.append(torch.as_tensor(m)) |
| 35 | + color_mask = np.concatenate([np.random.random(3), [0.35]]) |
| 36 | + img[m] = color_mask |
| 37 | + ax.imshow(img) |
| 38 | + return torch.stack(ms) |
| 39 | + |
| 40 | +image = cv2.imread('dog.jpg') |
| 41 | +image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) |
| 42 | + |
| 43 | + |
| 44 | +# from segment_anything_fast import sam_model_registry, sam_model_fast_registry, SamAutomaticMaskGenerator |
| 45 | +# |
| 46 | +# sam_checkpoint = "checkpoints/sam_vit_h_4b8939.pth" |
| 47 | +# model_type = "vit_h" |
| 48 | +device = "cuda" |
| 49 | +# |
| 50 | +# sam = sam_model_fast_registry[model_type](checkpoint=sam_checkpoint) |
| 51 | +# sam.to(device=device) |
| 52 | + |
| 53 | +from sam2.build_sam import build_sam2 |
| 54 | +from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator |
| 55 | + |
| 56 | +sam2_checkpoint = "checkpoints/sam2_hiera_large.pt" |
| 57 | +model_cfg = "sam2_hiera_l.yaml" |
| 58 | + |
| 59 | +sam2 = build_sam2(model_cfg, sam2_checkpoint, device=device, apply_postprocessing=False) |
| 60 | +sam2.to(device=device) |
| 61 | + |
| 62 | +# mask_generator = SAM2AutomaticMaskGenerator(sam2, points_per_batch=256) |
| 63 | +mask_generator = SAM2AutomaticMaskGenerator(sam2, points_per_batch=None) |
| 64 | + |
| 65 | +## NOTE: Causes numerical differences |
| 66 | +## TODO: Implement mIoU to allow approximations. |
| 67 | +# torch.set_float32_matmul_precision('high') |
| 68 | +# torch.autocast("cuda", dtype=torch.bfloat16).__enter__() |
| 69 | +## |
| 70 | + |
| 71 | +## TODO: Using CUDA graphs can cause numerical differences? |
| 72 | +mask_generator.predictor.model.image_encoder = torch.compile( |
| 73 | + mask_generator.predictor.model.image_encoder, |
| 74 | + # mode="max-autotune-no-cudagraphs", |
| 75 | + mode="max-autotune", |
| 76 | + fullgraph=True, |
| 77 | + dynamic=False, |
| 78 | +) |
| 79 | + |
| 80 | +# mask_generator.predictor._predict = torch.compile( |
| 81 | +# mask_generator.predictor._predict, |
| 82 | +# mode="max-autotune-no-cudagraphs", |
| 83 | +# fullgraph=True, |
| 84 | +# dynamic=False, |
| 85 | +# ) |
| 86 | + |
| 87 | +torch._dynamo.config.capture_dynamic_output_shape_ops = True |
| 88 | +mask_generator._process_batch = torch.compile( |
| 89 | + mask_generator._process_batch, |
| 90 | + mode="max-autotune-no-cudagraphs", |
| 91 | + fullgraph=True, |
| 92 | + dynamic=True, |
| 93 | +) |
| 94 | + |
| 95 | +# with torch.backends.cuda.sdp_kernel(enable_cudnn=False): #, enable_math=False, enable_mem_efficient=False): |
| 96 | +with torch.backends.cuda.sdp_kernel(enable_cudnn=True): #, enable_math=False, enable_mem_efficient=False): |
| 97 | + # Run thrice for warmup |
| 98 | + masks = mask_generator.generate(image) |
| 99 | + masks = mask_generator.generate(image) |
| 100 | + masks = mask_generator.generate(image) |
| 101 | + |
| 102 | + # Save an example |
| 103 | + plt.figure(figsize=(image.shape[1]/100., image.shape[0]/100.), dpi=100) |
| 104 | + plt.imshow(image) |
| 105 | + ms = show_anns(masks) |
| 106 | + ms_ref = torch.load("dog_mask_fast.pt") |
| 107 | + torch.testing.assert_allclose(ms, ms_ref) |
| 108 | + print("Masks match reference") |
| 109 | + # # torch.save(ms, "dog_mask_fast.pt") |
| 110 | + plt.axis('off') |
| 111 | + plt.tight_layout() |
| 112 | + plt.savefig('dog_mask_fast.png', format='png') |
| 113 | + |
| 114 | + # Benchmark |
| 115 | + torch.cuda.synchronize() |
| 116 | + start_event = torch.cuda.Event(enable_timing=True) |
| 117 | + end_event = torch.cuda.Event(enable_timing=True) |
| 118 | + start_event.record() |
| 119 | + for _ in range(10): |
| 120 | + masks = mask_generator.generate(image) |
| 121 | + end_event.record() |
| 122 | + torch.cuda.synchronize() |
| 123 | + print(start_event.elapsed_time(end_event) / 10.) |
| 124 | + |
| 125 | + # Save a GPU trace |
| 126 | + profiler_runner(f"amg_example_trace.json.gz", mask_generator.generate, image) |
| 127 | + |
| 128 | + # Write out memory usage |
| 129 | + max_memory_allocated_bytes = torch.cuda.max_memory_allocated() |
| 130 | + _, total_memory = torch.cuda.mem_get_info() |
| 131 | + max_memory_allocated_percentage = int(100 * (max_memory_allocated_bytes / total_memory)) |
| 132 | + max_memory_allocated_bytes = max_memory_allocated_bytes >> 20 |
| 133 | + print(f"memory(MiB): {max_memory_allocated_bytes} memory(%): {max_memory_allocated_percentage}") |
0 commit comments