(args, net: nn.Module, optimizer, train_loader, epoch, writer)
| 23 | |
| 24 | |
| 25 | def train_sam(args, net: nn.Module, optimizer, train_loader, epoch, writer): |
| 26 | |
| 27 | # use bfloat16 for the entire notebook |
| 28 | torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__() |
| 29 | |
| 30 | if torch.cuda.get_device_properties(0).major >= 8: |
| 31 | # turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices) |
| 32 | torch.backends.cuda.matmul.allow_tf32 = True |
| 33 | torch.backends.cudnn.allow_tf32 = True |
| 34 | |
| 35 | |
| 36 | # train mode |
| 37 | net.train() |
| 38 | optimizer.zero_grad() |
| 39 | |
| 40 | # init |
| 41 | epoch_loss = 0 |
| 42 | memory_bank_list = [] |
| 43 | lossfunc = criterion_G |
| 44 | feat_sizes = [(256, 256), (128, 128), (64, 64)] |
| 45 | |
| 46 | |
| 47 | with tqdm(total=len(train_loader), desc=f'Epoch {epoch}', unit='img') as pbar: |
| 48 | for ind, pack in enumerate(train_loader): |
| 49 | |
| 50 | to_cat_memory = [] |
| 51 | to_cat_memory_pos = [] |
| 52 | to_cat_image_embed = [] |
| 53 | |
| 54 | # input image and gt masks |
| 55 | imgs = pack['image'].to(dtype = mask_type, device = GPUdevice) |
| 56 | masks = pack['mask'].to(dtype = mask_type, device = GPUdevice) |
| 57 | name = pack['image_meta_dict']['filename_or_obj'] |
| 58 | |
| 59 | # click prompt: unsqueeze to indicate only one click, add more click across this dimension |
| 60 | if 'pt' in pack: |
| 61 | pt_temp = pack['pt'].to(device = GPUdevice) |
| 62 | pt = pt_temp.unsqueeze(1) |
| 63 | point_labels_temp = pack['p_label'].to(device = GPUdevice) |
| 64 | point_labels = point_labels_temp.unsqueeze(1) |
| 65 | coords_torch = torch.as_tensor(pt, dtype=torch.float, device=GPUdevice) |
| 66 | labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=GPUdevice) |
| 67 | else: |
| 68 | coords_torch = None |
| 69 | labels_torch = None |
| 70 | |
| 71 | '''Train image encoder''' |
| 72 | backbone_out = net.forward_image(imgs) |
| 73 | _, vision_feats, vision_pos_embeds, _ = net._prepare_backbone_features(backbone_out) |
| 74 | # dimension hint for your future use |
| 75 | # vision_feats: list: length = 3 |
| 76 | # vision_feats[0]: torch.Size([65536, batch, 32]) |
| 77 | # vision_feats[1]: torch.Size([16384, batch, 64]) |
| 78 | # vision_feats[2]: torch.Size([4096, batch, 256]) |
| 79 | # vision_pos_embeds[0]: torch.Size([65536, batch, 256]) |
| 80 | # vision_pos_embeds[1]: torch.Size([16384, batch, 256]) |
| 81 | # vision_pos_embeds[2]: torch.Size([4096, batch, 256]) |
| 82 |
nothing calls this directly
no test coverage detected