repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
IGEV
IGEV-main/IGEV-MVS/datasets/tanks.py
from torch.utils.data import Dataset from datasets.data_io import * import os import numpy as np import cv2 from PIL import Image class MVSDataset(Dataset): def __init__(self, datapath, n_views=7, img_wh=(1920, 1024), split='intermediate'): self.levels = 4 self.datapath = datapath self.img_wh = img_wh self.split = split self.build_metas() self.n_views = n_views def build_metas(self): self.metas = [] if self.split == 'intermediate': self.scans = ['Family', 'Francis', 'Horse', 'Lighthouse', 'M60', 'Panther', 'Playground', 'Train'] elif self.split == 'advanced': self.scans = ['Auditorium', 'Ballroom', 'Courtroom', 'Museum', 'Palace', 'Temple'] for scan in self.scans: with open(os.path.join(self.datapath, self.split, scan, 'pair.txt')) as f: num_viewpoint = int(f.readline()) for view_idx in range(num_viewpoint): ref_view = int(f.readline().rstrip()) src_views = [int(x) for x in f.readline().rstrip().split()[1::2]] if len(src_views) != 0: self.metas += [(scan, -1, ref_view, src_views)] def read_cam_file(self, filename): with open(filename) as f: lines = [line.rstrip() for line in f.readlines()] # extrinsics: line [1,5), 4x4 matrix extrinsics = np.fromstring(' '.join(lines[1:5]), dtype=np.float32, sep=' ') extrinsics = extrinsics.reshape((4, 4)) # intrinsics: line [7-10), 3x3 matrix intrinsics = np.fromstring(' '.join(lines[7:10]), dtype=np.float32, sep=' ') intrinsics = intrinsics.reshape((3, 3)) depth_min = float(lines[11].split()[0]) depth_max = float(lines[11].split()[-1]) return intrinsics, extrinsics, depth_min, depth_max def read_img(self, filename, h, w): img = Image.open(filename) # scale 0~255 to -1~1 np_img = 2*np.array(img, dtype=np.float32) / 255. - 1 original_h, original_w, _ = np_img.shape np_img = cv2.resize(np_img, self.img_wh, interpolation=cv2.INTER_LINEAR) np_img_ms = { "level_3": cv2.resize(np_img, (w//8, h//8), interpolation=cv2.INTER_LINEAR), "level_2": cv2.resize(np_img, (w//4, h//4), interpolation=cv2.INTER_LINEAR), "level_1": cv2.resize(np_img, (w//2, h//2), interpolation=cv2.INTER_LINEAR), "level_0": np_img } return np_img_ms, original_h, original_w def __len__(self): return len(self.metas) def __getitem__(self, idx): scan, _, ref_view, src_views = self.metas[idx] # use only the reference view and first nviews-1 source views view_ids = [ref_view] + src_views[:self.n_views-1] imgs_0 = [] imgs_1 = [] imgs_2 = [] imgs_3 = [] # depth = None depth_min = None depth_max = None proj_matrices_0 = [] proj_matrices_1 = [] proj_matrices_2 = [] proj_matrices_3 = [] for i, vid in enumerate(view_ids): img_filename = os.path.join(self.datapath, self.split, scan, f'images/{vid:08d}.jpg') proj_mat_filename = os.path.join(self.datapath, self.split, scan, f'cams_1/{vid:08d}_cam.txt') imgs, original_h, original_w = self.read_img(img_filename,self.img_wh[1], self.img_wh[0]) imgs_0.append(imgs['level_0']) imgs_1.append(imgs['level_1']) imgs_2.append(imgs['level_2']) imgs_3.append(imgs['level_3']) intrinsics, extrinsics, depth_min_, depth_max_ = self.read_cam_file(proj_mat_filename) intrinsics[0] *= self.img_wh[0]/original_w intrinsics[1] *= self.img_wh[1]/original_h proj_mat = extrinsics.copy() intrinsics[:2,:] *= 0.125 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_3.append(proj_mat) proj_mat = extrinsics.copy() intrinsics[:2,:] *= 2 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_2.append(proj_mat) proj_mat = extrinsics.copy() intrinsics[:2,:] *= 2 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_1.append(proj_mat) proj_mat = extrinsics.copy() intrinsics[:2,:] *= 2 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_0.append(proj_mat) if i == 0: # reference view depth_min = depth_min_ depth_max = depth_max_ # imgs: N*3*H0*W0, N is number of images imgs_0 = np.stack(imgs_0).transpose([0, 3, 1, 2]) imgs_1 = np.stack(imgs_1).transpose([0, 3, 1, 2]) imgs_2 = np.stack(imgs_2).transpose([0, 3, 1, 2]) imgs_3 = np.stack(imgs_3).transpose([0, 3, 1, 2]) imgs = {} imgs['level_0'] = imgs_0 imgs['level_1'] = imgs_1 imgs['level_2'] = imgs_2 imgs['level_3'] = imgs_3 # proj_matrices: N*4*4 proj_matrices_0 = np.stack(proj_matrices_0) proj_matrices_1 = np.stack(proj_matrices_1) proj_matrices_2 = np.stack(proj_matrices_2) proj_matrices_3 = np.stack(proj_matrices_3) proj={} proj['level_3']=proj_matrices_3 proj['level_2']=proj_matrices_2 proj['level_1']=proj_matrices_1 proj['level_0']=proj_matrices_0 return {"imgs": imgs, # N*3*H0*W0 "proj_matrices": proj, # N*4*4 "depth_min": depth_min, # scalar "depth_max": depth_max, "filename": scan + '/{}/' + '{:0>8}'.format(view_ids[0]) + "{}" }
5,974
37.057325
106
py
IGEV
IGEV-main/IGEV-MVS/datasets/blendedmvs.py
from torch.utils.data import Dataset from datasets.data_io import * import os import numpy as np import cv2 from PIL import Image from torchvision import transforms as T import random class MVSDataset(Dataset): def __init__(self, datapath, listfile, split, nviews, img_wh=(768, 576), robust_train=True): super(MVSDataset, self).__init__() self.levels = 4 self.datapath = datapath self.split = split self.listfile = listfile self.robust_train = robust_train assert self.split in ['train', 'val', 'all'], \ 'split must be either "train", "val" or "all"!' self.img_wh = img_wh if img_wh is not None: assert img_wh[0]%32==0 and img_wh[1]%32==0, \ 'img_wh must both be multiples of 32!' self.nviews = nviews self.scale_factors = {} # depth scale factors for each scan self.build_metas() self.color_augment = T.ColorJitter(brightness=0.5, contrast=0.5) def build_metas(self): self.metas = [] with open(self.listfile) as f: self.scans = [line.rstrip() for line in f.readlines()] for scan in self.scans: with open(os.path.join(self.datapath, scan, "cams/pair.txt")) as f: num_viewpoint = int(f.readline()) for _ in range(num_viewpoint): ref_view = int(f.readline().rstrip()) src_views = [int(x) for x in f.readline().rstrip().split()[1::2]] if len(src_views) >= self.nviews-1: self.metas += [(scan, ref_view, src_views)] def read_cam_file(self, scan, filename): with open(filename) as f: lines = f.readlines() lines = [line.rstrip() for line in lines] # extrinsics: line [1,5), 4x4 matrix extrinsics = np.fromstring(' '.join(lines[1:5]), dtype=np.float32, sep=' ').reshape((4, 4)) # intrinsics: line [7-10), 3x3 matrix intrinsics = np.fromstring(' '.join(lines[7:10]), dtype=np.float32, sep=' ').reshape((3, 3)) depth_min = float(lines[11].split()[0]) depth_max = float(lines[11].split()[-1]) if scan not in self.scale_factors: self.scale_factors[scan] = 100.0/depth_min depth_min *= self.scale_factors[scan] depth_max *= self.scale_factors[scan] extrinsics[:3, 3] *= self.scale_factors[scan] return intrinsics, extrinsics, depth_min, depth_max def read_depth_mask(self, scan, filename, depth_min, depth_max, scale): depth = np.array(read_pfm(filename)[0], dtype=np.float32) depth = depth * self.scale_factors[scan] * scale depth = np.squeeze(depth,2) mask = (depth>=depth_min) & (depth<=depth_max) mask = mask.astype(np.float32) if self.img_wh is not None: depth = cv2.resize(depth, self.img_wh, interpolation=cv2.INTER_NEAREST) h, w = depth.shape depth_ms = {} mask_ms = {} for i in range(4): depth_cur = cv2.resize(depth, (w//(2**i), h//(2**i)), interpolation=cv2.INTER_NEAREST) mask_cur = cv2.resize(mask, (w//(2**i), h//(2**i)), interpolation=cv2.INTER_NEAREST) depth_ms[f"level_{i}"] = depth_cur mask_ms[f"level_{i}"] = mask_cur return depth_ms, mask_ms def read_img(self, filename): img = Image.open(filename) if self.split=='train': img = self.color_augment(img) # scale 0~255 to -1~1 np_img = 2*np.array(img, dtype=np.float32) / 255. - 1 if self.img_wh is not None: np_img = cv2.resize(np_img, self.img_wh, interpolation=cv2.INTER_LINEAR) h, w, _ = np_img.shape np_img_ms = { "level_3": cv2.resize(np_img, (w//8, h//8), interpolation=cv2.INTER_LINEAR), "level_2": cv2.resize(np_img, (w//4, h//4), interpolation=cv2.INTER_LINEAR), "level_1": cv2.resize(np_img, (w//2, h//2), interpolation=cv2.INTER_LINEAR), "level_0": np_img } return np_img_ms def __len__(self): return len(self.metas) def __getitem__(self, idx): meta = self.metas[idx] scan, ref_view, src_views = meta if self.robust_train: num_src_views = len(src_views) index = random.sample(range(num_src_views), self.nviews - 1) view_ids = [ref_view] + [src_views[i] for i in index] scale = random.uniform(0.8, 1.25) else: view_ids = [ref_view] + src_views[:self.nviews - 1] scale = 1 imgs_0 = [] imgs_1 = [] imgs_2 = [] imgs_3 = [] mask = None depth = None depth_min = None depth_max = None proj_matrices_0 = [] proj_matrices_1 = [] proj_matrices_2 = [] proj_matrices_3 = [] for i, vid in enumerate(view_ids): img_filename = os.path.join(self.datapath, '{}/blended_images/{:0>8}.jpg'.format(scan, vid)) depth_filename = os.path.join(self.datapath, '{}/rendered_depth_maps/{:0>8}.pfm'.format(scan, vid)) proj_mat_filename = os.path.join(self.datapath, '{}/cams/{:0>8}_cam.txt'.format(scan, vid)) imgs = self.read_img(img_filename) imgs_0.append(imgs['level_0']) imgs_1.append(imgs['level_1']) imgs_2.append(imgs['level_2']) imgs_3.append(imgs['level_3']) # here, the intrinsics from file is already adjusted to the downsampled size of feature 1/4H0 * 1/4W0 intrinsics, extrinsics, depth_min_, depth_max_ = self.read_cam_file(scan, proj_mat_filename) extrinsics[:3, 3] *= scale proj_mat = extrinsics.copy() intrinsics[:2,:] *= 0.125 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_3.append(proj_mat) proj_mat = extrinsics.copy() intrinsics[:2,:] *= 2 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_2.append(proj_mat) proj_mat = extrinsics.copy() intrinsics[:2,:] *= 2 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_1.append(proj_mat) proj_mat = extrinsics.copy() intrinsics[:2,:] *= 2 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_0.append(proj_mat) if i == 0: # reference view depth_min = depth_min_ * scale depth_max = depth_max_ * scale depth, mask = self.read_depth_mask(scan, depth_filename, depth_min, depth_max, scale) for l in range(self.levels): mask[f'level_{l}'] = np.expand_dims(mask[f'level_{l}'],2) mask[f'level_{l}'] = mask[f'level_{l}'].transpose([2,0,1]) depth[f'level_{l}'] = np.expand_dims(depth[f'level_{l}'],2) depth[f'level_{l}'] = depth[f'level_{l}'].transpose([2,0,1]) # imgs: N*3*H0*W0, N is number of images imgs_0 = np.stack(imgs_0).transpose([0, 3, 1, 2]) imgs_1 = np.stack(imgs_1).transpose([0, 3, 1, 2]) imgs_2 = np.stack(imgs_2).transpose([0, 3, 1, 2]) imgs_3 = np.stack(imgs_3).transpose([0, 3, 1, 2]) imgs = {} imgs['level_0'] = imgs_0 imgs['level_1'] = imgs_1 imgs['level_2'] = imgs_2 imgs['level_3'] = imgs_3 # proj_matrices: N*4*4 proj_matrices_0 = np.stack(proj_matrices_0) proj_matrices_1 = np.stack(proj_matrices_1) proj_matrices_2 = np.stack(proj_matrices_2) proj_matrices_3 = np.stack(proj_matrices_3) proj={} proj['level_3']=proj_matrices_3 proj['level_2']=proj_matrices_2 proj['level_1']=proj_matrices_1 proj['level_0']=proj_matrices_0 # data is numpy array return {"imgs": imgs, # [N, 3, H, W] "proj_matrices": proj, # [N,4,4] "depth": depth, # [1, H, W] "depth_min": depth_min, # scalar "depth_max": depth_max, # scalar "mask": mask} # [1, H, W]
8,489
39.817308
113
py
IGEV
IGEV-main/IGEV-MVS/datasets/dtu_yao.py
from torch.utils.data import Dataset import numpy as np import os from PIL import Image from datasets.data_io import * import cv2 import random from torchvision import transforms class MVSDataset(Dataset): def __init__(self, datapath, listfile, mode, nviews, robust_train = False): super(MVSDataset, self).__init__() self.levels = 4 self.datapath = datapath self.listfile = listfile self.mode = mode self.nviews = nviews self.img_wh = (640, 512) # self.img_wh = (1440, 1056) self.robust_train = robust_train assert self.mode in ["train", "val", "test"] self.metas = self.build_list() self.color_augment = transforms.ColorJitter(brightness=0.5, contrast=0.5) def build_list(self): metas = [] with open(self.listfile) as f: scans = f.readlines() scans = [line.rstrip() for line in scans] for scan in scans: pair_file = "Cameras_1/pair.txt" with open(os.path.join(self.datapath, pair_file)) as f: self.num_viewpoint = int(f.readline()) # viewpoints (49) for view_idx in range(self.num_viewpoint): ref_view = int(f.readline().rstrip()) src_views = [int(x) for x in f.readline().rstrip().split()[1::2]] # light conditions 0-6 for light_idx in range(7): metas.append((scan, light_idx, ref_view, src_views)) print("dataset", self.mode, "metas:", len(metas)) return metas def __len__(self): return len(self.metas) def read_cam_file(self, filename): with open(filename) as f: lines = f.readlines() lines = [line.rstrip() for line in lines] # extrinsics: line [1,5), 4x4 matrix extrinsics = np.fromstring(' '.join(lines[1:5]), dtype=np.float32, sep=' ').reshape((4, 4)) # intrinsics: line [7-10), 3x3 matrix intrinsics = np.fromstring(' '.join(lines[7:10]), dtype=np.float32, sep=' ').reshape((3, 3)) depth_min = float(lines[11].split()[0]) depth_max = float(lines[11].split()[-1]) return intrinsics, extrinsics, depth_min, depth_max def read_img(self, filename): img = Image.open(filename) if self.mode=='train': img = self.color_augment(img) # scale 0~255 to -1~1 np_img = 2*np.array(img, dtype=np.float32) / 255. - 1 h, w, _ = np_img.shape np_img_ms = { "level_3": cv2.resize(np_img, (w//8, h//8), interpolation=cv2.INTER_LINEAR), "level_2": cv2.resize(np_img, (w//4, h//4), interpolation=cv2.INTER_LINEAR), "level_1": cv2.resize(np_img, (w//2, h//2), interpolation=cv2.INTER_LINEAR), "level_0": np_img } return np_img_ms def prepare_img(self, hr_img): #downsample h, w = hr_img.shape # original w,h: 1600, 1200; downsample -> 800, 600 ; crop -> 640, 512 hr_img = cv2.resize(hr_img, (w//2, h//2), interpolation=cv2.INTER_NEAREST) #crop h, w = hr_img.shape target_h, target_w = self.img_wh[1], self.img_wh[0] start_h, start_w = (h - target_h)//2, (w - target_w)//2 hr_img_crop = hr_img[start_h: start_h + target_h, start_w: start_w + target_w] return hr_img_crop def read_mask(self, filename): img = Image.open(filename) np_img = np.array(img, dtype=np.float32) np_img = (np_img > 10).astype(np.float32) return np_img def read_depth_mask(self, filename, mask_filename, scale): depth_hr = np.array(read_pfm(filename)[0], dtype=np.float32) * scale depth_hr = np.squeeze(depth_hr,2) depth_lr = self.prepare_img(depth_hr) mask = self.read_mask(mask_filename) mask = self.prepare_img(mask) mask = mask.astype(np.bool_) mask = mask.astype(np.float32) h, w = depth_lr.shape depth_lr_ms = {} mask_ms = {} for i in range(self.levels): depth_cur = cv2.resize(depth_lr, (w//(2**i), h//(2**i)), interpolation=cv2.INTER_NEAREST) mask_cur = cv2.resize(mask, (w//(2**i), h//(2**i)), interpolation=cv2.INTER_NEAREST) depth_lr_ms[f"level_{i}"] = depth_cur mask_ms[f"level_{i}"] = mask_cur return depth_lr_ms, mask_ms def __getitem__(self, idx): meta = self.metas[idx] scan, light_idx, ref_view, src_views = meta # robust training strategy if self.robust_train: num_src_views = len(src_views) index = random.sample(range(num_src_views), self.nviews - 1) view_ids = [ref_view] + [src_views[i] for i in index] scale = random.uniform(0.8, 1.25) else: view_ids = [ref_view] + src_views[:self.nviews - 1] scale = 1 imgs_0 = [] imgs_1 = [] imgs_2 = [] imgs_3 = [] mask = None depth = None depth_min = None depth_max = None proj_matrices_0 = [] proj_matrices_1 = [] proj_matrices_2 = [] proj_matrices_3 = [] for i, vid in enumerate(view_ids): img_filename = os.path.join(self.datapath, 'Rectified/{}_train/rect_{:0>3}_{}_r5000.png'.format(scan, vid + 1, light_idx)) proj_mat_filename = os.path.join(self.datapath, 'Cameras_1/{}_train/{:0>8}_cam.txt').format(scan, vid) mask_filename = os.path.join(self.datapath, 'Depths_raw/{}/depth_visual_{:0>4}.png'.format(scan, vid)) depth_filename = os.path.join(self.datapath, 'Depths_raw/{}/depth_map_{:0>4}.pfm'.format(scan, vid)) imgs = self.read_img(img_filename) imgs_0.append(imgs['level_0']) imgs_1.append(imgs['level_1']) imgs_2.append(imgs['level_2']) imgs_3.append(imgs['level_3']) intrinsics, extrinsics, depth_min_, depth_max_ = self.read_cam_file(proj_mat_filename) extrinsics[:3,3] *= scale intrinsics[0] *= 4 intrinsics[1] *= 4 proj_mat = extrinsics.copy() intrinsics[:2,:] *= 0.125 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_3.append(proj_mat) proj_mat = extrinsics.copy() intrinsics[:2,:] *= 2 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_2.append(proj_mat) proj_mat = extrinsics.copy() intrinsics[:2,:] *= 2 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_1.append(proj_mat) proj_mat = extrinsics.copy() intrinsics[:2,:] *= 2 proj_mat[:3, :4] = np.matmul(intrinsics, proj_mat[:3, :4]) proj_matrices_0.append(proj_mat) if i == 0: # reference view depth_min = depth_min_ * scale depth_max = depth_max_ * scale depth, mask = self.read_depth_mask(depth_filename, mask_filename, scale) for l in range(self.levels): mask[f'level_{l}'] = np.expand_dims(mask[f'level_{l}'],2) mask[f'level_{l}'] = mask[f'level_{l}'].transpose([2,0,1]) depth[f'level_{l}'] = np.expand_dims(depth[f'level_{l}'],2) depth[f'level_{l}'] = depth[f'level_{l}'].transpose([2,0,1]) # imgs: N*3*H0*W0, N is number of images imgs_0 = np.stack(imgs_0).transpose([0, 3, 1, 2]) imgs_1 = np.stack(imgs_1).transpose([0, 3, 1, 2]) imgs_2 = np.stack(imgs_2).transpose([0, 3, 1, 2]) imgs_3 = np.stack(imgs_3).transpose([0, 3, 1, 2]) imgs = {} imgs['level_0'] = imgs_0 imgs['level_1'] = imgs_1 imgs['level_2'] = imgs_2 imgs['level_3'] = imgs_3 # proj_matrices: N*4*4 proj_matrices_0 = np.stack(proj_matrices_0) proj_matrices_1 = np.stack(proj_matrices_1) proj_matrices_2 = np.stack(proj_matrices_2) proj_matrices_3 = np.stack(proj_matrices_3) proj={} proj['level_3']=proj_matrices_3 proj['level_2']=proj_matrices_2 proj['level_1']=proj_matrices_1 proj['level_0']=proj_matrices_0 # data is numpy array return {"imgs": imgs, # [N, 3, H, W] "proj_matrices": proj, # [N,4,4] "depth": depth, # [1, H, W] "depth_min": depth_min, # scalar "depth_max": depth_max, # scalar "mask": mask} # [1, H, W]
8,874
36.447257
115
py
IGEV
IGEV-main/IGEV-Stereo/evaluate_stereo.py
from __future__ import print_function, division import sys sys.path.append('core') import os # os.environ['CUDA_VISIBLE_DEVICES'] = '0' import argparse import time import logging import numpy as np import torch from tqdm import tqdm from igev_stereo import IGEVStereo, autocast import stereo_datasets as datasets from utils.utils import InputPadder from PIL import Image def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) @torch.no_grad() def validate_eth3d(model, iters=32, mixed_prec=False): """ Peform validation using the ETH3D (train) split """ model.eval() aug_params = {} val_dataset = datasets.ETH3D(aug_params) out_list, epe_list = [], [] for val_id in range(len(val_dataset)): (imageL_file, imageR_file, GT_file), image1, image2, flow_gt, valid_gt = val_dataset[val_id] image1 = image1[None].cuda() image2 = image2[None].cuda() padder = InputPadder(image1.shape, divis_by=32) image1, image2 = padder.pad(image1, image2) with autocast(enabled=mixed_prec): flow_pr = model(image1, image2, iters=iters, test_mode=True) flow_pr = padder.unpad(flow_pr.float()).cpu().squeeze(0) assert flow_pr.shape == flow_gt.shape, (flow_pr.shape, flow_gt.shape) epe = torch.sum((flow_pr - flow_gt)**2, dim=0).sqrt() epe_flattened = epe.flatten() occ_mask = Image.open(GT_file.replace('disp0GT.pfm', 'mask0nocc.png')) occ_mask = np.ascontiguousarray(occ_mask).flatten() val = (valid_gt.flatten() >= 0.5) & (occ_mask == 255) # val = (valid_gt.flatten() >= 0.5) out = (epe_flattened > 1.0) image_out = out[val].float().mean().item() image_epe = epe_flattened[val].mean().item() logging.info(f"ETH3D {val_id+1} out of {len(val_dataset)}. EPE {round(image_epe,4)} D1 {round(image_out,4)}") epe_list.append(image_epe) out_list.append(image_out) epe_list = np.array(epe_list) out_list = np.array(out_list) epe = np.mean(epe_list) d1 = 100 * np.mean(out_list) print("Validation ETH3D: EPE %f, D1 %f" % (epe, d1)) return {'eth3d-epe': epe, 'eth3d-d1': d1} @torch.no_grad() def validate_kitti(model, iters=32, mixed_prec=False): """ Peform validation using the KITTI-2015 (train) split """ model.eval() aug_params = {} val_dataset = datasets.KITTI(aug_params, image_set='training') torch.backends.cudnn.benchmark = True out_list, epe_list, elapsed_list = [], [], [] for val_id in range(len(val_dataset)): _, image1, image2, flow_gt, valid_gt = val_dataset[val_id] image1 = image1[None].cuda() image2 = image2[None].cuda() padder = InputPadder(image1.shape, divis_by=32) image1, image2 = padder.pad(image1, image2) with autocast(enabled=mixed_prec): start = time.time() flow_pr = model(image1, image2, iters=iters, test_mode=True) end = time.time() if val_id > 50: elapsed_list.append(end-start) flow_pr = padder.unpad(flow_pr).cpu().squeeze(0) assert flow_pr.shape == flow_gt.shape, (flow_pr.shape, flow_gt.shape) epe = torch.sum((flow_pr - flow_gt)**2, dim=0).sqrt() epe_flattened = epe.flatten() val = (valid_gt.flatten() >= 0.5) & (flow_gt.abs().flatten() < 192) # val = valid_gt.flatten() >= 0.5 out = (epe_flattened > 3.0) image_out = out[val].float().mean().item() image_epe = epe_flattened[val].mean().item() if val_id < 9 or (val_id+1)%10 == 0: logging.info(f"KITTI Iter {val_id+1} out of {len(val_dataset)}. EPE {round(image_epe,4)} D1 {round(image_out,4)}. Runtime: {format(end-start, '.3f')}s ({format(1/(end-start), '.2f')}-FPS)") epe_list.append(epe_flattened[val].mean().item()) out_list.append(out[val].cpu().numpy()) epe_list = np.array(epe_list) out_list = np.concatenate(out_list) epe = np.mean(epe_list) d1 = 100 * np.mean(out_list) avg_runtime = np.mean(elapsed_list) print(f"Validation KITTI: EPE {epe}, D1 {d1}, {format(1/avg_runtime, '.2f')}-FPS ({format(avg_runtime, '.3f')}s)") return {'kitti-epe': epe, 'kitti-d1': d1} @torch.no_grad() def validate_sceneflow(model, iters=32, mixed_prec=False): """ Peform validation using the Scene Flow (TEST) split """ model.eval() val_dataset = datasets.SceneFlowDatasets(dstype='frames_finalpass', things_test=True) out_list, epe_list = [], [] for val_id in tqdm(range(len(val_dataset))): _, image1, image2, flow_gt, valid_gt = val_dataset[val_id] image1 = image1[None].cuda() image2 = image2[None].cuda() padder = InputPadder(image1.shape, divis_by=32) image1, image2 = padder.pad(image1, image2) with autocast(enabled=mixed_prec): flow_pr = model(image1, image2, iters=iters, test_mode=True) flow_pr = padder.unpad(flow_pr).cpu().squeeze(0) assert flow_pr.shape == flow_gt.shape, (flow_pr.shape, flow_gt.shape) # epe = torch.sum((flow_pr - flow_gt)**2, dim=0).sqrt() epe = torch.abs(flow_pr - flow_gt) epe = epe.flatten() val = (valid_gt.flatten() >= 0.5) & (flow_gt.abs().flatten() < 192) if(np.isnan(epe[val].mean().item())): continue out = (epe > 3.0) epe_list.append(epe[val].mean().item()) out_list.append(out[val].cpu().numpy()) # if val_id == 400: # break epe_list = np.array(epe_list) out_list = np.concatenate(out_list) epe = np.mean(epe_list) d1 = 100 * np.mean(out_list) f = open('test.txt', 'a') f.write("Validation Scene Flow: %f, %f\n" % (epe, d1)) print("Validation Scene Flow: %f, %f" % (epe, d1)) return {'scene-disp-epe': epe, 'scene-disp-d1': d1} @torch.no_grad() def validate_middlebury(model, iters=32, split='F', mixed_prec=False): """ Peform validation using the Middlebury-V3 dataset """ model.eval() aug_params = {} val_dataset = datasets.Middlebury(aug_params, split=split) out_list, epe_list = [], [] for val_id in range(len(val_dataset)): (imageL_file, _, _), image1, image2, flow_gt, valid_gt = val_dataset[val_id] image1 = image1[None].cuda() image2 = image2[None].cuda() padder = InputPadder(image1.shape, divis_by=32) image1, image2 = padder.pad(image1, image2) with autocast(enabled=mixed_prec): flow_pr = model(image1, image2, iters=iters, test_mode=True) flow_pr = padder.unpad(flow_pr).cpu().squeeze(0) assert flow_pr.shape == flow_gt.shape, (flow_pr.shape, flow_gt.shape) epe = torch.sum((flow_pr - flow_gt)**2, dim=0).sqrt() epe_flattened = epe.flatten() occ_mask = Image.open(imageL_file.replace('im0.png', 'mask0nocc.png')).convert('L') occ_mask = np.ascontiguousarray(occ_mask, dtype=np.float32).flatten() val = (valid_gt.reshape(-1) >= 0.5) & (flow_gt[0].reshape(-1) < 192) & (occ_mask==255) out = (epe_flattened > 2.0) image_out = out[val].float().mean().item() image_epe = epe_flattened[val].mean().item() logging.info(f"Middlebury Iter {val_id+1} out of {len(val_dataset)}. EPE {round(image_epe,4)} D1 {round(image_out,4)}") epe_list.append(image_epe) out_list.append(image_out) epe_list = np.array(epe_list) out_list = np.array(out_list) epe = np.mean(epe_list) d1 = 100 * np.mean(out_list) print(f"Validation Middlebury{split}: EPE {epe}, D1 {d1}") return {f'middlebury{split}-epe': epe, f'middlebury{split}-d1': d1} if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--restore_ckpt', help="restore checkpoint", default='./pretrained_models/sceneflow/sceneflow.pth') parser.add_argument('--dataset', help="dataset for evaluation", default='sceneflow', choices=["eth3d", "kitti", "sceneflow"] + [f"middlebury_{s}" for s in 'FHQ']) parser.add_argument('--mixed_precision', default=False, action='store_true', help='use mixed precision') parser.add_argument('--valid_iters', type=int, default=32, help='number of flow-field updates during forward pass') # Architecure choices parser.add_argument('--hidden_dims', nargs='+', type=int, default=[128]*3, help="hidden state and context dimensions") parser.add_argument('--corr_implementation', choices=["reg", "alt", "reg_cuda", "alt_cuda"], default="reg", help="correlation volume implementation") parser.add_argument('--shared_backbone', action='store_true', help="use a single backbone for the context and feature encoders") parser.add_argument('--corr_levels', type=int, default=2, help="number of levels in the correlation pyramid") parser.add_argument('--corr_radius', type=int, default=4, help="width of the correlation pyramid") parser.add_argument('--n_downsample', type=int, default=2, help="resolution of the disparity field (1/2^K)") parser.add_argument('--slow_fast_gru', action='store_true', help="iterate the low-res GRUs more frequently") parser.add_argument('--n_gru_layers', type=int, default=3, help="number of hidden GRU levels") parser.add_argument('--max_disp', type=int, default=192, help="max disp of geometry encoding volume") args = parser.parse_args() model = torch.nn.DataParallel(IGEVStereo(args), device_ids=[0]) logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s') if args.restore_ckpt is not None: assert args.restore_ckpt.endswith(".pth") logging.info("Loading checkpoint...") checkpoint = torch.load(args.restore_ckpt) model.load_state_dict(checkpoint, strict=True) logging.info(f"Done loading checkpoint") model.cuda() model.eval() print(f"The model has {format(count_parameters(model)/1e6, '.2f')}M learnable parameters.") use_mixed_precision = args.corr_implementation.endswith("_cuda") if args.dataset == 'eth3d': validate_eth3d(model, iters=args.valid_iters, mixed_prec=use_mixed_precision) elif args.dataset == 'kitti': validate_kitti(model, iters=args.valid_iters, mixed_prec=use_mixed_precision) elif args.dataset in [f"middlebury_{s}" for s in 'FHQ']: validate_middlebury(model, iters=args.valid_iters, split=args.dataset[-1], mixed_prec=use_mixed_precision) elif args.dataset == 'sceneflow': validate_sceneflow(model, iters=args.valid_iters, mixed_prec=use_mixed_precision)
10,694
39.358491
201
py
IGEV
IGEV-main/IGEV-Stereo/demo_imgs.py
import sys sys.path.append('core') DEVICE = 'cuda' import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import argparse import glob import numpy as np import torch from tqdm import tqdm from pathlib import Path from igev_stereo import IGEVStereo from utils.utils import InputPadder from PIL import Image from matplotlib import pyplot as plt import os import cv2 def load_image(imfile): img = np.array(Image.open(imfile)).astype(np.uint8) img = torch.from_numpy(img).permute(2, 0, 1).float() return img[None].to(DEVICE) def demo(args): model = torch.nn.DataParallel(IGEVStereo(args), device_ids=[0]) model.load_state_dict(torch.load(args.restore_ckpt)) model = model.module model.to(DEVICE) model.eval() output_directory = Path(args.output_directory) output_directory.mkdir(exist_ok=True) with torch.no_grad(): left_images = sorted(glob.glob(args.left_imgs, recursive=True)) right_images = sorted(glob.glob(args.right_imgs, recursive=True)) print(f"Found {len(left_images)} images. Saving files to {output_directory}/") for (imfile1, imfile2) in tqdm(list(zip(left_images, right_images))): image1 = load_image(imfile1) image2 = load_image(imfile2) padder = InputPadder(image1.shape, divis_by=32) image1, image2 = padder.pad(image1, image2) disp = model(image1, image2, iters=args.valid_iters, test_mode=True) disp = disp.cpu().numpy() disp = padder.unpad(disp) file_stem = imfile1.split('/')[-2] filename = os.path.join(output_directory, f"{file_stem}.png") plt.imsave(output_directory / f"{file_stem}.png", disp.squeeze(), cmap='jet') # disp = np.round(disp * 256).astype(np.uint16) # cv2.imwrite(filename, cv2.applyColorMap(cv2.convertScaleAbs(disp.squeeze(), alpha=0.01),cv2.COLORMAP_JET), [int(cv2.IMWRITE_PNG_COMPRESSION), 0]) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--restore_ckpt', help="restore checkpoint", default='./pretrained_models/sceneflow/sceneflow.pth') parser.add_argument('--save_numpy', action='store_true', help='save output as numpy arrays') parser.add_argument('-l', '--left_imgs', help="path to all first (left) frames", default="./demo-imgs/*/im0.png") parser.add_argument('-r', '--right_imgs', help="path to all second (right) frames", default="./demo-imgs/*/im1.png") # parser.add_argument('-l', '--left_imgs', help="path to all first (left) frames", default="/data/Middlebury/trainingH/*/im0.png") # parser.add_argument('-r', '--right_imgs', help="path to all second (right) frames", default="/data/Middlebury/trainingH/*/im1.png") # parser.add_argument('-l', '--left_imgs', help="path to all first (left) frames", default="/data/ETH3D/two_view_training/*/im0.png") # parser.add_argument('-r', '--right_imgs', help="path to all second (right) frames", default="/data/ETH3D/two_view_training/*/im1.png") parser.add_argument('--output_directory', help="directory to save output", default="./demo-output/") parser.add_argument('--mixed_precision', action='store_true', help='use mixed precision') parser.add_argument('--valid_iters', type=int, default=32, help='number of flow-field updates during forward pass') # Architecture choices parser.add_argument('--hidden_dims', nargs='+', type=int, default=[128]*3, help="hidden state and context dimensions") parser.add_argument('--corr_implementation', choices=["reg", "alt", "reg_cuda", "alt_cuda"], default="reg", help="correlation volume implementation") parser.add_argument('--shared_backbone', action='store_true', help="use a single backbone for the context and feature encoders") parser.add_argument('--corr_levels', type=int, default=2, help="number of levels in the correlation pyramid") parser.add_argument('--corr_radius', type=int, default=4, help="width of the correlation pyramid") parser.add_argument('--n_downsample', type=int, default=2, help="resolution of the disparity field (1/2^K)") parser.add_argument('--slow_fast_gru', action='store_true', help="iterate the low-res GRUs more frequently") parser.add_argument('--n_gru_layers', type=int, default=3, help="number of hidden GRU levels") parser.add_argument('--max_disp', type=int, default=192, help="max disp of geometry encoding volume") args = parser.parse_args() Path(args.output_directory).mkdir(exist_ok=True, parents=True) demo(args)
4,564
50.292135
159
py
IGEV
IGEV-main/IGEV-Stereo/save_disp.py
import sys sys.path.append('core') import argparse import glob import numpy as np import torch from tqdm import tqdm from pathlib import Path from igev_stereo import IGEVStereo from utils.utils import InputPadder from PIL import Image from matplotlib import pyplot as plt import os import skimage.io import cv2 DEVICE = 'cuda' os.environ['CUDA_VISIBLE_DEVICES'] = '0' def load_image(imfile): img = np.array(Image.open(imfile)).astype(np.uint8) img = torch.from_numpy(img).permute(2, 0, 1).float() return img[None].to(DEVICE) def demo(args): model = torch.nn.DataParallel(IGEVStereo(args), device_ids=[0]) model.load_state_dict(torch.load(args.restore_ckpt)) model = model.module model.to(DEVICE) model.eval() output_directory = Path(args.output_directory) output_directory.mkdir(exist_ok=True) with torch.no_grad(): left_images = sorted(glob.glob(args.left_imgs, recursive=True)) right_images = sorted(glob.glob(args.right_imgs, recursive=True)) print(f"Found {len(left_images)} images. Saving files to {output_directory}/") for (imfile1, imfile2) in tqdm(list(zip(left_images, right_images))): image1 = load_image(imfile1) image2 = load_image(imfile2) padder = InputPadder(image1.shape, divis_by=32) image1, image2 = padder.pad(image1, image2) disp = model(image1, image2, iters=args.valid_iters, test_mode=True) disp = padder.unpad(disp) file_stem = os.path.join(output_directory, imfile1.split('/')[-1]) disp = disp.cpu().numpy().squeeze() disp = np.round(disp * 256).astype(np.uint16) skimage.io.imsave(file_stem, disp) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--restore_ckpt', help="restore checkpoint", default='./pretrained_models/kitti/kitti15.pth') parser.add_argument('--save_numpy', action='store_true', help='save output as numpy arrays') parser.add_argument('-l', '--left_imgs', help="path to all first (left) frames", default="/data/KITTI/KITTI_2015/testing/image_2/*_10.png") parser.add_argument('-r', '--right_imgs', help="path to all second (right) frames", default="/data/KITTI/KITTI_2015/testing/image_3/*_10.png") # parser.add_argument('-l', '--left_imgs', help="path to all first (left) frames", default="/data/KITTI/KITTI_2012/testing/colored_0/*_10.png") # parser.add_argument('-r', '--right_imgs', help="path to all second (right) frames", default="/data/KITTI/KITTI_2012/testing/colored_1/*_10.png") parser.add_argument('--output_directory', help="directory to save output", default="output") parser.add_argument('--mixed_precision', action='store_true', help='use mixed precision') parser.add_argument('--valid_iters', type=int, default=16, help='number of flow-field updates during forward pass') # Architecture choices parser.add_argument('--hidden_dims', nargs='+', type=int, default=[128]*3, help="hidden state and context dimensions") parser.add_argument('--corr_implementation', choices=["reg", "alt", "reg_cuda", "alt_cuda"], default="reg", help="correlation volume implementation") parser.add_argument('--shared_backbone', action='store_true', help="use a single backbone for the context and feature encoders") parser.add_argument('--corr_levels', type=int, default=2, help="number of levels in the correlation pyramid") parser.add_argument('--corr_radius', type=int, default=4, help="width of the correlation pyramid") parser.add_argument('--n_downsample', type=int, default=2, help="resolution of the disparity field (1/2^K)") parser.add_argument('--slow_fast_gru', action='store_true', help="iterate the low-res GRUs more frequently") parser.add_argument('--n_gru_layers', type=int, default=3, help="number of hidden GRU levels") parser.add_argument('--max_disp', type=int, default=192, help="max disp of geometry encoding volume") args = parser.parse_args() demo(args)
4,052
47.831325
153
py
IGEV
IGEV-main/IGEV-Stereo/demo_video.py
import sys sys.path.append('core') import cv2 import numpy as np import glob from pathlib import Path from tqdm import tqdm import torch from PIL import Image from igev_stereo import IGEVStereo import os import argparse from utils.utils import InputPadder torch.backends.cudnn.benchmark = True half_precision = True DEVICE = 'cuda' os.environ['CUDA_VISIBLE_DEVICES'] = '0' parser = argparse.ArgumentParser(description='Iterative Geometry Encoding Volume for Stereo Matching and Multi-View Stereo (IGEV-Stereo)') parser.add_argument('--restore_ckpt', help="restore checkpoint", default='./pretrained_models/kitti/kitti15.pth') parser.add_argument('--save_numpy', action='store_true', help='save output as numpy arrays') parser.add_argument('-l', '--left_imgs', help="path to all first (left) frames", default="/data/KITTI_raw/2011_09_26/2011_09_26_drive_0005_sync/image_02/data/*.png") parser.add_argument('-r', '--right_imgs', help="path to all second (right) frames", default="/data/KITTI_raw/2011_09_26/2011_09_26_drive_0005_sync/image_03/data/*.png") parser.add_argument('--mixed_precision', default=True, action='store_true', help='use mixed precision') parser.add_argument('--valid_iters', type=int, default=16, help='number of flow-field updates during forward pass') parser.add_argument('--hidden_dims', nargs='+', type=int, default=[128]*3, help="hidden state and context dimensions") parser.add_argument('--corr_implementation', choices=["reg", "alt", "reg_cuda", "alt_cuda"], default="reg", help="correlation volume implementation") parser.add_argument('--shared_backbone', action='store_true', help="use a single backbone for the context and feature encoders") parser.add_argument('--corr_levels', type=int, default=2, help="number of levels in the correlation pyramid") parser.add_argument('--corr_radius', type=int, default=4, help="width of the correlation pyramid") parser.add_argument('--n_downsample', type=int, default=2, help="resolution of the disparity field (1/2^K)") parser.add_argument('--slow_fast_gru', action='store_true', help="iterate the low-res GRUs more frequently") parser.add_argument('--n_gru_layers', type=int, default=3, help="number of hidden GRU levels") parser.add_argument('--max_disp', type=int, default=192, help="max disp of geometry encoding volume") args = parser.parse_args() model = torch.nn.DataParallel(IGEVStereo(args), device_ids=[0]) model.load_state_dict(torch.load(args.restore_ckpt)) model = model.module model.to(DEVICE) model.eval() left_images = sorted(glob.glob(args.left_imgs, recursive=True)) right_images = sorted(glob.glob(args.right_imgs, recursive=True)) print(f"Found {len(left_images)} images.") def load_image(imfile): img = np.array(Image.open(imfile)).astype(np.uint8) img = torch.from_numpy(img).permute(2, 0, 1).float() return img[None].to(DEVICE) if __name__ == '__main__': fps_list = np.array([]) videoWrite = cv2.VideoWriter('./IGEV_Stereo.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 10, (1242, 750)) for (imfile1, imfile2) in tqdm(list(zip(left_images, right_images))): image1 = load_image(imfile1) image2 = load_image(imfile2) padder = InputPadder(image1.shape, divis_by=32) image1_pad, image2_pad = padder.pad(image1, image2) torch.cuda.synchronize() start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record() with torch.no_grad(): with torch.cuda.amp.autocast(enabled=half_precision): disp = model(image1_pad, image2_pad, iters=16, test_mode=True) disp = padder.unpad(disp) end.record() torch.cuda.synchronize() runtime = start.elapsed_time(end) fps = 1000/runtime fps_list = np.append(fps_list, fps) if len(fps_list) > 5: fps_list = fps_list[-5:] avg_fps = np.mean(fps_list) print('Stereo runtime: {:.3f}'.format(1000/avg_fps)) disp_np = (2*disp).data.cpu().numpy().squeeze().astype(np.uint8) disp_np = cv2.applyColorMap(disp_np, cv2.COLORMAP_PLASMA) image_np = np.array(Image.open(imfile1)).astype(np.uint8) out_img = np.concatenate((image_np, disp_np), 0) cv2.putText( out_img, "%.1f fps" % (avg_fps), (10, image_np.shape[0]+30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) cv2.imshow('img', out_img) cv2.waitKey(1) videoWrite.write(out_img) videoWrite.release()
4,553
46.4375
168
py
IGEV
IGEV-main/IGEV-Stereo/train_stereo.py
from __future__ import print_function, division import os os.environ['CUDA_VISIBLE_DEVICES'] = '0, 1' import argparse import logging import numpy as np from pathlib import Path from tqdm import tqdm from torch.utils.tensorboard import SummaryWriter import torch import torch.nn as nn import torch.optim as optim from core.igev_stereo import IGEVStereo from evaluate_stereo import * import core.stereo_datasets as datasets import torch.nn.functional as F try: from torch.cuda.amp import GradScaler except: class GradScaler: def __init__(self): pass def scale(self, loss): return loss def unscale_(self, optimizer): pass def step(self, optimizer): optimizer.step() def update(self): pass def sequence_loss(disp_preds, disp_init_pred, disp_gt, valid, loss_gamma=0.9, max_disp=192): """ Loss function defined over sequence of flow predictions """ n_predictions = len(disp_preds) assert n_predictions >= 1 disp_loss = 0.0 mag = torch.sum(disp_gt**2, dim=1).sqrt() valid = ((valid >= 0.5) & (mag < max_disp)).unsqueeze(1) assert valid.shape == disp_gt.shape, [valid.shape, disp_gt.shape] assert not torch.isinf(disp_gt[valid.bool()]).any() disp_loss += 1.0 * F.smooth_l1_loss(disp_init_pred[valid.bool()], disp_gt[valid.bool()], size_average=True) for i in range(n_predictions): adjusted_loss_gamma = loss_gamma**(15/(n_predictions - 1)) i_weight = adjusted_loss_gamma**(n_predictions - i - 1) i_loss = (disp_preds[i] - disp_gt).abs() assert i_loss.shape == valid.shape, [i_loss.shape, valid.shape, disp_gt.shape, disp_preds[i].shape] disp_loss += i_weight * i_loss[valid.bool()].mean() epe = torch.sum((disp_preds[-1] - disp_gt)**2, dim=1).sqrt() epe = epe.view(-1)[valid.view(-1)] metrics = { 'epe': epe.mean().item(), '1px': (epe < 1).float().mean().item(), '3px': (epe < 3).float().mean().item(), '5px': (epe < 5).float().mean().item(), } return disp_loss, metrics def fetch_optimizer(args, model): """ Create the optimizer and learning rate scheduler """ optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wdecay, eps=1e-8) scheduler = optim.lr_scheduler.OneCycleLR(optimizer, args.lr, args.num_steps+100, pct_start=0.01, cycle_momentum=False, anneal_strategy='linear') return optimizer, scheduler class Logger: SUM_FREQ = 100 def __init__(self, model, scheduler): self.model = model self.scheduler = scheduler self.total_steps = 0 self.running_loss = {} self.writer = SummaryWriter(log_dir=args.logdir) def _print_training_status(self): metrics_data = [self.running_loss[k]/Logger.SUM_FREQ for k in sorted(self.running_loss.keys())] training_str = "[{:6d}, {:10.7f}] ".format(self.total_steps+1, self.scheduler.get_last_lr()[0]) metrics_str = ("{:10.4f}, "*len(metrics_data)).format(*metrics_data) # print the training status logging.info(f"Training Metrics ({self.total_steps}): {training_str + metrics_str}") if self.writer is None: self.writer = SummaryWriter(log_dir=args.logdir) for k in self.running_loss: self.writer.add_scalar(k, self.running_loss[k]/Logger.SUM_FREQ, self.total_steps) self.running_loss[k] = 0.0 def push(self, metrics): self.total_steps += 1 for key in metrics: if key not in self.running_loss: self.running_loss[key] = 0.0 self.running_loss[key] += metrics[key] if self.total_steps % Logger.SUM_FREQ == Logger.SUM_FREQ-1: self._print_training_status() self.running_loss = {} def write_dict(self, results): if self.writer is None: self.writer = SummaryWriter(log_dir=args.logdir) for key in results: self.writer.add_scalar(key, results[key], self.total_steps) def close(self): self.writer.close() def train(args): model = nn.DataParallel(IGEVStereo(args)) print("Parameter Count: %d" % count_parameters(model)) train_loader = datasets.fetch_dataloader(args) optimizer, scheduler = fetch_optimizer(args, model) total_steps = 0 logger = Logger(model, scheduler) if args.restore_ckpt is not None: assert args.restore_ckpt.endswith(".pth") logging.info("Loading checkpoint...") checkpoint = torch.load(args.restore_ckpt) model.load_state_dict(checkpoint, strict=True) logging.info(f"Done loading checkpoint") model.cuda() model.train() model.module.freeze_bn() # We keep BatchNorm frozen validation_frequency = 10000 scaler = GradScaler(enabled=args.mixed_precision) should_keep_training = True global_batch_num = 0 while should_keep_training: for i_batch, (_, *data_blob) in enumerate(tqdm(train_loader)): optimizer.zero_grad() image1, image2, disp_gt, valid = [x.cuda() for x in data_blob] assert model.training disp_init_pred, disp_preds = model(image1, image2, iters=args.train_iters) assert model.training loss, metrics = sequence_loss(disp_preds, disp_init_pred, disp_gt, valid, max_disp=args.max_disp) logger.writer.add_scalar("live_loss", loss.item(), global_batch_num) logger.writer.add_scalar(f'learning_rate', optimizer.param_groups[0]['lr'], global_batch_num) global_batch_num += 1 scaler.scale(loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) scaler.step(optimizer) scheduler.step() scaler.update() logger.push(metrics) if total_steps % validation_frequency == validation_frequency - 1: save_path = Path(args.logdir + '/%d_%s.pth' % (total_steps + 1, args.name)) logging.info(f"Saving file {save_path.absolute()}") torch.save(model.state_dict(), save_path) if 'sceneflow' in args.train_datasets: results = validate_sceneflow(model.module, iters=args.valid_iters) elif 'kitti' in args.train_datasets: results = validate_kitti(model.module, iters=args.valid_iters) else: raise Exception('Unknown validation dataset.') logger.write_dict(results) model.train() model.module.freeze_bn() total_steps += 1 if total_steps > args.num_steps: should_keep_training = False break if len(train_loader) >= 10000: save_path = Path(args.logdir + '/%d_epoch_%s.pth.gz' % (total_steps + 1, args.name)) logging.info(f"Saving file {save_path}") torch.save(model.state_dict(), save_path) print("FINISHED TRAINING") logger.close() PATH = args.logdir + '/%s.pth' % args.name torch.save(model.state_dict(), PATH) return PATH if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--name', default='igev-stereo', help="name your experiment") parser.add_argument('--restore_ckpt', default=None, help="load the weights from a specific checkpoint") parser.add_argument('--mixed_precision', default=True, action='store_true', help='use mixed precision') parser.add_argument('--logdir', default='./checkpoints/sceneflow', help='the directory to save logs and checkpoints') # Training parameters parser.add_argument('--batch_size', type=int, default=8, help="batch size used during training.") parser.add_argument('--train_datasets', nargs='+', default=['sceneflow'], help="training datasets.") parser.add_argument('--lr', type=float, default=0.0002, help="max learning rate.") parser.add_argument('--num_steps', type=int, default=200000, help="length of training schedule.") parser.add_argument('--image_size', type=int, nargs='+', default=[320, 736], help="size of the random image crops used during training.") parser.add_argument('--train_iters', type=int, default=22, help="number of updates to the disparity field in each forward pass.") parser.add_argument('--wdecay', type=float, default=.00001, help="Weight decay in optimizer.") # Validation parameters parser.add_argument('--valid_iters', type=int, default=32, help='number of flow-field updates during validation forward pass') # Architecure choices parser.add_argument('--corr_implementation', choices=["reg", "alt", "reg_cuda", "alt_cuda"], default="reg", help="correlation volume implementation") parser.add_argument('--shared_backbone', action='store_true', help="use a single backbone for the context and feature encoders") parser.add_argument('--corr_levels', type=int, default=2, help="number of levels in the correlation pyramid") parser.add_argument('--corr_radius', type=int, default=4, help="width of the correlation pyramid") parser.add_argument('--n_downsample', type=int, default=2, help="resolution of the disparity field (1/2^K)") parser.add_argument('--slow_fast_gru', action='store_true', help="iterate the low-res GRUs more frequently") parser.add_argument('--n_gru_layers', type=int, default=3, help="number of hidden GRU levels") parser.add_argument('--hidden_dims', nargs='+', type=int, default=[128]*3, help="hidden state and context dimensions") parser.add_argument('--max_disp', type=int, default=192, help="max disp of geometry encoding volume") # Data augmentation parser.add_argument('--img_gamma', type=float, nargs='+', default=None, help="gamma range") parser.add_argument('--saturation_range', type=float, nargs='+', default=[0, 1.4], help='color saturation') parser.add_argument('--do_flip', default=False, choices=['h', 'v'], help='flip the images horizontally or vertically') parser.add_argument('--spatial_scale', type=float, nargs='+', default=[-0.2, 0.4], help='re-scale the images randomly') parser.add_argument('--noyjitter', action='store_true', help='don\'t simulate imperfect rectification') args = parser.parse_args() torch.manual_seed(666) np.random.seed(666) logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s') Path(args.logdir).mkdir(exist_ok=True, parents=True) train(args)
10,683
41.907631
153
py
IGEV
IGEV-main/IGEV-Stereo/core/stereo_datasets.py
import numpy as np import torch import torch.utils.data as data import torch.nn.functional as F import logging import os import re import copy import math import random from pathlib import Path from glob import glob import os.path as osp from core.utils import frame_utils from core.utils.augmentor import FlowAugmentor, SparseFlowAugmentor class StereoDataset(data.Dataset): def __init__(self, aug_params=None, sparse=False, reader=None): self.augmentor = None self.sparse = sparse self.img_pad = aug_params.pop("img_pad", None) if aug_params is not None else None if aug_params is not None and "crop_size" in aug_params: if sparse: self.augmentor = SparseFlowAugmentor(**aug_params) else: self.augmentor = FlowAugmentor(**aug_params) if reader is None: self.disparity_reader = frame_utils.read_gen else: self.disparity_reader = reader self.is_test = False self.init_seed = False self.flow_list = [] self.disparity_list = [] self.image_list = [] self.extra_info = [] def __getitem__(self, index): if self.is_test: img1 = frame_utils.read_gen(self.image_list[index][0]) img2 = frame_utils.read_gen(self.image_list[index][1]) img1 = np.array(img1).astype(np.uint8)[..., :3] img2 = np.array(img2).astype(np.uint8)[..., :3] img1 = torch.from_numpy(img1).permute(2, 0, 1).float() img2 = torch.from_numpy(img2).permute(2, 0, 1).float() return img1, img2, self.extra_info[index] if not self.init_seed: worker_info = torch.utils.data.get_worker_info() if worker_info is not None: torch.manual_seed(worker_info.id) np.random.seed(worker_info.id) random.seed(worker_info.id) self.init_seed = True index = index % len(self.image_list) disp = self.disparity_reader(self.disparity_list[index]) if isinstance(disp, tuple): disp, valid = disp else: valid = disp < 512 img1 = frame_utils.read_gen(self.image_list[index][0]) img2 = frame_utils.read_gen(self.image_list[index][1]) img1 = np.array(img1).astype(np.uint8) img2 = np.array(img2).astype(np.uint8) disp = np.array(disp).astype(np.float32) flow = np.stack([disp, np.zeros_like(disp)], axis=-1) # grayscale images if len(img1.shape) == 2: img1 = np.tile(img1[...,None], (1, 1, 3)) img2 = np.tile(img2[...,None], (1, 1, 3)) else: img1 = img1[..., :3] img2 = img2[..., :3] if self.augmentor is not None: if self.sparse: img1, img2, flow, valid = self.augmentor(img1, img2, flow, valid) else: img1, img2, flow = self.augmentor(img1, img2, flow) img1 = torch.from_numpy(img1).permute(2, 0, 1).float() img2 = torch.from_numpy(img2).permute(2, 0, 1).float() flow = torch.from_numpy(flow).permute(2, 0, 1).float() if self.sparse: valid = torch.from_numpy(valid) else: valid = (flow[0].abs() < 512) & (flow[1].abs() < 512) if self.img_pad is not None: padH, padW = self.img_pad img1 = F.pad(img1, [padW]*2 + [padH]*2) img2 = F.pad(img2, [padW]*2 + [padH]*2) flow = flow[:1] return self.image_list[index] + [self.disparity_list[index]], img1, img2, flow, valid.float() def __mul__(self, v): copy_of_self = copy.deepcopy(self) copy_of_self.flow_list = v * copy_of_self.flow_list copy_of_self.image_list = v * copy_of_self.image_list copy_of_self.disparity_list = v * copy_of_self.disparity_list copy_of_self.extra_info = v * copy_of_self.extra_info return copy_of_self def __len__(self): return len(self.image_list) class SceneFlowDatasets(StereoDataset): def __init__(self, aug_params=None, root='/data/sceneflow/', dstype='frames_finalpass', things_test=False): super(SceneFlowDatasets, self).__init__(aug_params) self.root = root self.dstype = dstype if things_test: self._add_things("TEST") else: self._add_things("TRAIN") self._add_monkaa("TRAIN") self._add_driving("TRAIN") def _add_things(self, split='TRAIN'): """ Add FlyingThings3D data """ original_length = len(self.disparity_list) # root = osp.join(self.root, 'FlyingThings3D') root = self.root left_images = sorted( glob(osp.join(root, self.dstype, split, '*/*/left/*.png')) ) right_images = [ im.replace('left', 'right') for im in left_images ] disparity_images = [ im.replace(self.dstype, 'disparity').replace('.png', '.pfm') for im in left_images ] # Choose a random subset of 400 images for validation state = np.random.get_state() np.random.seed(1000) # val_idxs = set(np.random.permutation(len(left_images))[:100]) val_idxs = set(np.random.permutation(len(left_images))) np.random.set_state(state) for idx, (img1, img2, disp) in enumerate(zip(left_images, right_images, disparity_images)): if (split == 'TEST' and idx in val_idxs) or split == 'TRAIN': self.image_list += [ [img1, img2] ] self.disparity_list += [ disp ] logging.info(f"Added {len(self.disparity_list) - original_length} from FlyingThings {self.dstype}") def _add_monkaa(self, split="TRAIN"): """ Add FlyingThings3D data """ original_length = len(self.disparity_list) root = self.root left_images = sorted( glob(osp.join(root, self.dstype, split, '*/left/*.png')) ) right_images = [ image_file.replace('left', 'right') for image_file in left_images ] disparity_images = [ im.replace(self.dstype, 'disparity').replace('.png', '.pfm') for im in left_images ] for img1, img2, disp in zip(left_images, right_images, disparity_images): self.image_list += [ [img1, img2] ] self.disparity_list += [ disp ] logging.info(f"Added {len(self.disparity_list) - original_length} from Monkaa {self.dstype}") def _add_driving(self, split="TRAIN"): """ Add FlyingThings3D data """ original_length = len(self.disparity_list) root = self.root left_images = sorted( glob(osp.join(root, self.dstype, split, '*/*/*/left/*.png')) ) right_images = [ image_file.replace('left', 'right') for image_file in left_images ] disparity_images = [ im.replace(self.dstype, 'disparity').replace('.png', '.pfm') for im in left_images ] for img1, img2, disp in zip(left_images, right_images, disparity_images): self.image_list += [ [img1, img2] ] self.disparity_list += [ disp ] logging.info(f"Added {len(self.disparity_list) - original_length} from Driving {self.dstype}") class ETH3D(StereoDataset): def __init__(self, aug_params=None, root='/data/ETH3D', split='training'): super(ETH3D, self).__init__(aug_params, sparse=True) image1_list = sorted( glob(osp.join(root, f'two_view_{split}/*/im0.png')) ) image2_list = sorted( glob(osp.join(root, f'two_view_{split}/*/im1.png')) ) disp_list = sorted( glob(osp.join(root, 'two_view_training_gt/*/disp0GT.pfm')) ) if split == 'training' else [osp.join(root, 'two_view_training_gt/playground_1l/disp0GT.pfm')]*len(image1_list) for img1, img2, disp in zip(image1_list, image2_list, disp_list): self.image_list += [ [img1, img2] ] self.disparity_list += [ disp ] class SintelStereo(StereoDataset): def __init__(self, aug_params=None, root='datasets/SintelStereo'): super().__init__(aug_params, sparse=True, reader=frame_utils.readDispSintelStereo) image1_list = sorted( glob(osp.join(root, 'training/*_left/*/frame_*.png')) ) image2_list = sorted( glob(osp.join(root, 'training/*_right/*/frame_*.png')) ) disp_list = sorted( glob(osp.join(root, 'training/disparities/*/frame_*.png')) ) * 2 for img1, img2, disp in zip(image1_list, image2_list, disp_list): assert img1.split('/')[-2:] == disp.split('/')[-2:] self.image_list += [ [img1, img2] ] self.disparity_list += [ disp ] class FallingThings(StereoDataset): def __init__(self, aug_params=None, root='datasets/FallingThings'): super().__init__(aug_params, reader=frame_utils.readDispFallingThings) assert os.path.exists(root) with open(os.path.join(root, 'filenames.txt'), 'r') as f: filenames = sorted(f.read().splitlines()) image1_list = [osp.join(root, e) for e in filenames] image2_list = [osp.join(root, e.replace('left.jpg', 'right.jpg')) for e in filenames] disp_list = [osp.join(root, e.replace('left.jpg', 'left.depth.png')) for e in filenames] for img1, img2, disp in zip(image1_list, image2_list, disp_list): self.image_list += [ [img1, img2] ] self.disparity_list += [ disp ] class TartanAir(StereoDataset): def __init__(self, aug_params=None, root='datasets', keywords=[]): super().__init__(aug_params, reader=frame_utils.readDispTartanAir) assert os.path.exists(root) with open(os.path.join(root, 'tartanair_filenames.txt'), 'r') as f: filenames = sorted(list(filter(lambda s: 'seasonsforest_winter/Easy' not in s, f.read().splitlines()))) for kw in keywords: filenames = sorted(list(filter(lambda s: kw in s.lower(), filenames))) image1_list = [osp.join(root, e) for e in filenames] image2_list = [osp.join(root, e.replace('_left', '_right')) for e in filenames] disp_list = [osp.join(root, e.replace('image_left', 'depth_left').replace('left.png', 'left_depth.npy')) for e in filenames] for img1, img2, disp in zip(image1_list, image2_list, disp_list): self.image_list += [ [img1, img2] ] self.disparity_list += [ disp ] class KITTI(StereoDataset): def __init__(self, aug_params=None, root='/data/KITTI/KITTI_2015', image_set='training'): super(KITTI, self).__init__(aug_params, sparse=True, reader=frame_utils.readDispKITTI) assert os.path.exists(root) root_12 = '/data/KITTI/KITTI_2012' image1_list = sorted(glob(os.path.join(root_12, image_set, 'colored_0/*_10.png'))) image2_list = sorted(glob(os.path.join(root_12, image_set, 'colored_1/*_10.png'))) disp_list = sorted(glob(os.path.join(root_12, 'training', 'disp_occ/*_10.png'))) if image_set == 'training' else [osp.join(root, 'training/disp_occ/000085_10.png')]*len(image1_list) root_15 = '/data/KITTI/KITTI_2015' image1_list += sorted(glob(os.path.join(root_15, image_set, 'image_2/*_10.png'))) image2_list += sorted(glob(os.path.join(root_15, image_set, 'image_3/*_10.png'))) disp_list += sorted(glob(os.path.join(root_15, 'training', 'disp_occ_0/*_10.png'))) if image_set == 'training' else [osp.join(root, 'training/disp_occ_0/000085_10.png')]*len(image1_list) for idx, (img1, img2, disp) in enumerate(zip(image1_list, image2_list, disp_list)): self.image_list += [ [img1, img2] ] self.disparity_list += [ disp ] class Middlebury(StereoDataset): def __init__(self, aug_params=None, root='/data/Middlebury', split='F'): super(Middlebury, self).__init__(aug_params, sparse=True, reader=frame_utils.readDispMiddlebury) assert os.path.exists(root) assert split in "FHQ" lines = list(map(osp.basename, glob(os.path.join(root, "trainingH/*")))) # lines = list(filter(lambda p: any(s in p.split('/') for s in Path(os.path.join(root, "MiddEval3/official_train.txt")).read_text().splitlines()), lines)) # image1_list = sorted([os.path.join(root, "MiddEval3", f'training{split}', f'{name}/im0.png') for name in lines]) # image2_list = sorted([os.path.join(root, "MiddEval3", f'training{split}', f'{name}/im1.png') for name in lines]) # disp_list = sorted([os.path.join(root, "MiddEval3", f'training{split}', f'{name}/disp0GT.pfm') for name in lines]) image1_list = sorted([os.path.join(root, f'training{split}', f'{name}/im0.png') for name in lines]) image2_list = sorted([os.path.join(root, f'training{split}', f'{name}/im1.png') for name in lines]) disp_list = sorted([os.path.join(root, f'training{split}', f'{name}/disp0GT.pfm') for name in lines]) assert len(image1_list) == len(image2_list) == len(disp_list) > 0, [image1_list, split] for img1, img2, disp in zip(image1_list, image2_list, disp_list): self.image_list += [ [img1, img2] ] self.disparity_list += [ disp ] def fetch_dataloader(args): """ Create the data loader for the corresponding trainign set """ aug_params = {'crop_size': args.image_size, 'min_scale': args.spatial_scale[0], 'max_scale': args.spatial_scale[1], 'do_flip': False, 'yjitter': not args.noyjitter} if hasattr(args, "saturation_range") and args.saturation_range is not None: aug_params["saturation_range"] = args.saturation_range if hasattr(args, "img_gamma") and args.img_gamma is not None: aug_params["gamma"] = args.img_gamma if hasattr(args, "do_flip") and args.do_flip is not None: aug_params["do_flip"] = args.do_flip train_dataset = None for dataset_name in args.train_datasets: if re.compile("middlebury_.*").fullmatch(dataset_name): new_dataset = Middlebury(aug_params, split=dataset_name.replace('middlebury_','')) elif dataset_name == 'sceneflow': #clean_dataset = SceneFlowDatasets(aug_params, dstype='frames_cleanpass') final_dataset = SceneFlowDatasets(aug_params, dstype='frames_finalpass') #new_dataset = (clean_dataset*4) + (final_dataset*4) new_dataset = final_dataset logging.info(f"Adding {len(new_dataset)} samples from SceneFlow") elif 'kitti' in dataset_name: new_dataset = KITTI(aug_params) logging.info(f"Adding {len(new_dataset)} samples from KITTI") elif dataset_name == 'sintel_stereo': new_dataset = SintelStereo(aug_params)*140 logging.info(f"Adding {len(new_dataset)} samples from Sintel Stereo") elif dataset_name == 'falling_things': new_dataset = FallingThings(aug_params)*5 logging.info(f"Adding {len(new_dataset)} samples from FallingThings") elif dataset_name.startswith('tartan_air'): new_dataset = TartanAir(aug_params, keywords=dataset_name.split('_')[2:]) logging.info(f"Adding {len(new_dataset)} samples from Tartain Air") train_dataset = new_dataset if train_dataset is None else train_dataset + new_dataset train_loader = data.DataLoader(train_dataset, batch_size=args.batch_size, pin_memory=True, shuffle=True, num_workers=int(os.environ.get('SLURM_CPUS_PER_TASK', 6))-2, drop_last=True) logging.info('Training with %d image pairs' % len(train_dataset)) return train_loader
15,502
45.695783
200
py
IGEV
IGEV-main/IGEV-Stereo/core/update.py
import torch import torch.nn as nn import torch.nn.functional as F from opt_einsum import contract class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256, output_dim=2): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, output_dim, 3, padding=1) self.relu = nn.ReLU(inplace=True) def forward(self, x): return self.conv2(self.relu(self.conv1(x))) class DispHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256, output_dim=1): super(DispHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, output_dim, 3, padding=1) self.relu = nn.ReLU(inplace=True) def forward(self, x): return self.conv2(self.relu(self.conv1(x))) class ConvGRU(nn.Module): def __init__(self, hidden_dim, input_dim, kernel_size=3): super(ConvGRU, self).__init__() self.convz = nn.Conv2d(hidden_dim+input_dim, hidden_dim, kernel_size, padding=kernel_size//2) self.convr = nn.Conv2d(hidden_dim+input_dim, hidden_dim, kernel_size, padding=kernel_size//2) self.convq = nn.Conv2d(hidden_dim+input_dim, hidden_dim, kernel_size, padding=kernel_size//2) def forward(self, h, cz, cr, cq, *x_list): x = torch.cat(x_list, dim=1) hx = torch.cat([h, x], dim=1) z = torch.sigmoid(self.convz(hx) + cz) r = torch.sigmoid(self.convr(hx) + cr) q = torch.tanh(self.convq(torch.cat([r*h, x], dim=1)) + cq) h = (1-z) * h + z * q return h class SepConvGRU(nn.Module): def __init__(self, hidden_dim=128, input_dim=192+128): super(SepConvGRU, self).__init__() self.convz1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2)) self.convr1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2)) self.convq1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2)) self.convz2 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (5,1), padding=(2,0)) self.convr2 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (5,1), padding=(2,0)) self.convq2 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (5,1), padding=(2,0)) def forward(self, h, *x): # horizontal x = torch.cat(x, dim=1) hx = torch.cat([h, x], dim=1) z = torch.sigmoid(self.convz1(hx)) r = torch.sigmoid(self.convr1(hx)) q = torch.tanh(self.convq1(torch.cat([r*h, x], dim=1))) h = (1-z) * h + z * q # vertical hx = torch.cat([h, x], dim=1) z = torch.sigmoid(self.convz2(hx)) r = torch.sigmoid(self.convr2(hx)) q = torch.tanh(self.convq2(torch.cat([r*h, x], dim=1))) h = (1-z) * h + z * q return h class BasicMotionEncoder(nn.Module): def __init__(self, args): super(BasicMotionEncoder, self).__init__() self.args = args cor_planes = args.corr_levels * (2*args.corr_radius + 1) * (8+1) self.convc1 = nn.Conv2d(cor_planes, 64, 1, padding=0) self.convc2 = nn.Conv2d(64, 64, 3, padding=1) self.convd1 = nn.Conv2d(1, 64, 7, padding=3) self.convd2 = nn.Conv2d(64, 64, 3, padding=1) self.conv = nn.Conv2d(64+64, 128-1, 3, padding=1) def forward(self, disp, corr): cor = F.relu(self.convc1(corr)) cor = F.relu(self.convc2(cor)) disp_ = F.relu(self.convd1(disp)) disp_ = F.relu(self.convd2(disp_)) cor_disp = torch.cat([cor, disp_], dim=1) out = F.relu(self.conv(cor_disp)) return torch.cat([out, disp], dim=1) def pool2x(x): return F.avg_pool2d(x, 3, stride=2, padding=1) def pool4x(x): return F.avg_pool2d(x, 5, stride=4, padding=1) def interp(x, dest): interp_args = {'mode': 'bilinear', 'align_corners': True} return F.interpolate(x, dest.shape[2:], **interp_args) class BasicMultiUpdateBlock(nn.Module): def __init__(self, args, hidden_dims=[]): super().__init__() self.args = args self.encoder = BasicMotionEncoder(args) encoder_output_dim = 128 self.gru04 = ConvGRU(hidden_dims[2], encoder_output_dim + hidden_dims[1] * (args.n_gru_layers > 1)) self.gru08 = ConvGRU(hidden_dims[1], hidden_dims[0] * (args.n_gru_layers == 3) + hidden_dims[2]) self.gru16 = ConvGRU(hidden_dims[0], hidden_dims[1]) self.disp_head = DispHead(hidden_dims[2], hidden_dim=256, output_dim=1) factor = 2**self.args.n_downsample self.mask_feat_4 = nn.Sequential( nn.Conv2d(hidden_dims[2], 32, 3, padding=1), nn.ReLU(inplace=True)) def forward(self, net, inp, corr=None, disp=None, iter04=True, iter08=True, iter16=True, update=True): if iter16: net[2] = self.gru16(net[2], *(inp[2]), pool2x(net[1])) if iter08: if self.args.n_gru_layers > 2: net[1] = self.gru08(net[1], *(inp[1]), pool2x(net[0]), interp(net[2], net[1])) else: net[1] = self.gru08(net[1], *(inp[1]), pool2x(net[0])) if iter04: motion_features = self.encoder(disp, corr) if self.args.n_gru_layers > 1: net[0] = self.gru04(net[0], *(inp[0]), motion_features, interp(net[1], net[0])) else: net[0] = self.gru04(net[0], *(inp[0]), motion_features) if not update: return net delta_disp = self.disp_head(net[0]) mask_feat_4 = self.mask_feat_4(net[0]) return net, mask_feat_4, delta_disp
5,687
38.776224
107
py
IGEV
IGEV-main/IGEV-Stereo/core/submodule.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class BasicConv(nn.Module): def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, bn=True, relu=True, **kwargs): super(BasicConv, self).__init__() self.relu = relu self.use_bn = bn if is_3d: if deconv: self.conv = nn.ConvTranspose3d(in_channels, out_channels, bias=False, **kwargs) else: self.conv = nn.Conv3d(in_channels, out_channels, bias=False, **kwargs) self.bn = nn.BatchNorm3d(out_channels) else: if deconv: self.conv = nn.ConvTranspose2d(in_channels, out_channels, bias=False, **kwargs) else: self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) self.bn = nn.BatchNorm2d(out_channels) def forward(self, x): x = self.conv(x) if self.use_bn: x = self.bn(x) if self.relu: x = nn.LeakyReLU()(x)#, inplace=True) return x class Conv2x(nn.Module): def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, concat=True, keep_concat=True, bn=True, relu=True, keep_dispc=False): super(Conv2x, self).__init__() self.concat = concat self.is_3d = is_3d if deconv and is_3d: kernel = (4, 4, 4) elif deconv: kernel = 4 else: kernel = 3 if deconv and is_3d and keep_dispc: kernel = (1, 4, 4) stride = (1, 2, 2) padding = (0, 1, 1) self.conv1 = BasicConv(in_channels, out_channels, deconv, is_3d, bn=True, relu=True, kernel_size=kernel, stride=stride, padding=padding) else: self.conv1 = BasicConv(in_channels, out_channels, deconv, is_3d, bn=True, relu=True, kernel_size=kernel, stride=2, padding=1) if self.concat: mul = 2 if keep_concat else 1 self.conv2 = BasicConv(out_channels*2, out_channels*mul, False, is_3d, bn, relu, kernel_size=3, stride=1, padding=1) else: self.conv2 = BasicConv(out_channels, out_channels, False, is_3d, bn, relu, kernel_size=3, stride=1, padding=1) def forward(self, x, rem): x = self.conv1(x) if x.shape != rem.shape: x = F.interpolate( x, size=(rem.shape[-2], rem.shape[-1]), mode='nearest') if self.concat: x = torch.cat((x, rem), 1) else: x = x + rem x = self.conv2(x) return x class BasicConv_IN(nn.Module): def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, IN=True, relu=True, **kwargs): super(BasicConv_IN, self).__init__() self.relu = relu self.use_in = IN if is_3d: if deconv: self.conv = nn.ConvTranspose3d(in_channels, out_channels, bias=False, **kwargs) else: self.conv = nn.Conv3d(in_channels, out_channels, bias=False, **kwargs) self.IN = nn.InstanceNorm3d(out_channels) else: if deconv: self.conv = nn.ConvTranspose2d(in_channels, out_channels, bias=False, **kwargs) else: self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) self.IN = nn.InstanceNorm2d(out_channels) def forward(self, x): x = self.conv(x) if self.use_in: x = self.IN(x) if self.relu: x = nn.LeakyReLU()(x)#, inplace=True) return x class Conv2x_IN(nn.Module): def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, concat=True, keep_concat=True, IN=True, relu=True, keep_dispc=False): super(Conv2x_IN, self).__init__() self.concat = concat self.is_3d = is_3d if deconv and is_3d: kernel = (4, 4, 4) elif deconv: kernel = 4 else: kernel = 3 if deconv and is_3d and keep_dispc: kernel = (1, 4, 4) stride = (1, 2, 2) padding = (0, 1, 1) self.conv1 = BasicConv_IN(in_channels, out_channels, deconv, is_3d, IN=True, relu=True, kernel_size=kernel, stride=stride, padding=padding) else: self.conv1 = BasicConv_IN(in_channels, out_channels, deconv, is_3d, IN=True, relu=True, kernel_size=kernel, stride=2, padding=1) if self.concat: mul = 2 if keep_concat else 1 self.conv2 = BasicConv_IN(out_channels*2, out_channels*mul, False, is_3d, IN, relu, kernel_size=3, stride=1, padding=1) else: self.conv2 = BasicConv_IN(out_channels, out_channels, False, is_3d, IN, relu, kernel_size=3, stride=1, padding=1) def forward(self, x, rem): x = self.conv1(x) if x.shape != rem.shape: x = F.interpolate( x, size=(rem.shape[-2], rem.shape[-1]), mode='nearest') if self.concat: x = torch.cat((x, rem), 1) else: x = x + rem x = self.conv2(x) return x def groupwise_correlation(fea1, fea2, num_groups): B, C, H, W = fea1.shape assert C % num_groups == 0 channels_per_group = C // num_groups cost = (fea1 * fea2).view([B, num_groups, channels_per_group, H, W]).mean(dim=2) assert cost.shape == (B, num_groups, H, W) return cost def build_gwc_volume(refimg_fea, targetimg_fea, maxdisp, num_groups): B, C, H, W = refimg_fea.shape volume = refimg_fea.new_zeros([B, num_groups, maxdisp, H, W]) for i in range(maxdisp): if i > 0: volume[:, :, i, :, i:] = groupwise_correlation(refimg_fea[:, :, :, i:], targetimg_fea[:, :, :, :-i], num_groups) else: volume[:, :, i, :, :] = groupwise_correlation(refimg_fea, targetimg_fea, num_groups) volume = volume.contiguous() return volume def norm_correlation(fea1, fea2): cost = torch.mean(((fea1/(torch.norm(fea1, 2, 1, True)+1e-05)) * (fea2/(torch.norm(fea2, 2, 1, True)+1e-05))), dim=1, keepdim=True) return cost def build_norm_correlation_volume(refimg_fea, targetimg_fea, maxdisp): B, C, H, W = refimg_fea.shape volume = refimg_fea.new_zeros([B, 1, maxdisp, H, W]) for i in range(maxdisp): if i > 0: volume[:, :, i, :, i:] = norm_correlation(refimg_fea[:, :, :, i:], targetimg_fea[:, :, :, :-i]) else: volume[:, :, i, :, :] = norm_correlation(refimg_fea, targetimg_fea) volume = volume.contiguous() return volume def correlation(fea1, fea2): cost = torch.sum((fea1 * fea2), dim=1, keepdim=True) return cost def build_correlation_volume(refimg_fea, targetimg_fea, maxdisp): B, C, H, W = refimg_fea.shape volume = refimg_fea.new_zeros([B, 1, maxdisp, H, W]) for i in range(maxdisp): if i > 0: volume[:, :, i, :, i:] = correlation(refimg_fea[:, :, :, i:], targetimg_fea[:, :, :, :-i]) else: volume[:, :, i, :, :] = correlation(refimg_fea, targetimg_fea) volume = volume.contiguous() return volume def build_concat_volume(refimg_fea, targetimg_fea, maxdisp): B, C, H, W = refimg_fea.shape volume = refimg_fea.new_zeros([B, 2 * C, maxdisp, H, W]) for i in range(maxdisp): if i > 0: volume[:, :C, i, :, :] = refimg_fea[:, :, :, :] volume[:, C:, i, :, i:] = targetimg_fea[:, :, :, :-i] else: volume[:, :C, i, :, :] = refimg_fea volume[:, C:, i, :, :] = targetimg_fea volume = volume.contiguous() return volume def disparity_regression(x, maxdisp): assert len(x.shape) == 4 disp_values = torch.arange(0, maxdisp, dtype=x.dtype, device=x.device) disp_values = disp_values.view(1, maxdisp, 1, 1) return torch.sum(x * disp_values, 1, keepdim=True) class FeatureAtt(nn.Module): def __init__(self, cv_chan, feat_chan): super(FeatureAtt, self).__init__() self.feat_att = nn.Sequential( BasicConv(feat_chan, feat_chan//2, kernel_size=1, stride=1, padding=0), nn.Conv2d(feat_chan//2, cv_chan, 1)) def forward(self, cv, feat): ''' ''' feat_att = self.feat_att(feat).unsqueeze(2) cv = torch.sigmoid(feat_att)*cv return cv def context_upsample(disp_low, up_weights): ### # cv (b,1,h,w) # sp (b,9,4*h,4*w) ### b, c, h, w = disp_low.shape disp_unfold = F.unfold(disp_low.reshape(b,c,h,w),3,1,1).reshape(b,-1,h,w) disp_unfold = F.interpolate(disp_unfold,(h*4,w*4),mode='nearest').reshape(b,9,h*4,w*4) disp = (disp_unfold*up_weights).sum(1) return disp
8,910
34.221344
151
py
IGEV
IGEV-main/IGEV-Stereo/core/extractor.py
import torch import torch.nn as nn import torch.nn.functional as F from core.submodule import * import timm class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1) self.relu = nn.ReLU(inplace=True) num_groups = planes // 8 if norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) if not (stride == 1 and in_planes == planes): self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) elif norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(planes) self.norm2 = nn.BatchNorm2d(planes) if not (stride == 1 and in_planes == planes): self.norm3 = nn.BatchNorm2d(planes) elif norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(planes) self.norm2 = nn.InstanceNorm2d(planes) if not (stride == 1 and in_planes == planes): self.norm3 = nn.InstanceNorm2d(planes) elif norm_fn == 'none': self.norm1 = nn.Sequential() self.norm2 = nn.Sequential() if not (stride == 1 and in_planes == planes): self.norm3 = nn.Sequential() if stride == 1 and in_planes == planes: self.downsample = None else: self.downsample = nn.Sequential( nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3) def forward(self, x): y = x y = self.conv1(y) y = self.norm1(y) y = self.relu(y) y = self.conv2(y) y = self.norm2(y) y = self.relu(y) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y) class BottleneckBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(BottleneckBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes//4, kernel_size=1, padding=0) self.conv2 = nn.Conv2d(planes//4, planes//4, kernel_size=3, padding=1, stride=stride) self.conv3 = nn.Conv2d(planes//4, planes, kernel_size=1, padding=0) self.relu = nn.ReLU(inplace=True) num_groups = planes // 8 if norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4) self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4) self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) if not stride == 1: self.norm4 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) elif norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(planes//4) self.norm2 = nn.BatchNorm2d(planes//4) self.norm3 = nn.BatchNorm2d(planes) if not stride == 1: self.norm4 = nn.BatchNorm2d(planes) elif norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(planes//4) self.norm2 = nn.InstanceNorm2d(planes//4) self.norm3 = nn.InstanceNorm2d(planes) if not stride == 1: self.norm4 = nn.InstanceNorm2d(planes) elif norm_fn == 'none': self.norm1 = nn.Sequential() self.norm2 = nn.Sequential() self.norm3 = nn.Sequential() if not stride == 1: self.norm4 = nn.Sequential() if stride == 1: self.downsample = None else: self.downsample = nn.Sequential( nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm4) def forward(self, x): y = x y = self.relu(self.norm1(self.conv1(y))) y = self.relu(self.norm2(self.conv2(y))) y = self.relu(self.norm3(self.conv3(y))) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y) class BasicEncoder(nn.Module): def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0, downsample=3): super(BasicEncoder, self).__init__() self.norm_fn = norm_fn self.downsample = downsample if self.norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) elif self.norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(64) elif self.norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(64) elif self.norm_fn == 'none': self.norm1 = nn.Sequential() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=1 + (downsample > 2), padding=3) self.relu1 = nn.ReLU(inplace=True) self.in_planes = 64 self.layer1 = self._make_layer(64, stride=1) self.layer2 = self._make_layer(96, stride=1 + (downsample > 1)) self.layer3 = self._make_layer(128, stride=1 + (downsample > 0)) # output convolution self.conv2 = nn.Conv2d(128, output_dim, kernel_size=1) self.dropout = None if dropout > 0: self.dropout = nn.Dropout2d(p=dropout) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): if m.weight is not None: nn.init.constant_(m.weight, 1) if m.bias is not None: nn.init.constant_(m.bias, 0) def _make_layer(self, dim, stride=1): layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) layers = (layer1, layer2) self.in_planes = dim return nn.Sequential(*layers) def forward(self, x, dual_inp=False): # if input is list, combine batch dimension is_list = isinstance(x, tuple) or isinstance(x, list) if is_list: batch_dim = x[0].shape[0] x = torch.cat(x, dim=0) x = self.conv1(x) x = self.norm1(x) x = self.relu1(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.conv2(x) if self.training and self.dropout is not None: x = self.dropout(x) if is_list: x = x.split(split_size=batch_dim, dim=0) return x class MultiBasicEncoder(nn.Module): def __init__(self, output_dim=[128], norm_fn='batch', dropout=0.0, downsample=3): super(MultiBasicEncoder, self).__init__() self.norm_fn = norm_fn self.downsample = downsample # self.norm_111 = nn.BatchNorm2d(128, affine=False, track_running_stats=False) # self.norm_222 = nn.BatchNorm2d(128, affine=False, track_running_stats=False) if self.norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) elif self.norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(64) elif self.norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(64) elif self.norm_fn == 'none': self.norm1 = nn.Sequential() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=1 + (downsample > 2), padding=3) self.relu1 = nn.ReLU(inplace=True) self.in_planes = 64 self.layer1 = self._make_layer(64, stride=1) self.layer2 = self._make_layer(96, stride=1 + (downsample > 1)) self.layer3 = self._make_layer(128, stride=1 + (downsample > 0)) self.layer4 = self._make_layer(128, stride=2) self.layer5 = self._make_layer(128, stride=2) output_list = [] for dim in output_dim: conv_out = nn.Sequential( ResidualBlock(128, 128, self.norm_fn, stride=1), nn.Conv2d(128, dim[2], 3, padding=1)) output_list.append(conv_out) self.outputs04 = nn.ModuleList(output_list) output_list = [] for dim in output_dim: conv_out = nn.Sequential( ResidualBlock(128, 128, self.norm_fn, stride=1), nn.Conv2d(128, dim[1], 3, padding=1)) output_list.append(conv_out) self.outputs08 = nn.ModuleList(output_list) output_list = [] for dim in output_dim: conv_out = nn.Conv2d(128, dim[0], 3, padding=1) output_list.append(conv_out) self.outputs16 = nn.ModuleList(output_list) if dropout > 0: self.dropout = nn.Dropout2d(p=dropout) else: self.dropout = None for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): if m.weight is not None: nn.init.constant_(m.weight, 1) if m.bias is not None: nn.init.constant_(m.bias, 0) def _make_layer(self, dim, stride=1): layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) layers = (layer1, layer2) self.in_planes = dim return nn.Sequential(*layers) def forward(self, x, dual_inp=False, num_layers=3): x = self.conv1(x) x = self.norm1(x) x = self.relu1(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) if dual_inp: v = x x = x[:(x.shape[0]//2)] outputs04 = [f(x) for f in self.outputs04] if num_layers == 1: return (outputs04, v) if dual_inp else (outputs04,) y = self.layer4(x) outputs08 = [f(y) for f in self.outputs08] if num_layers == 2: return (outputs04, outputs08, v) if dual_inp else (outputs04, outputs08) z = self.layer5(y) outputs16 = [f(z) for f in self.outputs16] return (outputs04, outputs08, outputs16, v) if dual_inp else (outputs04, outputs08, outputs16) class SubModule(nn.Module): def __init__(self): super(SubModule, self).__init__() def weight_init(self): 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.Conv3d): n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * 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.BatchNorm3d): m.weight.data.fill_(1) m.bias.data.zero_() class Feature(SubModule): def __init__(self): super(Feature, self).__init__() pretrained = True model = timm.create_model('mobilenetv2_100', pretrained=pretrained, features_only=True) layers = [1,2,3,5,6] chans = [16, 24, 32, 96, 160] self.conv_stem = model.conv_stem self.bn1 = model.bn1 self.act1 = model.act1 self.block0 = torch.nn.Sequential(*model.blocks[0:layers[0]]) self.block1 = torch.nn.Sequential(*model.blocks[layers[0]:layers[1]]) self.block2 = torch.nn.Sequential(*model.blocks[layers[1]:layers[2]]) self.block3 = torch.nn.Sequential(*model.blocks[layers[2]:layers[3]]) self.block4 = torch.nn.Sequential(*model.blocks[layers[3]:layers[4]]) self.deconv32_16 = Conv2x_IN(chans[4], chans[3], deconv=True, concat=True) self.deconv16_8 = Conv2x_IN(chans[3]*2, chans[2], deconv=True, concat=True) self.deconv8_4 = Conv2x_IN(chans[2]*2, chans[1], deconv=True, concat=True) self.conv4 = BasicConv_IN(chans[1]*2, chans[1]*2, kernel_size=3, stride=1, padding=1) def forward(self, x): x = self.act1(self.bn1(self.conv_stem(x))) x2 = self.block0(x) x4 = self.block1(x2) x8 = self.block2(x4) x16 = self.block3(x8) x32 = self.block4(x16) x16 = self.deconv32_16(x32, x16) x8 = self.deconv16_8(x16, x8) x4 = self.deconv8_4(x8, x4) x4 = self.conv4(x4) return [x4, x8, x16, x32]
12,837
34.366391
102
py
IGEV
IGEV-main/IGEV-Stereo/core/geometry.py
import torch import torch.nn.functional as F from core.utils.utils import bilinear_sampler class Combined_Geo_Encoding_Volume: def __init__(self, init_fmap1, init_fmap2, geo_volume, num_levels=2, radius=4): self.num_levels = num_levels self.radius = radius self.geo_volume_pyramid = [] self.init_corr_pyramid = [] # all pairs correlation init_corr = Combined_Geo_Encoding_Volume.corr(init_fmap1, init_fmap2) b, h, w, _, w2 = init_corr.shape b, c, d, h, w = geo_volume.shape geo_volume = geo_volume.permute(0, 3, 4, 1, 2).reshape(b*h*w, c, 1, d) init_corr = init_corr.reshape(b*h*w, 1, 1, w2) self.geo_volume_pyramid.append(geo_volume) self.init_corr_pyramid.append(init_corr) for i in range(self.num_levels-1): geo_volume = F.avg_pool2d(geo_volume, [1,2], stride=[1,2]) self.geo_volume_pyramid.append(geo_volume) for i in range(self.num_levels-1): init_corr = F.avg_pool2d(init_corr, [1,2], stride=[1,2]) self.init_corr_pyramid.append(init_corr) def __call__(self, disp, coords): r = self.radius b, _, h, w = disp.shape out_pyramid = [] for i in range(self.num_levels): geo_volume = self.geo_volume_pyramid[i] dx = torch.linspace(-r, r, 2*r+1) dx = dx.view(1, 1, 2*r+1, 1).to(disp.device) x0 = dx + disp.reshape(b*h*w, 1, 1, 1) / 2**i y0 = torch.zeros_like(x0) disp_lvl = torch.cat([x0,y0], dim=-1) geo_volume = bilinear_sampler(geo_volume, disp_lvl) geo_volume = geo_volume.view(b, h, w, -1) init_corr = self.init_corr_pyramid[i] init_x0 = coords.reshape(b*h*w, 1, 1, 1)/2**i - disp.reshape(b*h*w, 1, 1, 1) / 2**i + dx init_coords_lvl = torch.cat([init_x0,y0], dim=-1) init_corr = bilinear_sampler(init_corr, init_coords_lvl) init_corr = init_corr.view(b, h, w, -1) out_pyramid.append(geo_volume) out_pyramid.append(init_corr) out = torch.cat(out_pyramid, dim=-1) return out.permute(0, 3, 1, 2).contiguous().float() @staticmethod def corr(fmap1, fmap2): B, D, H, W1 = fmap1.shape _, _, _, W2 = fmap2.shape fmap1 = fmap1.view(B, D, H, W1) fmap2 = fmap2.view(B, D, H, W2) corr = torch.einsum('aijk,aijh->ajkh', fmap1, fmap2) corr = corr.reshape(B, H, W1, 1, W2).contiguous() return corr
2,564
36.173913
100
py
IGEV
IGEV-main/IGEV-Stereo/core/igev_stereo.py
import torch import torch.nn as nn import torch.nn.functional as F from core.update import BasicMultiUpdateBlock from core.extractor import MultiBasicEncoder, Feature from core.geometry import Combined_Geo_Encoding_Volume from core.submodule import * import time try: autocast = torch.cuda.amp.autocast except: class autocast: def __init__(self, enabled): pass def __enter__(self): pass def __exit__(self, *args): pass class hourglass(nn.Module): def __init__(self, in_channels): super(hourglass, self).__init__() self.conv1 = nn.Sequential(BasicConv(in_channels, in_channels*2, is_3d=True, bn=True, relu=True, kernel_size=3, padding=1, stride=2, dilation=1), BasicConv(in_channels*2, in_channels*2, is_3d=True, bn=True, relu=True, kernel_size=3, padding=1, stride=1, dilation=1)) self.conv2 = nn.Sequential(BasicConv(in_channels*2, in_channels*4, is_3d=True, bn=True, relu=True, kernel_size=3, padding=1, stride=2, dilation=1), BasicConv(in_channels*4, in_channels*4, is_3d=True, bn=True, relu=True, kernel_size=3, padding=1, stride=1, dilation=1)) self.conv3 = nn.Sequential(BasicConv(in_channels*4, in_channels*6, is_3d=True, bn=True, relu=True, kernel_size=3, padding=1, stride=2, dilation=1), BasicConv(in_channels*6, in_channels*6, is_3d=True, bn=True, relu=True, kernel_size=3, padding=1, stride=1, dilation=1)) self.conv3_up = BasicConv(in_channels*6, in_channels*4, deconv=True, is_3d=True, bn=True, relu=True, kernel_size=(4, 4, 4), padding=(1, 1, 1), stride=(2, 2, 2)) self.conv2_up = BasicConv(in_channels*4, in_channels*2, deconv=True, is_3d=True, bn=True, relu=True, kernel_size=(4, 4, 4), padding=(1, 1, 1), stride=(2, 2, 2)) self.conv1_up = BasicConv(in_channels*2, 8, deconv=True, is_3d=True, bn=False, relu=False, kernel_size=(4, 4, 4), padding=(1, 1, 1), stride=(2, 2, 2)) self.agg_0 = nn.Sequential(BasicConv(in_channels*8, in_channels*4, is_3d=True, kernel_size=1, padding=0, stride=1), BasicConv(in_channels*4, in_channels*4, is_3d=True, kernel_size=3, padding=1, stride=1), BasicConv(in_channels*4, in_channels*4, is_3d=True, kernel_size=3, padding=1, stride=1),) self.agg_1 = nn.Sequential(BasicConv(in_channels*4, in_channels*2, is_3d=True, kernel_size=1, padding=0, stride=1), BasicConv(in_channels*2, in_channels*2, is_3d=True, kernel_size=3, padding=1, stride=1), BasicConv(in_channels*2, in_channels*2, is_3d=True, kernel_size=3, padding=1, stride=1)) self.feature_att_8 = FeatureAtt(in_channels*2, 64) self.feature_att_16 = FeatureAtt(in_channels*4, 192) self.feature_att_32 = FeatureAtt(in_channels*6, 160) self.feature_att_up_16 = FeatureAtt(in_channels*4, 192) self.feature_att_up_8 = FeatureAtt(in_channels*2, 64) def forward(self, x, features): conv1 = self.conv1(x) conv1 = self.feature_att_8(conv1, features[1]) conv2 = self.conv2(conv1) conv2 = self.feature_att_16(conv2, features[2]) conv3 = self.conv3(conv2) conv3 = self.feature_att_32(conv3, features[3]) conv3_up = self.conv3_up(conv3) conv2 = torch.cat((conv3_up, conv2), dim=1) conv2 = self.agg_0(conv2) conv2 = self.feature_att_up_16(conv2, features[2]) conv2_up = self.conv2_up(conv2) conv1 = torch.cat((conv2_up, conv1), dim=1) conv1 = self.agg_1(conv1) conv1 = self.feature_att_up_8(conv1, features[1]) conv = self.conv1_up(conv1) return conv class IGEVStereo(nn.Module): def __init__(self, args): super().__init__() self.args = args context_dims = args.hidden_dims self.cnet = MultiBasicEncoder(output_dim=[args.hidden_dims, context_dims], norm_fn="batch", downsample=args.n_downsample) self.update_block = BasicMultiUpdateBlock(self.args, hidden_dims=args.hidden_dims) self.context_zqr_convs = nn.ModuleList([nn.Conv2d(context_dims[i], args.hidden_dims[i]*3, 3, padding=3//2) for i in range(self.args.n_gru_layers)]) self.feature = Feature() self.stem_2 = nn.Sequential( BasicConv_IN(3, 32, kernel_size=3, stride=2, padding=1), nn.Conv2d(32, 32, 3, 1, 1, bias=False), nn.InstanceNorm2d(32), nn.ReLU() ) self.stem_4 = nn.Sequential( BasicConv_IN(32, 48, kernel_size=3, stride=2, padding=1), nn.Conv2d(48, 48, 3, 1, 1, bias=False), nn.InstanceNorm2d(48), nn.ReLU() ) self.spx = nn.Sequential(nn.ConvTranspose2d(2*32, 9, kernel_size=4, stride=2, padding=1),) self.spx_2 = Conv2x_IN(24, 32, True) self.spx_4 = nn.Sequential( BasicConv_IN(96, 24, kernel_size=3, stride=1, padding=1), nn.Conv2d(24, 24, 3, 1, 1, bias=False), nn.InstanceNorm2d(24), nn.ReLU() ) self.spx_2_gru = Conv2x(32, 32, True) self.spx_gru = nn.Sequential(nn.ConvTranspose2d(2*32, 9, kernel_size=4, stride=2, padding=1),) self.conv = BasicConv_IN(96, 96, kernel_size=3, padding=1, stride=1) self.desc = nn.Conv2d(96, 96, kernel_size=1, padding=0, stride=1) self.corr_stem = BasicConv(8, 8, is_3d=True, kernel_size=3, stride=1, padding=1) self.corr_feature_att = FeatureAtt(8, 96) self.cost_agg = hourglass(8) self.classifier = nn.Conv3d(8, 1, 3, 1, 1, bias=False) def freeze_bn(self): for m in self.modules(): if isinstance(m, nn.BatchNorm2d): m.eval() def upsample_disp(self, disp, mask_feat_4, stem_2x): with autocast(enabled=self.args.mixed_precision): xspx = self.spx_2_gru(mask_feat_4, stem_2x) spx_pred = self.spx_gru(xspx) spx_pred = F.softmax(spx_pred, 1) up_disp = context_upsample(disp*4., spx_pred).unsqueeze(1) return up_disp def forward(self, image1, image2, iters=12, flow_init=None, test_mode=False): """ Estimate disparity between pair of frames """ image1 = (2 * (image1 / 255.0) - 1.0).contiguous() image2 = (2 * (image2 / 255.0) - 1.0).contiguous() with autocast(enabled=self.args.mixed_precision): features_left = self.feature(image1) features_right = self.feature(image2) stem_2x = self.stem_2(image1) stem_4x = self.stem_4(stem_2x) stem_2y = self.stem_2(image2) stem_4y = self.stem_4(stem_2y) features_left[0] = torch.cat((features_left[0], stem_4x), 1) features_right[0] = torch.cat((features_right[0], stem_4y), 1) match_left = self.desc(self.conv(features_left[0])) match_right = self.desc(self.conv(features_right[0])) gwc_volume = build_gwc_volume(match_left, match_right, self.args.max_disp//4, 8) gwc_volume = self.corr_stem(gwc_volume) gwc_volume = self.corr_feature_att(gwc_volume, features_left[0]) geo_encoding_volume = self.cost_agg(gwc_volume, features_left) # Init disp from geometry encoding volume prob = F.softmax(self.classifier(geo_encoding_volume).squeeze(1), dim=1) init_disp = disparity_regression(prob, self.args.max_disp//4) del prob, gwc_volume if not test_mode: xspx = self.spx_4(features_left[0]) xspx = self.spx_2(xspx, stem_2x) spx_pred = self.spx(xspx) spx_pred = F.softmax(spx_pred, 1) cnet_list = self.cnet(image1, num_layers=self.args.n_gru_layers) net_list = [torch.tanh(x[0]) for x in cnet_list] inp_list = [torch.relu(x[1]) for x in cnet_list] inp_list = [list(conv(i).split(split_size=conv.out_channels//3, dim=1)) for i,conv in zip(inp_list, self.context_zqr_convs)] geo_block = Combined_Geo_Encoding_Volume geo_fn = geo_block(match_left.float(), match_right.float(), geo_encoding_volume.float(), radius=self.args.corr_radius, num_levels=self.args.corr_levels) b, c, h, w = match_left.shape coords = torch.arange(w).float().to(match_left.device).reshape(1,1,w,1).repeat(b, h, 1, 1) disp = init_disp disp_preds = [] # GRUs iterations to update disparity for itr in range(iters): disp = disp.detach() geo_feat = geo_fn(disp, coords) with autocast(enabled=self.args.mixed_precision): if self.args.n_gru_layers == 3 and self.args.slow_fast_gru: # Update low-res ConvGRU net_list = self.update_block(net_list, inp_list, iter16=True, iter08=False, iter04=False, update=False) if self.args.n_gru_layers >= 2 and self.args.slow_fast_gru:# Update low-res ConvGRU and mid-res ConvGRU net_list = self.update_block(net_list, inp_list, iter16=self.args.n_gru_layers==3, iter08=True, iter04=False, update=False) net_list, mask_feat_4, delta_disp = self.update_block(net_list, inp_list, geo_feat, disp, iter16=self.args.n_gru_layers==3, iter08=self.args.n_gru_layers>=2) disp = disp + delta_disp if test_mode and itr < iters-1: continue # upsample predictions disp_up = self.upsample_disp(disp, mask_feat_4, stem_2x) disp_preds.append(disp_up) if test_mode: return disp_up init_disp = context_upsample(init_disp*4., spx_pred.float()).unsqueeze(1) return init_disp, disp_preds
10,349
45.621622
173
py
IGEV
IGEV-main/IGEV-Stereo/core/utils/utils.py
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel', divis_by=8): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // divis_by) + 1) * divis_by - self.ht) % divis_by pad_wd = (((self.wd // divis_by) + 1) * divis_by - self.wd) % divis_by if mode == 'sintel': self._pad = [pad_wd//2, pad_wd - pad_wd//2, pad_ht//2, pad_ht - pad_ht//2] else: self._pad = [pad_wd//2, pad_wd - pad_wd//2, 0, pad_ht] def pad(self, *inputs): assert all((x.ndim == 4) for x in inputs) return [F.pad(x, self._pad, mode='replicate') for x in inputs] def unpad(self, x): assert x.ndim == 4 ht, wd = x.shape[-2:] c = [self._pad[2], ht-self._pad[3], self._pad[0], wd-self._pad[1]] return x[..., c[0]:c[1], c[2]:c[3]] def forward_interpolate(flow): flow = flow.detach().cpu().numpy() dx, dy = flow[0], flow[1] ht, wd = dx.shape x0, y0 = np.meshgrid(np.arange(wd), np.arange(ht)) x1 = x0 + dx y1 = y0 + dy x1 = x1.reshape(-1) y1 = y1.reshape(-1) dx = dx.reshape(-1) dy = dy.reshape(-1) valid = (x1 > 0) & (x1 < wd) & (y1 > 0) & (y1 < ht) x1 = x1[valid] y1 = y1[valid] dx = dx[valid] dy = dy[valid] flow_x = interpolate.griddata( (x1, y1), dx, (x0, y0), method='nearest', fill_value=0) flow_y = interpolate.griddata( (x1, y1), dy, (x0, y0), method='nearest', fill_value=0) flow = np.stack([flow_x, flow_y], axis=0) return torch.from_numpy(flow).float() def bilinear_sampler(img, coords, mode='bilinear', mask=False): """ Wrapper for grid_sample, uses pixel coordinates """ H, W = img.shape[-2:] # print("$$$55555", img.shape, coords.shape) xgrid, ygrid = coords.split([1,1], dim=-1) xgrid = 2*xgrid/(W-1) - 1 # print("######88888", xgrid) assert torch.unique(ygrid).numel() == 1 and H == 1 # This is a stereo problem grid = torch.cat([xgrid, ygrid], dim=-1) # print("###37777", grid.shape) img = F.grid_sample(img, grid, align_corners=True) if mask: mask = (xgrid > -1) & (ygrid > -1) & (xgrid < 1) & (ygrid < 1) return img, mask.float() return img def coords_grid(batch, ht, wd): coords = torch.meshgrid(torch.arange(ht), torch.arange(wd)) coords = torch.stack(coords[::-1], dim=0).float() return coords[None].repeat(batch, 1, 1, 1) def upflow8(flow, mode='bilinear'): new_size = (8 * flow.shape[2], 8 * flow.shape[3]) return 8 * F.interpolate(flow, size=new_size, mode=mode, align_corners=True) def gauss_blur(input, N=5, std=1): B, D, H, W = input.shape x, y = torch.meshgrid(torch.arange(N).float() - N//2, torch.arange(N).float() - N//2) unnormalized_gaussian = torch.exp(-(x.pow(2) + y.pow(2)) / (2 * std ** 2)) weights = unnormalized_gaussian / unnormalized_gaussian.sum().clamp(min=1e-4) weights = weights.view(1,1,N,N).to(input) output = F.conv2d(input.reshape(B*D,1,H,W), weights, padding=N//2) return output.view(B, D, H, W)
3,222
32.226804
89
py
IGEV
IGEV-main/IGEV-Stereo/core/utils/augmentor.py
import numpy as np import random import warnings import os import time from glob import glob from skimage import color, io from PIL import Image import cv2 cv2.setNumThreads(0) cv2.ocl.setUseOpenCL(False) import torch from torchvision.transforms import ColorJitter, functional, Compose import torch.nn.functional as F def get_middlebury_images(): root = "datasets/Middlebury/MiddEval3" with open(os.path.join(root, "official_train.txt"), 'r') as f: lines = f.read().splitlines() return sorted([os.path.join(root, 'trainingQ', f'{name}/im0.png') for name in lines]) def get_eth3d_images(): return sorted(glob('datasets/ETH3D/two_view_training/*/im0.png')) def get_kitti_images(): return sorted(glob('datasets/KITTI/training/image_2/*_10.png')) def transfer_color(image, style_mean, style_stddev): reference_image_lab = color.rgb2lab(image) reference_stddev = np.std(reference_image_lab, axis=(0,1), keepdims=True)# + 1 reference_mean = np.mean(reference_image_lab, axis=(0,1), keepdims=True) reference_image_lab = reference_image_lab - reference_mean lamb = style_stddev/reference_stddev style_image_lab = lamb * reference_image_lab output_image_lab = style_image_lab + style_mean l, a, b = np.split(output_image_lab, 3, axis=2) l = l.clip(0, 100) output_image_lab = np.concatenate((l,a,b), axis=2) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=UserWarning) output_image_rgb = color.lab2rgb(output_image_lab) * 255 return output_image_rgb class AdjustGamma(object): def __init__(self, gamma_min, gamma_max, gain_min=1.0, gain_max=1.0): self.gamma_min, self.gamma_max, self.gain_min, self.gain_max = gamma_min, gamma_max, gain_min, gain_max def __call__(self, sample): gain = random.uniform(self.gain_min, self.gain_max) gamma = random.uniform(self.gamma_min, self.gamma_max) return functional.adjust_gamma(sample, gamma, gain) def __repr__(self): return f"Adjust Gamma {self.gamma_min}, ({self.gamma_max}) and Gain ({self.gain_min}, {self.gain_max})" class FlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=True, yjitter=False, saturation_range=[0.6,1.4], gamma=[1,1,1,1]): # spatial augmentation params self.crop_size = crop_size self.min_scale = min_scale self.max_scale = max_scale self.spatial_aug_prob = 1.0 self.stretch_prob = 0.8 self.max_stretch = 0.2 # flip augmentation params self.yjitter = yjitter self.do_flip = do_flip self.h_flip_prob = 0.5 self.v_flip_prob = 0.1 # photometric augmentation params self.photo_aug = Compose([ColorJitter(brightness=0.4, contrast=0.4, saturation=saturation_range, hue=0.5/3.14), AdjustGamma(*gamma)]) self.asymmetric_color_aug_prob = 0.2 self.eraser_aug_prob = 0.5 def color_transform(self, img1, img2): """ Photometric augmentation """ # asymmetric if np.random.rand() < self.asymmetric_color_aug_prob: img1 = np.array(self.photo_aug(Image.fromarray(img1)), dtype=np.uint8) img2 = np.array(self.photo_aug(Image.fromarray(img2)), dtype=np.uint8) # symmetric else: image_stack = np.concatenate([img1, img2], axis=0) image_stack = np.array(self.photo_aug(Image.fromarray(image_stack)), dtype=np.uint8) img1, img2 = np.split(image_stack, 2, axis=0) return img1, img2 def eraser_transform(self, img1, img2, bounds=[50, 100]): """ Occlusion augmentation """ ht, wd = img1.shape[:2] if np.random.rand() < self.eraser_aug_prob: mean_color = np.mean(img2.reshape(-1, 3), axis=0) for _ in range(np.random.randint(1, 3)): x0 = np.random.randint(0, wd) y0 = np.random.randint(0, ht) dx = np.random.randint(bounds[0], bounds[1]) dy = np.random.randint(bounds[0], bounds[1]) img2[y0:y0+dy, x0:x0+dx, :] = mean_color return img1, img2 def spatial_transform(self, img1, img2, flow): # randomly sample scale ht, wd = img1.shape[:2] min_scale = np.maximum( (self.crop_size[0] + 8) / float(ht), (self.crop_size[1] + 8) / float(wd)) scale = 2 ** np.random.uniform(self.min_scale, self.max_scale) scale_x = scale scale_y = scale if np.random.rand() < self.stretch_prob: scale_x *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch) scale_y *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch) scale_x = np.clip(scale_x, min_scale, None) scale_y = np.clip(scale_y, min_scale, None) if np.random.rand() < self.spatial_aug_prob: # rescale the images img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) flow = cv2.resize(flow, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) flow = flow * [scale_x, scale_y] if self.do_flip: if np.random.rand() < self.h_flip_prob and self.do_flip == 'hf': # h-flip img1 = img1[:, ::-1] img2 = img2[:, ::-1] flow = flow[:, ::-1] * [-1.0, 1.0] if np.random.rand() < self.h_flip_prob and self.do_flip == 'h': # h-flip for stereo tmp = img1[:, ::-1] img1 = img2[:, ::-1] img2 = tmp if np.random.rand() < self.v_flip_prob and self.do_flip == 'v': # v-flip img1 = img1[::-1, :] img2 = img2[::-1, :] flow = flow[::-1, :] * [1.0, -1.0] if self.yjitter: y0 = np.random.randint(2, img1.shape[0] - self.crop_size[0] - 2) x0 = np.random.randint(2, img1.shape[1] - self.crop_size[1] - 2) y1 = y0 + np.random.randint(-2, 2 + 1) img1 = img1[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] img2 = img2[y1:y1+self.crop_size[0], x0:x0+self.crop_size[1]] flow = flow[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] else: y0 = np.random.randint(0, img1.shape[0] - self.crop_size[0]) x0 = np.random.randint(0, img1.shape[1] - self.crop_size[1]) img1 = img1[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] img2 = img2[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] flow = flow[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] return img1, img2, flow def __call__(self, img1, img2, flow): img1, img2 = self.color_transform(img1, img2) img1, img2 = self.eraser_transform(img1, img2) img1, img2, flow = self.spatial_transform(img1, img2, flow) img1 = np.ascontiguousarray(img1) img2 = np.ascontiguousarray(img2) flow = np.ascontiguousarray(flow) return img1, img2, flow class SparseFlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=False, yjitter=False, saturation_range=[0.7,1.3], gamma=[1,1,1,1]): # spatial augmentation params self.crop_size = crop_size self.min_scale = min_scale self.max_scale = max_scale self.spatial_aug_prob = 0.8 self.stretch_prob = 0.8 self.max_stretch = 0.2 # flip augmentation params self.do_flip = do_flip self.h_flip_prob = 0.5 self.v_flip_prob = 0.1 # photometric augmentation params self.photo_aug = Compose([ColorJitter(brightness=0.3, contrast=0.3, saturation=saturation_range, hue=0.3/3.14), AdjustGamma(*gamma)]) self.asymmetric_color_aug_prob = 0.2 self.eraser_aug_prob = 0.5 def color_transform(self, img1, img2): image_stack = np.concatenate([img1, img2], axis=0) image_stack = np.array(self.photo_aug(Image.fromarray(image_stack)), dtype=np.uint8) img1, img2 = np.split(image_stack, 2, axis=0) return img1, img2 def eraser_transform(self, img1, img2): ht, wd = img1.shape[:2] if np.random.rand() < self.eraser_aug_prob: mean_color = np.mean(img2.reshape(-1, 3), axis=0) for _ in range(np.random.randint(1, 3)): x0 = np.random.randint(0, wd) y0 = np.random.randint(0, ht) dx = np.random.randint(50, 100) dy = np.random.randint(50, 100) img2[y0:y0+dy, x0:x0+dx, :] = mean_color return img1, img2 def resize_sparse_flow_map(self, flow, valid, fx=1.0, fy=1.0): ht, wd = flow.shape[:2] coords = np.meshgrid(np.arange(wd), np.arange(ht)) coords = np.stack(coords, axis=-1) coords = coords.reshape(-1, 2).astype(np.float32) flow = flow.reshape(-1, 2).astype(np.float32) valid = valid.reshape(-1).astype(np.float32) coords0 = coords[valid>=1] flow0 = flow[valid>=1] ht1 = int(round(ht * fy)) wd1 = int(round(wd * fx)) coords1 = coords0 * [fx, fy] flow1 = flow0 * [fx, fy] xx = np.round(coords1[:,0]).astype(np.int32) yy = np.round(coords1[:,1]).astype(np.int32) v = (xx > 0) & (xx < wd1) & (yy > 0) & (yy < ht1) xx = xx[v] yy = yy[v] flow1 = flow1[v] flow_img = np.zeros([ht1, wd1, 2], dtype=np.float32) valid_img = np.zeros([ht1, wd1], dtype=np.int32) flow_img[yy, xx] = flow1 valid_img[yy, xx] = 1 return flow_img, valid_img def spatial_transform(self, img1, img2, flow, valid): # randomly sample scale ht, wd = img1.shape[:2] min_scale = np.maximum( (self.crop_size[0] + 1) / float(ht), (self.crop_size[1] + 1) / float(wd)) scale = 2 ** np.random.uniform(self.min_scale, self.max_scale) scale_x = np.clip(scale, min_scale, None) scale_y = np.clip(scale, min_scale, None) if np.random.rand() < self.spatial_aug_prob: # rescale the images img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) flow, valid = self.resize_sparse_flow_map(flow, valid, fx=scale_x, fy=scale_y) if self.do_flip: if np.random.rand() < self.h_flip_prob and self.do_flip == 'hf': # h-flip img1 = img1[:, ::-1] img2 = img2[:, ::-1] flow = flow[:, ::-1] * [-1.0, 1.0] if np.random.rand() < self.h_flip_prob and self.do_flip == 'h': # h-flip for stereo tmp = img1[:, ::-1] img1 = img2[:, ::-1] img2 = tmp if np.random.rand() < self.v_flip_prob and self.do_flip == 'v': # v-flip img1 = img1[::-1, :] img2 = img2[::-1, :] flow = flow[::-1, :] * [1.0, -1.0] margin_y = 20 margin_x = 50 y0 = np.random.randint(0, img1.shape[0] - self.crop_size[0] + margin_y) x0 = np.random.randint(-margin_x, img1.shape[1] - self.crop_size[1] + margin_x) y0 = np.clip(y0, 0, img1.shape[0] - self.crop_size[0]) x0 = np.clip(x0, 0, img1.shape[1] - self.crop_size[1]) img1 = img1[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] img2 = img2[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] flow = flow[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] valid = valid[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]] return img1, img2, flow, valid def __call__(self, img1, img2, flow, valid): img1, img2 = self.color_transform(img1, img2) img1, img2 = self.eraser_transform(img1, img2) img1, img2, flow, valid = self.spatial_transform(img1, img2, flow, valid) img1 = np.ascontiguousarray(img1) img2 = np.ascontiguousarray(img2) flow = np.ascontiguousarray(flow) valid = np.ascontiguousarray(valid) return img1, img2, flow, valid
12,411
37.7875
141
py
rl-mapping
rl-mapping-master/main.py
import argparse import os import random from envs import MappingEnvironment, LocalISM, RangeISM from model import CNNActorCritic, MLPActorCritic, ResNetActorCritic, LinearActorCritic from distributions import Multinomial import torch from torch import nn from torch.autograd import Variable import numpy as np parser = argparse.ArgumentParser() # General Stuff parser.add_argument('--experiment', default='run0/', help='folder to put results of experiment in') parser.add_argument('--cuda', action='store_true', help='enables cuda') # Neural Network parser.add_argument('--network', default='mlp', help='network type: mlp | cnn | resnet') # Environment parser.add_argument('--N', type=int, default=25, help='size of grid') parser.add_argument('--map_p', type=float, default=.1, help='probability map location is occupied') parser.add_argument('--prims', action='store_true', help='prims algorithm for filling in map') # Sensor parser.add_argument('--sensor_type', default='local', help='local | range') parser.add_argument('--sensor_span', type=int, default=2, help='span of sensor') parser.add_argument('--sensor_p', type=float, default=.8, help='probability sensor reading is correct') # MDP parser.add_argument('--gamma', type=float, default=.98, help='discount rate') parser.add_argument('--episode_length', type=int, default=200, help='length of mapping environment episodes') # Training parser.add_argument('--N_episodes', type=int, default=1000, help='number of episodes to train for') parser.add_argument('--max_steps', type=int, default=20, help='number of forward steps in A2C') parser.add_argument('--optimizer', default='adam', help='sgd | adam | rmsprop') parser.add_argument('--anneal_step_size', type=int, default=100, help='number of episodes until anneal learning rate') parser.add_argument('--anneal_gamma', type=float, default=.5, help='annealing multiplicative factor') parser.add_argument('--lr', type=float, default=1e-3, help='learning rate for ADAM optimizer') parser.add_argument('--lambda_entropy', type=float, default=.01, help='entropy term coefficient') parser.add_argument('--max_grad_norm', type=float, default=50., help='max gradient norm of actor_critic') parser.add_argument('--seed', type=int, default=random.randint(0, 10000), help='random seed') opt = parser.parse_args() opt.cuda = opt.cuda and torch.cuda.is_available() print(opt) # set random seeds random.seed(opt.seed) np.random.seed(opt.seed) torch.manual_seed(opt.seed) # make experiment path os.makedirs(opt.experiment, exist_ok=True) with open(os.path.join(opt.experiment, 'config.txt'), 'w') as f: f.write(str(opt)) # Initialize sensor if opt.sensor_type == 'local': ism_proto = lambda x: LocalISM(x, span=opt.sensor_span, p_correct=opt.sensor_p) elif opt.sensor_type == 'range': ism_proto = lambda x: RangeISM(x) else: raise Exception('sensor type not supported.') # Initialize environment env = MappingEnvironment(ism_proto, N=opt.N, p=opt.map_p, episode_length=opt.episode_length, prims=opt.prims) # Initialize actor critic neural network if opt.network == 'cnn': actor_critic = CNNActorCritic(H_in = env.observation_size(), nc = env.num_channels(), na = env.num_actions()) elif opt.network == 'mlp': actor_critic = MLPActorCritic(H_in = env.observation_size(), nc = env.num_channels(), na = env.num_actions()) elif opt.network == 'resnet': actor_critic = ResNetActorCritic(H_in = env.observation_size(), nc = env.num_channels(), na = env.num_actions()) else: raise Exception('network type not supported') if opt.cuda: actor_critic = actor_critic.cuda() # Initialize optimizer and learning rate scheduler if opt.optimizer == 'rmsprop': actor_critic_optimizer = torch.optim.RMSprop(actor_critic.parameters(), lr=opt.lr) elif opt.optimizer == 'adam': actor_critic_optimizer = torch.optim.Adam(actor_critic.parameters(), lr=opt.lr) elif opt.optimizer == 'sgd': actor_critic_optimizer = torch.optim.SGD(actor_critic.parameters(), lr=opt.lr) else: raise Exception('optimizer not supported. Try rmsprop/adam/sgd') # Initialize necessary variables obs = env.reset() done = False t = 0 episodes = 0 ep_rewards = [0] print ("Main training loop") while episodes < opt.N_episodes: t_start = t rewards, observations, actions = [], [], [] # on-policy training loop for max_steps timesteps while 1: # Perform a_t according to actor_critic obs_npy = obs.transpose(2, 0, 1)[None, :] obst = torch.Tensor(obs_npy) if opt.cuda: obst = obst.cuda() obsv = Variable(obst) actor_critic.eval() pa, V = actor_critic(obsv) pa = Multinomial(pa) a = pa.sample().data[0] # Receive reward r_t and new state s_t+1 obs, reward, done, info = env.step(a) t += 1 observations.append(obs_npy) actions.append(a) rewards.append(reward) ep_rewards[-1] += reward if done: # terminal s_t R = 0 episodes += 1 obs = env.reset() print ("Finished Episode %d:" % episodes, ep_rewards[-1], np.mean(ep_rewards[-50:])) ep_rewards.append(0.) if episodes > 0 and episodes % opt.anneal_step_size == 0: print ("Annealing learning rate: %.7f to %.7f" % (opt.lr, opt.lr*opt.anneal_gamma)) opt.lr *= opt.anneal_gamma if opt.optimizer == 'rmsprop': actor_critic_optimizer = torch.optim.RMSprop(actor_critic.parameters(), lr=opt.lr) elif opt.optimizer == 'adam': actor_critic_optimizer = torch.optim.Adam(actor_critic.parameters(), lr=opt.lr) elif opt.optimizer == 'sgd': actor_critic_optimizer = torch.optim.SGD(actor_critic.parameters(), lr=opt.lr) break if t - t_start == opt.max_steps: # reached num. forward steps R = V.data[0] break # accumulate rewards for advantage calculation i = len(rewards)-1 for r in rewards[::-1]: R = rewards[i] + opt.gamma*R rewards[i] = R i -= 1 actions_t = torch.Tensor(actions).type(torch.LongTensor) if opt.cuda: actions_t = actions_t.cuda() actions_v = Variable(actions_t) rewards_t = torch.Tensor(rewards) if opt.cuda: rewards_t = rewards_t.cuda() rewards_v = Variable(rewards_t) observations_npy = np.concatenate(observations) observations_t = torch.Tensor(observations_npy) if opt.cuda: observations_t = observations_t.cuda() observations_v = Variable(observations_t) actor_critic.train() pa, V = actor_critic(observations_v) pa_multinomial = Multinomial(pa) actor_critic.zero_grad() # gradient step policy_loss = (-pa_multinomial.log_prob(actions_v) * (rewards_v - V.detach())).mean() value_loss = (rewards_v - V).pow(2).mean() entropy = -torch.sum(pa * torch.log(pa), dim=1).mean() (policy_loss + value_loss - opt.lambda_entropy * entropy).backward() torch.nn.utils.clip_grad_norm(actor_critic.parameters(), opt.max_grad_norm) actor_critic_optimizer.step() np.save(os.path.join(opt.experiment, 'results'), ep_rewards) if episodes % 1000 == 0: torch.save(actor_critic.state_dict(), os.path.join(opt.experiment, 'actor_critic_episode%d.torch' % episodes)) torch.save(actor_critic.state_dict(), os.path.join(opt.experiment, 'actor_critic_episode%d.torch' % episodes)) np.save(os.path.join(opt.experiment, 'results'), ep_rewards) rewards = [] for k in range(1000): obs = env.reset() done = False R = 0 while not done: # Perform a_t according to actor_critic obs_npy = obs.transpose(2, 0, 1)[None, :] obst = torch.Tensor(obs_npy) if opt.cuda: obst = obst.cuda() obsv = Variable(obst) actor_critic.eval() pa, V = actor_critic(obsv) pa = Multinomial(pa) a = pa.sample().data[0] # Receive reward r_t and new state s_t+1 obs, reward, done, info = env.step(a) R += reward print (R) rewards.append(R) np.save(os.path.join(opt.experiment, 'rewards_test'), rewards)
8,245
35.486726
118
py
rl-mapping
rl-mapping-master/distributions.py
r""" The ``distributions`` package contains parameterizable probability distributions and sampling functions. Policy gradient methods can be implemented using the :meth:`~torch.distributions.Distribution.log_prob` method, when the probability density function is differentiable with respect to its parameters. A basic method is the REINFORCE rule: .. math:: \Delta\theta = \alpha r \frac{\partial\log p(a|\pi^\theta(s))}{\partial\theta} where :math:`\theta` are the parameters, :math:`\alpha` is the learning rate, :math:`r` is the reward and :math:`p(a|\pi^\theta(s))` is the probability of taking action :math:`a` in state :math:`s` given policy :math:`\pi^\theta`. In practice we would sample an action from the output of a network, apply this action in an environment, and then use ``log_prob`` to construct an equivalent loss function. Note that we use a negative because optimisers use gradient descent, whilst the rule above assumes gradient ascent. With a multinomial policy, the code for implementing REINFORCE would be as follows:: probs = policy_network(state) m = Multinomial(probs) action = m.sample() next_state, reward = env.step(action) loss = -m.log_prob(action) * reward loss.backward() """ import math from numbers import Number import torch __all__ = ['Distribution', 'Bernoulli', 'Multinomial', 'Normal'] class Distribution(object): r""" Distribution is the abstract base class for probability distributions. """ def sample(self): """ Generates a single sample or single batch of samples if the distribution parameters are batched. """ raise NotImplementedError def sample_n(self, n): """ Generates n samples or n batches of samples if the distribution parameters are batched. """ raise NotImplementedError def log_prob(self, value): """ Returns the log of the probability density/mass function evaluated at `value`. Args: value (Tensor or Variable): """ raise NotImplementedError class Bernoulli(Distribution): r""" Creates a Bernoulli distribution parameterized by `probs`. Samples are binary (0 or 1). They take the value `1` with probability `p` and `0` with probability `1 - p`. Example:: >>> m = Bernoulli(torch.Tensor([0.3])) >>> m.sample() # 30% chance 1; 70% chance 0 0.0 [torch.FloatTensor of size 1] Args: probs (Tensor or Variable): the probabilty of sampling `1` """ def __init__(self, probs): self.probs = probs def sample(self): return torch.bernoulli(self.probs) def sample_n(self, n): return torch.bernoulli(self.probs.expand(n, *self.probs.size())) def log_prob(self, value): # compute the log probabilities for 0 and 1 log_pmf = (torch.stack([1 - self.probs, self.probs])).log() # evaluate using the values return log_pmf.gather(0, value.unsqueeze(0).long()).squeeze(0) class Multinomial(Distribution): r""" Creates a multinomial distribution parameterized by `probs`. Samples are integers from `0 ... K-1` where `K` is probs.size(-1). If `probs` is 1D with length-`K`, each element is the relative probability of sampling the class at that index. If `probs` is 2D, it is treated as a batch of probability vectors. See also: :func:`torch.multinomial` Example:: >>> m = Multinomial(torch.Tensor([ 0.25, 0.25, 0.25, 0.25 ])) >>> m.sample() # equal probability of 0, 1, 2, 3 3 [torch.LongTensor of size 1] Args: probs (Tensor or Variable): event probabilities """ def __init__(self, probs): if probs.dim() != 1 and probs.dim() != 2: # TODO: treat higher dimensions as part of the batch raise ValueError("probs must be 1D or 2D") self.probs = probs def sample(self): return torch.multinomial(self.probs, 1, True).squeeze(-1) def sample_n(self, n): if n == 1: return self.sample().expand(1, 1) else: return torch.multinomial(self.probs, n, True).t() def log_prob(self, value): p = self.probs / self.probs.sum(-1, keepdim=True) if value.dim() == 1 and self.probs.dim() == 1: # special handling until we have 0-dim tensor support return p.gather(-1, value).log() return p.gather(-1, value.unsqueeze(-1)).squeeze(-1).log() class Normal(Distribution): r""" Creates a normal (also called Gaussian) distribution parameterized by `mean` and `std`. Example:: >>> m = Normal(torch.Tensor([0.0]), torch.Tensor([1.0])) >>> m.sample() # normally distributed with mean=0 and stddev=1 0.1046 [torch.FloatTensor of size 1] Args: mean (float or Tensor or Variable): mean of the distribution std (float or Tensor or Variable): standard deviation of the distribution """ def __init__(self, mean, std): self.mean = mean self.std = std def sample(self): return torch.normal(self.mean, self.std) def sample_n(self, n): # cleanly expand float or Tensor or Variable parameters def expand(v): if isinstance(v, Number): return torch.Tensor([v]).expand(n, 1) else: return v.expand(n, *v.size()) return torch.normal(expand(self.mean), expand(self.std)) def log_prob(self, value): # compute the variance var = (self.std ** 2) log_std = math.log(self.std) if isinstance(self.std, Number) else self.std.log() return -((value - self.mean) ** 2) / (2 * var) - log_std - math.log(math.sqrt(2 * math.pi))
5,853
29.175258
99
py
rl-mapping
rl-mapping-master/model.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from math import floor import IPython as ipy class LinearActorCritic(nn.Module): def __init__(self, H_in=100, nc=2, na=4): super(LinearActorCritic, self).__init__() self.H_in = H_in self.nc = nc self.na = na self.policy_linear = nn.Linear(self.nc*self.H_in*self.H_in, 4) self.critic_linear = nn.Linear(self.nc*self.H_in*self.H_in, 1) def forward(self, x): x = x.contiguous().view(-1, self.nc*self.H_in*self.H_in) pa = F.softmax(self.policy_linear(x)) V = self.critic_linear(x) return pa, V.view(-1) class MLPActorCritic(nn.Module): def __init__(self, H_in=100, nc=2, na=4): super(MLPActorCritic, self).__init__() self.H_in = H_in self.nc = nc self.na = na self.linear = nn.Linear(self.nc*self.H_in*self.H_in, 256) self.policy_linear = nn.Linear(256, self.na) self.critic_linear = nn.Linear(256, 1) def forward(self, x): x = x.contiguous().view(-1, self.nc*self.H_in*self.H_in) x = self.linear(x) x = F.relu(x) pa = F.softmax(self.policy_linear(x)) V = self.critic_linear(x) return pa, V.view(-1) class CNNActorCritic(nn.Module): def __init__(self, H_in=100, nc=2, na=4): super(CNNActorCritic, self).__init__() self.H_in = H_in self.nc = nc self.na = na self.conv1 = nn.Conv2d(self.nc, 32, 8, stride=2) self.H_1 = floor((self.H_in - (8-1)-1)/2+1) self.conv2 = nn.Conv2d(32, 64, 4, stride=2) self.H_2 = floor((self.H_1 - (4-1)-1)/2+1) self.conv3 = nn.Conv2d(64, 32, 3, stride=1) self.H_3 = floor((self.H_2 - (3-1)-1)/1+1) assert self.H_3 > 0 print (self.H_in, "x", self.H_in, "-> %d" % (self.H_3*self.H_3*32)) self.linear1 = nn.Linear(32 * self.H_3 * self.H_3 + 5*5, 64) self.policy_linear = nn.Linear(64, self.na) self.softmax = nn.Softmax() self.critic_linear = nn.Linear(64, 1) def forward(self, x): mid = self.H_in // 2 immediate = x[:,0,mid-2:mid+3,mid-2:mid+3].contiguous() immediate = immediate.view(immediate.size()[0], 5*5) x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = self.conv3(x) x = F.relu(x) x = x.view(-1, 32 * self.H_3 * self.H_3) x = self.linear1(torch.cat([x, immediate], dim=1)) x = F.relu(x) pa = self.softmax(self.policy_linear(x)) v = self.critic_linear(x) return pa, v.view(-1) class ResidualBlock(nn.Module): def __init__(self, nc): super(ResidualBlock, self).__init__() self.nc = nc self.conv1 = nn.Conv2d(self.nc, 32, kernel_size=3, stride=1, padding=1) self.conv2 = nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1) def forward(self, x): out = self.conv1(x) out = F.relu(out) out = self.conv2(out) out += x out = F.relu(out) return out class ResNetActorCritic(nn.Module): def __init__(self, H_in=100, nc=2, na=4): super(ResNetActorCritic, self).__init__() self.H_in = H_in self.nc = nc self.na = na self.conv1 = nn.Conv2d(self.nc, 32, kernel_size=3, stride=1, padding=1) self.tower = nn.Sequential(*[ResidualBlock(32) for _ in range(6)]) self.linear = nn.Linear(32*self.H_in*self.H_in, 256) self.policy_linear = nn.Linear(256, self.na) self.critic_linear = nn.Linear(256, 1) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.tower(x) x = x.view(-1, 32*self.H_in*self.H_in) x = self.linear(x) x = F.relu(x) pa = F.softmax(self.policy_linear(x)) V = self.critic_linear(x) return pa, V.view(-1) if __name__ == '__main__': obs = torch.randn(32, 2, 70, 70) obsv = Variable(obs) pi = CNNActorCritic(H_in = 70, nc = 2, na = 4) pa, v = pi(obsv)
4,148
28.635714
79
py
vexcl
vexcl-master/docs/conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # VexCL documentation build configuration file, created by # sphinx-quickstart on Fri Mar 11 13:53:31 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex import subprocess import pip on_rtd = os.environ.get('READTHEDOCS', None) == 'True' sys.path.append('.') from git_version import git_version if on_rtd: subprocess.call('doxygen', shell=True) import sphinx_bootstrap_theme # 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. #sys.path.insert(0, os.path.abspath('.')) # -- 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 = ['breathe', 'sphinx.ext.mathjax', 'sphinx.ext.autodoc', 'matplotlib.sphinxext.plot_directive'] breathe_projects = {'VEXCL' : 'xml'} breathe_default_project = 'VEXCL' # 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' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'VexCL' copyright = '2012-2018, Denis Demidov <dennis.demidov@gmail.com>' author = 'Denis Demidov' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = git_version() # The full version, including alpha/beta/rc tags. release = version # 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 # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- 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_path = sphinx_bootstrap_theme.get_html_theme_path() html_theme = 'bootstrap' html_theme_options = { 'bootswatch_theme': 'yeti', 'navbar_links' : [ ("GitHub", "https://github.com/ddemidov/vexcl", True) ] } # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # 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'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'VexCLdoc' # -- 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, 'VexCL.tex', 'VexCL Documentation', 'Denis Demidov', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- 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, 'vexcl', 'VexCL Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- 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, 'VexCL', 'VexCL Documentation', author, 'VexCL', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
9,667
30.802632
80
py
MGMN
MGMN-main/src/ged_train.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # ************************************ # @Time : 2019/3/3 22:34 # @Author : Xiang Ling # @Lab : nesa.zju.edu.cn # @File : ged_train.py # ************************************ import numpy as np import os import torch import torch.nn.functional as functional from datetime import datetime from data import GEDDataset from ged_config import ged_args from model.DenseGraphMatching import MultiLevelGraphMatchNetwork from simgnn_utils import computing_precision_ks from utils import create_dir_if_not_exists, write_log_file from utils import metrics_kendall_tau, metrics_spearmanr_rho, metrics_mean_square_error class GEDTrainer(object): def __init__(self, data_dir, device, best_model_path, args, log_path): super(GEDTrainer, self).__init__() # training parameters self.max_iterations = args.iterations self.iter_val_start = args.iter_val_start self.iter_val_every = args.iter_val_every self.batch_size = args.batch_size self.lr = args.lr self.device = device self.validation_data = None self.best_model_path = best_model_path self.log_file = log_path self.dataset = GEDDataset(ged_main_dir=data_dir, args=args) self.flag_inclusive = args.inclusive write_log_file(self.log_file, str(args)) self.model = MultiLevelGraphMatchNetwork(node_init_dims=self.dataset.input_dim, arguments=args, device=self.device).to(self.device) write_log_file(self.log_file, str(self.model)) self.optimizer = torch.optim.Adam(self.model.parameters(), lr=args.lr) print("\n\n", self.model.state_dict().keys()) def _need_val(self, iteration): return iteration >= self.iter_val_start and iteration % self.iter_val_every == 0 def batch_pairs_predication(self, batch_feature_1, batch_adjacent_1, batch_mask_1, batch_feature_2, batch_adjacent_2, batch_mask_2): feature_1 = np.array(batch_feature_1) feature_2 = np.array(batch_feature_2) adj_1 = np.array(batch_adjacent_1) adj_2 = np.array(batch_adjacent_2) predictions = self.model(batch_x_p=feature_1, batch_x_h=feature_2, batch_adj_p=adj_1, batch_adj_h=adj_2) return predictions def training_batch_predication(self, batch_feature_1, batch_adjacent_1, batch_mask_1, batch_feature_2, batch_adjacent_2, batch_mask_2, ged_pairs): self.model.train() self.optimizer.zero_grad() predictions = self.batch_pairs_predication(batch_feature_1, batch_adjacent_1, batch_mask_1, batch_feature_2, batch_adjacent_2, batch_mask_2) trues = torch.from_numpy(np.array(ged_pairs, dtype=np.float32)).to(self.device) loss = functional.mse_loss(predictions, trues) loss.backward() self.optimizer.step() return loss.item(), torch.stack((trues, predictions), 1) def val_batch_predication(self, batch_feature_1, batch_adjacent_1, batch_mask_1, batch_feature_2, batch_adjacent_2, batch_mask_2, ged_pairs): st_time = datetime.now() self.model.eval() nr_examples = batch_adjacent_1.shape[0] # Number of graphs assert batch_feature_1.shape[0] == batch_adjacent_1.shape[0] and batch_feature_2.shape[0] == batch_adjacent_2.shape[0] st = 0 batch_size = self.batch_size predictions = [] with torch.no_grad(): while st < nr_examples: if st + batch_size >= nr_examples: ed = nr_examples else: ed = st + batch_size feature_1 = batch_feature_1[st:ed] feature_2 = batch_feature_2[st:ed] adjacent_1 = batch_adjacent_1[st:ed] adjacent_2 = batch_adjacent_2[st:ed] mask_1 = batch_mask_1[st:ed] mask_2 = batch_mask_2[st:ed] batch_pred = self.batch_pairs_predication(feature_1, adjacent_1, mask_1, feature_2, adjacent_2, mask_2) predictions.append(batch_pred) st = ed predictions = torch.cat(predictions) trues = torch.from_numpy(np.array(ged_pairs, dtype=np.float32)).to(self.device) loss = torch.nn.functional.mse_loss(predictions, trues) return loss.data.item(), np.stack((trues.cpu().detach().numpy(), predictions.cpu().detach().numpy()), 1), datetime.now() - st_time def testing_prediction(self): results = np.zeros((len(self.dataset.testing_graphs), len(self.dataset.train_val_graphs))) write_log_file(self.log_file, 'result shape is {} '.format(results.shape)) for row in range(len(self.dataset.testing_graphs)): batch_rows_feature, batch_rows_adjacent, batch_rows_mask, batch_cols_feature, batch_cols_adjacent, batch_cols_mask = self.dataset.extract_test_matrices(row) st = 0 pred = [] while st < len(self.dataset.train_val_graphs): if st + self.batch_size < len(self.dataset.train_val_graphs): ed = st + self.batch_size else: ed = len(self.dataset.train_val_graphs) batch_rows_feature_small = batch_rows_feature[st:ed] batch_rows_adjacent_small = batch_rows_adjacent[st:ed] batch_rows_mask_small = batch_rows_mask[st:ed] batch_cols_feature_small = batch_cols_feature[st:ed] batch_cols_adjacent_small = batch_cols_adjacent[st:ed] batch_cols_mask_small = batch_cols_mask[st:ed] with torch.no_grad(): cur_pred = self.batch_pairs_predication(batch_rows_feature_small, batch_rows_adjacent_small, batch_rows_mask_small, batch_cols_feature_small, batch_cols_adjacent_small, batch_cols_mask_small) pred.append(cur_pred) st = ed pred = torch.cat(pred) results[row] = pred.detach().cpu().numpy() return results def fit(self): self.model.train() time = datetime.now() best_val_loss = None for iteration in range(self.max_iterations): batch_feature_1, batch_adj_1, batch_mask_1, batch_feature_2, batch_adj_2, batch_mask_2, batch_ged = self.dataset.get_training_batch() train_loss, train_true_pred = self.training_batch_predication(batch_feature_1, batch_adj_1, batch_mask_1, batch_feature_2, batch_adj_2, batch_mask_2, batch_ged) # print in training steps if iteration % int(self.max_iterations / 20) == 0: time_spent = datetime.now() - time time = datetime.now() write_log_file(self.log_file, "Iteration = {}\tbatch loss={} (e-3) @ {}".format(iteration, train_loss * 1000, time_spent)) # validation if self._need_val(iteration=iteration): self.model.eval() # only load once at first if self.validation_data is None: self.validation_data = self.dataset.get_all_validation() val_feature_1, val_adj_1, val_mask_1, val_feature_2, val_adj_2, val_mask_2, val_ged = self.validation_data else: val_feature_1, val_adj_1, val_mask_1, val_feature_2, val_adj_2, val_mask_2, val_ged = self.validation_data val_loss, val_true_pred, time_spent = self.val_batch_predication(val_feature_1, val_adj_1, val_mask_1, val_feature_2, val_adj_2, val_mask_2, val_ged) write_log_file(self.log_file, "\nvalidation iteration={}, loss={}(e-3), spend time = {} @ {}".format(iteration, val_loss * 1000, time_spent, datetime.now())) if not best_val_loss or val_loss <= best_val_loss: write_log_file(self.log_file, '\tvalidation mse decreased ( {} ---> {} (e-3) ), and save the model ... '.format(best_val_loss, val_loss * 1000)) best_val_loss = val_loss torch.save(self.model.state_dict(), self.best_model_path) write_log_file(self.log_file, '\tbest validation mse = {} (e-3)'.format(best_val_loss * 1000)) def testing(self): # load the last checkpoint with the best model self.model.load_state_dict(torch.load(self.best_model_path)) self.model.eval() self.model.to(self.device) # Double check validation if self.validation_data is None: self.validation_data = self.dataset.get_all_validation() val_feature_1, val_adj_1, val_mask_1, val_feature_2, val_adj_2, val_mask_2, val_ged = self.validation_data else: val_feature_1, val_adj_1, val_mask_1, val_feature_2, val_adj_2, val_mask_2, val_ged = self.validation_data val_loss, val_true_pred, time_spent = self.val_batch_predication(val_feature_1, val_adj_1, val_mask_1, val_feature_2, val_adj_2, val_mask_2, val_ged) write_log_file(self.log_file, "\nDouble check validation, loss = {}(e-3) @ {}".format(val_loss * 1000, datetime.now())) # testing test_predictions = self.testing_prediction() test_mse = metrics_mean_square_error(self.dataset.ground_truth.flatten(), test_predictions.flatten()) test_rho = metrics_spearmanr_rho(self.dataset.ground_truth.flatten(), test_predictions.flatten()) test_tau = metrics_kendall_tau(self.dataset.ground_truth.flatten(), test_predictions.flatten()) ps, inclusive_true_ks, inclusive_pred_ks = computing_precision_ks(trues=self.dataset.ground_truth, predictions=test_predictions, ks=[10, 20], inclusive=self.flag_inclusive, rm=0) test_results = { 'mse': test_mse, 'rho': test_rho, 'tau': test_tau, 'test_p10': ps[0], 'test_p20': ps[1] } write_log_file(self.log_file, 'Test results:') for k, v in test_results.items(): write_log_file(self.log_file, '\t {} = {}'.format(k, v)) if __name__ == '__main__': d = torch.device('cuda' if torch.cuda.is_available() else 'cpu') os.environ['CUDA_VISIBLE_DEVICES'] = ged_args.gpu_index create_dir_if_not_exists(ged_args.log_path) log_root_dir = ged_args.log_path signature = ged_args.dataset + '@' + datetime.now().strftime("%Y-%m-%d@%H:%M:%S") current_run_dir = os.path.join(log_root_dir, signature) create_dir_if_not_exists(current_run_dir) model_save_path = os.path.join(current_run_dir, 'best_model.pt') log_file_path = os.path.join(current_run_dir, 'log.txt') ged_main_dir = ged_args.data_dir trainer = GEDTrainer(data_dir=ged_main_dir, device=d, best_model_path=model_save_path, args=ged_args, log_path=log_file_path) trainer.fit() trainer.testing()
11,120
49.55
186
py
MGMN
MGMN-main/src/cfg_train.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # ************************************ # @Time : 2019/7/3 22:34 # @Author : Xiang Ling # @Lab : nesa.zju.edu.cn # @File : cfg_train.py # ************************************ import numpy as np import os import torch from datetime import datetime from sklearn.metrics import auc, roc_curve from cfg_config import cfg_args from data import CFGDataset from model.DenseGraphMatching import MultiLevelGraphMatchNetwork from utils import create_dir_if_not_exists, write_log_file from utils import generate_epoch_pair class CFGTrainer(object): def __init__(self, node_init_dims, data_dir, device, log_file, best_model_file, args): super(CFGTrainer, self).__init__() # training parameters self.max_epoch = args.epochs self.batch_size = args.batch_size self.lr = args.lr self.device = device self.log_file = log_file self.best_model_path = best_model_file self.model = MultiLevelGraphMatchNetwork(node_init_dims=node_init_dims, arguments=args, device=device).to(device) write_log_file(self.log_file, str(self.model)) self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr) cfg = CFGDataset(data_dir=data_dir, batch_size=self.batch_size) self.graph_train = cfg.graph_train self.classes_train = cfg.classes_train self.epoch_data_valid = cfg.valid_epoch self.epoch_data_test = cfg.test_epoch init_val_auc = self.eval_auc_epoch(model=self.model, eval_epoch_data=self.epoch_data_valid) # evaluate the auc of init model for validation dataset write_log_file(self.log_file, "Initial Validation AUC = {0} @ {1}".format(init_val_auc, datetime.now())) def fit(self): best_val_auc = None for i in range(1, self.max_epoch + 1): # train loss_avg = self.train_one_epoch(model=self.model, optimizer=self.optimizer, graphs=self.graph_train, classes=self.classes_train, batch_size=self.batch_size, device=self.device, load_data=None) write_log_file(self.log_file, "EPOCH {0}/{1}:\tMSE loss = {2} @ {3}".format(i, self.max_epoch, loss_avg, datetime.now())) # validation valid_auc = self.eval_auc_epoch(model=self.model, eval_epoch_data=self.epoch_data_valid) write_log_file(self.log_file, "Validation AUC = {0} @ {1}".format(valid_auc, datetime.now())) # save the best validation if best_val_auc is None or best_val_auc < valid_auc: write_log_file(self.log_file, 'Validation AUC increased ({} ---> {}), and saving the model ... '.format(best_val_auc, valid_auc)) best_val_auc = valid_auc torch.save(self.model.state_dict(), self.best_model_path) write_log_file(self.log_file, 'Best Validation auc = {} '.format(best_val_auc)) return best_val_auc def testing(self): # load the last checkpoint with the best model self.model.load_state_dict(torch.load(self.best_model_path)) self.model.eval() # double check the save checkpoint model for validation double_val_auc = self.eval_auc_epoch(model=self.model, eval_epoch_data=self.epoch_data_valid) # evaluating on the testing dataset final_test_auc = self.eval_auc_epoch(model=self.model, eval_epoch_data=self.epoch_data_test) write_log_file(self.log_file, "\nDouble check for the saved best checkpoint model for validation {} ".format(double_val_auc)) write_log_file(self.log_file, "Finally, testing auc = {} @ {}".format(final_test_auc, datetime.now())) return final_test_auc @staticmethod def train_one_epoch(model, optimizer, graphs, classes, batch_size, device, load_data=None): model.train() if load_data is None: epoch_data = generate_epoch_pair(graphs, classes, batch_size) else: epoch_data = load_data perm = np.random.permutation(len(epoch_data)) # Random shuffle cum_loss = 0.0 num = 0 for index in perm: cur_data = epoch_data[index] x1, x2, adj1, adj2, y = cur_data batch_output = model(batch_x_p=x1, batch_x_h=x2, batch_adj_p=adj1, batch_adj_h=adj2) y = torch.FloatTensor(y).to(device) mse_loss = torch.nn.functional.mse_loss(batch_output, y) optimizer.zero_grad() mse_loss.backward() optimizer.step() cum_loss += mse_loss if num % int(len(perm) / 10) == 0: print('\tTraining: {}/{}: index = {} loss = {}'.format(num, len(epoch_data), index, mse_loss)) num = num + 1 return cum_loss / len(perm) @staticmethod def eval_auc_epoch(model, eval_epoch_data): model.eval() with torch.no_grad(): tot_diff = [] tot_truth = [] for cur_data in eval_epoch_data: x1, x2, adj1, adj2, y = cur_data batch_output = model(batch_x_p=x1, batch_x_h=x2, batch_adj_p=adj1, batch_adj_h=adj2) tot_diff += list(batch_output.data.cpu().numpy()) tot_truth += list(y > 0) diff = np.array(tot_diff) * -1 truth = np.array(tot_truth) fpr, tpr, _ = roc_curve(truth, (1 - diff) / 2) model_auc = auc(fpr, tpr) return model_auc if __name__ == '__main__': d = torch.device('cuda' if torch.cuda.is_available() else 'cpu') os.environ["CUDA_VISIBLE_DEVICES"] = str(cfg_args.gpu_index) main_data_dir = cfg_args.data_dir graph_name = cfg_args.dataset graph_min = cfg_args.graph_size_min graph_max = cfg_args.graph_size_max graph_init_dim = cfg_args.graph_init_dim # <-><-><-> only for log, delete below if open source title = '{}_Min{}_Max{}'.format(graph_name, graph_min, graph_max) main_log_dir = cfg_args.log_path + '{}_Min{}_Max{}_InitDims{}_Task_{}/'.format(graph_name, graph_min, graph_max, graph_init_dim, cfg_args.task) create_log_str = create_dir_if_not_exists(main_log_dir) best_model_dir = main_log_dir + 'BestModels_{}_{}_Repeat_{}/'.format(cfg_args.match_agg, cfg_args.global_agg, cfg_args.repeat_run) create_BestModel_dir = create_dir_if_not_exists(best_model_dir) LOG_FILE = main_log_dir + 'repeat_{}_'.format(cfg_args.repeat_run) + title + '.txt' BestModel_FILE = best_model_dir + title + '.BestModel' CSV_FILE = main_log_dir + title + '.csv' # <-><-><-> only for log, delete above if open source sub_data_dir = '{}_{}ACFG_min{}_max{}'.format(graph_name, graph_init_dim, graph_min, graph_max) cfg_data_dir = os.path.join(main_data_dir, sub_data_dir) if 'ffmpeg' in sub_data_dir else os.path.join(main_data_dir, sub_data_dir, 'acfgSSL_6') assert os.path.exists(cfg_data_dir), "the path of {} is not exist!".format(cfg_data_dir) if cfg_args.only_test is True: model_save_path = cfg_args.model_path LOG_FILE = main_log_dir + 'OnlyTest_repeat_{}_'.format(cfg_args.repeat_run) + title + '.txt' write_log_file(LOG_FILE, create_log_str) write_log_file(LOG_FILE, create_BestModel_dir) write_log_file(LOG_FILE, str(cfg_args)) cfg_trainer = CFGTrainer(node_init_dims=graph_init_dim, data_dir=cfg_data_dir, device=d, log_file=LOG_FILE, best_model_file=model_save_path, args=cfg_args) ret_final_test_auc = cfg_trainer.testing() else: write_log_file(LOG_FILE, create_log_str) write_log_file(LOG_FILE, create_BestModel_dir) write_log_file(LOG_FILE, str(cfg_args)) cfg_trainer = CFGTrainer(node_init_dims=graph_init_dim, data_dir=cfg_data_dir, device=d, log_file=LOG_FILE, best_model_file=BestModel_FILE, args=cfg_args) ret_best_val_auc = cfg_trainer.fit() ret_final_test_auc = cfg_trainer.testing()
8,114
46.45614
168
py
MGMN
MGMN-main/src/model/DenseGraphMatching.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # ************************************ # @Time : 2019/3/4 17:16 # @Author : Xiang Ling # @Lab : nesa.zju.edu.cn # @File : DenseGraphMatching.py # ************************************ import torch import torch.nn as nn import torch.nn.functional as functional from model.DenseGGNN import DenseGGNN from torch_geometric.nn.dense.dense_gcn_conv import DenseGCNConv from torch_geometric.nn.dense.dense_gin_conv import DenseGINConv from torch_geometric.nn.dense.dense_sage_conv import DenseSAGEConv class MultiLevelGraphMatchNetwork(torch.nn.Module): def __init__(self, node_init_dims, arguments, device): super(MultiLevelGraphMatchNetwork, self).__init__() self.node_init_dims = node_init_dims self.args = arguments self.device = device self.dropout = arguments.dropout # ---------- Node Embedding Layer ---------- filters = self.args.filters.split('_') self.gcn_filters = [int(n_filter) for n_filter in filters] # GCNs' filter sizes self.gcn_numbers = len(self.gcn_filters) self.gcn_last_filter = self.gcn_filters[-1] # last filter size of node embedding layer gcn_parameters = [dict(in_channels=self.gcn_filters[i - 1], out_channels=self.gcn_filters[i], bias=True) for i in range(1, self.gcn_numbers)] gcn_parameters.insert(0, dict(in_channels=node_init_dims, out_channels=self.gcn_filters[0], bias=True)) gin_parameters = [dict(nn=nn.Linear(in_features=self.gcn_filters[i - 1], out_features=self.gcn_filters[i])) for i in range(1, self.gcn_numbers)] gin_parameters.insert(0, {'nn': nn.Linear(in_features=node_init_dims, out_features=self.gcn_filters[0])}) ggnn_parameters = [dict(out_channels=self.gcn_filters[i]) for i in range(self.gcn_numbers)] conv_layer_constructor = { 'gcn': dict(constructor=DenseGCNConv, kwargs=gcn_parameters), 'graphsage': dict(constructor=DenseSAGEConv, kwargs=gcn_parameters), 'gin': dict(constructor=DenseGINConv, kwargs=gin_parameters), 'ggnn': dict(constructor=DenseGGNN, kwargs=ggnn_parameters) } conv = conv_layer_constructor[self.args.conv] constructor = conv['constructor'] # build GCN layers setattr(self, 'gc{}'.format(1), constructor(**conv['kwargs'][0])) for i in range(1, self.gcn_numbers): setattr(self, 'gc{}'.format(i + 1), constructor(**conv['kwargs'][i])) # global aggregation self.global_flag = self.args.global_flag if self.global_flag is True: self.global_agg = self.args.global_agg if self.global_agg.lower() == 'max_pool': print("Only Max Pooling") elif self.global_agg.lower() == 'fc_max_pool': self.global_fc_agg = nn.Linear(self.gcn_last_filter, self.gcn_last_filter) elif self.global_agg.lower() == 'mean_pool': print("Only Mean Pooling") elif self.global_agg.lower() == 'fc_mean_pool': self.global_fc_agg = nn.Linear(self.gcn_last_filter, self.gcn_last_filter) elif self.global_agg.lower() == 'lstm': self.global_lstm_agg = nn.LSTM(input_size=self.gcn_last_filter, hidden_size=self.gcn_last_filter, num_layers=1, bidirectional=True, batch_first=True) else: raise NotImplementedError # ---------- Node-Graph Matching Layer ---------- self.perspectives = self.args.perspectives # number of perspectives for multi-perspective matching function if self.args.match.lower() == 'node-graph': self.mp_w = nn.Parameter(torch.rand(self.perspectives, self.gcn_last_filter)) # trainable weight matrix for multi-perspective matching function self.lstm_input_size = self.perspectives else: raise NotImplementedError # ---------- Aggregation Layer ---------- self.hidden_size = self.args.hidden_size # fixed the dimension size of aggregation hidden size # match aggregation if self.args.match_agg.lower() == 'bilstm': self.agg_bilstm = nn.LSTM(input_size=self.lstm_input_size, hidden_size=self.hidden_size, num_layers=1, bidirectional=True, batch_first=True) elif self.args.match_agg.lower() == 'fc_avg' or self.args.match_agg.lower() == 'fc_max': self.fc_agg = nn.Linear(self.lstm_input_size, self.lstm_input_size) elif self.args.match_agg.lower() == 'avg' or self.args.match_agg.lower() == 'max': pass else: raise NotImplementedError # ---------- Prediction Layer ---------- if self.args.task.lower() == 'regression': if self.global_flag is True: if self.global_agg.lower() == 'lstm': factor_global = 2 else: factor_global = 1 else: factor_global = 0 if self.args.match_agg == 'bilstm': factor_match_agg = 2 else: factor_match_agg = 1 factor = factor_match_agg + factor_global self.predict_fc1 = nn.Linear(int(self.hidden_size * 2 * factor), int(self.hidden_size * factor)) self.predict_fc2 = nn.Linear(int(self.hidden_size * factor), int((self.hidden_size * factor) / 2)) self.predict_fc3 = nn.Linear(int((self.hidden_size * factor) / 2), int((self.hidden_size * factor) / 4)) self.predict_fc4 = nn.Linear(int((self.hidden_size * factor) / 4), 1) elif self.args.task.lower() == 'classification': print("classification task") else: raise NotImplementedError def global_aggregation_info(self, v, agg_func_name): """ :param v: (batch, len, dim) :param agg_func_name: :return: (batch, len) """ if agg_func_name.lower() == 'max_pool': agg_v = torch.max(v, 1)[0] elif agg_func_name.lower() == 'fc_max_pool': agg_v = self.global_fc_agg(v) agg_v = torch.max(agg_v, 1)[0] elif agg_func_name.lower() == 'mean_pool': agg_v = torch.mean(v, dim=1) elif agg_func_name.lower() == 'fc_mean_pool': agg_v = self.global_fc_agg(v) agg_v = torch.mean(agg_v, dim=1) elif agg_func_name.lower() == 'lstm': _, (agg_v_last, _) = self.global_lstm_agg(v) agg_v = agg_v_last.permute(1, 0, 2).contiguous().view(-1, self.gcn_last_filter * 2) else: raise NotImplementedError return agg_v @staticmethod def div_with_small_value(n, d, eps=1e-8): # too small values are replaced by 1e-8 to prevent it from exploding. d = d * (d > eps).float() + eps * (d <= eps).float() return n / d def cosine_attention(self, v1, v2): """ :param v1: (batch, len1, dim) :param v2: (batch, len2, dim) :return: (batch, len1, len2) """ # (batch, len1, len2) a = torch.bmm(v1, v2.permute(0, 2, 1)) v1_norm = v1.norm(p=2, dim=2, keepdim=True) # (batch, len1, 1) v2_norm = v2.norm(p=2, dim=2, keepdim=True).permute(0, 2, 1) # (batch, len2, 1) d = v1_norm * v2_norm return self.div_with_small_value(a, d) def multi_perspective_match_func(self, v1, v2, w): """ :param v1: (batch, len, dim) :param v2: (batch, len, dim) :param w: (perspectives, dim) :return: (batch, len, perspectives) """ w = w.transpose(1, 0).unsqueeze(0).unsqueeze(0) # (1, 1, dim, perspectives) v1 = w * torch.stack([v1] * self.perspectives, dim=3) # (batch, len, dim, perspectives) v2 = w * torch.stack([v2] * self.perspectives, dim=3) # (batch, len, dim, perspectives) return functional.cosine_similarity(v1, v2, dim=2) # (batch, len, perspectives) def forward_dense_gcn_layers(self, feat, adj): feat_in = feat for i in range(1, self.gcn_numbers + 1): feat_out = functional.relu(getattr(self, 'gc{}'.format(i))(x=feat_in, adj=adj, mask=None, add_loop=False), inplace=True) feat_out = functional.dropout(feat_out, p=self.dropout, training=self.training) feat_in = feat_out return feat_out def forward(self, batch_x_p, batch_x_h, batch_adj_p, batch_adj_h): # ---------- Node Embedding Layer ---------- feature_p_init = torch.FloatTensor(batch_x_p).to(self.device) adj_p = torch.FloatTensor(batch_adj_p).to(self.device) feature_h_init = torch.FloatTensor(batch_x_h).to(self.device) adj_h = torch.FloatTensor(batch_adj_h).to(self.device) feature_p = self.forward_dense_gcn_layers(feat=feature_p_init, adj=adj_p) # (batch, len_p, dim) feature_h = self.forward_dense_gcn_layers(feat=feature_h_init, adj=adj_h) # (batch, len_h, dim) # ---------- Node-Graph Matching Layer ---------- attention = self.cosine_attention(feature_p, feature_h) # (batch, len_p, len_h) attention_h = feature_h.unsqueeze(1) * attention.unsqueeze(3) # (batch, 1, len_h, dim) * (batch, len_p, len_h, dim) => (batch, len_p, len_h, dim) attention_p = feature_p.unsqueeze(2) * attention.unsqueeze(3) # (batch, len_p, 1, dim) * (batch, len_p, len_h, dim) => (batch, len_p, len_h, dim) att_mean_h = self.div_with_small_value(attention_h.sum(dim=2), attention.sum(dim=2, keepdim=True)) # (batch, len_p, dim) att_mean_p = self.div_with_small_value(attention_p.sum(dim=1), attention.sum(dim=1, keepdim=True).permute(0, 2, 1)) # (batch, len_h, dim) if self.args.match.lower() == "node-graph": multi_p = self.multi_perspective_match_func(v1=feature_p, v2=att_mean_h, w=self.mp_w) multi_h = self.multi_perspective_match_func(v1=feature_h, v2=att_mean_p, w=self.mp_w) else: raise NotImplementedError match_p = multi_p match_h = multi_h # ---------- Aggregation Layer ---------- if self.args.match_agg.lower() == 'bilstm': p_agg_bilstm_h0 = torch.zeros(2 * 1, match_p.size(0), self.gcn_last_filter, dtype=torch.float32).to(self.device) p_agg_bilstm_c0 = torch.zeros(2 * 1, match_p.size(0), self.gcn_last_filter, dtype=torch.float32).to(self.device) h_agg_bilstm_h0 = torch.zeros(2 * 1, match_h.size(0), self.gcn_last_filter, dtype=torch.float32).to(self.device) h_agg_bilstm_c0 = torch.zeros(2 * 1, match_h.size(0), self.gcn_last_filter, dtype=torch.float32).to(self.device) _, (agg_p_last, _) = self.agg_bilstm(match_p, (p_agg_bilstm_h0, p_agg_bilstm_c0)) # (batch, seq_len, l) -> (2, batch, hidden_size) agg_p = agg_p_last.permute(1, 0, 2).contiguous().view(-1, self.hidden_size * 2) _, (agg_h_last, _) = self.agg_bilstm(match_h, (h_agg_bilstm_h0, h_agg_bilstm_c0)) agg_h = agg_h_last.permute(1, 0, 2).contiguous().view(-1, self.hidden_size * 2) elif self.args.match_agg.lower() == 'avg': agg_p = torch.mean(match_p, dim=1) agg_h = torch.mean(match_h, dim=1) elif self.args.match_agg.lower() == 'fc_avg': agg_p = torch.mean(self.fc_agg(match_p), dim=1) agg_h = torch.mean(self.fc_agg(match_h), dim=1) elif self.args.match_agg.lower() == 'max': agg_p = torch.max(match_p, dim=1)[0] agg_h = torch.max(match_h, dim=1)[0] elif self.args.match_agg.lower() == 'fc_max': agg_p = torch.max(self.fc_agg(match_p), dim=1)[0] agg_h = torch.max(self.fc_agg(match_h), dim=1)[0] else: raise NotImplementedError # option: global aggregation if self.global_flag is True: global_gcn_agg_p = self.global_aggregation_info(v=feature_p, agg_func_name=self.global_agg) global_gcn_agg_h = self.global_aggregation_info(v=feature_h, agg_func_name=self.global_agg) agg_p = torch.cat([agg_p, global_gcn_agg_p], dim=1) agg_h = torch.cat([agg_h, global_gcn_agg_h], dim=1) # ---------- Prediction Layer ---------- if self.args.task.lower() == 'regression': x = torch.cat([agg_p, agg_h], dim=1) x = functional.dropout(x, p=self.dropout, training=self.training) x = functional.relu(self.predict_fc1(x)) x = functional.dropout(x, p=self.dropout, training=self.training) x = functional.relu(self.predict_fc2(x)) x = functional.dropout(x, p=self.dropout, training=self.training) x = functional.relu(self.predict_fc3(x)) x = functional.dropout(x, p=self.dropout, training=self.training) x = self.predict_fc4(x) x = torch.sigmoid(x).squeeze(-1) return x elif self.args.task.lower() == 'classification': sim = functional.cosine_similarity(agg_p, agg_h, dim=1).clamp(min=-1, max=1) return sim else: raise NotImplementedError
13,447
50.13308
165
py
MGMN
MGMN-main/src/model/DenseGGNN.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # ************************************ # @Time : 2019/3/3 17:16 # @Author : Xiang Ling # @Lab : nesa.zju.edu.cn # @File : DenseGGNN.py # ************************************ import torch import torch.nn as nn from torch_geometric.nn.conv.gated_graph_conv import GatedGraphConv from torch_geometric.utils import dense_to_sparse class DenseGGNN(nn.Module): def __init__(self, out_channels, num_layers=1): super(DenseGGNN, self).__init__() self.model = GatedGraphConv(out_channels=out_channels, num_layers=num_layers) def forward(self, x, adj, **kwargs): B = x.size()[0] N = x.size()[1] D = x.size()[2] indices = [] for i in range(B): edge_index = dense_to_sparse(adj[i]) indices.append(edge_index[0] + i * N) edge_index = torch.cat(indices, dim=1) x = x.reshape(-1, D) output = self.model(x, edge_index) return output.reshape(B, N, -1)
1,024
29.147059
85
py
papa
papa-main/transformers/src/transformers/papa_modules.py
import torch from torch import nn import json import os from .modeling_utils import ModuleUtilsMixin import numpy as np from .activations import ACT2FN class FreezeExtractPoller(nn.Module): def __init__(self, config): super().__init__() self.dense_across_layers = nn.Linear((config.num_hidden_layers+1) * config.hidden_size, config.hidden_size) temp_weights = torch.ones(config.num_hidden_layers+1, config.max_seq_length) / config.max_seq_length self.weights_per_layer = nn.Parameter(temp_weights, requires_grad=True) self.activation = nn.Tanh() self.output_dim = config.hidden_size def forward(self, hidden_states, mask=None): concat_tensor = None for i in range(len(hidden_states)): w = self.weights_per_layer[i] if mask is not None: w = torch.unsqueeze(w * mask, dim=1) current_tensor = torch.squeeze(torch.bmm(w, hidden_states[i])) if concat_tensor is None: concat_tensor = current_tensor else: concat_tensor = torch.cat([concat_tensor, current_tensor], 1) pooled_output = self.dense_across_layers(concat_tensor) pooled_output = self.activation(pooled_output) return pooled_output class FreezeExtractPollerTokenClassification(nn.Module): def __init__(self, config, mlm=False): super().__init__() self.dense_across_layers_1 = nn.Linear((config.num_hidden_layers+1) * config.hidden_size, config.hidden_size) if mlm: self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias if isinstance(config.hidden_act, str): self.activation = ACT2FN[config.hidden_act] else: self.activation = config.hidden_act else: self.decoder = nn.Linear(config.hidden_size, config.num_labels) self.activation = nn.Tanh() def forward(self, hidden_states): concat_tensor = None for i in range(len(hidden_states)): current_tensor = hidden_states[i] if concat_tensor is None: concat_tensor = current_tensor else: concat_tensor = torch.cat([concat_tensor, current_tensor], -1) pooled_output = self.dense_across_layers_1(concat_tensor) pooled_output = self.activation(pooled_output) pooled_output = self.decoder(pooled_output) return pooled_output def get_sorting_heads_dict(sorting_heads_dir, num_heads): if num_heads == 0: return None with open(os.path.join(sorting_heads_dir, 'sorted_heads.json'), "r") as fp: heads_sorted = json.load(fp) layers_dict = {} for layer, head in heads_sorted[:num_heads]: if layer not in layers_dict: layers_dict[layer] = [head] else: layers_dict[layer].append(head) return layers_dict def get_att_pattern_from_mask(att_mask): batch_size = att_mask.shape[0] seq_len = att_mask.shape[-1] if list(att_mask.shape) == [batch_size, 1, seq_len, seq_len]: return att_mask my_attention_mask = att_mask * -1 max_val = torch.max(my_attention_mask) if torch.abs(max_val) > 0: my_attention_mask /= torch.max(my_attention_mask) my_attention_mask = 1 - my_attention_mask my_attention_mask = my_attention_mask[:,0] full_pattern = torch.bmm(torch.transpose(my_attention_mask, dim0=-1, dim1=-2), my_attention_mask) return torch.unsqueeze(full_pattern, 1) def mask_and_normalize(att_probs, att_mask): cur_attention_pattern = get_att_pattern_from_mask(att_mask) new_att_probs = att_probs * cur_attention_pattern new_att_probs = torch.nn.functional.normalize(new_att_probs, p=1.0, dim=-1) return new_att_probs def combine_static_and_dynamic_att(att_probs, static_heads, att_mask, static_heads_indexes, num_attention_heads): att_probs_shape = att_probs.shape batch = att_probs_shape[0] seq_len = att_probs_shape[-1] new_att_probs = torch.zeros((batch, num_attention_heads, seq_len, seq_len), device=att_probs.device) dynamic_heads_indexes = list(set(range(num_attention_heads)) - set(static_heads_indexes)) new_att_probs[:, dynamic_heads_indexes] = att_probs new_att_probs[:, static_heads_indexes] = static_heads # apply my masking and normalization over all the heads, this is a bit of # an overhead, but looks much simpler: new_att_probs = mask_and_normalize(new_att_probs, att_mask) return new_att_probs
4,804
39.041667
120
py
papa
papa-main/transformers/src/transformers/modeling_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import os import re from contextlib import contextmanager from dataclasses import dataclass from functools import partial from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import torch from packaging import version from torch import Tensor, device, nn from torch.nn import CrossEntropyLoss from requests import HTTPError from .activations import get_activation from .configuration_utils import PretrainedConfig from .deepspeed import deepspeed_config, is_deepspeed_zero3_enabled from .file_utils import ( DUMMY_INPUTS, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, WEIGHTS_NAME, EntryNotFoundError, ModelOutput, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_path, copy_func, has_file, hf_bucket_url, is_offline_mode, is_remote_url, replace_return_docstrings, ) from .generation_utils import GenerationMixin from .utils import logging from .utils.versions import require_version_core logger = logging.get_logger(__name__) _init_weights = True @contextmanager def no_init_weights(_enable=True): """ Context manager to globally disable weight initialization to speed up loading large models. TODO(Patrick): Delete safety argument `_enable=True` at next major version. . """ global _init_weights if _enable: _init_weights = False try: yield finally: _init_weights = True try: from torch.nn import Identity except ImportError: # Older PyTorch compatibility class Identity(nn.Module): r"""A placeholder identity operator that is argument-insensitive.""" def __init__(self, *args, **kwargs): super().__init__() def forward(self, input): return input def find_pruneable_heads_and_indices( heads: List[int], n_heads: int, head_size: int, already_pruned_heads: Set[int] ) -> Tuple[Set[int], torch.LongTensor]: """ Finds the heads and their indices taking `already_pruned_heads` into account. Args: heads (`List[int]`): List of the indices of heads to prune. n_heads (`int`): The number of heads in the model. head_size (`int`): The size of each head. already_pruned_heads (`Set[int]`): A set of already pruned heads. Returns: `Tuple[Set[int], torch.LongTensor]`: A tuple with the remaining heads and their corresponding indices. """ mask = torch.ones(n_heads, head_size) heads = set(heads) - already_pruned_heads # Convert to set and remove already pruned heads for head in heads: # Compute how many pruned heads are before the head and move the index accordingly head = head - sum(1 if h < head else 0 for h in already_pruned_heads) mask[head] = 0 mask = mask.view(-1).contiguous().eq(1) index: torch.LongTensor = torch.arange(len(mask))[mask].long() return heads, index def get_parameter_device(parameter: Union[nn.Module, GenerationMixin, "ModuleUtilsMixin"]): try: return next(parameter.parameters()).device except StopIteration: # For nn.DataParallel compatibility in PyTorch 1.5 def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]: tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)] return tuples gen = parameter._named_members(get_members_fn=find_tensor_attributes) first_tuple = next(gen) return first_tuple[1].device def get_parameter_dtype(parameter: Union[nn.Module, GenerationMixin, "ModuleUtilsMixin"]): try: return next(parameter.parameters()).dtype except StopIteration: # For nn.DataParallel compatibility in PyTorch 1.5 def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]: tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)] return tuples gen = parameter._named_members(get_members_fn=find_tensor_attributes) first_tuple = next(gen) return first_tuple[1].dtype class ModuleUtilsMixin: """ A few utilities for `torch.nn.Modules`, to be used as a mixin. """ @staticmethod def _hook_rss_memory_pre_forward(module, *args, **kwargs): try: import psutil except (ImportError): raise ImportError("You need to install psutil (pip install psutil) to use memory tracing.") process = psutil.Process(os.getpid()) mem = process.memory_info() module.mem_rss_pre_forward = mem.rss return None @staticmethod def _hook_rss_memory_post_forward(module, *args, **kwargs): try: import psutil except (ImportError): raise ImportError("You need to install psutil (pip install psutil) to use memory tracing.") process = psutil.Process(os.getpid()) mem = process.memory_info() module.mem_rss_post_forward = mem.rss mem_rss_diff = module.mem_rss_post_forward - module.mem_rss_pre_forward module.mem_rss_diff = mem_rss_diff + (module.mem_rss_diff if hasattr(module, "mem_rss_diff") else 0) return None def add_memory_hooks(self): """ Add a memory hook before and after each sub-module forward pass to record increase in memory consumption. Increase in memory consumption is stored in a `mem_rss_diff` attribute for each module and can be reset to zero with `model.reset_memory_hooks_state()`. """ for module in self.modules(): module.register_forward_pre_hook(self._hook_rss_memory_pre_forward) module.register_forward_hook(self._hook_rss_memory_post_forward) self.reset_memory_hooks_state() def reset_memory_hooks_state(self): """ Reset the `mem_rss_diff` attribute of each module (see [`~modeling_utils.ModuleUtilsMixin.add_memory_hooks`]). """ for module in self.modules(): module.mem_rss_diff = 0 module.mem_rss_post_forward = 0 module.mem_rss_pre_forward = 0 @property def device(self) -> device: """ `torch.device`: The device on which the module is (assuming that all the module parameters are on the same device). """ return get_parameter_device(self) @property def dtype(self) -> torch.dtype: """ `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype). """ return get_parameter_dtype(self) def invert_attention_mask(self, encoder_attention_mask: Tensor) -> Tensor: """ Invert an attention mask (e.g., switches 0. and 1.). Args: encoder_attention_mask (`torch.Tensor`): An attention mask. Returns: `torch.Tensor`: The inverted attention mask. """ if encoder_attention_mask.dim() == 3: encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) encoder_extended_attention_mask = encoder_extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility if self.dtype == torch.float16: encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -1e4 elif self.dtype in [torch.bfloat16, torch.float32]: encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -1e9 else: raise ValueError( f"{self.dtype} not recognized. `dtype` should be set to either `torch.float32` or `torch.float16`" ) return encoder_extended_attention_mask def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device) -> Tensor: """ Makes broadcastable attention and causal masks so that future and masked tokens are ignored. Arguments: attention_mask (`torch.Tensor`): Mask with ones indicating tokens to attend to, zeros for tokens to ignore. input_shape (`Tuple[int]`): The shape of the input to the model. device: (`torch.device`): The device of the input to the model. Returns: `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`. """ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. if attention_mask.dim() == 3: extended_attention_mask = attention_mask[:, None, :, :] elif attention_mask.dim() == 2: # Provided a padding mask of dimensions [batch_size, seq_length] # - if the model is a decoder, apply a causal mask in addition to the padding mask # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder: batch_size, seq_length = input_shape seq_ids = torch.arange(seq_length, device=device) causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None] # in case past_key_values are used we need to add a prefix ones mask to the causal mask # causal and attention masks must have same type with pytorch version < 1.3 causal_mask = causal_mask.to(attention_mask.dtype) if causal_mask.shape[1] < attention_mask.shape[1]: prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] causal_mask = torch.cat( [ torch.ones( (batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype ), causal_mask, ], axis=-1, ) extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :] else: extended_attention_mask = attention_mask[:, None, None, :] else: raise ValueError( f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})" ) # Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and -10000.0 for masked positions. # Since we are adding it to the raw scores before the softmax, this is # effectively the same as removing these entirely. extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 return extended_attention_mask def get_head_mask( self, head_mask: Optional[Tensor], num_hidden_layers: int, is_attention_chunked: bool = False ) -> Tensor: """ Prepare the head mask if needed. Args: head_mask (`torch.Tensor` with shape `[num_heads]` or `[num_hidden_layers x num_heads]`, *optional*): The mask indicating if we should keep the heads or not (1.0 for keep, 0.0 for discard). num_hidden_layers (`int`): The number of hidden layers in the model. is_attention_chunked: (`bool`, *optional*, defaults to `False`): Whether or not the attentions scores are computed by chunks or not. Returns: `torch.Tensor` with shape `[num_hidden_layers x batch x num_heads x seq_length x seq_length]` or list with `[None]` for each layer. """ if head_mask is not None: head_mask = self._convert_head_mask_to_5d(head_mask, num_hidden_layers) if is_attention_chunked is True: head_mask = head_mask.unsqueeze(-1) else: head_mask = [None] * num_hidden_layers return head_mask def _convert_head_mask_to_5d(self, head_mask, num_hidden_layers): """-> [num_hidden_layers x batch x num_heads x seq_length x seq_length]""" if head_mask.dim() == 1: head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1) head_mask = head_mask.expand(num_hidden_layers, -1, -1, -1, -1) elif head_mask.dim() == 2: head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1) # We can specify head_mask for each layer assert head_mask.dim() == 5, f"head_mask.dim != 5, instead {head_mask.dim()}" head_mask = head_mask.to(dtype=self.dtype) # switch to float if need + fp16 compatibility return head_mask def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int: """ Get number of (optionally, trainable or non-embeddings) parameters in the module. Args: only_trainable (`bool`, *optional*, defaults to `False`): Whether or not to return only the number of trainable parameters exclude_embeddings (`bool`, *optional*, defaults to `False`): Whether or not to return only the number of non-embeddings parameters Returns: `int`: The number of parameters. """ if exclude_embeddings: embedding_param_names = [ f"{name}.weight" for name, module_type in self.named_modules() if isinstance(module_type, nn.Embedding) ] non_embedding_parameters = [ parameter for name, parameter in self.named_parameters() if name not in embedding_param_names ] return sum(p.numel() for p in non_embedding_parameters if p.requires_grad or not only_trainable) else: return sum(p.numel() for p in self.parameters() if p.requires_grad or not only_trainable) def estimate_tokens(self, input_dict: Dict[str, Union[torch.Tensor, Any]]) -> int: """ Helper function to estimate the total number of tokens from the model inputs. Args: inputs (`dict`): The model inputs. Returns: `int`: The total number of tokens. """ if self.main_input_name in input_dict: return input_dict[self.main_input_name].numel() else: logger.warn( "Could not estimate the number of tokens of the input, floating-point operations will not be computed" ) return 0 def floating_point_ops( self, input_dict: Dict[str, Union[torch.Tensor, Any]], exclude_embeddings: bool = True ) -> int: """ Get number of (optionally, non-embeddings) floating-point operations for the forward and backward passes of a batch with this transformer model. Default approximation neglects the quadratic dependency on the number of tokens (valid if `12 * d_model << sequence_length`) as laid out in [this paper](https://arxiv.org/pdf/2001.08361.pdf) section 2.1. Should be overridden for transformers with parameter re-use e.g. Albert or Universal Transformers, or if doing long-range modeling with very high sequence lengths. Args: batch_size (`int`): The batch size for the forward pass. sequence_length (`int`): The number of tokens in each line of the batch. exclude_embeddings (`bool`, *optional*, defaults to `True`): Whether or not to count embedding and softmax operations. Returns: `int`: The number of floating-point operations. """ return 6 * self.estimate_tokens(input_dict) * self.num_parameters(exclude_embeddings=exclude_embeddings) class PreTrainedModel(nn.Module, ModuleUtilsMixin, GenerationMixin, PushToHubMixin): r""" Base class for all models. [`PreTrainedModel`] takes care of storing the configuration of the models and handles methods for loading, downloading and saving models as well as a few methods common to all models to: - resize the input embeddings, - prune heads in the self-attention heads. Class attributes (overridden by derived classes): - **config_class** ([`PretrainedConfig`]) -- A subclass of [`PretrainedConfig`] to use as configuration class for this model architecture. - **load_tf_weights** (`Callable`) -- A python *method* for loading a TensorFlow checkpoint in a PyTorch model, taking as arguments: - **model** ([`PreTrainedModel`]) -- An instance of the model on which to load the TensorFlow checkpoint. - **config** ([`PreTrainedConfig`]) -- An instance of the configuration associated to the model. - **path** (`str`) -- A path to the TensorFlow checkpoint. - **base_model_prefix** (`str`) -- A string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model. - **is_parallelizable** (`bool`) -- A flag indicating whether this model supports model parallelization. - **main_input_name** (`str`) -- The name of the principal input to the model (often `input_ids` for NLP models, `pixel_values` for vision models and `input_values` for speech models). """ config_class = None base_model_prefix = "" main_input_name = "input_ids" # a list of re pattern of tensor names to ignore from the model when loading the model weights # (and avoid unnecessary warnings). _keys_to_ignore_on_load_missing = None # a list of re pattern of tensor names to ignore from the weights when loading the model weights # (and avoid unnecessary warnings). _keys_to_ignore_on_load_unexpected = None # a list of of tensor names to ignore when saving the model (useful for keys that aren't # trained, but which are deterministic, or tied variables) _keys_to_ignore_on_save = None is_parallelizable = False supports_gradient_checkpointing = False @property def dummy_inputs(self) -> Dict[str, torch.Tensor]: """ `Dict[str, torch.Tensor]`: Dummy inputs to do a forward pass in the network. """ return {"input_ids": torch.tensor(DUMMY_INPUTS)} @property def framework(self) -> str: """ :str: Identifies that this is a PyTorch model. """ return "pt" def __init__(self, config: PretrainedConfig, *inputs, **kwargs): super().__init__() if not isinstance(config, PretrainedConfig): raise ValueError( f"Parameter config in `{self.__class__.__name__}(config)` should be an instance of class " "`PretrainedConfig`. To create a model from a pretrained model use " f"`model = {self.__class__.__name__}.from_pretrained(PRETRAINED_MODEL_NAME)`" ) # Save config and origin of the pretrained weights if given in model self.config = config self.name_or_path = config.name_or_path def post_init(self): """ A method executed at the end of each Transformer model initialization, to execute code that needs the model's modules properly initialized (such as weight initialization). """ self.init_weights() self._backward_compatibility_gradient_checkpointing() def _backward_compatibility_gradient_checkpointing(self): if self.supports_gradient_checkpointing and getattr(self.config, "gradient_checkpointing", False): self.gradient_checkpointing_enable() # Remove the attribute now that is has been consumed, so it's no saved in the config. delattr(self.config, "gradient_checkpointing") @classmethod def _from_config(cls, config, **kwargs): """ All context managers that the model should be initialized under go here. Args: torch_dtype (`torch.dtype`, *optional*): Override the default `torch.dtype` and load the model under this dtype. """ torch_dtype = kwargs.pop("torch_dtype", None) # override default dtype if needed dtype_orig = None if torch_dtype is not None: dtype_orig = cls._set_default_torch_dtype(torch_dtype) if is_deepspeed_zero3_enabled(): import deepspeed logger.info("Detected DeepSpeed ZeRO-3: activating zero.init() for this model") # this immediately partitions the model across all gpus, to avoid the overhead in time # and memory copying it on CPU or each GPU first with deepspeed.zero.Init(config_dict_or_path=deepspeed_config()): model = cls(config, **kwargs) else: model = cls(config, **kwargs) # restore default dtype if it was modified if dtype_orig is not None: torch.set_default_dtype(dtype_orig) return model @classmethod def _set_default_torch_dtype(cls, dtype: torch.dtype) -> torch.dtype: """ Change the default dtype and return the previous one. This is needed when wanting to instantiate the model under specific dtype. Args: dtype (`torch.dtype`): a floating dtype to set to. Returns: `torch.dtype`: the original `dtype` that can be used to restore `torch.set_default_dtype(dtype)` if it was modified. If it wasn't, returns `None`. Note `set_default_dtype` currently only works with floating-point types and asserts if for example, `torch.int64` is passed. So if a non-float `dtype` is passed this functions will throw an exception. """ if not dtype.is_floating_point: raise ValueError( f"Can't instantiate {cls.__name__} model under dtype={dtype} since it is not a floating point dtype" ) logger.info(f"Instantiating {cls.__name__} model under default dtype {dtype}.") dtype_orig = torch.get_default_dtype() torch.set_default_dtype(dtype) return dtype_orig @property def base_model(self) -> nn.Module: """ `torch.nn.Module`: The main body of the model. """ return getattr(self, self.base_model_prefix, self) def get_input_embeddings(self) -> nn.Module: """ Returns the model's input embeddings. Returns: `nn.Module`: A torch module mapping vocabulary to hidden states. """ base_model = getattr(self, self.base_model_prefix, self) if base_model is not self: return base_model.get_input_embeddings() else: raise NotImplementedError def set_input_embeddings(self, value: nn.Module): """ Set model's input embeddings. Args: value (`nn.Module`): A module mapping vocabulary to hidden states. """ base_model = getattr(self, self.base_model_prefix, self) if base_model is not self: base_model.set_input_embeddings(value) else: raise NotImplementedError def get_output_embeddings(self) -> nn.Module: """ Returns the model's output embeddings. Returns: `nn.Module`: A torch module mapping hidden states to vocabulary. """ return None # Overwrite for models with output embeddings def _init_weights(self, module): """ Initialize the weights. This method should be overridden by derived class. """ raise NotImplementedError(f"Make sure `_init_weights` is implemented for {self.__class__}") def tie_weights(self): """ Tie the weights between the input embeddings and the output embeddings. If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning the weights instead. """ output_embeddings = self.get_output_embeddings() if output_embeddings is not None and self.config.tie_word_embeddings: self._tie_or_clone_weights(output_embeddings, self.get_input_embeddings()) if self.config.is_encoder_decoder and self.config.tie_encoder_decoder: if hasattr(self, self.base_model_prefix): self = getattr(self, self.base_model_prefix) self._tie_encoder_decoder_weights(self.encoder, self.decoder, self.base_model_prefix) for module in self.modules(): if hasattr(module, "_tie_weights"): module._tie_weights() @staticmethod def _tie_encoder_decoder_weights(encoder: nn.Module, decoder: nn.Module, base_model_prefix: str): uninitialized_encoder_weights: List[str] = [] if decoder.__class__ != encoder.__class__: logger.info( f"{decoder.__class__} and {encoder.__class__} are not equal. In this case make sure that all encoder weights are correctly initialized." ) def tie_encoder_to_decoder_recursively( decoder_pointer: nn.Module, encoder_pointer: nn.Module, module_name: str, uninitialized_encoder_weights: List[str], depth=0, ): assert isinstance(decoder_pointer, nn.Module) and isinstance( encoder_pointer, nn.Module ), f"{decoder_pointer} and {encoder_pointer} have to be of type nn.Module" if hasattr(decoder_pointer, "weight"): assert hasattr(encoder_pointer, "weight") encoder_pointer.weight = decoder_pointer.weight if hasattr(decoder_pointer, "bias"): assert hasattr(encoder_pointer, "bias") encoder_pointer.bias = decoder_pointer.bias return encoder_modules = encoder_pointer._modules decoder_modules = decoder_pointer._modules if len(decoder_modules) > 0: assert ( len(encoder_modules) > 0 ), f"Encoder module {encoder_pointer} does not match decoder module {decoder_pointer}" all_encoder_weights = set([module_name + "/" + sub_name for sub_name in encoder_modules.keys()]) encoder_layer_pos = 0 for name, module in decoder_modules.items(): if name.isdigit(): encoder_name = str(int(name) + encoder_layer_pos) decoder_name = name if not isinstance(decoder_modules[decoder_name], type(encoder_modules[encoder_name])) and len( encoder_modules ) != len(decoder_modules): # this can happen if the name corresponds to the position in a list module list of layers # in this case the decoder has added a cross-attention that the encoder does not have # thus skip this step and subtract one layer pos from encoder encoder_layer_pos -= 1 continue elif name not in encoder_modules: continue elif depth > 500: raise ValueError( "Max depth of recursive function `tie_encoder_to_decoder` reached. It seems that there is a circular dependency between two or more `nn.Modules` of your model." ) else: decoder_name = encoder_name = name tie_encoder_to_decoder_recursively( decoder_modules[decoder_name], encoder_modules[encoder_name], module_name + "/" + name, uninitialized_encoder_weights, depth=depth + 1, ) all_encoder_weights.remove(module_name + "/" + encoder_name) uninitialized_encoder_weights += list(all_encoder_weights) # tie weights recursively tie_encoder_to_decoder_recursively(decoder, encoder, base_model_prefix, uninitialized_encoder_weights) if len(uninitialized_encoder_weights) > 0: logger.warning( f"The following encoder weights were not tied to the decoder {uninitialized_encoder_weights}" ) def _tie_or_clone_weights(self, output_embeddings, input_embeddings): """Tie or clone module weights depending of whether we are using TorchScript or not""" if self.config.torchscript: output_embeddings.weight = nn.Parameter(input_embeddings.weight.clone()) else: output_embeddings.weight = input_embeddings.weight if getattr(output_embeddings, "bias", None) is not None: output_embeddings.bias.data = nn.functional.pad( output_embeddings.bias.data, ( 0, output_embeddings.weight.shape[0] - output_embeddings.bias.shape[0], ), "constant", 0, ) if hasattr(output_embeddings, "out_features") and hasattr(input_embeddings, "num_embeddings"): output_embeddings.out_features = input_embeddings.num_embeddings def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding: """ Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. Takes care of tying weights embeddings afterwards if the model class has a `tie_weights()` method. Arguments: new_num_tokens (`int`, *optional*): The number of new tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just returns a pointer to the input tokens `torch.nn.Embedding` module of the model without doing anything. Return: `torch.nn.Embedding`: Pointer to the input tokens Embeddings Module of the model. """ model_embeds = self._resize_token_embeddings(new_num_tokens) if new_num_tokens is None: return model_embeds # Update base model and current model config self.config.vocab_size = new_num_tokens self.vocab_size = new_num_tokens # Tie weights again if needed self.tie_weights() return model_embeds def _resize_token_embeddings(self, new_num_tokens): old_embeddings = self.get_input_embeddings() new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens) self.set_input_embeddings(new_embeddings) # if word embeddings are not tied, make sure that lm head is resized as well if self.get_output_embeddings() is not None and not self.config.tie_word_embeddings: old_lm_head = self.get_output_embeddings() new_lm_head = self._get_resized_lm_head(old_lm_head, new_num_tokens) self.set_output_embeddings(new_lm_head) return self.get_input_embeddings() def _get_resized_embeddings( self, old_embeddings: nn.Embedding, new_num_tokens: Optional[int] = None ) -> nn.Embedding: """ Build a resized Embedding Module from a provided token Embedding Module. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_embeddings (`torch.nn.Embedding`): Old embeddings to be resized. new_num_tokens (`int`, *optional*): New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just returns a pointer to the input tokens ``torch.nn.Embedding``` module of the model without doing anything. Return: `torch.nn.Embedding`: Pointer to the resized Embedding Module or the old Embedding Module if `new_num_tokens` is `None` """ if new_num_tokens is None: return old_embeddings if is_deepspeed_zero3_enabled(): import deepspeed with deepspeed.zero.GatheredParameters(old_embeddings.weight, modifier_rank=None): old_num_tokens, old_embedding_dim = old_embeddings.weight.size() else: old_num_tokens, old_embedding_dim = old_embeddings.weight.size() if old_num_tokens == new_num_tokens: return old_embeddings if not isinstance(old_embeddings, nn.Embedding): raise TypeError( f"Old embeddings are of type {type(old_embeddings)}, which is not an instance of {nn.Embedding}. " f"You should either use a different resize function or make sure that `old_embeddings` are an instance of {nn.Embedding}." ) # Build new embeddings new_embeddings = nn.Embedding(new_num_tokens, old_embedding_dim) new_embeddings.to(self.device, dtype=old_embeddings.weight.dtype) # initialize all new embeddings (in particular added tokens) self._init_weights(new_embeddings) # Copy token embeddings from the previous weights # numbers of tokens to copy n = min(old_num_tokens, new_num_tokens) if is_deepspeed_zero3_enabled(): import deepspeed with deepspeed.zero.GatheredParameters(old_embeddings.weight, modifier_rank=0): if torch.distributed.get_rank() == 0: new_embeddings.weight.data[:n, :] = old_embeddings.weight.data[:n, :] else: new_embeddings.weight.data[:n, :] = old_embeddings.weight.data[:n, :] return new_embeddings def _get_resized_lm_head( self, old_lm_head: nn.Linear, new_num_tokens: Optional[int] = None, transposed: Optional[bool] = False ) -> nn.Linear: """ Build a resized Linear Module from a provided old Linear Module. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_lm_head (`torch.nn.Linear`): Old lm head liner layer to be resized. new_num_tokens (`int`, *optional*): New number of tokens in the linear matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just returns a pointer to the input tokens ``torch.nn.Linear``` module of the model without doing anything. transposed (`bool`, *optional*, defaults to `False`): Whether `old_lm_head` is transposed or not. If True `old_lm_head.size()` is `lm_head_dim, vocab_size` else `vocab_size, lm_head_dim`. Return: `torch.nn.Linear`: Pointer to the resized Linear Module or the old Linear Module if `new_num_tokens` is `None` """ if new_num_tokens is None: return old_lm_head if is_deepspeed_zero3_enabled(): import deepspeed with deepspeed.zero.GatheredParameters(old_lm_head.weight, modifier_rank=None): old_num_tokens, old_lm_head_dim = ( old_lm_head.weight.size() if not transposed else old_lm_head.weight.t().size() ) else: old_num_tokens, old_lm_head_dim = ( old_lm_head.weight.size() if not transposed else old_lm_head.weight.t().size() ) if old_num_tokens == new_num_tokens: return old_lm_head if not isinstance(old_lm_head, nn.Linear): raise TypeError( f"Old language model head is of type {type(old_lm_head)}, which is not an instance of {nn.Linear}. " f"You should either use a different resize function or make sure that `old_lm_head` are an instance of {nn.Linear}." ) # Build new lm head new_lm_head_shape = (old_lm_head_dim, new_num_tokens) if not transposed else (new_num_tokens, old_lm_head_dim) has_new_lm_head_bias = old_lm_head.bias is not None new_lm_head = nn.Linear(*new_lm_head_shape, bias=has_new_lm_head_bias) new_lm_head = new_lm_head.to(self.device, dtype=old_lm_head.weight.dtype) # initialize new lm head (in particular added tokens) self._init_weights(new_lm_head) num_tokens_to_copy = min(old_num_tokens, new_num_tokens) # XXX: put the long block of code in a wrapper if is_deepspeed_zero3_enabled(): import deepspeed with deepspeed.zero.GatheredParameters(old_lm_head.weight, modifier_rank=0): if torch.distributed.get_rank() == 0: # Copy old lm head weights to new lm head if not transposed: new_lm_head.weight.data[:num_tokens_to_copy, :] = old_lm_head.weight.data[ :num_tokens_to_copy, : ] else: new_lm_head.weight.data[:, :num_tokens_to_copy] = old_lm_head.weight.data[ :, :num_tokens_to_copy ] # Copy bias weights to new lm head if has_new_lm_head_bias: new_lm_head.bias.data[:num_tokens_to_copy] = old_lm_head.bias.data[:num_tokens_to_copy] else: # Copy old lm head weights to new lm head if not transposed: new_lm_head.weight.data[:num_tokens_to_copy, :] = old_lm_head.weight.data[:num_tokens_to_copy, :] else: new_lm_head.weight.data[:, :num_tokens_to_copy] = old_lm_head.weight.data[:, :num_tokens_to_copy] # Copy bias weights to new lm head if has_new_lm_head_bias: new_lm_head.bias.data[:num_tokens_to_copy] = old_lm_head.bias.data[:num_tokens_to_copy] return new_lm_head def resize_position_embeddings(self, new_num_position_embeddings: int): raise NotImplementedError( f"`resize_position_embeddings` is not implemented for {self.__class__}`. To implement it, you should " f"overwrite this method in the class {self.__class__} in `modeling_{self.__class__.__module__}.py`" ) def get_position_embeddings(self) -> Union[nn.Embedding, Tuple[nn.Embedding]]: raise NotImplementedError( f"`get_position_embeddings` is not implemented for {self.__class__}`. To implement it, you should " f"overwrite this method in the class {self.__class__} in `modeling_{self.__class__.__module__}.py`" ) def init_weights(self): """ If needed prunes and maybe initializes weights. """ # Prune heads if needed if self.config.pruned_heads: self.prune_heads(self.config.pruned_heads) if _init_weights: # Initialize weights self.apply(self._init_weights) # Tie weights should be skipped when not initializing all weights # since from_pretrained(...) calls tie weights anyways self.tie_weights() def prune_heads(self, heads_to_prune: Dict[int, List[int]]): """ Prunes heads of the base model. Arguments: heads_to_prune (`Dict[int, List[int]]`): Dictionary with keys being selected layer indices (`int`) and associated values being the list of heads to prune in said layer (list of `int`). For instance {1: [0, 2], 2: [2, 3]} will prune heads 0 and 2 on layer 1 and heads 2 and 3 on layer 2. """ # save new sets of pruned heads as union of previously stored pruned heads and newly pruned heads for layer, heads in heads_to_prune.items(): union_heads = set(self.config.pruned_heads.get(layer, [])) | set(heads) self.config.pruned_heads[layer] = list(union_heads) # Unfortunately we have to store it as list for JSON self.base_model._prune_heads(heads_to_prune) def prune_static_heads(self): self.base_model._prune_static_heads() def gradient_checkpointing_enable(self): """ Activates gradient checkpointing for the current model. Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint activations". """ if not self.supports_gradient_checkpointing: raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.") self.apply(partial(self._set_gradient_checkpointing, value=True)) def gradient_checkpointing_disable(self): """ Deactivates gradient checkpointing for the current model. Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint activations". """ if self.supports_gradient_checkpointing: self.apply(partial(self._set_gradient_checkpointing, value=False)) @property def is_gradient_checkpointing(self) -> bool: """ Whether gradient checkpointing is activated for this model or not. Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint activations". """ return any(hasattr(m, "gradient_checkpointing") and m.gradient_checkpointing for m in self.modules()) def save_pretrained( self, save_directory: Union[str, os.PathLike], save_config: bool = True, state_dict: Optional[dict] = None, save_function: Callable = torch.save, push_to_hub: bool = False, **kwargs, ): """ Save a model and its configuration file to a directory, so that it can be re-loaded using the `[`~PreTrainedModel.from_pretrained`]` class method. Arguments: save_directory (`str` or `os.PathLike`): Directory to which to save. Will be created if it doesn't exist. save_config (`bool`, *optional*, defaults to `True`): Whether or not to save the config of the model. Useful when in distributed training like TPUs and need to call this function on all processes. In this case, set `save_config=True` only on the main process to avoid race conditions. state_dict (nested dictionary of `torch.Tensor`): The state dictionary of the model to save. Will default to `self.state_dict()`, but can be used to only save parts of the model or if special precautions need to be taken when recovering the state dictionary of a model (like when using model parallelism). save_function (`Callable`): The function to use to save the state dictionary. Useful on distributed training like TPUs when one need to replace `torch.save` by another method. push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. <Tip warning={true}> Using `push_to_hub=True` will synchronize the repository you are pushing to with `save_directory`, which requires `save_directory` to be a local clone of the repo you are pushing to if it's an existing folder. Pass along `temp_dir=True` to use a temporary directory instead. </Tip> kwargs: Additional key word arguments passed along to the [`~file_utils.PushToHubMixin.push_to_hub`] method. """ if os.path.isfile(save_directory): logger.error(f"Provided path ({save_directory}) should be a directory, not a file") return if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo = self._create_or_get_repo(save_directory, **kwargs) os.makedirs(save_directory, exist_ok=True) # Only save the model itself if we are using distributed training model_to_save = unwrap_model(self) # save the string version of dtype to the config, e.g. convert torch.float32 => "float32" # we currently don't use this setting automatically, but may start to use with v5 dtype = get_parameter_dtype(model_to_save) model_to_save.config.torch_dtype = str(dtype).split(".")[1] # Attach architecture to the config model_to_save.config.architectures = [model_to_save.__class__.__name__] # Save the config if save_config: model_to_save.config.save_pretrained(save_directory) # Save the model if state_dict is None: state_dict = model_to_save.state_dict() # Handle the case where some state_dict keys shouldn't be saved if self._keys_to_ignore_on_save is not None: for ignore_key in self._keys_to_ignore_on_save: if ignore_key in state_dict.keys(): del state_dict[ignore_key] # If we save using the predefined names, we can load using `from_pretrained` output_model_file = os.path.join(save_directory, WEIGHTS_NAME) save_function(state_dict, output_model_file) logger.info(f"Model weights saved in {output_model_file}") if push_to_hub: url = self._push_to_hub(repo, commit_message=commit_message) logger.info(f"Model pushed to the hub in this commit: {url}") @classmethod def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs): r""" Instantiate a pretrained pytorch model from a pre-trained model configuration. The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train the model, you should first set it back in training mode with `model.train()`. The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task. The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those weights are discarded. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*): Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - A path to a *directory* containing model weights saved using [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In this case, `from_tf` should be set to `True` and a configuration object should be provided as `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. - A path or url to a model folder containing a *flax checkpoint file* in *.msgpack* format (e.g, `./flax_model/` containing `flax_model.msgpack`). In this case, `from_flax` should be set to `True`. - `None` if you are both providing the configuration and state dictionary (resp. with keyword arguments `config` and `state_dict`). model_args (sequence of positional arguments, *optional*): All remaining positional arguments will be passed to the underlying model's `__init__` method. config (`Union[PretrainedConfig, str, os.PathLike]`, *optional*): Can be either: - an instance of a class derived from [`PretrainedConfig`], - a string or path valid as input to [`~PretrainedConfig.from_pretrained`]. Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when: - The model is a model provided by the library (loaded with the *model id* string of a pretrained model). - The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the save directory. - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory. state_dict (`Dict[str, torch.Tensor]`, *optional*): A state dictionary to use instead of a state dictionary loaded from saved weights file. This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using [`~PreTrainedModel.save_pretrained`] and [`~PreTrainedModel.from_pretrained`] is not a simpler option. cache_dir (`Union[str, os.PathLike]`, *optional*): Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. from_tf (`bool`, *optional*, defaults to `False`): Load the model weights from a TensorFlow checkpoint save file (see docstring of `pretrained_model_name_or_path` argument). from_flax (`bool`, *optional*, defaults to `False`): Load the model weights from a Flax checkpoint save file (see docstring of `pretrained_model_name_or_path` argument). ignore_mismatched_sizes (`bool`, *optional*, defaults to `False`): Whether or not to raise an error if some of the weights from the checkpoint do not have the same size as the weights of the model (if for instance, you are instantiating a model with 10 labels from a checkpoint with 3 labels). force_download (`bool`, *optional*, defaults to `False`): Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. resume_download (`bool`, *optional*, defaults to `False`): Whether or not to delete incompletely received files. Will attempt to resume the download if such a file exists. proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. output_loading_info(`bool`, *optional*, defaults to `False`): Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. local_files_only(`bool`, *optional*, defaults to `False`): Whether or not to only look at local files (i.e., do not try to download the model). use_auth_token (`str` or *bool*, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated when running `transformers-cli login` (stored in `~/.huggingface`). revision(`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. mirror(`str`, *optional*): Mirror source to accelerate downloads in China. If you are from China and have an accessibility problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety. Please refer to the mirror site for more information. _fast_init(`bool`, *optional*, defaults to ```True`): Whether or not to disable fast initialization. low_cpu_mem_usage(`bool``, *optional*, defaults to ```False`): Tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model. This is an experimental feature and a subject to change at any moment. torch_dtype (`str` or `torch.dtype`, *optional*): Override the default `torch.dtype` and load the model under this dtype. If `"auto"` is passed the dtype will be automatically derived from the model's weights. <Tip warning={true}> One should only disable *_fast_init* to ensure backwards compatibility with `transformers.__version__ < 4.6.0` for seeded model initialization. This argument will be removed at the next major version. See [pull request 11471](https://github.com/huggingface/transformers/pull/11471) for more information. </Tip> kwargs (remaining dictionary of keyword arguments, *optional*): Can be used to update the configuration object (after it being loaded) and initiate the model (e.g., `output_attentions=True`). Behaves differently depending on whether a `config` is provided or automatically loaded: - If a configuration is provided with `config`, `**kwargs` will be directly passed to the underlying model's `__init__` method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided, `kwargs` will be first passed to the configuration class initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that corresponds to a configuration attribute will be used to override said attribute with the supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model's `__init__` function. <Tip> Passing `use_auth_token=True`` is required when you want to use a private model. </Tip> <Tip> Activate the special ["offline-mode"](https://huggingface.co/transformers/installation.html#offline-mode) to use this method in a firewalled environment. </Tip> Examples: ```python >>> from transformers import BertConfig, BertModel >>> # Download model and configuration from huggingface.co and cache. >>> model = BertModel.from_pretrained("bert-base-uncased") >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable). >>> model = BertModel.from_pretrained("./test/saved_model/") >>> # Update configuration during loading. >>> model = BertModel.from_pretrained("bert-base-uncased", output_attentions=True) >>> assert model.config.output_attentions == True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower, for example purposes, not runnable). >>> config = BertConfig.from_json_file("./tf_model/my_tf_model_config.json") >>> model = BertModel.from_pretrained("./tf_model/my_tf_checkpoint.ckpt.index", from_tf=True, config=config) >>> # Loading from a Flax checkpoint file instead of a PyTorch model (slower) >>> model = BertModel.from_pretrained("bert-base-uncased", from_flax=True) ```""" config = kwargs.pop("config", None) state_dict = kwargs.pop("state_dict", None) cache_dir = kwargs.pop("cache_dir", None) from_tf = kwargs.pop("from_tf", False) from_flax = kwargs.pop("from_flax", False) ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False) force_download = kwargs.pop("force_download", False) resume_download = kwargs.pop("resume_download", False) proxies = kwargs.pop("proxies", None) output_loading_info = kwargs.pop("output_loading_info", False) local_files_only = kwargs.pop("local_files_only", False) use_auth_token = kwargs.pop("use_auth_token", None) revision = kwargs.pop("revision", None) mirror = kwargs.pop("mirror", None) from_pipeline = kwargs.pop("_from_pipeline", None) from_auto_class = kwargs.pop("_from_auto", False) _fast_init = kwargs.pop("_fast_init", True) torch_dtype = kwargs.pop("torch_dtype", None) low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", False) from_pt = not (from_tf | from_flax) user_agent = {"file_type": "model", "framework": "pytorch", "from_auto_class": from_auto_class} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline if is_offline_mode() and not local_files_only: logger.info("Offline mode: forcing local_files_only=True") local_files_only = True # Load config if we don't provide a configuration if not isinstance(config, PretrainedConfig): config_path = config if config is not None else pretrained_model_name_or_path config, model_kwargs = cls.config_class.from_pretrained( config_path, cache_dir=cache_dir, return_unused_kwargs=True, force_download=force_download, resume_download=resume_download, proxies=proxies, local_files_only=local_files_only, use_auth_token=use_auth_token, revision=revision, _from_auto=from_auto_class, _from_pipeline=from_pipeline, **kwargs, ) else: model_kwargs = kwargs # Load model if pretrained_model_name_or_path is not None: pretrained_model_name_or_path = str(pretrained_model_name_or_path) if os.path.isdir(pretrained_model_name_or_path): if from_tf and os.path.isfile(os.path.join(pretrained_model_name_or_path, TF_WEIGHTS_NAME + ".index")): # Load from a TF 1.0 checkpoint in priority if from_tf archive_file = os.path.join(pretrained_model_name_or_path, TF_WEIGHTS_NAME + ".index") elif from_tf and os.path.isfile(os.path.join(pretrained_model_name_or_path, TF2_WEIGHTS_NAME)): # Load from a TF 2.0 checkpoint in priority if from_tf archive_file = os.path.join(pretrained_model_name_or_path, TF2_WEIGHTS_NAME) elif from_flax and os.path.isfile(os.path.join(pretrained_model_name_or_path, FLAX_WEIGHTS_NAME)): # Load from a Flax checkpoint in priority if from_flax archive_file = os.path.join(pretrained_model_name_or_path, FLAX_WEIGHTS_NAME) elif os.path.isfile(os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)): # Load from a PyTorch checkpoint archive_file = os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME) # At this stage we don't have a weight file so we will raise an error. elif os.path.isfile( os.path.join(pretrained_model_name_or_path, TF_WEIGHTS_NAME + ".index") ) or os.path.isfile(os.path.join(pretrained_model_name_or_path, TF2_WEIGHTS_NAME)): raise EnvironmentError( f"Error no file named {WEIGHTS_NAME} found in directory {pretrained_model_name_or_path} but " "there is a file for TensorFlow weights. Use `from_tf=True` to load this model from those " "weights." ) elif os.path.join(pretrained_model_name_or_path, FLAX_WEIGHTS_NAME): raise EnvironmentError( f"Error no file named {WEIGHTS_NAME} found in directory {pretrained_model_name_or_path} but " "there is a file for Flax weights. Use `from_flax=True` to load this model from those " "weights." ) else: raise EnvironmentError( f"Error no file named {WEIGHTS_NAME}, {TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME + '.index'} or " f"{FLAX_WEIGHTS_NAME} found in directory {pretrained_model_name_or_path}." ) elif os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path): archive_file = pretrained_model_name_or_path elif os.path.isfile(pretrained_model_name_or_path + ".index"): if not from_tf: raise ValueError( f"We found a TensorFlow checkpoint at {pretrained_model_name_or_path + '.index'}, please set " "from_tf to True to load from this checkpoint." ) archive_file = pretrained_model_name_or_path + ".index" else: # set correct filename if from_tf: filename = TF2_WEIGHTS_NAME elif from_flax: filename = FLAX_WEIGHTS_NAME else: filename = WEIGHTS_NAME archive_file = hf_bucket_url( pretrained_model_name_or_path, filename=filename, revision=revision, mirror=mirror, ) try: # Load from URL or cache if already cached resolved_archive_file = cached_path( archive_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, local_files_only=local_files_only, use_auth_token=use_auth_token, user_agent=user_agent, ) except RepositoryNotFoundError as err: logger.error(err) raise EnvironmentError( f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier " "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a " "token having permission to this repo with `use_auth_token` or log in with `huggingface-cli " "login` and pass `use_auth_token=True`." ) except RevisionNotFoundError as err: logger.error(err) raise EnvironmentError( f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for " "this model name. Check the model page at " f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions." ) except EntryNotFoundError as err: logger.error(err) if filename == WEIGHTS_NAME: has_file_kwargs = { "revision": revision, "mirror": mirror, "proxies": proxies, "use_auth_token": use_auth_token, } if has_file(pretrained_model_name_or_path, TF2_WEIGHTS_NAME, **has_file_kwargs): raise EnvironmentError( f"{pretrained_model_name_or_path} does not appear to have a file named {WEIGHTS_NAME} but " "there is a file for TensorFlow weights. Use `from_tf=True` to load this model from those " "weights." ) elif has_file(pretrained_model_name_or_path, FLAX_WEIGHTS_NAME, **has_file_kwargs): raise EnvironmentError( f"{pretrained_model_name_or_path} does not appear to have a file named {WEIGHTS_NAME} but " "there is a file for Flax weights. Use `from_flax=True` to load this model from those " "weights." ) else: logger.error(err) raise EnvironmentError( f"{pretrained_model_name_or_path} does not appear to have a file named {WEIGHTS_NAME}, " f"{TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME} or {FLAX_WEIGHTS_NAME}." ) else: raise EnvironmentError( f"{pretrained_model_name_or_path} does not appear to have a file named {filename}." ) except HTTPError as err: logger.error(err) raise EnvironmentError( "We couldn't connect to 'https://huggingface.co/' to load this model and it looks like " f"{pretrained_model_name_or_path} is not the path to a directory conaining a a file named " f"{WEIGHTS_NAME}, {TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME} or {FLAX_WEIGHTS_NAME}.\n" "Checkout your internet connection or see how to run the library in offline mode at " "'https://huggingface.co/docs/transformers/installation#offline-mode'." ) except EnvironmentError as err: logger.error(err) raise EnvironmentError( f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from " "'https://huggingface.co/models', make sure you don't have a local directory with the same name. " f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory " f"containing a file named {WEIGHTS_NAME}, {TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME} or " f"{FLAX_WEIGHTS_NAME}." ) if resolved_archive_file == archive_file: logger.info(f"loading weights file {archive_file}") else: logger.info(f"loading weights file {archive_file} from cache at {resolved_archive_file}") else: resolved_archive_file = None # load pt weights early so that we know which dtype to init the model under if from_pt: if state_dict is None: try: state_dict = torch.load(resolved_archive_file, map_location="cpu") except Exception as e: try: with open(resolved_archive_file) as f: if f.read().startswith("version"): raise OSError( "You seem to have cloned a repository without having git-lfs installed. Please install " "git-lfs and run `git lfs install` followed by `git lfs pull` in the folder " "you cloned." ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise OSError( f"Unable to load weights from pytorch checkpoint file for '{pretrained_model_name_or_path}' " f"at '{resolved_archive_file}'. " "If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True." ) # set dtype to instantiate the model under: # 1. If torch_dtype is not None, we use that dtype # 2. If torch_dtype is "auto", we auto-detect dtype from the loaded state_dict, by checking its first # weights entry - we assume all weights are of the same dtype # we also may have config.torch_dtype available, but we won't rely on it till v5 dtype_orig = None if torch_dtype is not None: if isinstance(torch_dtype, str): if torch_dtype == "auto": torch_dtype = next(iter(state_dict.values())).dtype else: raise ValueError( f"`torch_dtype` can be either a `torch.dtype` or `auto`, but received {torch_dtype}" ) dtype_orig = cls._set_default_torch_dtype(torch_dtype) if low_cpu_mem_usage: # save the keys loaded_state_dict_keys = [k for k in state_dict.keys()] del state_dict # free CPU memory - will reload again later config.name_or_path = pretrained_model_name_or_path # Instantiate model. if is_deepspeed_zero3_enabled(): import deepspeed logger.info("Detected DeepSpeed ZeRO-3: activating zero.init() for this model") # this immediately partitions the model across all gpus, to avoid the overhead in time # and memory copying it on CPU or each GPU first with deepspeed.zero.Init(config_dict_or_path=deepspeed_config()): with no_init_weights(_enable=_fast_init): model = cls(config, *model_args, **model_kwargs) else: with no_init_weights(_enable=_fast_init): model = cls(config, *model_args, **model_kwargs) if from_pt: # restore default dtype if dtype_orig is not None: torch.set_default_dtype(dtype_orig) if from_tf: if resolved_archive_file.endswith(".index"): # Load from a TensorFlow 1.X checkpoint - provided by original authors model = cls.load_tf_weights(model, config, resolved_archive_file[:-6]) # Remove the '.index' else: # Load from our TensorFlow 2.0 checkpoints try: from .modeling_tf_pytorch_utils import load_tf2_checkpoint_in_pytorch_model model = load_tf2_checkpoint_in_pytorch_model(model, resolved_archive_file, allow_missing_keys=True) except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see " "https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions." ) raise elif from_flax: try: from .modeling_flax_pytorch_utils import load_flax_checkpoint_in_pytorch_model model = load_flax_checkpoint_in_pytorch_model(model, resolved_archive_file) except ImportError: logger.error( "Loading a Flax model in PyTorch, requires both PyTorch and Flax to be installed. Please see " "https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation instructions." ) raise elif from_pt: if low_cpu_mem_usage: cls._load_state_dict_into_model_low_mem(model, loaded_state_dict_keys, resolved_archive_file) else: model, missing_keys, unexpected_keys, mismatched_keys, error_msgs = cls._load_state_dict_into_model( model, state_dict, pretrained_model_name_or_path, ignore_mismatched_sizes=ignore_mismatched_sizes, _fast_init=_fast_init, ) # make sure token embedding weights are still tied if needed model.tie_weights() # Set model in evaluation mode to deactivate DropOut modules by default model.eval() if output_loading_info: loading_info = { "missing_keys": missing_keys, "unexpected_keys": unexpected_keys, "mismatched_keys": mismatched_keys, "error_msgs": error_msgs, } return model, loading_info return model @classmethod def _load_state_dict_into_model( cls, model, state_dict, pretrained_model_name_or_path, ignore_mismatched_sizes=False, _fast_init=True ): # Convert old format to new format if needed from a PyTorch state_dict old_keys = [] new_keys = [] for key in state_dict.keys(): new_key = None if "gamma" in key: new_key = key.replace("gamma", "weight") if "beta" in key: new_key = key.replace("beta", "bias") if new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key in zip(old_keys, new_keys): state_dict[new_key] = state_dict.pop(old_key) # Retrieve missing & unexpected_keys model_state_dict = model.state_dict() expected_keys = list(model_state_dict.keys()) loaded_keys = list(state_dict.keys()) prefix = model.base_model_prefix has_prefix_module = any(s.startswith(prefix) for s in loaded_keys) expects_prefix_module = any(s.startswith(prefix) for s in expected_keys) # key re-naming operations are never done on the keys # that are loaded, but always on the keys of the newly initialized model remove_prefix_from_model = not has_prefix_module and expects_prefix_module add_prefix_to_model = has_prefix_module and not expects_prefix_module if remove_prefix_from_model: expected_keys_not_prefixed = [s for s in expected_keys if not s.startswith(prefix)] expected_keys = [".".join(s.split(".")[1:]) if s.startswith(prefix) else s for s in expected_keys] elif add_prefix_to_model: expected_keys = [".".join([prefix, s]) for s in expected_keys] missing_keys = list(set(expected_keys) - set(loaded_keys)) unexpected_keys = list(set(loaded_keys) - set(expected_keys)) # Mistmatched keys contains tuples key/shape1/shape2 of weights in the checkpoint that have a shape not # matching the weights in the model. mismatched_keys = [] if ignore_mismatched_sizes: for checkpoint_key in loaded_keys: model_key = checkpoint_key if remove_prefix_from_model: # The model key starts with `prefix` but `checkpoint_key` doesn't so we add it. model_key = f"{prefix}.{checkpoint_key}" elif add_prefix_to_model: # The model key doesn't start with `prefix` but `checkpoint_key` does so we remove it. model_key = ".".join(checkpoint_key.split(".")[1:]) if ( model_key in model_state_dict and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape ): mismatched_keys.append( (checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape) ) del state_dict[checkpoint_key] # Some models may have keys that are not in the state by design, removing them before needlessly warning # the user. if cls._keys_to_ignore_on_load_missing is not None: for pat in cls._keys_to_ignore_on_load_missing: missing_keys = [k for k in missing_keys if re.search(pat, k) is None] if cls._keys_to_ignore_on_load_unexpected is not None: for pat in cls._keys_to_ignore_on_load_unexpected: unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None] if _fast_init: # retrieve unintialized modules and initialize uninitialized_modules = model.retrieve_modules_from_names( missing_keys, add_prefix=add_prefix_to_model, remove_prefix=remove_prefix_from_model ) for module in uninitialized_modules: model._init_weights(module) # copy state_dict so _load_from_state_dict can modify it metadata = getattr(state_dict, "_metadata", None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata error_msgs = [] # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants # so we need to apply the function recursively. def load(module: nn.Module, prefix=""): local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {}) args = (state_dict, prefix, local_metadata, True, [], [], error_msgs) if is_deepspeed_zero3_enabled(): import deepspeed # because zero3 puts placeholders in model params, this context # manager gathers (unpartitions) the params of the current layer, then loads from # the state dict and then re-partitions them again with deepspeed.zero.GatheredParameters(list(module.parameters(recurse=False)), modifier_rank=0): if torch.distributed.get_rank() == 0: module._load_from_state_dict(*args) else: module._load_from_state_dict(*args) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + ".") # Make sure we are able to load base models as well as derived models (with heads) start_prefix = "" model_to_load = model if not hasattr(model, cls.base_model_prefix) and has_prefix_module: start_prefix = cls.base_model_prefix + "." if hasattr(model, cls.base_model_prefix) and not has_prefix_module: model_to_load = getattr(model, cls.base_model_prefix) if any(key in expected_keys_not_prefixed for key in loaded_keys): raise ValueError( "The state dictionary of the model you are training to load is corrupted. Are you sure it was " "properly saved?" ) load(model_to_load, prefix=start_prefix) if len(error_msgs) > 0: error_msg = "\n\t".join(error_msgs) raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}") if len(unexpected_keys) > 0: logger.warning( f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when " f"initializing {model.__class__.__name__}: {unexpected_keys}\n" f"- This IS expected if you are initializing {model.__class__.__name__} from the checkpoint of a model trained on another task " f"or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n" f"- This IS NOT expected if you are initializing {model.__class__.__name__} from the checkpoint of a model that you expect " f"to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model)." ) else: logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n") if len(missing_keys) > 0: logger.warning( f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at {pretrained_model_name_or_path} " f"and are newly initialized: {missing_keys}\n" f"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference." ) elif len(mismatched_keys) == 0: logger.info( f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at {pretrained_model_name_or_path}.\n" f"If your task is similar to the task the model of the checkpoint was trained on, " f"you can already use {model.__class__.__name__} for predictions without further training." ) if len(mismatched_keys) > 0: mismatched_warning = "\n".join( [ f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated" for key, shape1, shape2 in mismatched_keys ] ) logger.warning( f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at {pretrained_model_name_or_path} " f"and are newly initialized because the shapes did not match:\n{mismatched_warning}\n" f"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference." ) return model, missing_keys, unexpected_keys, mismatched_keys, error_msgs def retrieve_modules_from_names(self, names, add_prefix=False, remove_prefix=False): module_keys = set([".".join(key.split(".")[:-1]) for key in names]) # torch.nn.ParameterList is a special case where two parameter keywords # are appended to the module name, *e.g.* bert.special_embeddings.0 module_keys = module_keys.union(set([".".join(key.split(".")[:-2]) for key in names if key[-1].isdigit()])) retrieved_modules = [] # retrieve all modules that has at least one missing weight name for name, module in self.named_modules(): if remove_prefix: name = ".".join(name.split(".")[1:]) if name.startswith(self.base_model_prefix) else name elif add_prefix: name = ".".join([self.base_model_prefix, name]) if len(name) > 0 else self.base_model_prefix if name in module_keys: retrieved_modules.append(module) return retrieved_modules @classmethod def _load_state_dict_into_model_low_mem(cls, model, loaded_state_dict_keys, resolved_archive_file): """ This is an experimental function that loads the model using ~1.x model size CPU memory Before it gets called we do: 1. save which state_dict keys we have 2. drop state_dict before model is created, since the latter takes 1x model size memory Here then we continue: 3. switch to the meta device all params/buffers that are going to be replaced from the loaded state_dict 4. load state_dict 2nd time 5. replace the params/buffers from the state_dict Currently, it doesn't handle missing_keys, unexpected_keys, mismatched_keys. It can't handle deepspeed. """ require_version_core("torch>=1.9") if is_deepspeed_zero3_enabled(): raise ValueError("low_cpu_mem_usage arg cannot be used with DeepSpeed ZeRO-3") # a helper util to find the last sub-module and the param/buffer name def find_submodule_and_param_name(model, long_key): split_key = long_key.split(".") submodule = model while len(split_key) > 1: if hasattr(submodule, split_key[0]): submodule = getattr(submodule, split_key[0]) del split_key[0] else: submodule = None break return submodule, split_key[0] # dematerialize param storage for keys that are going to be replaced by state_dict, by # putting those on the meta device for k in loaded_state_dict_keys: submodule, param_name = find_submodule_and_param_name(model, k) if submodule is not None: # selectively switch to the meta device only those params/buffers that will # be next replaced from state_dict. This a complex way to do p.to_("meta") # since we have no in-place to_ for tensors. new_val = getattr(submodule, param_name) if isinstance(new_val, torch.nn.Parameter): # isinstance returns False for Params on meta device, so switch after the check new_val = torch.nn.Parameter(new_val.to("meta")) else: new_val = new_val.to("meta") setattr(submodule, param_name, new_val) # only now can load state_dict state_dict = torch.load(resolved_archive_file, map_location="cpu") # materialize state_dict entries one by one on CPU for k in loaded_state_dict_keys: submodule, param_name = find_submodule_and_param_name(model, k) if submodule is not None: new_val = state_dict[k] if isinstance(getattr(submodule, param_name), torch.nn.Parameter): new_val = torch.nn.Parameter(new_val) setattr(submodule, param_name, new_val) del state_dict # To update the docstring, we need to copy the method, otherwise we change the original docstring. PreTrainedModel.push_to_hub = copy_func(PreTrainedModel.push_to_hub) PreTrainedModel.push_to_hub.__doc__ = PreTrainedModel.push_to_hub.__doc__.format( object="model", object_class="AutoModel", object_files="model checkpoint" ) class Conv1D(nn.Module): """ 1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Args: nf (`int`): The number of output features. nx (`int`): The number of input features. """ def __init__(self, nf, nx): super().__init__() self.nf = nf w = torch.empty(nx, nf) nn.init.normal_(w, std=0.02) self.weight = nn.Parameter(w) self.bias = nn.Parameter(torch.zeros(nf)) def forward(self, x): size_out = x.size()[:-1] + (self.nf,) x = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight) x = x.view(*size_out) return x class PoolerStartLogits(nn.Module): """ Compute SQuAD start logits from sequence hidden states. Args: config ([`PretrainedConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model. """ def __init__(self, config: PretrainedConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, 1) def forward( self, hidden_states: torch.FloatTensor, p_mask: Optional[torch.FloatTensor] = None ) -> torch.FloatTensor: """ Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`): The final hidden states of the model. p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*): Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token should be masked. Returns: `torch.FloatTensor`: The start logits for SQuAD. """ x = self.dense(hidden_states).squeeze(-1) if p_mask is not None: if get_parameter_dtype(self) == torch.float16: x = x * (1 - p_mask) - 65500 * p_mask else: x = x * (1 - p_mask) - 1e30 * p_mask return x class PoolerEndLogits(nn.Module): """ Compute SQuAD end logits from sequence hidden states. Args: config ([`PretrainedConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps` to use. """ def __init__(self, config: PretrainedConfig): super().__init__() self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size) self.activation = nn.Tanh() self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dense_1 = nn.Linear(config.hidden_size, 1) def forward( self, hidden_states: torch.FloatTensor, start_states: Optional[torch.FloatTensor] = None, start_positions: Optional[torch.LongTensor] = None, p_mask: Optional[torch.FloatTensor] = None, ) -> torch.FloatTensor: """ Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`): The final hidden states of the model. start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*): The hidden states of the first tokens for the labeled span. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): The position of the first token for the labeled span. p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*): Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token should be masked. <Tip> One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides `start_states`. </Tip> Returns: `torch.FloatTensor`: The end logits for SQuAD. """ assert ( start_states is not None or start_positions is not None ), "One of start_states, start_positions should be not None" if start_positions is not None: slen, hsz = hidden_states.shape[-2:] start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz) start_states = hidden_states.gather(-2, start_positions) # shape (bsz, 1, hsz) start_states = start_states.expand(-1, slen, -1) # shape (bsz, slen, hsz) x = self.dense_0(torch.cat([hidden_states, start_states], dim=-1)) x = self.activation(x) x = self.LayerNorm(x) x = self.dense_1(x).squeeze(-1) if p_mask is not None: if get_parameter_dtype(self) == torch.float16: x = x * (1 - p_mask) - 65500 * p_mask else: x = x * (1 - p_mask) - 1e30 * p_mask return x class PoolerAnswerClass(nn.Module): """ Compute SQuAD 2.0 answer class from classification and start tokens hidden states. Args: config ([`PretrainedConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model. """ def __init__(self, config): super().__init__() self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size) self.activation = nn.Tanh() self.dense_1 = nn.Linear(config.hidden_size, 1, bias=False) def forward( self, hidden_states: torch.FloatTensor, start_states: Optional[torch.FloatTensor] = None, start_positions: Optional[torch.LongTensor] = None, cls_index: Optional[torch.LongTensor] = None, ) -> torch.FloatTensor: """ Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`): The final hidden states of the model. start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*): The hidden states of the first tokens for the labeled span. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): The position of the first token for the labeled span. cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Position of the CLS token for each sentence in the batch. If `None`, takes the last token. <Tip> One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides `start_states`. </Tip> Returns: `torch.FloatTensor`: The SQuAD 2.0 answer class. """ # No dependency on end_feature so that we can obtain one single `cls_logits` for each sample. hsz = hidden_states.shape[-1] assert ( start_states is not None or start_positions is not None ), "One of start_states, start_positions should be not None" if start_positions is not None: start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz) start_states = hidden_states.gather(-2, start_positions).squeeze(-2) # shape (bsz, hsz) if cls_index is not None: cls_index = cls_index[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz) cls_token_state = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, hsz) else: cls_token_state = hidden_states[:, -1, :] # shape (bsz, hsz) x = self.dense_0(torch.cat([start_states, cls_token_state], dim=-1)) x = self.activation(x) x = self.dense_1(x).squeeze(-1) return x @dataclass class SquadHeadOutput(ModelOutput): """ Base class for outputs of question answering models using a [`~modeling_utils.SQuADHead`]. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided): Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses. start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided): Log probabilities for the top config.start_n_top start token possibilities (beam-search). start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided): Indices for the top config.start_n_top start token possibilities (beam-search). end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided): Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search). end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided): Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search). cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided): Log probabilities for the `is_impossible` label of the answers. """ loss: Optional[torch.FloatTensor] = None start_top_log_probs: Optional[torch.FloatTensor] = None start_top_index: Optional[torch.LongTensor] = None end_top_log_probs: Optional[torch.FloatTensor] = None end_top_index: Optional[torch.LongTensor] = None cls_logits: Optional[torch.FloatTensor] = None class SQuADHead(nn.Module): r""" A SQuAD head inspired by XLNet. Args: config ([`PretrainedConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps` to use. """ def __init__(self, config): super().__init__() self.start_n_top = config.start_n_top self.end_n_top = config.end_n_top self.start_logits = PoolerStartLogits(config) self.end_logits = PoolerEndLogits(config) self.answer_class = PoolerAnswerClass(config) @replace_return_docstrings(output_type=SquadHeadOutput, config_class=PretrainedConfig) def forward( self, hidden_states: torch.FloatTensor, start_positions: Optional[torch.LongTensor] = None, end_positions: Optional[torch.LongTensor] = None, cls_index: Optional[torch.LongTensor] = None, is_impossible: Optional[torch.LongTensor] = None, p_mask: Optional[torch.FloatTensor] = None, return_dict: bool = False, ) -> Union[SquadHeadOutput, Tuple[torch.FloatTensor]]: """ Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`): Final hidden states of the model on the sequence tokens. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Positions of the first token for the labeled span. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Positions of the last token for the labeled span. cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Position of the CLS token for each sentence in the batch. If `None`, takes the last token. is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Whether the question has a possible answer in the paragraph or not. p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*): Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token should be masked. return_dict (`bool`, *optional*, defaults to `False`): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. Returns: """ start_logits = self.start_logits(hidden_states, p_mask=p_mask) if start_positions is not None and end_positions is not None: # If we are on multi-GPU, let's remove the dimension added by batch splitting for x in (start_positions, end_positions, cls_index, is_impossible): if x is not None and x.dim() > 1: x.squeeze_(-1) # during training, compute the end logits based on the ground truth of the start position end_logits = self.end_logits(hidden_states, start_positions=start_positions, p_mask=p_mask) loss_fct = CrossEntropyLoss() start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if cls_index is not None and is_impossible is not None: # Predict answerability from the representation of CLS and START cls_logits = self.answer_class(hidden_states, start_positions=start_positions, cls_index=cls_index) loss_fct_cls = nn.BCEWithLogitsLoss() cls_loss = loss_fct_cls(cls_logits, is_impossible) # note(zhiliny): by default multiply the loss by 0.5 so that the scale is comparable to start_loss and end_loss total_loss += cls_loss * 0.5 return SquadHeadOutput(loss=total_loss) if return_dict else (total_loss,) else: # during inference, compute the end logits based on beam search bsz, slen, hsz = hidden_states.size() start_log_probs = nn.functional.softmax(start_logits, dim=-1) # shape (bsz, slen) start_top_log_probs, start_top_index = torch.topk( start_log_probs, self.start_n_top, dim=-1 ) # shape (bsz, start_n_top) start_top_index_exp = start_top_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz) start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz) start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz) hidden_states_expanded = hidden_states.unsqueeze(2).expand_as( start_states ) # shape (bsz, slen, start_n_top, hsz) p_mask = p_mask.unsqueeze(-1) if p_mask is not None else None end_logits = self.end_logits(hidden_states_expanded, start_states=start_states, p_mask=p_mask) end_log_probs = nn.functional.softmax(end_logits, dim=1) # shape (bsz, slen, start_n_top) end_top_log_probs, end_top_index = torch.topk( end_log_probs, self.end_n_top, dim=1 ) # shape (bsz, end_n_top, start_n_top) end_top_log_probs = end_top_log_probs.view(-1, self.start_n_top * self.end_n_top) end_top_index = end_top_index.view(-1, self.start_n_top * self.end_n_top) start_states = torch.einsum("blh,bl->bh", hidden_states, start_log_probs) cls_logits = self.answer_class(hidden_states, start_states=start_states, cls_index=cls_index) if not return_dict: return (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits) else: return SquadHeadOutput( start_top_log_probs=start_top_log_probs, start_top_index=start_top_index, end_top_log_probs=end_top_log_probs, end_top_index=end_top_index, cls_logits=cls_logits, ) class SequenceSummary(nn.Module): r""" Compute a single vector summary of a sequence hidden states. Args: config ([`PretrainedConfig`]): The config used by the model. Relevant arguments in the config class of the model are (refer to the actual config class of your model for the default values it uses): - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are: - `"last"` -- Take the last token hidden state (like XLNet) - `"first"` -- Take the first token hidden state (like Bert) - `"mean"` -- Take the mean of all tokens hidden states - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2) - `"attn"` -- Not implemented now, use multi-head attention - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction. - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes (otherwise to `config.hidden_size`). - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output, another string or `None` will add no activation. - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation. - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation. """ def __init__(self, config: PretrainedConfig): super().__init__() self.summary_type = getattr(config, "summary_type", "last") if self.summary_type == "attn": # We should use a standard multi-head attention module with absolute positional embedding for that. # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276 # We can probably just use the multi-head attention module of PyTorch >=1.1.0 raise NotImplementedError self.summary = Identity() if hasattr(config, "summary_use_proj") and config.summary_use_proj: if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0: num_classes = config.num_labels else: num_classes = config.hidden_size self.summary = nn.Linear(config.hidden_size, num_classes) activation_string = getattr(config, "summary_activation", None) self.activation: Callable = get_activation(activation_string) if activation_string else Identity() self.first_dropout = Identity() if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0: self.first_dropout = nn.Dropout(config.summary_first_dropout) self.last_dropout = Identity() if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0: self.last_dropout = nn.Dropout(config.summary_last_dropout) def forward( self, hidden_states: torch.FloatTensor, cls_index: Optional[torch.LongTensor] = None ) -> torch.FloatTensor: """ Compute a single vector summary of a sequence hidden states. Args: hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`): The hidden states of the last layer. cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*): Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token. Returns: `torch.FloatTensor`: The summary of the sequence hidden states. """ if self.summary_type == "last": output = hidden_states[:, -1] elif self.summary_type == "first": output = hidden_states[:, 0] elif self.summary_type == "mean": output = hidden_states.mean(dim=1) elif self.summary_type == "cls_index": if cls_index is None: cls_index = torch.full_like( hidden_states[..., :1, :], hidden_states.shape[-2] - 1, dtype=torch.long, ) else: cls_index = cls_index.unsqueeze(-1).unsqueeze(-1) cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),)) # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size) elif self.summary_type == "attn": raise NotImplementedError output = self.first_dropout(output) output = self.summary(output) output = self.activation(output) output = self.last_dropout(output) return output def unwrap_model(model: nn.Module) -> nn.Module: """ Recursively unwraps a model from potential containers (as used in distributed training). Args: model (`torch.nn.Module`): The model to unwrap. """ # since there could be multiple levels of wrapping, unwrap recursively if hasattr(model, "module"): return unwrap_model(model.module) else: return model def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: int = 0) -> nn.Linear: """ Prune a linear layer to keep only entries in index. Used to remove heads. Args: layer (`torch.nn.Linear`): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*, defaults to 0): The dimension on which to keep the indices. Returns: `torch.nn.Linear`: The pruned layer as a new layer with `requires_grad=True`. """ index = index.to(layer.weight.device) W = layer.weight.index_select(dim, index).clone().detach() if layer.bias is not None: if dim == 1: b = layer.bias.clone().detach() else: b = layer.bias[index].clone().detach() new_size = list(layer.weight.size()) new_size[dim] = len(index) new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None).to(layer.weight.device) new_layer.weight.requires_grad = False new_layer.weight.copy_(W.contiguous()) new_layer.weight.requires_grad = True if layer.bias is not None: new_layer.bias.requires_grad = False new_layer.bias.copy_(b.contiguous()) new_layer.bias.requires_grad = True return new_layer def prune_conv1d_layer(layer: Conv1D, index: torch.LongTensor, dim: int = 1) -> Conv1D: """ Prune a Conv1D layer to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights are transposed. Used to remove heads. Args: layer ([`~modeling_utils.Conv1D`]): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*, defaults to 1): The dimension on which to keep the indices. Returns: [`~modeling_utils.Conv1D`]: The pruned layer as a new layer with `requires_grad=True`. """ index = index.to(layer.weight.device) W = layer.weight.index_select(dim, index).clone().detach() if dim == 0: b = layer.bias.clone().detach() else: b = layer.bias[index].clone().detach() new_size = list(layer.weight.size()) new_size[dim] = len(index) new_layer = Conv1D(new_size[1], new_size[0]).to(layer.weight.device) new_layer.weight.requires_grad = False new_layer.weight.copy_(W.contiguous()) new_layer.weight.requires_grad = True new_layer.bias.requires_grad = False new_layer.bias.copy_(b.contiguous()) new_layer.bias.requires_grad = True return new_layer def prune_layer( layer: Union[nn.Linear, Conv1D], index: torch.LongTensor, dim: Optional[int] = None ) -> Union[nn.Linear, Conv1D]: """ Prune a Conv1D or linear layer to keep only entries in index. Used to remove heads. Args: layer (`Union[torch.nn.Linear, Conv1D]`): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*): The dimension on which to keep the indices. Returns: `torch.nn.Linear` or [`~modeling_utils.Conv1D`]: The pruned layer as a new layer with `requires_grad=True`. """ if isinstance(layer, nn.Linear): return prune_linear_layer(layer, index, dim=0 if dim is None else dim) elif isinstance(layer, Conv1D): return prune_conv1d_layer(layer, index, dim=1 if dim is None else dim) else: raise ValueError(f"Can't prune layer of class {layer.__class__}") def apply_chunking_to_forward( forward_fn: Callable[..., torch.Tensor], chunk_size: int, chunk_dim: int, *input_tensors ) -> torch.Tensor: """ This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension `chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory. If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result as directly applying `forward_fn` to `input_tensors`. Args: forward_fn (`Callable[..., torch.Tensor]`): The forward function of the model. chunk_size (`int`): The chunk size of a chunked tensor: `num_chunks = len(input_tensors[0]) / chunk_size`. chunk_dim (`int`): The dimension over which the `input_tensors` should be chunked. input_tensors (`Tuple[torch.Tensor]`): The input tensors of `forward_fn` which will be chunked Returns: `torch.Tensor`: A tensor with the same shape as the `forward_fn` would have given if applied`. Examples: ```python # rename the usual forward() fn to forward_chunk() def forward_chunk(self, hidden_states): hidden_states = self.decoder(hidden_states) return hidden_states # implement a chunked forward function def forward(self, hidden_states): return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states) ```""" assert len(input_tensors) > 0, f"{input_tensors} has to be a tuple/list of tensors" # inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility num_args_in_forward_chunk_fn = len(inspect.signature(forward_fn).parameters) if num_args_in_forward_chunk_fn != len(input_tensors): raise ValueError( f"forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(input_tensors)} input " "tensors are given" ) if chunk_size > 0: tensor_shape = input_tensors[0].shape[chunk_dim] for input_tensor in input_tensors: if input_tensor.shape[chunk_dim] != tensor_shape: raise ValueError( f"All input tenors have to be of the same shape: {tensor_shape}, " f"found shape {input_tensor.shape[chunk_dim]}" ) if input_tensors[0].shape[chunk_dim] % chunk_size != 0: raise ValueError( f"The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk " f"size {chunk_size}" ) num_chunks = input_tensors[0].shape[chunk_dim] // chunk_size # chunk input tensor into tuples input_tensors_chunks = tuple(input_tensor.chunk(num_chunks, dim=chunk_dim) for input_tensor in input_tensors) # apply forward fn to every tuple output_chunks = tuple(forward_fn(*input_tensors_chunk) for input_tensors_chunk in zip(*input_tensors_chunks)) # concatenate output at same dimension return torch.cat(output_chunks, dim=chunk_dim) return forward_fn(*input_tensors) def torch_int_div(tensor1, tensor2): """ A function that performs integer division across different versions of PyTorch. """ if version.parse(torch.__version__) < version.parse("1.8.0"): return tensor1 // tensor2 else: return torch.div(tensor1, tensor2, rounding_mode="floor")
117,076
46.747553
189
py
papa
papa-main/transformers/src/transformers/models/deberta/modeling_deberta.py
# coding=utf-8 # Copyright 2020 Microsoft and the Hugging Face Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch DeBERTa model.""" import math import os from collections.abc import Sequence import torch from torch import _softmax_backward_data, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutput, MaskedLMOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_deberta import DebertaConfig from ...modeling_utils import ( find_pruneable_heads_and_indices, prune_linear_layer, ) from ...papa_modules import FreezeExtractPoller, combine_static_and_dynamic_att, FreezeExtractPollerTokenClassification, mask_and_normalize logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "DebertaConfig" _TOKENIZER_FOR_DOC = "DebertaTokenizer" _CHECKPOINT_FOR_DOC = "microsoft/deberta-base" DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST = [ "microsoft/deberta-base", "microsoft/deberta-large", "microsoft/deberta-xlarge", "microsoft/deberta-base-mnli", "microsoft/deberta-large-mnli", "microsoft/deberta-xlarge-mnli", ] class ContextPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size) self.dropout = StableDropout(config.pooler_dropout) self.config = config def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. context_token = hidden_states[:, 0] context_token = self.dropout(context_token) pooled_output = self.dense(context_token) pooled_output = ACT2FN[self.config.pooler_hidden_act](pooled_output) return pooled_output @property def output_dim(self): return self.config.hidden_size class XSoftmax(torch.autograd.Function): """ Masked Softmax which is optimized for saving memory Args: input (`torch.tensor`): The input tensor that will apply softmax. mask (`torch.IntTensor`): The mask matrix where 0 indicate that element will be ignored in the softmax calculation. dim (int): The dimension that will apply softmax Example: ```python >>> import torch >>> from transformers.models.deberta.modeling_deberta import XSoftmax >>> # Make a tensor >>> x = torch.randn([4, 20, 100]) >>> # Create a mask >>> mask = (x > 0).int() >>> # Specify the dimension to apply softmax >>> dim = -1 >>> y = XSoftmax.apply(x, mask, dim) ```""" @staticmethod def forward(self, input, mask, dim): self.dim = dim rmask = ~(mask.bool()) output = input.masked_fill(rmask, float("-inf")) output = torch.softmax(output, self.dim) output.masked_fill_(rmask, 0) self.save_for_backward(output) return output @staticmethod def backward(self, grad_output): (output,) = self.saved_tensors inputGrad = _softmax_backward_data(grad_output, output, self.dim, output) return inputGrad, None, None @staticmethod def symbolic(g, self, mask, dim): import torch.onnx.symbolic_helper as sym_help from torch.onnx.symbolic_opset9 import masked_fill, softmax mask_cast_value = g.op("Cast", mask, to_i=sym_help.cast_pytorch_to_onnx["Long"]) r_mask = g.op( "Cast", g.op("Sub", g.op("Constant", value_t=torch.tensor(1, dtype=torch.int64)), mask_cast_value), to_i=sym_help.cast_pytorch_to_onnx["Byte"], ) output = masked_fill(g, self, r_mask, g.op("Constant", value_t=torch.tensor(float("-inf")))) output = softmax(g, output, dim) return masked_fill(g, output, r_mask, g.op("Constant", value_t=torch.tensor(0, dtype=torch.uint8))) class DropoutContext(object): def __init__(self): self.dropout = 0 self.mask = None self.scale = 1 self.reuse_mask = True def get_mask(input, local_context): if not isinstance(local_context, DropoutContext): dropout = local_context mask = None else: dropout = local_context.dropout dropout *= local_context.scale mask = local_context.mask if local_context.reuse_mask else None if dropout > 0 and mask is None: mask = (1 - torch.empty_like(input).bernoulli_(1 - dropout)).bool() if isinstance(local_context, DropoutContext): if local_context.mask is None: local_context.mask = mask return mask, dropout class XDropout(torch.autograd.Function): """Optimized dropout function to save computation and memory by using mask operation instead of multiplication.""" @staticmethod def forward(ctx, input, local_ctx): mask, dropout = get_mask(input, local_ctx) ctx.scale = 1.0 / (1 - dropout) if dropout > 0: ctx.save_for_backward(mask) return input.masked_fill(mask, 0) * ctx.scale else: return input @staticmethod def backward(ctx, grad_output): if ctx.scale > 1: (mask,) = ctx.saved_tensors return grad_output.masked_fill(mask, 0) * ctx.scale, None else: return grad_output, None class StableDropout(nn.Module): """ Optimized dropout module for stabilizing the training Args: drop_prob (float): the dropout probabilities """ def __init__(self, drop_prob): super().__init__() self.drop_prob = drop_prob self.count = 0 self.context_stack = None def forward(self, x): """ Call the module Args: x (`torch.tensor`): The input tensor to apply dropout """ if self.training and self.drop_prob > 0: return XDropout.apply(x, self.get_context()) return x def clear_context(self): self.count = 0 self.context_stack = None def init_context(self, reuse_mask=True, scale=1): if self.context_stack is None: self.context_stack = [] self.count = 0 for c in self.context_stack: c.reuse_mask = reuse_mask c.scale = scale def get_context(self): if self.context_stack is not None: if self.count >= len(self.context_stack): self.context_stack.append(DropoutContext()) ctx = self.context_stack[self.count] ctx.dropout = self.drop_prob self.count += 1 return ctx else: return self.drop_prob class DebertaLayerNorm(nn.Module): """LayerNorm module in the TF style (epsilon inside the square root).""" def __init__(self, size, eps=1e-12): super().__init__() self.weight = nn.Parameter(torch.ones(size)) self.bias = nn.Parameter(torch.zeros(size)) self.variance_epsilon = eps def forward(self, hidden_states): input_type = hidden_states.dtype hidden_states = hidden_states.float() mean = hidden_states.mean(-1, keepdim=True) variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True) hidden_states = (hidden_states - mean) / torch.sqrt(variance + self.variance_epsilon) hidden_states = hidden_states.to(input_type) y = self.weight * hidden_states + self.bias return y class DebertaSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = DebertaLayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class DebertaAttention(nn.Module): def __init__(self, config, layer_num=-1): super().__init__() self.self = DisentangledSelfAttention(config, layer_num=layer_num) self.output = DebertaSelfOutput(config) self.config = config self.static_pruned_heads = set() def prune_static_heads(self): # my pruning: def prune_bias(bias): b = bias[index].clone().detach() bias.requires_grad = False return b if self.self.num_static_heads == 0 or self.static_pruned_heads: return heads, index = find_pruneable_heads_and_indices( self.self.static_heads_indexes, self.self.num_attention_heads, self.self.attention_head_size, self.static_pruned_heads ) self.self.q_bias = nn.Parameter(prune_bias(self.self.q_bias)) if "c2p" in self.self.pos_att_type: self.self.pos_proj = prune_linear_layer(self.self.pos_proj, index) if "p2c" in self.self.pos_att_type: self.self.pos_q_proj = prune_linear_layer(self.self.pos_q_proj, index) heads, index = find_pruneable_heads_and_indices( self.self.static_heads_indexes, self.self.num_attention_heads, 1, self.static_pruned_heads ) self.self.query_indexes = self.self.query_indexes[index] self.self.key_indexes = self.self.key_indexes[index] self.static_pruned_heads = self.static_pruned_heads.union(self.self.static_heads_indexes) def forward( self, hidden_states, attention_mask, output_attentions=False, query_states=None, relative_pos=None, rel_embeddings=None, ): self_output = self.self( hidden_states, attention_mask, output_attentions, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if output_attentions: self_output, att_matrix = self_output if query_states is None: query_states = hidden_states attention_output = self.output(self_output, query_states) if output_attentions: return (attention_output, att_matrix) else: return attention_output # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Deberta class DebertaIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class DebertaOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = DebertaLayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class DebertaLayer(nn.Module): def __init__(self, config, layer_num=-1): super().__init__() self.attention = DebertaAttention(config, layer_num=layer_num) self.intermediate = DebertaIntermediate(config) self.output = DebertaOutput(config) def forward( self, hidden_states, attention_mask, query_states=None, relative_pos=None, rel_embeddings=None, output_attentions=False, ): attention_output = self.attention( hidden_states, attention_mask, output_attentions=output_attentions, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if output_attentions: attention_output, att_matrix = attention_output intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) if output_attentions: return (layer_output, att_matrix) else: return layer_output class DebertaEncoder(nn.Module): """Modified BertEncoder with relative position bias support""" def __init__(self, config): super().__init__() self.layer = nn.ModuleList([DebertaLayer(config, layer_num=l) for l in range(config.num_hidden_layers)]) self.relative_attention = getattr(config, "relative_attention", False) if self.relative_attention: self.max_relative_positions = getattr(config, "max_relative_positions", -1) if self.max_relative_positions < 1: self.max_relative_positions = config.max_position_embeddings self.rel_embeddings = nn.Embedding(self.max_relative_positions * 2, config.hidden_size) self.gradient_checkpointing = False def get_rel_embedding(self): rel_embeddings = self.rel_embeddings.weight if self.relative_attention else None return rel_embeddings def get_attention_mask(self, attention_mask): if attention_mask.dim() <= 2: extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) attention_mask = extended_attention_mask * extended_attention_mask.squeeze(-2).unsqueeze(-1) attention_mask = attention_mask.byte() elif attention_mask.dim() == 3: attention_mask = attention_mask.unsqueeze(1) return attention_mask def get_rel_pos(self, hidden_states, query_states=None, relative_pos=None): if self.relative_attention and relative_pos is None: q = query_states.size(-2) if query_states is not None else hidden_states.size(-2) relative_pos = build_relative_position(q, hidden_states.size(-2), hidden_states.device) return relative_pos def forward( self, hidden_states, attention_mask, output_hidden_states=True, output_attentions=False, query_states=None, relative_pos=None, return_dict=True, ): attention_mask = self.get_attention_mask(attention_mask) relative_pos = self.get_rel_pos(hidden_states, query_states, relative_pos) all_hidden_states = () if output_hidden_states else None all_attentions = () if output_attentions else None if isinstance(hidden_states, Sequence): next_kv = hidden_states[0] else: next_kv = hidden_states rel_embeddings = self.get_rel_embedding() for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if self.gradient_checkpointing and self.training: def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, output_attentions) return custom_forward hidden_states = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), next_kv, attention_mask, query_states, relative_pos, rel_embeddings, ) else: hidden_states = layer_module( next_kv, attention_mask, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, output_attentions=output_attentions, ) if output_attentions: hidden_states, att_m = hidden_states if query_states is not None: query_states = hidden_states if isinstance(hidden_states, Sequence): next_kv = hidden_states[i + 1] if i + 1 < len(self.layer) else None else: next_kv = hidden_states if output_attentions: all_attentions = all_attentions + (att_m,) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions ) def build_relative_position(query_size, key_size, device): """ Build relative position according to the query and key We assume the absolute position of query \\(P_q\\) is range from (0, query_size) and the absolute position of key \\(P_k\\) is range from (0, key_size), The relative positions from query to key is \\(R_{q \\rightarrow k} = P_q - P_k\\) Args: query_size (int): the length of query key_size (int): the length of key Return: `torch.LongTensor`: A tensor with shape [1, query_size, key_size] """ q_ids = torch.arange(query_size, dtype=torch.long, device=device) k_ids = torch.arange(key_size, dtype=torch.long, device=device) rel_pos_ids = q_ids[:, None] - k_ids.view(1, -1).repeat(query_size, 1) rel_pos_ids = rel_pos_ids[:query_size, :] rel_pos_ids = rel_pos_ids.unsqueeze(0) return rel_pos_ids @torch.jit.script def c2p_dynamic_expand(c2p_pos, query_layer, relative_pos): return c2p_pos.expand([query_layer.size(0), query_layer.size(1), query_layer.size(2), relative_pos.size(-1)]) @torch.jit.script def p2c_dynamic_expand(c2p_pos, query_layer, key_layer): return c2p_pos.expand([query_layer.size(0), query_layer.size(1), key_layer.size(-2), key_layer.size(-2)]) @torch.jit.script def pos_dynamic_expand(pos_index, p2c_att, key_layer): return pos_index.expand(p2c_att.size()[:2] + (pos_index.size(-2), key_layer.size(-2))) class DisentangledSelfAttention(nn.Module): """ Disentangled self-attention module Parameters: config (`str`): A model config class instance with the configuration to build a new model. The schema is similar to *BertConfig*, for more details, please refer [`DebertaConfig`] """ def __init__(self, config, layer_num=-1): super().__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.in_proj = nn.Linear(config.hidden_size, self.all_head_size * 3, bias=False) self.q_bias = nn.Parameter(torch.zeros((self.all_head_size), dtype=torch.float)) self.v_bias = nn.Parameter(torch.zeros((self.all_head_size), dtype=torch.float)) self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else [] self.relative_attention = getattr(config, "relative_attention", False) self.talking_head = getattr(config, "talking_head", False) if self.talking_head: self.head_logits_proj = nn.Linear(config.num_attention_heads, config.num_attention_heads, bias=False) self.head_weights_proj = nn.Linear(config.num_attention_heads, config.num_attention_heads, bias=False) if self.relative_attention: self.max_relative_positions = getattr(config, "max_relative_positions", -1) if self.max_relative_positions < 1: self.max_relative_positions = config.max_position_embeddings self.pos_dropout = StableDropout(config.hidden_dropout_prob) if "c2p" in self.pos_att_type: self.pos_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=False) if "p2c" in self.pos_att_type: self.pos_q_proj = nn.Linear(config.hidden_size, self.all_head_size) self.num_static_heads = 0 if config.static_heads and layer_num in config.static_heads['heads']: self.query_indexes, self.key_indexes, self.value_indexes = [ torch.Tensor([list(range(head * self.attention_head_size * 3 + k * self.attention_head_size, head * self.attention_head_size * 3 + (k+1) * self.attention_head_size)) for head in range(self.num_attention_heads)]).type(torch.long) for k in range(3)] exp_heads = sorted(config.static_heads['heads'][layer_num]) self.num_static_heads = len(exp_heads) self.static_heads_indexes = exp_heads all_static_heads = torch.load(os.path.join(config.static_heads['heads_dir'], 'avgs.pt')) self.static_heads_content = nn.Parameter(torch.stack([all_static_heads[layer_num, head] for head in self.static_heads_indexes]), requires_grad=True) self.sort_calculating = False if config.sort_calculating: self.sort_calculating = True all_static_heads = torch.load(os.path.join(config.sort_calculating['heads_dir'], 'avgs.pt')) self.static_heads_content = nn.Parameter(torch.stack([all_static_heads[layer_num, head] for head in range(config.num_attention_heads)]), requires_grad=True) lambdas = torch.zeros([self.num_attention_heads]) lambdas = torch.unsqueeze(torch.unsqueeze(torch.unsqueeze(lambdas, 0), -1), -1) self.lambdas = nn.Parameter(lambdas, requires_grad=True) self.dropout = StableDropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, -1) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def transpose_for_scores_KQ(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads - self.num_static_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states, attention_mask, output_attentions=False, query_states=None, relative_pos=None, rel_embeddings=None, ): """ Call the module Args: hidden_states (`torch.FloatTensor`): Input states to the module usually the output from previous layer, it will be the Q,K and V in *Attention(Q,K,V)* attention_mask (`torch.ByteTensor`): An attention mask matrix of shape [*B*, *N*, *N*] where *B* is the batch size, *N* is the maximum sequence length in which element [i,j] = *1* means the *i* th token in the input can attend to the *j* th token. output_attentions (`bool`, optional): Whether return the attention matrix. query_states (`torch.FloatTensor`, optional): The *Q* state in *Attention(Q,K,V)*. relative_pos (`torch.LongTensor`): The relative position encoding between the tokens in the sequence. It's of shape [*B*, *N*, *N*] with values ranging in [*-max_relative_positions*, *max_relative_positions*]. rel_embeddings (`torch.FloatTensor`): The embedding of relative distances. It's a tensor of shape [\\(2 \\times \\text{max_relative_positions}\\), *hidden_size*]. """ if query_states is None: if self.num_static_heads == 0: qp = self.in_proj(hidden_states) # .split(self.all_head_size, dim=-1) query_layer, key_layer, value_layer = self.transpose_for_scores(qp).chunk(3, dim=-1) else: query_layer = self.transpose_for_scores_KQ(torch.matmul(hidden_states, self.in_proj.weight[self.query_indexes.flatten()].t())) key_layer = self.transpose_for_scores_KQ(torch.matmul(hidden_states, self.in_proj.weight[self.key_indexes.flatten()].t())) value_layer = self.transpose_for_scores(torch.matmul(hidden_states, self.in_proj.weight[self.value_indexes.flatten()].t())) else: def linear(w, b, x): if b is not None: return torch.matmul(x, w.t()) + b.t() else: return torch.matmul(x, w.t()) # + b.t() ws = self.in_proj.weight.chunk(self.num_attention_heads * 3, dim=0) qkvw = [torch.cat([ws[i * 3 + k] for i in range(self.num_attention_heads)], dim=0) for k in range(3)] qkvb = [None] * 3 q = linear(qkvw[0], qkvb[0], query_states) k, v = [linear(qkvw[i], qkvb[i], hidden_states) for i in range(1, 3)] query_layer, key_layer, value_layer = [self.transpose_for_scores(x) for x in [q, k, v]] query_layer = query_layer + self.transpose_for_scores_KQ(self.q_bias[None, None, :]) value_layer = value_layer + self.transpose_for_scores(self.v_bias[None, None, :]) rel_att = None # Take the dot product between "query" and "key" to get the raw attention scores. scale_factor = 1 + len(self.pos_att_type) scale = math.sqrt(query_layer.size(-1) * scale_factor) query_layer = query_layer / scale attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) if self.relative_attention: rel_embeddings = self.pos_dropout(rel_embeddings) rel_att = self.disentangled_att_bias(query_layer, key_layer, relative_pos, rel_embeddings, scale_factor) if rel_att is not None: attention_scores = attention_scores + rel_att # bxhxlxd if self.talking_head: attention_scores = self.head_logits_proj(attention_scores.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) attention_probs = XSoftmax.apply(attention_scores, attention_mask, -1) if self.num_static_heads > 0: attention_probs = combine_static_and_dynamic_att(attention_probs, self.static_heads_content, attention_mask, self.static_heads_indexes, self.num_attention_heads) if self.sort_calculating: cur_lambdas = torch.sigmoid(self.lambdas) attention_probs = cur_lambdas * attention_probs + (1-cur_lambdas) * mask_and_normalize(self.static_heads_content, attention_mask) attention_probs = self.dropout(attention_probs) if self.talking_head: attention_probs = self.head_weights_proj(attention_probs.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (-1,) context_layer = context_layer.view(*new_context_layer_shape) if output_attentions: return (context_layer, attention_probs) else: return context_layer def disentangled_att_bias(self, query_layer, key_layer, relative_pos, rel_embeddings, scale_factor): if relative_pos is None: q = query_layer.size(-2) relative_pos = build_relative_position(q, key_layer.size(-2), query_layer.device) if relative_pos.dim() == 2: relative_pos = relative_pos.unsqueeze(0).unsqueeze(0) elif relative_pos.dim() == 3: relative_pos = relative_pos.unsqueeze(1) # bxhxqxk elif relative_pos.dim() != 4: raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}") att_span = min(max(query_layer.size(-2), key_layer.size(-2)), self.max_relative_positions) relative_pos = relative_pos.long().to(query_layer.device) rel_embeddings = rel_embeddings[ self.max_relative_positions - att_span : self.max_relative_positions + att_span, : ].unsqueeze(0) score = 0 # content->position if "c2p" in self.pos_att_type: pos_key_layer = self.pos_proj(rel_embeddings) pos_key_layer = self.transpose_for_scores_KQ(pos_key_layer) c2p_att = torch.matmul(query_layer, pos_key_layer.transpose(-1, -2)) c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1) c2p_att = torch.gather(c2p_att, dim=-1, index=c2p_dynamic_expand(c2p_pos, query_layer, relative_pos)) score += c2p_att # position->content if "p2c" in self.pos_att_type: pos_query_layer = self.pos_q_proj(rel_embeddings) pos_query_layer = self.transpose_for_scores_KQ(pos_query_layer) pos_query_layer /= math.sqrt(pos_query_layer.size(-1) * scale_factor) if query_layer.size(-2) != key_layer.size(-2): r_pos = build_relative_position(key_layer.size(-2), key_layer.size(-2), query_layer.device) else: r_pos = relative_pos p2c_pos = torch.clamp(-r_pos + att_span, 0, att_span * 2 - 1) p2c_att = torch.matmul(key_layer, pos_query_layer.transpose(-1, -2)) p2c_att = torch.gather( p2c_att, dim=-1, index=p2c_dynamic_expand(p2c_pos, query_layer, key_layer) ).transpose(-1, -2) if query_layer.size(-2) != key_layer.size(-2): pos_index = relative_pos[:, :, :, 0].unsqueeze(-1) p2c_att = torch.gather(p2c_att, dim=-2, index=pos_dynamic_expand(pos_index, p2c_att, key_layer)) score += p2c_att return score class DebertaEmbeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings.""" def __init__(self, config): super().__init__() pad_token_id = getattr(config, "pad_token_id", 0) self.embedding_size = getattr(config, "embedding_size", config.hidden_size) self.word_embeddings = nn.Embedding(config.vocab_size, self.embedding_size, padding_idx=pad_token_id) self.position_biased_input = getattr(config, "position_biased_input", True) if not self.position_biased_input: self.position_embeddings = None else: self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.embedding_size) if config.type_vocab_size > 0: self.token_type_embeddings = nn.Embedding(config.type_vocab_size, self.embedding_size) if self.embedding_size != config.hidden_size: self.embed_proj = nn.Linear(self.embedding_size, config.hidden_size, bias=False) self.LayerNorm = DebertaLayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) def forward(self, input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] if position_ids is None: position_ids = self.position_ids[:, :seq_length] if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) if self.position_embeddings is not None: position_embeddings = self.position_embeddings(position_ids.long()) else: position_embeddings = torch.zeros_like(inputs_embeds) embeddings = inputs_embeds if self.position_biased_input: embeddings += position_embeddings if self.config.type_vocab_size > 0: token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings += token_type_embeddings if self.embedding_size != self.config.hidden_size: embeddings = self.embed_proj(embeddings) embeddings = self.LayerNorm(embeddings) if mask is not None: if mask.dim() != embeddings.dim(): if mask.dim() == 4: mask = mask.squeeze(1).squeeze(1) mask = mask.unsqueeze(2) mask = mask.to(embeddings.dtype) embeddings = embeddings * mask embeddings = self.dropout(embeddings) return embeddings class DebertaPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = DebertaConfig base_model_prefix = "deberta" _keys_to_ignore_on_load_missing = ["position_ids"] _keys_to_ignore_on_load_unexpected = ["position_embeddings"] supports_gradient_checkpointing = True def _init_weights(self, module): """Initialize the weights.""" if isinstance(module, nn.Linear): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, DebertaEncoder): module.gradient_checkpointing = value DEBERTA_START_DOCSTRING = r""" The DeBERTa model was proposed in [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. It's build on top of BERT/RoBERTa with two improvements, i.e. disentangled attention and enhanced mask decoder. With those two improvements, it out perform BERT/RoBERTa on a majority of tasks with 80GB pretraining data. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.``` Parameters: config ([`DebertaConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ DEBERTA_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `({0})`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`DebertaTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-ids) position_ids (`torch.LongTensor` of shape `({0})`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert *input_ids* indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.", DEBERTA_START_DOCSTRING, ) class DebertaModel(DebertaPreTrainedModel): def __init__(self, config): super().__init__(config) self.embeddings = DebertaEmbeddings(config) self.encoder = DebertaEncoder(config) self.z_steps = 0 self.config = config # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, new_embeddings): self.embeddings.word_embeddings = new_embeddings def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ raise NotImplementedError("The prune function is not implemented in DeBERTa model.") def _prune_static_heads(self): for layer in range(len(self.encoder.layer)): self.encoder.layer[layer].attention.prune_static_heads() @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: attention_mask = torch.ones(input_shape, device=device) if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) embedding_output = self.embeddings( input_ids=input_ids, token_type_ids=token_type_ids, position_ids=position_ids, mask=attention_mask, inputs_embeds=inputs_embeds, ) encoder_outputs = self.encoder( embedding_output, attention_mask, output_hidden_states=True, output_attentions=output_attentions, return_dict=return_dict, ) encoded_layers = encoder_outputs[1] if self.z_steps > 1: hidden_states = encoded_layers[-2] layers = [self.encoder.layer[-1] for _ in range(self.z_steps)] query_states = encoded_layers[-1] rel_embeddings = self.encoder.get_rel_embedding() attention_mask = self.encoder.get_attention_mask(attention_mask) rel_pos = self.encoder.get_rel_pos(embedding_output) for layer in layers[1:]: query_states = layer( hidden_states, attention_mask, output_attentions=False, query_states=query_states, relative_pos=rel_pos, rel_embeddings=rel_embeddings, ) encoded_layers.append(query_states) sequence_output = encoded_layers[-1] if not return_dict: return (sequence_output,) + encoder_outputs[(1 if output_hidden_states else 2) :] return BaseModelOutput( last_hidden_state=sequence_output, hidden_states=encoder_outputs.hidden_states if output_hidden_states else None, attentions=encoder_outputs.attentions, ) @add_start_docstrings("""DeBERTa Model with a `language modeling` head on top.""", DEBERTA_START_DOCSTRING) class DebertaForMaskedLM(DebertaPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] def __init__(self, config): super().__init__(config) self.deberta = DebertaModel(config) self.cls = DebertaOnlyMLMHead(config) self.use_freeze_extract_token_predictor = config.use_freeze_extract_pooler # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.use_freeze_extract_token_predictor, return_dict=return_dict, ) sequence_output = outputs[1] if self.use_freeze_extract_token_predictor else outputs[0] prediction_scores = self.cls(sequence_output) masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() # -100 index = padding token masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (prediction_scores,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) # copied from transformers.models.bert.BertPredictionHeadTransform with bert -> deberta class DebertaPredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states # copied from transformers.models.bert.BertLMPredictionHead with bert -> deberta class DebertaLMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = DebertaPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states # copied from transformers.models.bert.BertOnlyMLMHead with bert -> deberta class DebertaOnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = FreezeExtractPollerTokenClassification(config, mlm=True) if config.use_freeze_extract_pooler else DebertaLMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores @add_start_docstrings( """ DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """, DEBERTA_START_DOCSTRING, ) class DebertaForSequenceClassification(DebertaPreTrainedModel): def __init__(self, config): super().__init__(config) num_labels = getattr(config, "num_labels", 2) self.num_labels = num_labels self.deberta = DebertaModel(config) self.pooler = FreezeExtractPoller(config) if config.use_freeze_extract_pooler else ContextPooler(config) output_dim = self.pooler.output_dim self.classifier = nn.Linear(output_dim, num_labels) drop_out = getattr(config, "cls_dropout", None) drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out self.dropout = StableDropout(drop_out) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.deberta.get_input_embeddings() def set_input_embeddings(self, new_embeddings): self.deberta.set_input_embeddings(new_embeddings) @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.config.use_freeze_extract_pooler, return_dict=return_dict, ) encoder_layer = outputs[0] if self.config.use_freeze_extract_pooler: encoder_layer = outputs[1] pooled_output = self.pooler(encoder_layer, attention_mask) else: pooled_output = self.pooler(encoder_layer) pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: # regression task loss_fn = nn.MSELoss() logits = logits.view(-1).to(labels.dtype) loss = loss_fn(logits, labels.view(-1)) elif labels.dim() == 1 or labels.size(-1) == 1: label_index = (labels >= 0).nonzero() labels = labels.long() if label_index.size(0) > 0: labeled_logits = torch.gather( logits, 0, label_index.expand(label_index.size(0), logits.size(1)) ) labels = torch.gather(labels, 0, label_index.view(-1)) loss_fct = CrossEntropyLoss() loss = loss_fct(labeled_logits.view(-1, self.num_labels).float(), labels.view(-1)) else: loss = torch.tensor(0).to(logits) else: log_softmax = nn.LogSoftmax(-1) loss = -((log_softmax(logits) * labels).sum(-1)).mean() elif self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(logits.squeeze(), labels.squeeze()) else: loss = loss_fct(logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(logits, labels) if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=outputs.attentions ) @add_start_docstrings( """ DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """, DEBERTA_START_DOCSTRING, ) class DebertaForTokenClassification(DebertaPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.deberta = DebertaModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.use_freeze_extract_token_class = config.use_freeze_extract_pooler self.classifier = FreezeExtractPollerTokenClassification(config) if self.use_freeze_extract_token_class else nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.use_freeze_extract_token_class, return_dict=return_dict, ) if not self.use_freeze_extract_token_class: sequence_output = outputs[0] sequence_output = self.dropout(sequence_output) else: # self.use_freeze_extract_token_class: sequence_output = outputs[1] logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=outputs.attentions ) @add_start_docstrings( """ DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). """, DEBERTA_START_DOCSTRING, ) class DebertaForQuestionAnswering(DebertaPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.deberta = DebertaModel(config) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous() total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = (start_logits, end_logits) + outputs[1:] return ((total_loss,) + output) if total_loss is not None else output return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
61,716
39.523309
181
py
papa
papa-main/transformers/src/transformers/models/roberta/modeling_roberta.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PyTorch RoBERTa model.""" import math import os import torch import torch.utils.checkpoint from packaging import version from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN, gelu from ...file_utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings, ) from ...modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWithPoolingAndCrossAttentions, CausalLMOutputWithCrossAttentions, MaskedLMOutput, MultipleChoiceModelOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from ...modeling_utils import ( PreTrainedModel, apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer, ) from ...utils import logging from .configuration_roberta import RobertaConfig from ...papa_modules import FreezeExtractPoller, combine_static_and_dynamic_att, FreezeExtractPollerTokenClassification, mask_and_normalize logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "roberta-base" _CONFIG_FOR_DOC = "RobertaConfig" _TOKENIZER_FOR_DOC = "RobertaTokenizer" ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST = [ "roberta-base", "roberta-large", "roberta-large-mnli", "distilroberta-base", "roberta-base-openai-detector", "roberta-large-openai-detector", # See all RoBERTa models at https://huggingface.co/models?filter=roberta ] class RobertaEmbeddings(nn.Module): """ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing. """ # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__ def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) if version.parse(torch.__version__) > version.parse("1.6.0"): self.register_buffer( "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False, ) # End copy self.padding_idx = config.pad_token_id self.position_embeddings = nn.Embedding( config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx ) def forward( self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0 ): if position_ids is None: if input_ids is not None: # Create the position ids from the input token ids. Any padded tokens remain padded. position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length) else: position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds) if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves # issue #5664 if token_type_ids is None: if hasattr(self, "token_type_ids"): buffered_token_type_ids = self.token_type_ids[:, :seq_length] buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length) token_type_ids = buffered_token_type_ids_expanded else: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = inputs_embeds + token_type_embeddings if self.position_embedding_type == "absolute": position_embeddings = self.position_embeddings(position_ids) embeddings += position_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings def create_position_ids_from_inputs_embeds(self, inputs_embeds): """ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids. Args: inputs_embeds: torch.Tensor Returns: torch.Tensor """ input_shape = inputs_embeds.size()[:-1] sequence_length = input_shape[1] position_ids = torch.arange( self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device ) return position_ids.unsqueeze(0).expand(input_shape) # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Roberta class RobertaSelfAttention(nn.Module): def __init__(self, config, layer_num=-1, position_embedding_type=None): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.num_static_heads = 0 if config.static_heads and layer_num in config.static_heads['heads']: exp_heads = sorted(config.static_heads['heads'][layer_num]) self.num_static_heads = len(exp_heads) self.static_heads_indexes = exp_heads all_static_heads = torch.load(os.path.join(config.static_heads['heads_dir'], 'avgs.pt')) self.static_heads_content = nn.Parameter(torch.stack([all_static_heads[layer_num, head] for head in self.static_heads_indexes]), requires_grad=True) self.sort_calculating = False if config.sort_calculating: self.sort_calculating = True all_static_heads = torch.load(os.path.join(config.sort_calculating['heads_dir'], 'avgs.pt')) self.static_heads_content = nn.Parameter(torch.stack([all_static_heads[layer_num, head] for head in range(config.num_attention_heads)]), requires_grad=True) lambdas = torch.zeros([self.num_attention_heads]) lambdas = torch.unsqueeze(torch.unsqueeze(torch.unsqueeze(lambdas, 0), -1), -1) self.lambdas = nn.Parameter(lambdas, requires_grad=True) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.position_embedding_type = position_embedding_type or getattr( config, "position_embedding_type", "absolute" ) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": self.max_position_embeddings = config.max_position_embeddings self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) self.is_decoder = config.is_decoder def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def transpose_for_scores_KQ(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads - self.num_static_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): mixed_query_layer = self.query(hidden_states) # If this is instantiated as a cross-attention module, the keys # and values come from an encoder; the attention mask needs to be # such that the encoder's padding tokens are not attended to. is_cross_attention = encoder_hidden_states is not None if is_cross_attention and past_key_value is not None: # reuse k,v, cross_attentions key_layer = past_key_value[0] value_layer = past_key_value[1] attention_mask = encoder_attention_mask elif is_cross_attention: key_layer = self.transpose_for_scores_KQ(self.key(encoder_hidden_states)) value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) attention_mask = encoder_attention_mask elif past_key_value is not None: key_layer = self.transpose_for_scores_KQ(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) key_layer = torch.cat([past_key_value[0], key_layer], dim=2) value_layer = torch.cat([past_key_value[1], value_layer], dim=2) else: key_layer = self.transpose_for_scores_KQ(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) query_layer = self.transpose_for_scores_KQ(mixed_query_layer) if self.is_decoder: # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. # Further calls to cross_attention layer can then reuse all cross-attention # key/value_states (first "if" case) # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of # all previous decoder key/value_states. Further calls to uni-directional self-attention # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) # if encoder bi-directional self-attention `past_key_value` is always `None` past_key_value = (key_layer, value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": seq_length = hidden_states.size()[1] position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1) distance = position_ids_l - position_ids_r positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility if self.position_embedding_type == "relative_key": relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores elif self.position_embedding_type == "relative_key_query": relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.functional.softmax(attention_scores, dim=-1) if self.num_static_heads > 0: attention_probs = combine_static_and_dynamic_att(attention_probs, self.static_heads_content, attention_mask, self.static_heads_indexes, self.num_attention_heads) if self.sort_calculating: cur_lambdas = torch.sigmoid(self.lambdas) attention_probs = cur_lambdas * attention_probs + (1-cur_lambdas) * mask_and_normalize(self.static_heads_content, attention_mask) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs = attention_probs * head_mask context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) if self.is_decoder: outputs = outputs + (past_key_value,) return outputs # Copied from transformers.models.bert.modeling_bert.BertSelfOutput class RobertaSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Roberta class RobertaAttention(nn.Module): def __init__(self, config, layer_num=-1, position_embedding_type=None): super().__init__() self.self = RobertaSelfAttention(config, layer_num=layer_num, position_embedding_type=position_embedding_type) self.output = RobertaSelfOutput(config) self.pruned_heads = set() self.static_pruned_heads = set() def prune_heads(self, heads): if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices( heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads ) # Prune linear layers self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.self.value = prune_linear_layer(self.self.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.self.num_attention_heads = self.self.num_attention_heads - len(heads) self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def prune_static_heads(self): # my pruning: if self.self.num_static_heads == 0 or self.static_pruned_heads: return self.static_pruned_heads = self.static_pruned_heads.union(self.pruned_heads) heads, index = find_pruneable_heads_and_indices( self.self.static_heads_indexes, self.self.num_attention_heads, self.self.attention_head_size, self.static_pruned_heads ) self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.static_pruned_heads = self.static_pruned_heads.union(self.self.static_heads_indexes) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): self_outputs = self.self( hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) attention_output = self.output(self_outputs[0], hidden_states) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs # Copied from transformers.models.bert.modeling_bert.BertIntermediate class RobertaIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertOutput class RobertaOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Roberta class RobertaLayer(nn.Module): def __init__(self, config, layer_num=-1): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = RobertaAttention(config, layer_num=layer_num) self.is_decoder = config.is_decoder self.add_cross_attention = config.add_cross_attention if self.add_cross_attention: if not self.is_decoder: raise ValueError(f"{self} should be used as a decoder model if cross attention is added") self.crossattention = RobertaAttention(config, position_embedding_type="absolute") self.intermediate = RobertaIntermediate(config) self.output = RobertaOutput(config) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None self_attention_outputs = self.attention( hidden_states, attention_mask, head_mask, output_attentions=output_attentions, past_key_value=self_attn_past_key_value, ) attention_output = self_attention_outputs[0] # if decoder, the last output is tuple of self-attn cache if self.is_decoder: outputs = self_attention_outputs[1:-1] present_key_value = self_attention_outputs[-1] else: outputs = self_attention_outputs[1:] # add self attentions if we output attention weights cross_attn_present_key_value = None if self.is_decoder and encoder_hidden_states is not None: if not hasattr(self, "crossattention"): raise ValueError( f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`" ) # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None cross_attention_outputs = self.crossattention( attention_output, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, cross_attn_past_key_value, output_attentions, ) attention_output = cross_attention_outputs[0] outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights # add cross-attn cache to positions 3,4 of present_key_value tuple cross_attn_present_key_value = cross_attention_outputs[-1] present_key_value = present_key_value + cross_attn_present_key_value layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output ) outputs = (layer_output,) + outputs # if decoder, return the attn key/values as the last output if self.is_decoder: outputs = outputs + (present_key_value,) return outputs def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Roberta class RobertaEncoder(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([RobertaLayer(config, layer_num=layer_num) for layer_num in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=True, ): all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None next_decoder_cache = () if use_cache else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_head_mask = head_mask[i] if head_mask is not None else None past_key_value = past_key_values[i] if past_key_values is not None else None if self.gradient_checkpointing and self.training: if use_cache: logger.warning( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, past_key_value, output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, ) else: layer_outputs = layer_module( hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache += (layer_outputs[-1],) if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if self.config.add_cross_attention: all_cross_attentions = all_cross_attentions + (layer_outputs[2],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [ hidden_states, next_decoder_cache, all_hidden_states, all_self_attentions, all_cross_attentions, ] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_decoder_cache, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, ) # Copied from transformers.models.bert.modeling_bert.BertPooler class RobertaPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output class RobertaPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = RobertaConfig base_model_prefix = "roberta" supports_gradient_checkpointing = True # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights def _init_weights(self, module): """Initialize the weights""" if isinstance(module, nn.Linear): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, RobertaEncoder): module.gradient_checkpointing = value def update_keys_to_ignore(self, config, del_keys_to_ignore): """Remove some keys from ignore list""" if not config.tie_word_embeddings: # must make a new list, or the class variable gets modified! self._keys_to_ignore_on_save = [k for k in self._keys_to_ignore_on_save if k not in del_keys_to_ignore] self._keys_to_ignore_on_load_missing = [ k for k in self._keys_to_ignore_on_load_missing if k not in del_keys_to_ignore ] ROBERTA_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`RobertaConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ ROBERTA_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `({0})`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`RobertaTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-ids) position_ids (`torch.LongTensor` of shape `({0})`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare RoBERTa Model transformer outputting raw hidden-states without any specific head on top.", ROBERTA_START_DOCSTRING, ) class RobertaModel(RobertaPreTrainedModel): """ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of cross-attention is added between the self-attention layers, following the architecture described in *Attention is all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass. .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762 """ _keys_to_ignore_on_load_missing = [r"position_ids"] # Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->Roberta def __init__(self, config, add_pooling_layer=True): super().__init__(config) self.config = config self.embeddings = RobertaEmbeddings(config) self.encoder = RobertaEncoder(config) if add_pooling_layer: self.pooler = FreezeExtractPoller(config) if config.use_freeze_extract_pooler else RobertaPooler(config) else: self.pooler = None # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) def _prune_static_heads(self): for layer in range(len(self.encoder.layer)): self.encoder.layer[layer].attention.prune_static_heads() @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=BaseModelOutputWithPoolingAndCrossAttentions, config_class=_CONFIG_FOR_DOC, ) # Copied from transformers.models.bert.modeling_bert.BertModel.forward def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if self.config.is_decoder: use_cache = use_cache if use_cache is not None else self.config.use_cache else: use_cache = False if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") batch_size, seq_length = input_shape device = input_ids.device if input_ids is not None else inputs_embeds.device # past_key_values_length past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 if attention_mask is None: attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) if token_type_ids is None: if hasattr(self.embeddings, "token_type_ids"): buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length] buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length) token_type_ids = buffered_token_type_ids_expanded else: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device) # If a 2D or 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds, past_key_values_length=past_key_values_length, ) encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.config.use_freeze_extract_pooler, return_dict=return_dict, ) sequence_output = encoder_outputs[0] if self.pooler is not None: if self.config.use_freeze_extract_pooler: pooled_output = self.pooler(encoder_outputs[1], attention_mask) else: pooled_output = self.pooler(sequence_output) else: pooled_output = None if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, past_key_values=encoder_outputs.past_key_values, hidden_states=encoder_outputs.hidden_states if output_hidden_states else None, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions, ) @add_start_docstrings( """RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.""", ROBERTA_START_DOCSTRING ) class RobertaForCausalLM(RobertaPreTrainedModel): _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"] _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"] _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) if not config.is_decoder: logger.warning("If you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`") self.roberta = RobertaModel(config, add_pooling_layer=False) self.lm_head = RobertaLMHead(config) # The LM head weights require special treatment only when they are tied with the word embeddings self.update_keys_to_ignore(config, ["lm_head.decoder.weight"]) # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.lm_head.decoder def set_output_embeddings(self, new_embeddings): self.lm_head.decoder = new_embeddings @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). Returns: Example: ```python >>> from transformers import RobertaTokenizer, RobertaForCausalLM, RobertaConfig >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained("roberta-base") >>> config = RobertaConfig.from_pretrained("roberta-base") >>> config.is_decoder = True >>> model = RobertaForCausalLM.from_pretrained("roberta-base", config=config) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> prediction_logits = outputs.logits ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None: use_cache = False outputs = self.roberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] prediction_scores = self.lm_head(sequence_output) lm_loss = None if labels is not None: # we are doing next-token prediction; shift prediction scores and input ids by one shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() labels = labels[:, 1:].contiguous() loss_fct = CrossEntropyLoss() lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (prediction_scores,) + outputs[2:] return ((lm_loss,) + output) if lm_loss is not None else output return CausalLMOutputWithCrossAttentions( loss=lm_loss, logits=prediction_scores, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions, ) def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, **model_kwargs): input_shape = input_ids.shape # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly if attention_mask is None: attention_mask = input_ids.new_ones(input_shape) # cut decoder_input_ids if past is used if past is not None: input_ids = input_ids[:, -1:] return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past} def _reorder_cache(self, past, beam_idx): reordered_past = () for layer_past in past: reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) return reordered_past @add_start_docstrings("""RoBERTa Model with a `language modeling` head on top.""", ROBERTA_START_DOCSTRING) class RobertaForMaskedLM(RobertaPreTrainedModel): _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"] _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"] _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) if config.is_decoder: logger.warning( "If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for " "bi-directional self-attention." ) self.use_freeze_extract_token_predictor = config.use_freeze_extract_pooler self.roberta = RobertaModel(config, add_pooling_layer=False) self.lm_head = FreezeExtractPollerTokenClassification(config, mlm=True) if self.use_freeze_extract_token_predictor else RobertaLMHead(config) # The LM head weights require special treatment only when they are tied with the word embeddings self.update_keys_to_ignore(config, ["lm_head.decoder.weight"]) # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.lm_head.decoder def set_output_embeddings(self, new_embeddings): self.lm_head.decoder = new_embeddings @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC, mask="<mask>", ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` kwargs (`Dict[str, any]`, optional, defaults to *{}*): Used to hide legacy arguments that have been deprecated. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.roberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.use_freeze_extract_token_predictor, return_dict=return_dict, ) sequence_output = outputs[1] if self.use_freeze_extract_token_predictor else outputs[0] prediction_scores = self.lm_head(sequence_output) masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (prediction_scores,) + outputs[2:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=outputs.attentions, ) class RobertaLMHead(nn.Module): """Roberta Head for masked language modeling.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.decoder = nn.Linear(config.hidden_size, config.vocab_size) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) self.decoder.bias = self.bias def forward(self, features, **kwargs): x = self.dense(features) x = gelu(x) x = self.layer_norm(x) # project back to size of vocabulary with bias x = self.decoder(x) return x def _tie_weights(self): # To tie those two weights if they get disconnected (on TPU or when the bias is resized) self.bias = self.decoder.bias @add_start_docstrings( """ RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """, ROBERTA_START_DOCSTRING, ) class RobertaForSequenceClassification(RobertaPreTrainedModel): _keys_to_ignore_on_load_missing = [r"position_ids"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.config = config if config.use_freeze_extract_pooler: self.roberta = RobertaModel(config, add_pooling_layer=True) self.classifier = nn.Linear(config.hidden_size, config.num_labels) else: self.roberta = RobertaModel(config, add_pooling_layer=False) self.classifier = RobertaClassificationHead(config) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.roberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] if self.config.use_freeze_extract_pooler: sequence_output = outputs[1] logits = self.classifier(sequence_output) loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(logits.squeeze(), labels.squeeze()) else: loss = loss_fct(logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(logits, labels) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ Roberta Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks. """, ROBERTA_START_DOCSTRING, ) class RobertaForMultipleChoice(RobertaPreTrainedModel): _keys_to_ignore_on_load_missing = [r"position_ids"] def __init__(self, config): super().__init__(config) self.roberta = RobertaModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, 1) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=MultipleChoiceModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, token_type_ids=None, attention_mask=None, labels=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above) """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1] flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None flat_inputs_embeds = ( inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1)) if inputs_embeds is not None else None ) outputs = self.roberta( flat_input_ids, position_ids=flat_position_ids, token_type_ids=flat_token_type_ids, attention_mask=flat_attention_mask, head_mask=head_mask, inputs_embeds=flat_inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) reshaped_logits = logits.view(-1, num_choices) loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(reshaped_logits, labels) if not return_dict: output = (reshaped_logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return MultipleChoiceModelOutput( loss=loss, logits=reshaped_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ Roberta Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """, ROBERTA_START_DOCSTRING, ) class RobertaForTokenClassification(RobertaPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.roberta = RobertaModel(config, add_pooling_layer=False) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dropout(classifier_dropout) self.use_freeze_extract_token_class = config.use_freeze_extract_pooler self.classifier = FreezeExtractPollerTokenClassification(config) if self.use_freeze_extract_token_class else nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.roberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.use_freeze_extract_token_class, return_dict=return_dict, ) if not self.use_freeze_extract_token_class: sequence_output = outputs[0] sequence_output = self.dropout(sequence_output) else: # self.use_freeze_extract_token_class: sequence_output = outputs[1] logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=outputs.attentions, ) class RobertaClassificationHead(nn.Module): """Head for sentence-level classification tasks.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dropout(classifier_dropout) self.out_proj = nn.Linear(config.hidden_size, config.num_labels) def forward(self, features, **kwargs): x = features[:, 0, :] # take <s> token (equiv. to [CLS]) x = self.dropout(x) x = self.dense(x) x = torch.tanh(x) x = self.dropout(x) x = self.out_proj(x) return x @add_start_docstrings( """ Roberta Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). """, ROBERTA_START_DOCSTRING, ) class RobertaForQuestionAnswering(RobertaPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.roberta = RobertaModel(config, add_pooling_layer=False) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.roberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous() total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = (start_logits, end_logits) + outputs[2:] return ((total_loss,) + output) if total_loss is not None else output return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0): """ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. Args: x: torch.Tensor x: Returns: torch.Tensor """ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA. mask = input_ids.ne(padding_idx).int() incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask return incremental_indices.long() + padding_idx
72,547
42.888687
198
py
papa
papa-main/transformers/src/transformers/models/bert/modeling_bert.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PyTorch BERT model.""" import math import os import warnings from dataclasses import dataclass from typing import Optional, Tuple import torch import torch.utils.checkpoint from packaging import version from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...file_utils import ( ModelOutput, add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings, ) from ...modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWithPoolingAndCrossAttentions, CausalLMOutputWithCrossAttentions, MaskedLMOutput, MultipleChoiceModelOutput, NextSentencePredictorOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from ...modeling_utils import ( PreTrainedModel, apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer, ) from ...utils import logging from .configuration_bert import BertConfig from ...papa_modules import FreezeExtractPoller, combine_static_and_dynamic_att, FreezeExtractPollerTokenClassification, mask_and_normalize logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "bert-base-uncased" _CONFIG_FOR_DOC = "BertConfig" _TOKENIZER_FOR_DOC = "BertTokenizer" BERT_PRETRAINED_MODEL_ARCHIVE_LIST = [ "bert-base-uncased", "bert-large-uncased", "bert-base-cased", "bert-large-cased", "bert-base-multilingual-uncased", "bert-base-multilingual-cased", "bert-base-chinese", "bert-base-german-cased", "bert-large-uncased-whole-word-masking", "bert-large-cased-whole-word-masking", "bert-large-uncased-whole-word-masking-finetuned-squad", "bert-large-cased-whole-word-masking-finetuned-squad", "bert-base-cased-finetuned-mrpc", "bert-base-german-dbmdz-cased", "bert-base-german-dbmdz-uncased", "cl-tohoku/bert-base-japanese", "cl-tohoku/bert-base-japanese-whole-word-masking", "cl-tohoku/bert-base-japanese-char", "cl-tohoku/bert-base-japanese-char-whole-word-masking", "TurkuNLP/bert-base-finnish-cased-v1", "TurkuNLP/bert-base-finnish-uncased-v1", "wietsedv/bert-base-dutch-cased", # See all BERT models at https://huggingface.co/models?filter=bert ] def load_tf_weights_in_bert(model, config, tf_checkpoint_path): """Load tf checkpoints in a pytorch model.""" try: import re import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise tf_path = os.path.abspath(tf_checkpoint_path) logger.info(f"Converting TensorFlow checkpoint from {tf_path}") # Load weights from TF model init_vars = tf.train.list_variables(tf_path) names = [] arrays = [] for name, shape in init_vars: logger.info(f"Loading TF weight {name} with shape {shape}") array = tf.train.load_variable(tf_path, name) names.append(name) arrays.append(array) for name, array in zip(names, arrays): name = name.split("/") # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if any( n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"] for n in name ): logger.info(f"Skipping {'/'.join(name)}") continue pointer = model for m_name in name: if re.fullmatch(r"[A-Za-z]+_\d+", m_name): scope_names = re.split(r"_(\d+)", m_name) else: scope_names = [m_name] if scope_names[0] == "kernel" or scope_names[0] == "gamma": pointer = getattr(pointer, "weight") elif scope_names[0] == "output_bias" or scope_names[0] == "beta": pointer = getattr(pointer, "bias") elif scope_names[0] == "output_weights": pointer = getattr(pointer, "weight") elif scope_names[0] == "squad": pointer = getattr(pointer, "classifier") else: try: pointer = getattr(pointer, scope_names[0]) except AttributeError: logger.info(f"Skipping {'/'.join(name)}") continue if len(scope_names) >= 2: num = int(scope_names[1]) pointer = pointer[num] if m_name[-11:] == "_embeddings": pointer = getattr(pointer, "weight") elif m_name == "kernel": array = np.transpose(array) try: if pointer.shape != array.shape: raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched") except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info(f"Initialize PyTorch weight {name}") pointer.data = torch.from_numpy(array) return model class BertEmbeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings.""" def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) if version.parse(torch.__version__) > version.parse("1.6.0"): self.register_buffer( "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False, ) def forward( self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0 ): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] if position_ids is None: position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length] # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves # issue #5664 if token_type_ids is None: if hasattr(self, "token_type_ids"): buffered_token_type_ids = self.token_type_ids[:, :seq_length] buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length) token_type_ids = buffered_token_type_ids_expanded else: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = inputs_embeds + token_type_embeddings if self.position_embedding_type == "absolute": position_embeddings = self.position_embeddings(position_ids) embeddings += position_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings class BertSelfAttention(nn.Module): def __init__(self, config, layer_num=-1, position_embedding_type=None): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.num_static_heads = 0 if config.static_heads and layer_num in config.static_heads['heads']: exp_heads = sorted(config.static_heads['heads'][layer_num]) self.num_static_heads = len(exp_heads) self.static_heads_indexes = exp_heads all_static_heads = torch.load(os.path.join(config.static_heads['heads_dir'], 'avgs.pt')) self.static_heads_content = nn.Parameter(torch.stack([all_static_heads[layer_num, head] for head in self.static_heads_indexes]), requires_grad=True) self.sort_calculating = False if config.sort_calculating: self.sort_calculating = True all_static_heads = torch.load(os.path.join(config.sort_calculating['heads_dir'], 'avgs.pt')) self.static_heads_content = nn.Parameter(torch.stack([all_static_heads[layer_num, head] for head in range(config.num_attention_heads)]), requires_grad=True) lambdas = torch.zeros([self.num_attention_heads]) lambdas = torch.unsqueeze(torch.unsqueeze(torch.unsqueeze(lambdas, 0), -1), -1) self.lambdas = nn.Parameter(lambdas, requires_grad=True) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.position_embedding_type = position_embedding_type or getattr( config, "position_embedding_type", "absolute" ) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": self.max_position_embeddings = config.max_position_embeddings self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) self.is_decoder = config.is_decoder def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def transpose_for_scores_KQ(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads - self.num_static_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): mixed_query_layer = self.query(hidden_states) # If this is instantiated as a cross-attention module, the keys # and values come from an encoder; the attention mask needs to be # such that the encoder's padding tokens are not attended to. is_cross_attention = encoder_hidden_states is not None if is_cross_attention and past_key_value is not None: # reuse k,v, cross_attentions key_layer = past_key_value[0] value_layer = past_key_value[1] attention_mask = encoder_attention_mask elif is_cross_attention: key_layer = self.transpose_for_scores_KQ(self.key(encoder_hidden_states)) value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) attention_mask = encoder_attention_mask elif past_key_value is not None: key_layer = self.transpose_for_scores_KQ(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) key_layer = torch.cat([past_key_value[0], key_layer], dim=2) value_layer = torch.cat([past_key_value[1], value_layer], dim=2) else: key_layer = self.transpose_for_scores_KQ(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) query_layer = self.transpose_for_scores_KQ(mixed_query_layer) if self.is_decoder: # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. # Further calls to cross_attention layer can then reuse all cross-attention # key/value_states (first "if" case) # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of # all previous decoder key/value_states. Further calls to uni-directional self-attention # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) # if encoder bi-directional self-attention `past_key_value` is always `None` past_key_value = (key_layer, value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": seq_length = hidden_states.size()[1] position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1) distance = position_ids_l - position_ids_r positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility if self.position_embedding_type == "relative_key": relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores elif self.position_embedding_type == "relative_key_query": relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.functional.softmax(attention_scores, dim=-1) if self.num_static_heads > 0: attention_probs = combine_static_and_dynamic_att(attention_probs, self.static_heads_content, attention_mask, self.static_heads_indexes, self.num_attention_heads) if self.sort_calculating: cur_lambdas = torch.sigmoid(self.lambdas) attention_probs = cur_lambdas * attention_probs + (1-cur_lambdas) * mask_and_normalize(self.static_heads_content, attention_mask) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs = attention_probs * head_mask context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) if self.is_decoder: outputs = outputs + (past_key_value,) return outputs class BertSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertAttention(nn.Module): def __init__(self, config, layer_num=-1, position_embedding_type=None): super().__init__() self.self = BertSelfAttention(config, layer_num=layer_num, position_embedding_type=position_embedding_type) self.output = BertSelfOutput(config) self.pruned_heads = set() self.static_pruned_heads = set() def prune_heads(self, heads): if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices( heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads ) # Prune linear layers self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.self.value = prune_linear_layer(self.self.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.self.num_attention_heads = self.self.num_attention_heads - len(heads) self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def prune_static_heads(self): # my pruning: if self.self.num_static_heads == 0 or self.static_pruned_heads: return self.static_pruned_heads = self.static_pruned_heads.union(self.pruned_heads) heads, index = find_pruneable_heads_and_indices( self.self.static_heads_indexes, self.self.num_attention_heads, self.self.attention_head_size, self.static_pruned_heads ) self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.static_pruned_heads = self.static_pruned_heads.union(self.self.static_heads_indexes) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): self_outputs = self.self( hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) attention_output = self.output(self_outputs[0], hidden_states) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs class BertIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class BertOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertLayer(nn.Module): def __init__(self, config, layer_num=-1): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = BertAttention(config, layer_num=layer_num) self.is_decoder = config.is_decoder self.add_cross_attention = config.add_cross_attention if self.add_cross_attention: if not self.is_decoder: raise ValueError(f"{self} should be used as a decoder model if cross attention is added") self.crossattention = BertAttention(config, position_embedding_type="absolute") self.intermediate = BertIntermediate(config) self.output = BertOutput(config) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None self_attention_outputs = self.attention( hidden_states, attention_mask, head_mask, output_attentions=output_attentions, past_key_value=self_attn_past_key_value, ) attention_output = self_attention_outputs[0] # if decoder, the last output is tuple of self-attn cache if self.is_decoder: outputs = self_attention_outputs[1:-1] present_key_value = self_attention_outputs[-1] else: outputs = self_attention_outputs[1:] # add self attentions if we output attention weights cross_attn_present_key_value = None if self.is_decoder and encoder_hidden_states is not None: if not hasattr(self, "crossattention"): raise ValueError( f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`" ) # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None cross_attention_outputs = self.crossattention( attention_output, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, cross_attn_past_key_value, output_attentions, ) attention_output = cross_attention_outputs[0] outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights # add cross-attn cache to positions 3,4 of present_key_value tuple cross_attn_present_key_value = cross_attention_outputs[-1] present_key_value = present_key_value + cross_attn_present_key_value layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output ) outputs = (layer_output,) + outputs # if decoder, return the attn key/values as the last output if self.is_decoder: outputs = outputs + (present_key_value,) return outputs def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output class BertEncoder(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([BertLayer(config, layer_num=layer_num) for layer_num in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=True, ): all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None next_decoder_cache = () if use_cache else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_head_mask = head_mask[i] if head_mask is not None else None past_key_value = past_key_values[i] if past_key_values is not None else None if self.gradient_checkpointing and self.training: if use_cache: logger.warning( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, past_key_value, output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, ) else: layer_outputs = layer_module( hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache += (layer_outputs[-1],) if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if self.config.add_cross_attention: all_cross_attentions = all_cross_attentions + (layer_outputs[2],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [ hidden_states, next_decoder_cache, all_hidden_states, all_self_attentions, all_cross_attentions, ] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_decoder_cache, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, ) class BertPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output class BertPredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states class BertLMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states class BertOnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = FreezeExtractPollerTokenClassification(config, mlm=True) if config.use_freeze_extract_pooler else BertLMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores class BertOnlyNSPHead(nn.Module): def __init__(self, config): super().__init__() self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, pooled_output): seq_relationship_score = self.seq_relationship(pooled_output) return seq_relationship_score class BertPreTrainingHeads(nn.Module): def __init__(self, config): super().__init__() self.predictions = BertLMPredictionHead(config) self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, sequence_output, pooled_output): prediction_scores = self.predictions(sequence_output) seq_relationship_score = self.seq_relationship(pooled_output) return prediction_scores, seq_relationship_score class BertPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = BertConfig load_tf_weights = load_tf_weights_in_bert base_model_prefix = "bert" supports_gradient_checkpointing = True _keys_to_ignore_on_load_missing = [r"position_ids"] def _init_weights(self, module): """Initialize the weights""" if isinstance(module, nn.Linear): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, BertEncoder): module.gradient_checkpointing = value @dataclass class BertForPreTrainingOutput(ModelOutput): """ Output type of [`BertForPreTraining`]. Args: loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`): Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss. prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`): Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax). hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[torch.FloatTensor] = None prediction_logits: torch.FloatTensor = None seq_relationship_logits: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None BERT_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`BertConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ BERT_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `({0})`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-ids) position_ids (`torch.LongTensor` of shape `({0})`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.", BERT_START_DOCSTRING, ) class BertModel(BertPreTrainedModel): """ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of cross-attention is added between the self-attention layers, following the architecture described in [Attention is all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass. """ def __init__(self, config, add_pooling_layer=True): super().__init__(config) self.config = config self.embeddings = BertEmbeddings(config) self.encoder = BertEncoder(config) if add_pooling_layer: self.pooler = FreezeExtractPoller(config) if config.use_freeze_extract_pooler else BertPooler(config) else: self.pooler = None # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) def _prune_static_heads(self): for layer in range(len(self.encoder.layer)): self.encoder.layer[layer].attention.prune_static_heads() @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=BaseModelOutputWithPoolingAndCrossAttentions, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if self.config.is_decoder: use_cache = use_cache if use_cache is not None else self.config.use_cache else: use_cache = False if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") batch_size, seq_length = input_shape device = input_ids.device if input_ids is not None else inputs_embeds.device # past_key_values_length past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 if attention_mask is None: attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) if token_type_ids is None: if hasattr(self.embeddings, "token_type_ids"): buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length] buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length) token_type_ids = buffered_token_type_ids_expanded else: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device) # If a 2D or 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds, past_key_values_length=past_key_values_length, ) encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.config.use_freeze_extract_pooler, return_dict=return_dict, ) sequence_output = encoder_outputs[0] if self.pooler is not None: if self.config.use_freeze_extract_pooler: sequence_output = encoder_outputs[1] pooled_output = self.pooler(sequence_output, attention_mask) else: pooled_output = self.pooler(sequence_output) else: pooled_output = None if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, past_key_values=encoder_outputs.past_key_values, hidden_states=encoder_outputs.hidden_states if output_hidden_states else None, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions, ) @add_start_docstrings( """ Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next sentence prediction (classification)` head. """, BERT_START_DOCSTRING, ) class BertForPreTraining(BertPreTrainedModel): def __init__(self, config): super().__init__(config) self.bert = BertModel(config) self.cls = BertPreTrainingHeads(config) # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @replace_return_docstrings(output_type=BertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, next_sentence_label=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see `input_ids` docstring) Indices should be in `[0, 1]`: - 0 indicates sequence B is a continuation of sequence A, - 1 indicates sequence B is a random sequence. kwargs (`Dict[str, any]`, optional, defaults to *{}*): Used to hide legacy arguments that have been deprecated. Returns: Example: ```python >>> from transformers import BertTokenizer, BertForPreTraining >>> import torch >>> tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") >>> model = BertForPreTraining.from_pretrained("bert-base-uncased") >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> prediction_logits = outputs.prediction_logits >>> seq_relationship_logits = outputs.seq_relationship_logits ``` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output, pooled_output = outputs[:2] prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output) total_loss = None if labels is not None and next_sentence_label is not None: loss_fct = CrossEntropyLoss() masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1)) total_loss = masked_lm_loss + next_sentence_loss if not return_dict: output = (prediction_scores, seq_relationship_score) + outputs[2:] return ((total_loss,) + output) if total_loss is not None else output return BertForPreTrainingOutput( loss=total_loss, prediction_logits=prediction_scores, seq_relationship_logits=seq_relationship_score, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """Bert Model with a `language modeling` head on top for CLM fine-tuning.""", BERT_START_DOCSTRING ) class BertLMHeadModel(BertPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] def __init__(self, config): super().__init__(config) if not config.is_decoder: logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`") self.bert = BertModel(config, add_pooling_layer=False) self.cls = BertOnlyMLMHead(config) # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]` past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). Returns: Example: ```python >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig >>> import torch >>> tokenizer = BertTokenizer.from_pretrained("bert-base-cased") >>> config = BertConfig.from_pretrained("bert-base-cased") >>> config.is_decoder = True >>> model = BertLMHeadModel.from_pretrained("bert-base-cased", config=config) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> prediction_logits = outputs.logits ``` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None: use_cache = False outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] prediction_scores = self.cls(sequence_output) lm_loss = None if labels is not None: # we are doing next-token prediction; shift prediction scores and input ids by one shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() labels = labels[:, 1:].contiguous() loss_fct = CrossEntropyLoss() lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (prediction_scores,) + outputs[2:] return ((lm_loss,) + output) if lm_loss is not None else output return CausalLMOutputWithCrossAttentions( loss=lm_loss, logits=prediction_scores, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions, ) def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, **model_kwargs): input_shape = input_ids.shape # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly if attention_mask is None: attention_mask = input_ids.new_ones(input_shape) # cut decoder_input_ids if past is used if past is not None: input_ids = input_ids[:, -1:] return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past} def _reorder_cache(self, past, beam_idx): reordered_past = () for layer_past in past: reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) return reordered_past @add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING) class BertForMaskedLM(BertPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] def __init__(self, config): super().__init__(config) if config.is_decoder: logger.warning( "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for " "bi-directional self-attention." ) self.bert = BertModel(config, add_pooling_layer=False) self.cls = BertOnlyMLMHead(config) self.use_freeze_extract_token_predictor = config.use_freeze_extract_pooler # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.use_freeze_extract_token_predictor, return_dict=return_dict, ) sequence_output = outputs[1] if self.use_freeze_extract_token_predictor else outputs[0] prediction_scores = self.cls(sequence_output) masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() # -100 index = padding token masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (prediction_scores,) + outputs[2:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=outputs.attentions, ) def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs): input_shape = input_ids.shape effective_batch_size = input_shape[0] # add a dummy token if self.config.pad_token_id is None: raise ValueError("The PAD token should be defined for generation") attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1) dummy_token = torch.full( (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device ) input_ids = torch.cat([input_ids, dummy_token], dim=1) return {"input_ids": input_ids, "attention_mask": attention_mask} @add_start_docstrings( """Bert Model with a `next sentence prediction (classification)` head on top.""", BERT_START_DOCSTRING, ) class BertForNextSentencePrediction(BertPreTrainedModel): def __init__(self, config): super().__init__(config) self.bert = BertModel(config) self.cls = BertOnlyNSPHead(config) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs, ): r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see `input_ids` docstring). Indices should be in `[0, 1]`: - 0 indicates sequence B is a continuation of sequence A, - 1 indicates sequence B is a random sequence. Returns: Example: ```python >>> from transformers import BertTokenizer, BertForNextSentencePrediction >>> import torch >>> tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") >>> model = BertForNextSentencePrediction.from_pretrained("bert-base-uncased") >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light." >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt") >>> outputs = model(**encoding, labels=torch.LongTensor([1])) >>> logits = outputs.logits >>> assert logits[0, 0] < logits[0, 1] # next sentence was random ``` """ if "next_sentence_label" in kwargs: warnings.warn( "The `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.", FutureWarning, ) labels = kwargs.pop("next_sentence_label") return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) pooled_output = outputs[1] seq_relationship_scores = self.cls(pooled_output) next_sentence_loss = None if labels is not None: loss_fct = CrossEntropyLoss() next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1)) if not return_dict: output = (seq_relationship_scores,) + outputs[2:] return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output return NextSentencePredictorOutput( loss=next_sentence_loss, logits=seq_relationship_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """, BERT_START_DOCSTRING, ) class BertForSequenceClassification(BertPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.config = config self.bert = BertModel(config) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dropout(classifier_dropout) self.classifier = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(logits.squeeze(), labels.squeeze()) else: loss = loss_fct(logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(logits, labels) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks. """, BERT_START_DOCSTRING, ) class BertForMultipleChoice(BertPreTrainedModel): def __init__(self, config): super().__init__(config) self.bert = BertModel(config) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dropout(classifier_dropout) self.classifier = nn.Linear(config.hidden_size, 1) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=MultipleChoiceModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above) """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1] input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None inputs_embeds = ( inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1)) if inputs_embeds is not None else None ) outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) reshaped_logits = logits.view(-1, num_choices) loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(reshaped_logits, labels) if not return_dict: output = (reshaped_logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return MultipleChoiceModelOutput( loss=loss, logits=reshaped_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """, BERT_START_DOCSTRING, ) class BertForTokenClassification(BertPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.bert = BertModel(config, add_pooling_layer=False) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dropout(classifier_dropout) self.use_freeze_extract_token_class = config.use_freeze_extract_pooler self.classifier = FreezeExtractPollerTokenClassification(config) if self.use_freeze_extract_token_class else nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.use_freeze_extract_token_class, return_dict=return_dict, ) if not self.use_freeze_extract_token_class: sequence_output = outputs[0] sequence_output = self.dropout(sequence_output) else: # self.use_freeze_extract_token_class: sequence_output = outputs[1] logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=outputs.attentions, ) @add_start_docstrings( """ Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). """, BERT_START_DOCSTRING, ) class BertForQuestionAnswering(BertPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.bert = BertModel(config, add_pooling_layer=False) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states or self.use_freeze_extract_qa, return_dict=return_dict, ) if not self.use_freeze_extract_qa: sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) else: # self.use_freeze_extract_qa sequence_output = outputs[1] logits = self.qa_outputs(sequence_output, attention_mask) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous() total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = (start_logits, end_logits) + outputs[2:] return ((total_loss,) + output) if total_loss is not None else output return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=outputs.attentions, )
83,962
41.903935
202
py
papa
papa-main/transformers/papa_scripts/run_papa_ner_avgs_creator.py
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Fine-tuning a 🤗 Transformers model on token classification tasks (NER, POS, CHUNKS) relying on the accelerate library without using a Trainer. """ import argparse import logging import math import os import random from pathlib import Path import json import numpy as np import datasets import torch from datasets import ClassLabel, load_dataset, load_metric from torch.utils.data import DataLoader from tqdm.auto import tqdm import transformers from accelerate import Accelerator from huggingface_hub import Repository from transformers import ( CONFIG_MAPPING, MODEL_MAPPING, AdamW, AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorForTokenClassification, PretrainedConfig, SchedulerType, default_data_collator, get_scheduler, set_seed, ) from transformers.file_utils import get_full_repo_name from transformers.utils.versions import require_version logger = logging.getLogger(__name__) require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/token-classification/requirements.txt") # You should update this to your particular problem to have better documentation of `model_type` MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys()) MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def parse_args(): parser = argparse.ArgumentParser( description="Finetune a transformers model on a text classification task (NER) with accelerate library" ) parser.add_argument( "--dataset_name", type=str, default=None, help="The name of the dataset to use (via the datasets library).", ) parser.add_argument( "--dataset_config_name", type=str, default=None, help="The configuration name of the dataset to use (via the datasets library).", ) parser.add_argument( "--train_file", type=str, default=None, help="A csv or a json file containing the training data." ) parser.add_argument( "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data." ) parser.add_argument( "--text_column_name", type=str, default=None, help="The column name of text to input in the file (a csv or JSON file).", ) parser.add_argument( "--label_column_name", type=str, default=None, help="The column name of label to input in the file (a csv or JSON file).", ) parser.add_argument( "--max_length", type=int, default=128, help=( "The maximum total input sequence length after tokenization. Sequences longer than this will be truncated," " sequences shorter will be padded if `--pad_to_max_length` is passed." ), ) parser.add_argument( "--pad_to_max_length", action="store_true", help="If passed, pad all samples to `max_length`. Otherwise, dynamic padding is used.", ) parser.add_argument( "--model_name_or_path", type=str, help="Path to pretrained model or model identifier from huggingface.co/models.", required=True, ) parser.add_argument( "--config_name", type=str, default=None, help="Pretrained config name or path if not the same as model_name", ) parser.add_argument( "--tokenizer_name", type=str, default=None, help="Pretrained tokenizer name or path if not the same as model_name", ) parser.add_argument( "--per_device_train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader.", ) parser.add_argument( "--per_device_eval_batch_size", type=int, default=8, help="Batch size (per device) for the evaluation dataloader.", ) parser.add_argument( "--learning_rate", type=float, default=5e-5, help="Initial learning rate (after the potential warmup period) to use.", ) parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.") parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.") parser.add_argument( "--max_train_steps", type=int, default=None, help="Total number of training steps to perform. If provided, overrides num_train_epochs.", ) parser.add_argument( "--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument( "--lr_scheduler_type", type=SchedulerType, default="linear", help="The scheduler type to use.", choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"], ) parser.add_argument( "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler." ) parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.") parser.add_argument("--sort_output_dir", type=str, default=None, help="Where to store the final sorting.") parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") parser.add_argument( "--model_type", type=str, default=None, help="Model type to use if training from scratch.", choices=MODEL_TYPES, ) parser.add_argument( "--label_all_tokens", action="store_true", help="Setting labels of all special tokens to -100 and thus PyTorch will ignore them.", ) parser.add_argument( "--return_entity_level_metrics", action="store_true", help="Indication whether entity level metrics are to be returner.", ) parser.add_argument( "--task_name", type=str, default="ner", choices=["ner", "pos", "chunk"], help="The name of the task.", ) parser.add_argument( "--debug", action="store_true", help="Activate debug mode and run training only with a subset of data.", ) parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.") parser.add_argument( "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`." ) parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.") parser.add_argument( "--use_papa_preprocess", type=bool, default=False, help="Use PAPA preprocess for glue dataset.", ) parser.add_argument( "--cache_dir", type=str, default=None, help="Where do you want to store the pretrained models downloaded from huggingface.co.", ) args = parser.parse_args() # Sanity checks if args.task_name is None and args.train_file is None and args.validation_file is None: raise ValueError("Need either a task name or a training/validation file.") else: if args.train_file is not None: extension = args.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if args.validation_file is not None: extension = args.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." if args.push_to_hub: assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed." return args def main(): args = parse_args() # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. accelerator = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) logger.info(accelerator.state) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Handle the repository creation if accelerator.is_main_process: if args.push_to_hub: if args.hub_model_id is None: repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token) else: repo_name = args.hub_model_id repo = Repository(args.output_dir, clone_from=repo_name) elif args.output_dir is not None: os.makedirs(args.output_dir, exist_ok=True) accelerator.wait_for_everyone() # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets for token classification task available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'tokens' or the first column if no column called # 'tokens' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name, cache_dir=args.cache_dir) else: data_files = {} if args.train_file is not None: data_files["train"] = args.train_file if args.validation_file is not None: data_files["validation"] = args.validation_file extension = args.train_file.split(".")[-1] raw_datasets = load_dataset(extension, data_files=data_files) # Trim a number of training examples if args.debug: for split in raw_datasets.keys(): raw_datasets[split] = raw_datasets[split].select(range(100)) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. if raw_datasets["train"] is not None: column_names = raw_datasets["train"].column_names features = raw_datasets["train"].features else: column_names = raw_datasets["validation"].column_names features = raw_datasets["validation"].features if args.text_column_name is not None: text_column_name = args.text_column_name elif "tokens" in column_names: text_column_name = "tokens" else: text_column_name = column_names[0] if args.label_column_name is not None: label_column_name = args.label_column_name elif f"{args.task_name}_tags" in column_names: label_column_name = f"{args.task_name}_tags" else: label_column_name = column_names[1] # In the event the labels are not a `Sequence[ClassLabel]`, we will need to go through the dataset to get the # unique labels. def get_label_list(labels): unique_labels = set() for label in labels: unique_labels = unique_labels | set(label) label_list = list(unique_labels) label_list.sort() return label_list if isinstance(features[label_column_name].feature, ClassLabel): label_list = features[label_column_name].feature.names label_keys = list(range(len(label_list))) else: label_list = get_label_list(raw_datasets["train"][label_column_name]) label_keys = label_list num_labels = len(label_list) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if args.config_name: config = AutoConfig.from_pretrained(args.config_name, num_labels=num_labels) elif args.model_name_or_path: config = AutoConfig.from_pretrained(args.model_name_or_path, num_labels=num_labels) else: config = CONFIG_MAPPING[args.model_type]() logger.warning("You are instantiating a new config instance from scratch.") tokenizer_name_or_path = args.tokenizer_name if args.tokenizer_name else args.model_name_or_path if not tokenizer_name_or_path: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) print(config.model_type) if config.model_type in {"gpt2", "roberta", "deberta"}: tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True, add_prefix_space=True) else: tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True) if args.model_name_or_path: model = AutoModelForTokenClassification.from_pretrained( args.model_name_or_path, from_tf=bool(".ckpt" in args.model_name_or_path), config=config, cache_dir=args.cache_dir, ) else: logger.info("Training new model from scratch") model = AutoModelForTokenClassification.from_config(config) model.resize_token_embeddings(len(tokenizer)) if model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id: label_name_to_id = {k: v for k, v in model.config.label2id.items()} if list(sorted(label_name_to_id.keys())) == list(sorted(label_list)): label_to_id = {k: int(label_name_to_id[k]) for k in label_keys} else: logger.warning( "Your model seems to have been trained with labels, but they don't match the dataset: ", f"model labels: {list(sorted(label_name_to_id.keys()))}, dataset labels: {list(sorted(label_list))}." "\nIgnoring the model labels as a result.", ) else: label_to_id = {k: i for i, k in enumerate(label_keys)} model.config.label2id = label_to_id model.config.id2label = {i: l for l, i in label_to_id.items()} # Map that sends B-Xxx label to its I-Xxx counterpart b_to_i_label = [] for idx, label in enumerate(label_list): if label.startswith("B-") and label.replace("B-", "I-") in label_list: b_to_i_label.append(label_list.index(label.replace("B-", "I-"))) else: b_to_i_label.append(idx) # Preprocessing the datasets. # First we tokenize all the texts. padding = "max_length" if args.pad_to_max_length else False def add_preprocess_func(tokenized_inputs): for i in range(len(tokenized_inputs.data['input_ids'])): sep_index = tokenized_inputs.data['input_ids'][i].index(tokenizer.sep_token_id) tokenized_inputs.data['input_ids'][i][sep_index] = tokenizer.pad_token_id tokenized_inputs.data['attention_mask'][i][sep_index] = 0 tokenized_inputs.data['input_ids'][i][-1] = tokenizer.sep_token_id tokenized_inputs.data['attention_mask'][i][-1] = 1 # Tokenize all texts and align the labels with them. def tokenize_and_align_labels(examples): tokenized_inputs = tokenizer( examples[text_column_name], max_length=args.max_length, padding=padding, truncation=True, # We use this argument because the texts in our dataset are lists of words (with a label for each word). is_split_into_words=True, ) if args.use_papa_preprocess: add_preprocess_func(tokenized_inputs) labels = [] for i, label in enumerate(examples[label_column_name]): word_ids = tokenized_inputs.word_ids(batch_index=i) previous_word_idx = None label_ids = [] for word_idx in word_ids: # Special tokens have a word id that is None. We set the label to -100 so they are automatically # ignored in the loss function. if word_idx is None: label_ids.append(-100) # We set the label for the first token of each word. elif word_idx != previous_word_idx: label_ids.append(label_to_id[label[word_idx]]) # For the other tokens in a word, we set the label to either the current label or -100, depending on # the label_all_tokens flag. else: if args.label_all_tokens: label_ids.append(b_to_i_label[label_to_id[label[word_idx]]]) else: label_ids.append(-100) previous_word_idx = word_idx labels.append(label_ids) tokenized_inputs["labels"] = labels return tokenized_inputs with accelerator.main_process_first(): processed_raw_datasets = raw_datasets.map( tokenize_and_align_labels, batched=True, remove_columns=raw_datasets["train"].column_names, desc="Running tokenizer on dataset", ) train_dataset = processed_raw_datasets["train"] eval_dataset = processed_raw_datasets["validation"] # Log a few random samples from the training set: for index in random.sample(range(len(train_dataset)), 3): logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") # DataLoaders creation: if args.pad_to_max_length: # If padding was already done ot max length, we use the default data collator that will just convert everything # to tensors. data_collator = default_data_collator else: # Otherwise, `DataCollatorForTokenClassification` will apply dynamic padding for us (by padding to the maximum length of # the samples passed). When using mixed precision, we add `pad_to_multiple_of=8` to pad all tensors to multiple # of 8s, which will enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta). data_collator = DataCollatorForTokenClassification( tokenizer, pad_to_multiple_of=(8 if accelerator.use_fp16 else None) ) train_dataloader = DataLoader( train_dataset, shuffle=True, collate_fn=data_collator, batch_size=args.per_device_train_batch_size ) eval_dataloader = DataLoader(eval_dataset, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size) # Optimizer # Split weights in two groups, one with weight decay and the other not. no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": args.weight_decay, }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate) # Use the device given by the `accelerator` object. device = accelerator.device model.to(device) # Prepare everything with our `accelerator`. model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare( model, optimizer, train_dataloader, eval_dataloader ) # Note -> the training dataloader needs to be prepared before we grab his length below (cause its length will be # shorter in multiprocess) # Scheduler and math around the number of training steps. num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) if args.max_train_steps is None: args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch else: args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) lr_scheduler = get_scheduler( name=args.lr_scheduler_type, optimizer=optimizer, num_warmup_steps=args.num_warmup_steps, num_training_steps=args.max_train_steps, ) # Metrics metric = load_metric("seqeval") def get_labels(predictions, references): # Transform predictions and references tensos to numpy arrays if device.type == "cpu": y_pred = predictions.detach().clone().numpy() y_true = references.detach().clone().numpy() else: y_pred = predictions.detach().cpu().clone().numpy() y_true = references.detach().cpu().clone().numpy() # Remove ignored index (special tokens) true_predictions = [ [label_list[p] for (p, l) in zip(pred, gold_label) if l != -100] for pred, gold_label in zip(y_pred, y_true) ] true_labels = [ [label_list[l] for (p, l) in zip(pred, gold_label) if l != -100] for pred, gold_label in zip(y_pred, y_true) ] return true_predictions, true_labels def compute_metrics(): results = metric.compute() if args.return_entity_level_metrics: # Unpack nested dictionaries final_results = {} for key, value in results.items(): if isinstance(value, dict): for n, v in value.items(): final_results[f"{key}_{n}"] = v else: final_results[key] = value return final_results else: return { "precision": results["overall_precision"], "recall": results["overall_recall"], "f1": results["overall_f1"], "accuracy": results["overall_accuracy"], } # Train! total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps logger.info("***** Running training *****") logger.info(f" Num examples = {len(train_dataset)}") logger.info(f" Num Epochs = {args.num_train_epochs}") logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") logger.info(f" Total optimization steps = {args.max_train_steps}") # Only show the progress bar once on each machine. progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) completed_steps = 0 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') with torch.no_grad(): attentions_sums = torch.zeros((config.num_hidden_layers, config.num_attention_heads, args.max_length, args.max_length)).to(device) attention_patterns_sums = torch.zeros((args.max_length, args.max_length)).to(device) model.eval() for epoch in range(1): for step, batch in enumerate(train_dataloader): outputs = model(**batch, output_attentions=True, return_dict=True) loss = outputs.loss att_mask = batch['attention_mask'].float() cur_attention_pattern = torch.bmm(torch.unsqueeze(att_mask, -1), torch.unsqueeze(att_mask, 1)) attention_patterns_sums += torch.sum(cur_attention_pattern, dim=0) cur = torch.zeros((cur_attention_pattern.shape[0], config.num_hidden_layers, config.num_attention_heads, args.max_length, args.max_length)).to(device) for l in range(config.num_hidden_layers): cur[:, l] = outputs.attentions[l] cur = cur * torch.unsqueeze(torch.unsqueeze(cur_attention_pattern, 1), 1) attentions_sums += torch.sum(cur, dim=0) final_avgs = torch.nan_to_num(attentions_sums / attention_patterns_sums).to(device) #save!! torch.save(attentions_sums.cpu(), os.path.join(args.output_dir, "attention_sums.pt")) torch.save(attention_patterns_sums.cpu(), os.path.join(args.output_dir, "attention_patterns_sums.pt")) torch.save(final_avgs.cpu(), os.path.join(args.output_dir, "avgs.pt")) if __name__ == "__main__": main()
25,813
40.236422
166
py
papa
papa-main/transformers/papa_scripts/run_papa_ner.py
#!/usr/bin/env python # coding=utf-8 # Copyright 2020 The HuggingFace Team All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Fine-tuning the library models for token classification. """ # You can also adapt this script on your own token classification task and datasets. Pointers for this are left as # comments. import torch import json import logging import os import sys from dataclasses import dataclass, field from typing import Optional import random import datasets import numpy as np from datasets import ClassLabel, load_dataset, load_metric import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorForTokenClassification, HfArgumentParser, PretrainedConfig, PreTrainedTokenizerFast, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version from transformers import papa_modules # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.17.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/token-classification/requirements.txt") logger = logging.getLogger(__name__) @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) config_name: Optional[str] = field( default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) tokenizer_name: Optional[str] = field( default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) model_revision: str = field( default="main", metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, ) use_auth_token: bool = field( default=False, metadata={ "help": "Will use the token generated when running `transformers-cli login` (necessary to use this script " "with private models)." }, ) use_freeze_extract_pooler: bool = field( default=False, metadata={ "help": "Whether to use the freeze pooler." }, ) grad_for_classifier_only: bool = field( default=False, metadata={ "help": "Update the classifier only." }, ) grad_for_classifier_and_static_only: bool = field( default=False, metadata={ "help": "Update the classifier and static matrices only." }, ) static_heads_dir: str = field( default=None, metadata={ "help": "The static heads dir." }, ) sorting_heads_dir: str = field( default=None, metadata={ "help": "The heads sorting dir." }, ) static_heads_num: int = field( default=0, metadata={ "help": "The number of static heads." }, ) sort_calculating: bool = field( default=False, metadata={ "help": "The number of static heads." }, ) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. """ use_papa_preprocess: bool = field( default=False, metadata={"help": "Use PAPA preprocess for token classification datasets."} ) task_name: Optional[str] = field(default="ner", metadata={"help": "The name of the task (ner, pos...)."}) dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) train_file: Optional[str] = field( default=None, metadata={"help": "The input training data file (a csv or JSON file)."} ) validation_file: Optional[str] = field( default=None, metadata={"help": "An optional input evaluation data file to evaluate on (a csv or JSON file)."}, ) test_file: Optional[str] = field( default=None, metadata={"help": "An optional input test data file to predict on (a csv or JSON file)."}, ) text_column_name: Optional[str] = field( default=None, metadata={"help": "The column name of text to input in the file (a csv or JSON file)."} ) label_column_name: Optional[str] = field( default=None, metadata={"help": "The column name of label to input in the file (a csv or JSON file)."} ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) max_seq_length: int = field( default=None, metadata={ "help": "The maximum total input sequence length after tokenization. If set, sequences longer " "than this will be truncated, sequences shorter will be padded." }, ) pad_to_max_length: bool = field( default=False, metadata={ "help": "Whether to pad all samples to model maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." }, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." }, ) max_predict_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." }, ) label_all_tokens: bool = field( default=False, metadata={ "help": "Whether to put the label for one word on all tokens of generated by that word or just on the " "one (in which case the other tokens will have a padding index)." }, ) return_entity_level_metrics: bool = field( default=False, metadata={"help": "Whether to return all the entity levels during evaluation or just the overall ones."}, ) def __post_init__(self): if self.dataset_name is None and self.train_file is None and self.validation_file is None: raise ValueError("Need either a dataset name or a training/validation file.") else: if self.train_file is not None: extension = self.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: extension = self.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." self.task_name = self.task_name.lower() def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir ) else: data_files = {} if data_args.train_file is not None: data_files["train"] = data_args.train_file if data_args.validation_file is not None: data_files["validation"] = data_args.validation_file if data_args.test_file is not None: data_files["test"] = data_args.test_file extension = data_args.train_file.split(".")[-1] raw_datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. if training_args.do_train: column_names = raw_datasets["train"].column_names features = raw_datasets["train"].features else: column_names = raw_datasets["validation"].column_names features = raw_datasets["validation"].features if data_args.text_column_name is not None: text_column_name = data_args.text_column_name elif "tokens" in column_names: text_column_name = "tokens" else: text_column_name = column_names[0] if data_args.label_column_name is not None: label_column_name = data_args.label_column_name elif f"{data_args.task_name}_tags" in column_names: label_column_name = f"{data_args.task_name}_tags" else: label_column_name = column_names[1] # In the event the labels are not a `Sequence[ClassLabel]`, we will need to go through the dataset to get the # unique labels. def get_label_list(labels): unique_labels = set() for label in labels: unique_labels = unique_labels | set(label) label_list = list(unique_labels) label_list.sort() return label_list if isinstance(features[label_column_name].feature, ClassLabel): label_list = features[label_column_name].feature.names label_keys = list(range(len(label_list))) else: label_list = get_label_list(raw_datasets["train"][label_column_name]) label_keys = label_list num_labels = len(label_list) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) config.use_freeze_extract_pooler = model_args.use_freeze_extract_pooler config.max_seq_length = data_args.max_seq_length if model_args.static_heads_num > 0: config.static_heads = {'heads_dir': model_args.static_heads_dir} config.static_heads['heads'] = papa_modules.get_sorting_heads_dict(model_args.sorting_heads_dir, model_args.static_heads_num) if model_args.sort_calculating: config.sort_calculating = {'heads_dir': model_args.static_heads_dir} tokenizer_name_or_path = model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path if config.model_type in {"gpt2", "roberta", "deberta"}: tokenizer = AutoTokenizer.from_pretrained( tokenizer_name_or_path, cache_dir=model_args.cache_dir, use_fast=True, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, add_prefix_space=True, ) else: tokenizer = AutoTokenizer.from_pretrained( tokenizer_name_or_path, cache_dir=model_args.cache_dir, use_fast=True, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) model = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) if config.static_heads: model.prune_static_heads() if int(model_args.sort_calculating) + int(model_args.grad_for_classifier_only) + int(model_args.grad_for_classifier_and_static_only) > 1: raise Exception("Just one frozen gradients type is allowed") if model_args.sort_calculating: for param_name, param in list(model.named_parameters()): if param_name.startswith("classifier") or "pooler" in param_name or 'lambdas' in param_name: print("Not frozen param: ", param_name) continue param.requires_grad = False if model_args.grad_for_classifier_only: for param_name, param in list(model.named_parameters()): if "classifier" in param_name: print("Not frozen param: ", param_name) continue param.requires_grad = False if model_args.grad_for_classifier_and_static_only: for param_name, param in list(model.named_parameters()): if "classifier" in param_name or "static_heads_content" in param_name: print("Not frozen param: ", param_name) continue param.requires_grad = False # Tokenizer check: this script requires a fast tokenizer. if not isinstance(tokenizer, PreTrainedTokenizerFast): raise ValueError( "This example script only works for models that have a fast tokenizer. Checkout the big table of models " "at https://huggingface.co/transformers/index.html#supported-frameworks to find the model types that meet this " "requirement" ) if model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id: label_name_to_id = {k: v for k, v in model.config.label2id.items()} if list(sorted(label_name_to_id.keys())) == list(sorted(label_list)): label_to_id = {k: int(label_name_to_id[k]) for k in label_keys} else: logger.warning( "Your model seems to have been trained with labels, but they don't match the dataset: ", f"model labels: {list(sorted(label_name_to_id.keys()))}, dataset labels: {list(sorted(label_list))}." "\nIgnoring the model labels as a result.", ) else: label_to_id = {k: i for i, k in enumerate(label_keys)} model.config.label2id = label_to_id model.config.id2label = {i: l for l, i in label_to_id.items()} # Map that sends B-Xxx label to its I-Xxx counterpart b_to_i_label = [] for idx, label in enumerate(label_list): if label.startswith("B-") and label.replace("B-", "I-") in label_list: b_to_i_label.append(label_list.index(label.replace("B-", "I-"))) else: b_to_i_label.append(idx) # Preprocessing the dataset # Padding strategy padding = "max_length" if data_args.pad_to_max_length else False def add_preprocess_func(tokenized_inputs): for i in range(len(tokenized_inputs.data['input_ids'])): sep_index = tokenized_inputs.data['input_ids'][i].index(tokenizer.sep_token_id) tokenized_inputs.data['input_ids'][i][sep_index] = tokenizer.pad_token_id tokenized_inputs.data['attention_mask'][i][sep_index] = 0 tokenized_inputs.data['input_ids'][i][-1] = tokenizer.sep_token_id tokenized_inputs.data['attention_mask'][i][-1] = 1 # Tokenize all texts and align the labels with them. def tokenize_and_align_labels(examples): tokenized_inputs = tokenizer( examples[text_column_name], padding=padding, truncation=True, max_length=data_args.max_seq_length, # We use this argument because the texts in our dataset are lists of words (with a label for each word). is_split_into_words=True, ) if data_args.use_papa_preprocess: add_preprocess_func(tokenized_inputs) labels = [] for i, label in enumerate(examples[label_column_name]): word_ids = tokenized_inputs.word_ids(batch_index=i) previous_word_idx = None label_ids = [] for word_idx in word_ids: # Special tokens have a word id that is None. We set the label to -100 so they are automatically # ignored in the loss function. if word_idx is None: label_ids.append(-100) # We set the label for the first token of each word. elif word_idx != previous_word_idx: label_ids.append(label_to_id[label[word_idx]]) # For the other tokens in a word, we set the label to either the current label or -100, depending on # the label_all_tokens flag. else: if data_args.label_all_tokens: label_ids.append(b_to_i_label[label_to_id[label[word_idx]]]) else: label_ids.append(-100) previous_word_idx = word_idx labels.append(label_ids) tokenized_inputs["labels"] = labels return tokenized_inputs if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset") train_dataset = raw_datasets["train"] if data_args.max_train_samples is not None: train_dataset = train_dataset.select(range(data_args.max_train_samples)) with training_args.main_process_first(desc="train dataset map pre-processing"): train_dataset = train_dataset.map( tokenize_and_align_labels, batched=True, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on train dataset", ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset") eval_dataset = raw_datasets["validation"] if data_args.max_eval_samples is not None: eval_dataset = eval_dataset.select(range(data_args.max_eval_samples)) with training_args.main_process_first(desc="validation dataset map pre-processing"): eval_dataset = eval_dataset.map( tokenize_and_align_labels, batched=True, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on validation dataset", ) if training_args.do_predict: if "test" not in raw_datasets: raise ValueError("--do_predict requires a test dataset") predict_dataset = raw_datasets["test"] if data_args.max_predict_samples is not None: predict_dataset = predict_dataset.select(range(data_args.max_predict_samples)) with training_args.main_process_first(desc="prediction dataset map pre-processing"): predict_dataset = predict_dataset.map( tokenize_and_align_labels, batched=True, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on prediction dataset", ) # Data collator data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8 if training_args.fp16 else None) # Metrics metric = load_metric("seqeval") def compute_metrics(p): predictions, labels = p predictions = np.argmax(predictions, axis=2) # Remove ignored index (special tokens) true_predictions = [ [label_list[p] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] true_labels = [ [label_list[l] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] results = metric.compute(predictions=true_predictions, references=true_labels) if data_args.return_entity_level_metrics: # Unpack nested dictionaries final_results = {} for key, value in results.items(): if isinstance(value, dict): for n, v in value.items(): final_results[f"{key}_{n}"] = v else: final_results[key] = value return final_results else: return { "precision": results["overall_precision"], "recall": results["overall_recall"], "f1": results["overall_f1"], "accuracy": results["overall_accuracy"], } # Initialize our Trainer trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, tokenizer=tokenizer, data_collator=data_collator, compute_metrics=compute_metrics, ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(train_dataset)), 3): logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") # Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint elif last_checkpoint is not None: checkpoint = last_checkpoint train_result = trainer.train(resume_from_checkpoint=checkpoint) metrics = train_result.metrics if training_args.save_total_limit != 0: trainer.save_model() # Saves the tokenizer too for easy upload else: config.save_pretrained(training_args.output_dir) if model_args.sort_calculating: lambdas = np.array([torch.squeeze(l.attention.self.lambdas).cpu().detach().numpy() for l in model.base_model.encoder.layer]) np.save(os.path.join(training_args.output_dir, "lambdas"), lambdas) lambdas_sorted = np.argsort(lambdas.flatten()) with open(os.path.join(training_args.output_dir, "sorted_heads.json"), "w") as fp: heads_sorted = [[int(h // config.num_attention_heads), int(h % config.num_attention_heads)] for h in lambdas_sorted] json.dump(heads_sorted, fp) max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) ) metrics["train_samples"] = min(max_train_samples, len(train_dataset)) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***") metrics = trainer.evaluate() max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) # Predict if training_args.do_predict: logger.info("*** Predict ***") predictions, labels, metrics = trainer.predict(predict_dataset, metric_key_prefix="predict") predictions = np.argmax(predictions, axis=2) # Remove ignored index (special tokens) true_predictions = [ [label_list[p] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] trainer.log_metrics("predict", metrics) trainer.save_metrics("predict", metrics) # Save predictions output_predictions_file = os.path.join(training_args.output_dir, "predictions.txt") if trainer.is_world_process_zero(): with open(output_predictions_file, "w") as writer: for prediction in true_predictions: writer.write(" ".join(prediction) + "\n") kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "token-classification"} if data_args.dataset_name is not None: kwargs["dataset_tags"] = data_args.dataset_name if data_args.dataset_config_name is not None: kwargs["dataset_args"] = data_args.dataset_config_name kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" else: kwargs["dataset"] = data_args.dataset_name if training_args.push_to_hub: trainer.push_to_hub(**kwargs) else: trainer.create_model_card(**kwargs) def _mp_fn(index): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
29,358
40.119048
141
py
papa
papa-main/transformers/papa_scripts/run_papa_glue_avgs_creator.py
# coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Finetuning a 🤗 Transformers model for sequence classification on GLUE.""" import argparse import logging import math import os import random from pathlib import Path import json import datasets from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from tqdm.auto import tqdm import torch import numpy as np import transformers from accelerate import Accelerator from huggingface_hub import Repository from transformers import ( AdamW, AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, PretrainedConfig, SchedulerType, default_data_collator, get_scheduler, set_seed, ) from transformers.file_utils import get_full_repo_name from transformers.utils.versions import require_version logger = logging.getLogger(__name__) require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") task_to_keys = { "cola": ("sentence", None), "mnli": ("premise", "hypothesis"), "mrpc": ("sentence1", "sentence2"), "qnli": ("question", "sentence"), "qqp": ("question1", "question2"), "rte": ("sentence1", "sentence2"), "sst2": ("sentence", None), "stsb": ("sentence1", "sentence2"), "wnli": ("sentence1", "sentence2"), } def parse_args(): parser = argparse.ArgumentParser(description="Finetune a transformers model on a text classification task") parser.add_argument( "--task_name", type=str, default=None, help="The name of the glue task to train on.", choices=list(task_to_keys.keys()), ) parser.add_argument( "--use_papa_preprocess", type=bool, default=False, help="Use papa preprocess for glue dataset.", ) parser.add_argument( "--cache_dir", type=str, default=None, help="Where do you want to store the pretrained models downloaded from huggingface.co.", ) parser.add_argument( "--train_file", type=str, default=None, help="A csv or a json file containing the training data." ) parser.add_argument( "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data." ) parser.add_argument( "--max_length", type=int, default=128, help=( "The maximum total input sequence length after tokenization. Sequences longer than this will be truncated," " sequences shorter will be padded if `--pad_to_max_lengh` is passed." ), ) parser.add_argument( "--pad_to_max_length", action="store_true", help="If passed, pad all samples to `max_length`. Otherwise, dynamic padding is used.", ) parser.add_argument( "--model_name_or_path", type=str, help="Path to pretrained model or model identifier from huggingface.co/models.", required=True, ) parser.add_argument( "--use_slow_tokenizer", action="store_true", help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).", ) parser.add_argument( "--per_device_train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader.", ) parser.add_argument( "--per_device_eval_batch_size", type=int, default=8, help="Batch size (per device) for the evaluation dataloader.", ) parser.add_argument( "--learning_rate", type=float, default=5e-5, help="Initial learning rate (after the potential warmup period) to use.", ) parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.") parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.") parser.add_argument( "--max_train_steps", type=int, default=None, help="Total number of training steps to perform. If provided, overrides num_train_epochs.", ) parser.add_argument( "--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument( "--lr_scheduler_type", type=SchedulerType, default="linear", help="The scheduler type to use.", choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"], ) parser.add_argument( "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler." ) parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.") parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.") parser.add_argument( "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`." ) parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.") args = parser.parse_args() # Sanity checks if args.task_name is None and args.train_file is None and args.validation_file is None: raise ValueError("Need either a task name or a training/validation file.") else: if args.train_file is not None: extension = args.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if args.validation_file is not None: extension = args.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." if args.push_to_hub: assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed." return args def main(): args = parse_args() # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. accelerator = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) logger.info(accelerator.state) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Handle the repository creation if accelerator.is_main_process: if args.push_to_hub: if args.hub_model_id is None: repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token) else: repo_name = args.hub_model_id repo = Repository(args.output_dir, clone_from=repo_name) elif args.output_dir is not None: os.makedirs(args.output_dir, exist_ok=True) accelerator.wait_for_everyone() # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the # sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named # label if at least two columns are provided. # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if args.task_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset("glue", args.task_name, cache_dir=args.cache_dir) else: # Loading the dataset from local csv or json file. data_files = {} if args.train_file is not None: data_files["train"] = args.train_file if args.validation_file is not None: data_files["validation"] = args.validation_file extension = (args.train_file if args.train_file is not None else args.valid_file).split(".")[-1] raw_datasets = load_dataset(extension, data_files=data_files) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels if args.task_name is not None: is_regression = args.task_name == "stsb" if not is_regression: label_list = raw_datasets["train"].features["label"].names num_labels = len(label_list) else: num_labels = 1 else: # Trying to have good defaults here, don't hesitate to tweak to your needs. is_regression = raw_datasets["train"].features["label"].dtype in ["float32", "float64"] if is_regression: num_labels = 1 else: # A useful fast method: # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.unique label_list = raw_datasets["train"].unique("label") label_list.sort() # Let's sort it for determinism num_labels = len(label_list) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config = AutoConfig.from_pretrained(args.model_name_or_path, num_labels=num_labels, finetuning_task=args.task_name) tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer) model = AutoModelForSequenceClassification.from_pretrained( args.model_name_or_path, from_tf=bool(".ckpt" in args.model_name_or_path), config=config, cache_dir=args.cache_dir, ) # Preprocessing the datasets if args.task_name is not None: sentence1_key, sentence2_key = task_to_keys[args.task_name] else: # Again, we try to have some nice defaults but don't hesitate to tweak to your use case. non_label_column_names = [name for name in raw_datasets["train"].column_names if name != "label"] if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names: sentence1_key, sentence2_key = "sentence1", "sentence2" else: if len(non_label_column_names) >= 2: sentence1_key, sentence2_key = non_label_column_names[:2] else: sentence1_key, sentence2_key = non_label_column_names[0], None # Some models have set the order of the labels to use, so let's make sure we do use it. label_to_id = None if ( model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id and args.task_name is not None and not is_regression ): # Some have all caps in their config, some don't. label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()} if list(sorted(label_name_to_id.keys())) == list(sorted(label_list)): logger.info( f"The configuration of the model provided the following label correspondence: {label_name_to_id}. " "Using it!" ) label_to_id = {i: label_name_to_id[label_list[i]] for i in range(num_labels)} else: logger.warning( "Your model seems to have been trained with labels, but they don't match the dataset: ", f"model labels: {list(sorted(label_name_to_id.keys()))}, dataset labels: {list(sorted(label_list))}." "\nIgnoring the model labels as a result.", ) elif args.task_name is None: label_to_id = {v: i for i, v in enumerate(label_list)} if label_to_id is not None: model.config.label2id = label_to_id model.config.id2label = {id: label for label, id in config.label2id.items()} elif args.task_name is not None and not is_regression: model.config.label2id = {l: i for i, l in enumerate(label_list)} model.config.id2label = {id: label for label, id in config.label2id.items()} padding = "max_length" if args.pad_to_max_length else False def add_preprocess_func(result): input_ids = result.data['input_ids'] att_mask = result.data['attention_mask'] max_seq_length = args.max_length new_input_ids = [[tokenizer.pad_token_id] * max_seq_length for i in range(len(input_ids))] new_att_mask = [[0] * max_seq_length for i in range(len(input_ids))] for i, cur_input_ids, cur_att_mask in zip(range(len(input_ids)), input_ids, att_mask): first_sep_index = cur_input_ids.index(tokenizer.sep_token_id) last_sep_index = len(cur_input_ids) - list(reversed(cur_input_ids)).index(tokenizer.sep_token_id) - 1 for j in range(min(first_sep_index, max_seq_length // 2)): new_input_ids[i][j] = cur_input_ids[j] new_att_mask[i][j] = 1 for j in range(first_sep_index, last_sep_index): if max_seq_length // 2 + j - first_sep_index == len(new_input_ids[i]) - 1: break new_input_ids[i][max_seq_length // 2 + j - first_sep_index] = cur_input_ids[j] new_att_mask[i][max_seq_length // 2 + j - first_sep_index] = 1 new_input_ids[i][-1] = cur_input_ids[last_sep_index] new_att_mask[i][-1] = 1 result.data['input_ids'] = new_input_ids result.data['attention_mask'] = new_att_mask def preprocess_function(examples): # Tokenize the texts texts = ( (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key]) ) result = tokenizer(*texts, padding=padding, max_length=args.max_length, truncation=True) if args.use_papa_preprocess: add_preprocess_func(result) if "label" in examples: if label_to_id is not None: # Map labels to IDs (not necessary for GLUE tasks) result["labels"] = [label_to_id[l] for l in examples["label"]] else: # In all cases, rename the column to labels because the model will expect that. result["labels"] = examples["label"] return result with accelerator.main_process_first(): processed_datasets = raw_datasets.map( preprocess_function, batched=True, remove_columns=raw_datasets["train"].column_names, load_from_cache_file=True, desc="Running tokenizer on dataset", ) train_dataset = processed_datasets["train"] eval_dataset = processed_datasets["validation_matched" if args.task_name == "mnli" else "validation"] # Log a few random samples from the training set: for index in random.sample(range(len(train_dataset)), 3): logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") # DataLoaders creation: if args.pad_to_max_length: # If padding was already done ot max length, we use the default data collator that will just convert everything # to tensors. data_collator = default_data_collator else: # Otherwise, `DataCollatorWithPadding` will apply dynamic padding for us (by padding to the maximum length of # the samples passed). When using mixed precision, we add `pad_to_multiple_of=8` to pad all tensors to multiple # of 8s, which will enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta). data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=(8 if accelerator.use_fp16 else None)) train_dataloader = DataLoader( train_dataset, shuffle=True, collate_fn=data_collator, batch_size=args.per_device_train_batch_size ) eval_dataloader = DataLoader(eval_dataset, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size) # Optimizer # Split weights in two groups, one with weight decay and the other not. no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": args.weight_decay, }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate) # Prepare everything with our `accelerator`. model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare( model, optimizer, train_dataloader, eval_dataloader ) # Note -> the training dataloader needs to be prepared before we grab his length below (cause its length will be # shorter in multiprocess) # Scheduler and math around the number of training steps. num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) if args.max_train_steps is None: args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch else: args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) lr_scheduler = get_scheduler( name=args.lr_scheduler_type, optimizer=optimizer, num_warmup_steps=args.num_warmup_steps, num_training_steps=args.max_train_steps, ) # Get the metric function if args.task_name is not None: metric = load_metric("glue", args.task_name) else: metric = load_metric("accuracy") # Train! total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps logger.info("***** Running training *****") logger.info(f" Num examples = {len(train_dataset)}") logger.info(f" Num Epochs = {args.num_train_epochs}") logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") logger.info(f" Total optimization steps = {args.max_train_steps}") # Only show the progress bar once on each machine. progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) completed_steps = 0 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') with torch.no_grad(): attentions_sums = torch.zeros((config.num_hidden_layers, config.num_attention_heads, args.max_length, args.max_length)).to(device) attention_patterns_sums = torch.zeros((args.max_length, args.max_length)).to(device) model.eval() for epoch in range(1): for step, batch in enumerate(train_dataloader): outputs = model(**batch, output_attentions=True, return_dict=True) loss = outputs.loss att_mask = batch['attention_mask'].float() cur_attention_pattern = torch.bmm(torch.unsqueeze(att_mask, -1), torch.unsqueeze(att_mask, 1)) attention_patterns_sums += torch.sum(cur_attention_pattern, dim=0) cur = torch.zeros((cur_attention_pattern.shape[0], config.num_hidden_layers, config.num_attention_heads, args.max_length, args.max_length)).to(device) for l in range(config.num_hidden_layers): cur[:, l] = outputs.attentions[l] cur = cur * torch.unsqueeze(torch.unsqueeze(cur_attention_pattern, 1), 1) attentions_sums += torch.sum(cur, dim=0) final_avgs = torch.nan_to_num(attentions_sums / attention_patterns_sums).to(device) #save!! torch.save(attentions_sums.cpu(), os.path.join(args.output_dir, "attention_sums.pt")) torch.save(attention_patterns_sums.cpu(), os.path.join(args.output_dir, "attention_patterns_sums.pt")) torch.save(final_avgs.cpu(), os.path.join(args.output_dir, "avgs.pt")) if __name__ == "__main__": main()
21,837
42.763527
166
py
papa
papa-main/transformers/papa_scripts/run_papa_glue.py
#!/usr/bin/env python # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Finetuning the library models for sequence classification on GLUE.""" # You can also adapt this script on your own text classification task. Pointers for this are left as comments. import torch import json import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np from datasets import load_dataset, load_metric import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, PretrainedConfig, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version from transformers import papa_modules # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.17.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") task_to_keys = { "cola": ("sentence", None), "mnli": ("premise", "hypothesis"), "mrpc": ("sentence1", "sentence2"), "qnli": ("question", "sentence"), "qqp": ("question1", "question2"), "rte": ("sentence1", "sentence2"), "sst2": ("sentence", None), "stsb": ("sentence1", "sentence2"), "wnli": ("sentence1", "sentence2"), } logger = logging.getLogger(__name__) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command line. """ use_papa_preprocess: bool = field( default=False, metadata={"help": "Use PAPA preprocess for seq classification datasets"} ) task_name: Optional[str] = field( default=None, metadata={"help": "The name of the task to train on: " + ", ".join(task_to_keys.keys())}, ) dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) max_seq_length: int = field( default=128, metadata={ "help": "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." }, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) pad_to_max_length: bool = field( default=True, metadata={ "help": "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." }, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." }, ) max_predict_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." }, ) train_file: Optional[str] = field( default=None, metadata={"help": "A csv or a json file containing the training data."} ) validation_file: Optional[str] = field( default=None, metadata={"help": "A csv or a json file containing the validation data."} ) test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."}) def __post_init__(self): if self.task_name is not None: self.task_name = self.task_name.lower() if self.task_name not in task_to_keys.keys(): raise ValueError("Unknown task, you should pick one in " + ",".join(task_to_keys.keys())) elif self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError("Need either a GLUE task, a training/validation file or a dataset name.") else: train_extension = self.train_file.split(".")[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." validation_extension = self.validation_file.split(".")[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) config_name: Optional[str] = field( default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) tokenizer_name: Optional[str] = field( default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) use_fast_tokenizer: bool = field( default=True, metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, ) model_revision: str = field( default="main", metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, ) use_auth_token: bool = field( default=False, metadata={ "help": "Will use the token generated when running `transformers-cli login` (necessary to use this script " "with private models)." }, ) use_freeze_extract_pooler: bool = field( default=False, metadata={ "help": "Whether to use the freeze pooler." }, ) grad_for_classifier_only: bool = field( default=False, metadata={ "help": "Update the classifier only." }, ) grad_for_classifier_and_static_only: bool = field( default=False, metadata={ "help": "Update the classifier and static matrices only." }, ) static_heads_dir: str = field( default=None, metadata={ "help": "The static heads dir." }, ) sorting_heads_dir: str = field( default=None, metadata={ "help": "The heads sorting dir." }, ) static_heads_num: int = field( default=0, metadata={ "help": "The number of static heads." }, ) sort_calculating: bool = field( default=False, metadata={ "help": "The number of static heads." }, ) def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the # sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named # label if at least two columns are provided. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.task_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset("glue", data_args.task_name, cache_dir=model_args.cache_dir) elif data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. data_files = {"train": data_args.train_file, "validation": data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: train_extension = data_args.train_file.split(".")[-1] test_extension = data_args.test_file.split(".")[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." data_files["test"] = data_args.test_file else: raise ValueError("Need either a GLUE task or a test file for `do_predict`.") for key in data_files.keys(): logger.info(f"load a local file for {key}: {data_files[key]}") if data_args.train_file.endswith(".csv"): # Loading a dataset from local csv files raw_datasets = load_dataset("csv", data_files=data_files, cache_dir=model_args.cache_dir) else: # Loading a dataset from local json files raw_datasets = load_dataset("json", data_files=data_files, cache_dir=model_args.cache_dir) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels if data_args.task_name is not None: is_regression = data_args.task_name == "stsb" if not is_regression: label_list = raw_datasets["train"].features["label"].names num_labels = len(label_list) else: num_labels = 1 else: # Trying to have good defaults here, don't hesitate to tweak to your needs. is_regression = raw_datasets["train"].features["label"].dtype in ["float32", "float64"] if is_regression: num_labels = 1 else: # A useful fast method: # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.unique label_list = raw_datasets["train"].unique("label") label_list.sort() # Let's sort it for determinism num_labels = len(label_list) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) config.use_freeze_extract_pooler = model_args.use_freeze_extract_pooler config.max_seq_length = data_args.max_seq_length if model_args.static_heads_num > 0: config.static_heads = {'heads_dir': model_args.static_heads_dir} config.static_heads['heads'] = papa_modules.get_sorting_heads_dict(model_args.sorting_heads_dir, model_args.static_heads_num) if model_args.sort_calculating: config.sort_calculating = {'heads_dir': model_args.static_heads_dir} tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) model = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) if config.static_heads: model.prune_static_heads() if int(model_args.sort_calculating) + int(model_args.grad_for_classifier_only) + int(model_args.grad_for_classifier_and_static_only) > 1: raise Exception("Just one frozen gradients type is allowed") if model_args.sort_calculating: for param_name, param in list(model.named_parameters()): if param_name.startswith("classifier") or "pooler" in param_name or 'lambdas' in param_name: print("Not frozen param: ", param_name) continue param.requires_grad = False if model_args.grad_for_classifier_only: for param_name, param in list(model.named_parameters()): if param_name.startswith("classifier") or "pooler" in param_name: print("Not frozen param: ", param_name) continue param.requires_grad = False if model_args.grad_for_classifier_and_static_only: for param_name, param in list(model.named_parameters()): if param_name.startswith("classifier") or "pooler" in param_name or "static_heads_content" in param_name: print("Not frozen param: ", param_name) continue param.requires_grad = False # Preprocessing the raw_datasets if data_args.task_name is not None: sentence1_key, sentence2_key = task_to_keys[data_args.task_name] else: # Again, we try to have some nice defaults but don't hesitate to tweak to your use case. non_label_column_names = [name for name in raw_datasets["train"].column_names if name != "label"] if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names: sentence1_key, sentence2_key = "sentence1", "sentence2" else: if len(non_label_column_names) >= 2: sentence1_key, sentence2_key = non_label_column_names[:2] else: sentence1_key, sentence2_key = non_label_column_names[0], None # Padding strategy if data_args.pad_to_max_length: padding = "max_length" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch padding = False # Some models have set the order of the labels to use, so let's make sure we do use it. label_to_id = None if ( model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id and data_args.task_name is not None and not is_regression ): # Some have all caps in their config, some don't. label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()} if list(sorted(label_name_to_id.keys())) == list(sorted(label_list)): label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)} else: logger.warning( "Your model seems to have been trained with labels, but they don't match the dataset: ", f"model labels: {list(sorted(label_name_to_id.keys()))}, dataset labels: {list(sorted(label_list))}." "\nIgnoring the model labels as a result.", ) elif data_args.task_name is None and not is_regression: label_to_id = {v: i for i, v in enumerate(label_list)} if label_to_id is not None: model.config.label2id = label_to_id model.config.id2label = {id: label for label, id in config.label2id.items()} elif data_args.task_name is not None and not is_regression: model.config.label2id = {l: i for i, l in enumerate(label_list)} model.config.id2label = {id: label for label, id in config.label2id.items()} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the" f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) def add_preprocess_func(result): input_ids = result.data['input_ids'] att_mask = result.data['attention_mask'] result.data['old_input_ids'] = result.data['input_ids'] result.data['old_attention_mask'] = result.data['attention_mask'] new_input_ids = [[tokenizer.pad_token_id] * max_seq_length for i in range(len(input_ids))] new_att_mask = [[0] * max_seq_length for i in range(len(input_ids))] for i, cur_input_ids, cur_att_mask in zip(range(len(input_ids)), input_ids, att_mask): first_sep_index = cur_input_ids.index(tokenizer.sep_token_id) last_sep_index = len(cur_input_ids) - list(reversed(cur_input_ids)).index(tokenizer.sep_token_id) - 1 for j in range(min(first_sep_index, max_seq_length // 2)): new_input_ids[i][j] = cur_input_ids[j] new_att_mask[i][j] = 1 for j in range(first_sep_index, last_sep_index): if max_seq_length // 2 + j - first_sep_index == len(new_input_ids[i]) - 1: break new_input_ids[i][max_seq_length // 2 + j - first_sep_index] = cur_input_ids[j] new_att_mask[i][max_seq_length // 2 + j - first_sep_index] = 1 new_input_ids[i][-1] = cur_input_ids[last_sep_index] new_att_mask[i][-1] = 1 result.data['input_ids'] = new_input_ids result.data['attention_mask'] = new_att_mask def preprocess_function(examples): # Tokenize the texts args = ( (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key]) ) result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True) if data_args.use_papa_preprocess: add_preprocess_func(result) # Map labels to IDs (not necessary for GLUE tasks) if label_to_id is not None and "label" in examples: result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]] return result with training_args.main_process_first(desc="dataset map pre-processing"): raw_datasets = raw_datasets.map( preprocess_function, batched=True, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on dataset", ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset") train_dataset = raw_datasets["train"] if data_args.max_train_samples is not None: train_dataset = train_dataset.select(range(data_args.max_train_samples)) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset") eval_dataset = raw_datasets["validation_matched" if data_args.task_name == "mnli" else "validation"] if data_args.max_eval_samples is not None: eval_dataset = eval_dataset.select(range(data_args.max_eval_samples)) if training_args.do_predict or data_args.task_name is not None or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError("--do_predict requires a test dataset") predict_dataset = raw_datasets["test_matched" if data_args.task_name == "mnli" else "test"] if data_args.max_predict_samples is not None: predict_dataset = predict_dataset.select(range(data_args.max_predict_samples)) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(train_dataset)), 3): logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") # Get the metric function if data_args.task_name is not None: metric = load_metric("glue", data_args.task_name) else: metric = load_metric("accuracy") # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(p: EvalPrediction): preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1) if data_args.task_name is not None: result = metric.compute(predictions=preds, references=p.label_ids) if len(result) > 1: result["combined_score"] = np.mean(list(result.values())).item() return result elif is_regression: return {"mse": ((preds - p.label_ids) ** 2).mean().item()} else: return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: data_collator = default_data_collator elif training_args.fp16: data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) else: data_collator = None # Initialize our Trainer trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, compute_metrics=compute_metrics, tokenizer=tokenizer, data_collator=data_collator, ) # Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint elif last_checkpoint is not None: checkpoint = last_checkpoint train_result = trainer.train(resume_from_checkpoint=checkpoint) metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) ) metrics["train_samples"] = min(max_train_samples, len(train_dataset)) if training_args.save_total_limit != 0: trainer.save_model() # Saves the tokenizer too for easy upload else: config.save_pretrained(training_args.output_dir) if model_args.sort_calculating: lambdas = np.array([torch.squeeze(l.attention.self.lambdas).cpu().detach().numpy() for l in model.base_model.encoder.layer]) np.save(os.path.join(training_args.output_dir, "lambdas"), lambdas) lambdas_sorted = np.argsort(lambdas.flatten()) with open(os.path.join(training_args.output_dir, "sorted_heads.json"), "w") as fp: heads_sorted = [[int(h // config.num_attention_heads), int(h % config.num_attention_heads)] for h in lambdas_sorted] json.dump(heads_sorted, fp) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***") # Loop to handle MNLI double evaluation (matched, mis-matched) tasks = [data_args.task_name] eval_datasets = [eval_dataset] if data_args.task_name == "mnli": tasks.append("mnli-mm") eval_datasets.append(raw_datasets["validation_mismatched"]) for eval_dataset, task in zip(eval_datasets, tasks): metrics = trainer.evaluate(eval_dataset=eval_dataset) max_eval_samples = ( data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) ) metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) split = "eval" if task.startswith('mnli'): split = eval_dataset.split._name trainer.log_metrics(split, metrics) trainer.save_metrics(split, metrics) if training_args.do_predict: logger.info("*** Predict ***") # Loop to handle MNLI double evaluation (matched, mis-matched) tasks = [data_args.task_name] predict_datasets = [predict_dataset] if data_args.task_name == "mnli": tasks.append("mnli-mm") predict_datasets.append(raw_datasets["test_mismatched"]) for predict_dataset, task in zip(predict_datasets, tasks): metrics = trainer.evaluate(eval_dataset=predict_dataset) max_eval_samples = ( data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) ) metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) split = "test" if task.startswith('mnli'): split = predict_dataset.split._name trainer.log_metrics(split, metrics) trainer.save_metrics(split, metrics) for predict_dataset, task in zip(predict_datasets, tasks): # Removing the `label` columns because it contains -1 and Trainer won't like that. predict_dataset = predict_dataset.remove_columns("label") predictions = trainer.predict(predict_dataset, metric_key_prefix="predict").predictions predictions = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1) output_predict_file = os.path.join(training_args.output_dir, f"predict_results_{task}.txt") if trainer.is_world_process_zero(): with open(output_predict_file, "w") as writer: logger.info(f"***** Predict results {task} *****") writer.write("index\tprediction\n") for index, item in enumerate(predictions): if is_regression: writer.write(f"{index}\t{item:3.3f}\n") else: item = label_list[item] writer.write(f"{index}\t{item}\n") kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-classification"} if data_args.task_name is not None: kwargs["language"] = "en" kwargs["dataset_tags"] = "glue" kwargs["dataset_args"] = data_args.task_name kwargs["dataset"] = f"GLUE {data_args.task_name.upper()}" if training_args.push_to_hub: trainer.push_to_hub(**kwargs) else: trainer.create_model_card(**kwargs) def _mp_fn(index): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
31,178
42.064917
141
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/inference.py
import logging import torch from torch.utils.data import DataLoader from tqdm import tqdm from modelling.datasets import DataConfig, collaters_factory, datasets_factory from modelling.configs import model_configs_factory from modelling.models import models_factory from utils.evaluation import evaluators_factory from utils.parser import Parser from utils.train_inference_utils import get_device, move_batch_to_device @torch.no_grad() def inference(args): # Set up logging logging.basicConfig(level=logging.INFO) # Check for CUDA device = get_device(logger=logging.getLogger(__name__)) logging.info("Preparing dataset...") data_config = DataConfig( dataset_name=args.dataset_name, dataset_path=args.test_dataset_path, labels_path=args.labels_path, videoid2size_path=args.videoid2size_path, layout_num_frames=args.layout_num_frames, appearance_num_frames=args.appearance_num_frames, videos_path=args.videos_path, train=False, ) test_dataset = datasets_factory[args.dataset_type](data_config) num_samples = len(test_dataset) logging.info(f"Inference on {num_samples}") collater = collaters_factory[args.dataset_type](data_config) # Prepare loader test_loader = DataLoader( test_dataset, batch_size=args.batch_size, collate_fn=collater, num_workers=args.num_workers, pin_memory=True if args.num_workers else False, ) logging.info("Preparing model...") # Prepare model num_classes = len(test_dataset.labels) model_config = model_configs_factory[args.model_name]( num_classes=num_classes, unique_categories=len(data_config.category2id), num_spatial_layers=args.num_spatial_layers, num_temporal_layers=args.num_temporal_layers, appearance_num_frames=args.appearance_num_frames, resnet_model_path=args.resnet_model_path, ) logging.info("==================================") logging.info(f"The model's configuration is:\n{model_config}") logging.info("==================================") model = models_factory[args.model_name](model_config).to(device) try: model.load_state_dict(torch.load(args.checkpoint_path, map_location=device)) except RuntimeError as e: logging.warning( "Default loading failed, loading with strict=False. If it's only " "score_embedding modules it's ok. Otherwise see exception below" ) logging.warning(e) model.load_state_dict( torch.load(args.checkpoint_path, map_location=device), strict=False ) model.train(False) logging.info("Starting inference...") evaluator = evaluators_factory[args.dataset_name]( num_samples, num_classes, model.logit_names ) for batch in tqdm(test_loader): batch = move_batch_to_device(batch, device) logits = model(batch) evaluator.process(logits, batch["labels"]) metrics = evaluator.evaluate() logging.info("=================================") logging.info("The metrics are:") for m in metrics.keys(): logging.info(f"{m}: {round(metrics[m] * 100, 2)}") logging.info("=================================") def main(): parser = Parser("Inference with a model, currenly STLT, LCF, CAF, and CACNF.") inference(parser.parse_args()) if __name__ == "__main__": main()
3,445
35.273684
84
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/dump_perframe_features.py
import argparse import io import json import logging import h5py import numpy as np import torch from natsort import natsorted from PIL import Image from torch import nn from torchvision import resnet152, transforms class FrameEncoder(nn.Module): def __init__(self): super(FrameEncoder, self).__init__() self.resnet = torch.nn.Sequential( *(list(resnet152(pretrained=True).children())[:-1]) ) def forward(self, images: torch.Tensor): embedded_images = torch.flatten(self.resnet(images), start_dim=1) return embedded_images class FrameTransformer: def __init__(self): super(FrameTransformer, self).__init__() self.transformer = transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), transforms.CenterCrop((224, 224)), ] ) def __call__(self, image: Image): return self.transformer(image) @torch.no_grad() def dump_video_frames(args): if args.log_filepath: logging.basicConfig( level=logging.INFO, filename=args.log_filepath, filemode="w" ) else: logging.basicConfig(level=logging.INFO) # Prepare model device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") logging.info("Loading model...") model = FrameEncoder().to(device) model.eval() # Prepare transforms video_transforms = FrameTransformer() # Prepare data logging.info("Loading dataset...") video_ids = json.load(open(args.videoid2size_path)) with h5py.File( args.videos_path, "r", libver="latest", swmr=True ) as videos, h5py.File(args.save_features_path, "a") as video_features: cur_video_featues = set(video_features.keys()) # Start dumping logging.info("Dumping features...") for index, video_id in enumerate(video_ids.keys()): if video_id in cur_video_featues: continue frame_ids = natsorted([frame_id for frame_id in videos[video_id].keys()]) video_frames = torch.stack( [ video_transforms( Image.open(io.BytesIO(np.array(videos[video_id][frame_id]))) ) for frame_id in frame_ids ], dim=0, ).to(device) # Obtain model output and save features features = model(video_frames).cpu().numpy() video_features.create_dataset(video_id, data=features) if index % args.print_freq == 0: logging.info(f"Current index is {index}") def main(): parser = argparse.ArgumentParser( description="Dumps perframe features from ResNet152." ) parser.add_argument( "--videos_path", type=str, default="data/dataset.hdf5", help="From where to load the videos.", ) parser.add_argument( "--videoid2size_path", type=str, default="data/videoid2size.json", help="Path to the videoid2size file.", ) parser.add_argument( "--save_features_path", type=str, default="data/per_frame_features.hdf5", help="Where to save the per-frame features.", ) parser.add_argument( "--print_freq", type=int, default=1000, help="How often to print.", ) parser.add_argument( "--log_filepath", type=str, default=None, help="The logging destination.", ) args = parser.parse_args() dump_video_frames(args) if __name__ == "__main__": main()
3,736
28.425197
87
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/dump_perbox_features.py
import argparse import io import json import logging from typing import List import h5py import numpy as np import torch from natsort import natsorted from PIL import Image from torch import nn from torchvision import transforms from torchvision.models.detection import fasterrcnn_resnet50_fpn from torchvision.models.detection.transform import resize_boxes class FeatureExtractor(nn.Module): def __init__(self): super(FeatureExtractor, self).__init__() self.model = fasterrcnn_resnet50_fpn( pretrained=True, min_size=240, max_size=540 ) self.pooler = nn.AdaptiveAvgPool2d(output_size=(3, 3)) def forward(self, frames: List[torch.Tensor], boxes: List[torch.Tensor]): org_sizes = [frame.shape[-2:] for frame in frames] transformed_frames, _ = self.model.transform(frames) proposals = [ resize_boxes(boxes[i], org_sizes[i], transformed_frames.image_sizes[i]) for i in range(len(boxes)) ] backbone_output = self.model.backbone(transformed_frames.tensors) selected_rois = self.model.roi_heads.box_roi_pool( backbone_output, proposals, transformed_frames.image_sizes ) pooled_rois = self.pooler(selected_rois).flatten(1) return pooled_rois @torch.no_grad() def dump_video_frames(args): if args.log_filepath: logging.basicConfig( level=logging.INFO, filename=args.log_filepath, filemode="w" ) else: logging.basicConfig(level=logging.INFO) # Prepare model device = torch.device(args.device) logging.info("Loading model...") model = FeatureExtractor().to(device) model.eval() # Prepare data logging.info("Loading dataset...") json_file = json.load(open(args.dataset_path)) # Start dumping logging.info("Dumping features...") with h5py.File( args.videos_path, "r", libver="latest", swmr=True ) as videos, h5py.File(args.save_features_path, "a") as video_features: cur_video_featues = set(video_features.keys()) for index, element in enumerate(json_file): video_id = element["id"] if video_id in cur_video_featues: continue frame_ids = natsorted([frame_id for frame_id in videos[video_id].keys()]) num_frames = min(len(frame_ids), len(element["frames"])) video_frames = [] boxes = [] boxes_per_image = [] for frame_index in range(num_frames): video_frames.append( transforms.ToTensor()( Image.open( io.BytesIO( np.array(videos[video_id][frame_ids[frame_index]]) ) ) ).to(device) ) h, w = video_frames[0].shape[1:3] frame_boxes = [[0, 0, w, h]] for box in element["frames"][frame_index]: frame_boxes.append([box["x1"], box["y1"], box["x2"], box["y2"]]) boxes.append(torch.tensor(frame_boxes, device=device)) boxes_per_image.append(len(frame_boxes)) # Obtain model output and save features features = model(video_frames, boxes).cpu().split(boxes_per_image, 0) grp = video_features.create_group(video_id) for frame_index in range(len(features)): assert ( len(element["frames"][frame_index]) + 1 # Because of [0,0,w,h] == features[frame_index].size()[0] ) grp.create_dataset( f"{frame_index}-frame", data=features[frame_index][0].numpy() ) for box_index in range(1, features[frame_index].size()[0]): grp.create_dataset( f"{frame_index}-frame-{box_index-1}-box", data=features[frame_index][box_index].numpy(), ) if index % args.print_freq == 0: logging.info(f"Current index is {index}") def main(): parser = argparse.ArgumentParser( description="Dumps per-frame and per-bounding box features from Faster R-CNN." ) parser.add_argument( "--videos_path", type=str, default="data/dataset.hdf5", help="From where to load the videos.", ) parser.add_argument( "--dataset_path", type=str, default="data/val_dataset_174.json", help="Path to a smth-smth dataset.", ) parser.add_argument( "--save_features_path", type=str, default="data/per_box_features", help="Where to save the per-frame/per-box features.", ) parser.add_argument( "--print_freq", type=int, default=1000, help="How often to print.", ) parser.add_argument( "--log_filepath", type=str, default=None, help="The logging destination.", ) parser.add_argument( "--device", type=str, default="cpu", help="The device to be used", ) args = parser.parse_args() dump_video_frames(args) if __name__ == "__main__": main()
5,332
32.968153
86
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/train.py
import logging import os import torch from torch import optim from torch.utils.data import DataLoader from tqdm import tqdm from modelling.datasets import collaters_factory, datasets_factory from modelling.configs import model_configs_factory, DataConfig from modelling.models import models_factory from utils.evaluation import evaluators_factory from utils.parser import Parser from utils.train_inference_utils import ( add_weight_decay, get_device, get_linear_schedule_with_warmup, move_batch_to_device, Criterion, ) def train(args): if args.log_filepath: # Set up logging if os.path.exists(args.log_filepath): raise ValueError(f"There is a log at {args.log_filepath}!") logging.basicConfig( level=logging.INFO, filename=args.log_filepath, filemode="w" ) else: logging.basicConfig(level=logging.INFO) # Check for CUDA device = get_device(logger=logging.getLogger(__name__)) # Prepare datasets logging.info("Preparing datasets...") # Prepare train dataset train_data_config = DataConfig( dataset_name=args.dataset_name, dataset_path=args.train_dataset_path, labels_path=args.labels_path, videoid2size_path=args.videoid2size_path, layout_num_frames=args.layout_num_frames, appearance_num_frames=args.appearance_num_frames, videos_path=args.videos_path, train=True, ) train_dataset = datasets_factory[args.dataset_type](train_data_config) num_training_samples = len(train_dataset) # Prepare validation dataset val_data_config = DataConfig( dataset_name=args.dataset_name, dataset_path=args.val_dataset_path, labels_path=args.labels_path, videoid2size_path=args.videoid2size_path, layout_num_frames=args.layout_num_frames, appearance_num_frames=args.appearance_num_frames, videos_path=args.videos_path, train=False, ) val_dataset = datasets_factory[args.dataset_type](val_data_config) num_validation_samples = len(val_dataset) num_classes = len(val_dataset.labels) logging.info(f"Training on {num_training_samples}") logging.info(f"Validating on {num_validation_samples}") # Prepare collaters train_collater = collaters_factory[args.dataset_type](train_data_config) val_collater = collaters_factory[args.dataset_type](val_data_config) # Prepare loaders train_loader = DataLoader( train_dataset, batch_size=args.batch_size, shuffle=True, collate_fn=train_collater, num_workers=args.num_workers, pin_memory=True if args.num_workers else False, ) val_loader = DataLoader( val_dataset, batch_size=args.batch_size, collate_fn=val_collater, num_workers=args.num_workers, pin_memory=True if args.num_workers else False, ) logging.info("Preparing model...") # Prepare model model_config = model_configs_factory[args.model_name]( num_classes=num_classes, appearance_num_frames=args.appearance_num_frames, unique_categories=len(val_data_config.category2id), num_spatial_layers=args.num_spatial_layers, num_temporal_layers=args.num_temporal_layers, load_backbone_path=args.load_backbone_path, freeze_backbone=args.freeze_backbone, resnet_model_path=args.resnet_model_path, ) logging.info("==================================") logging.info(f"The model's configuration is:\n{model_config}") logging.info("==================================") model = models_factory[args.model_name](model_config).to(device) # Prepare loss and optimize criterion = Criterion(args.dataset_name) parameters = add_weight_decay(model, args.weight_decay) optimizer = optim.AdamW(parameters, lr=args.learning_rate) num_batches = len(train_dataset) // args.batch_size scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=args.warmup_epochs * num_batches, num_training_steps=args.epochs * num_batches, ) evaluator = evaluators_factory[args.dataset_name]( num_validation_samples, num_classes, model.logit_names ) logging.info("Starting training...") for epoch in range(args.epochs): # Training loop model.train(True) with tqdm(total=len(train_loader)) as pbar: for batch in train_loader: # Remove past gradients optimizer.zero_grad() # Move tensors to device batch = move_batch_to_device(batch, device) # Obtain outputs logits = model(batch) # Measure loss and update weights loss = criterion(logits, batch["labels"]) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip_val) optimizer.step() # Update the scheduler scheduler.step() # Update progress bar pbar.update(1) pbar.set_postfix({"Loss": loss.item()}) # Validation loop model.train(False) evaluator.reset() with torch.no_grad(): for batch in tqdm(val_loader): batch = move_batch_to_device(batch, device) logits = model(batch) evaluator.process(logits, batch["labels"]) # Saving logic metrics = evaluator.evaluate() if evaluator.is_best(): logging.info("=================================") logging.info(f"Found new best on epoch {epoch+1}!") logging.info("=================================") torch.save(model.state_dict(), args.save_model_path) if args.save_backbone_path: torch.save(model.backbone.state_dict(), args.save_backbone_path) for m in metrics.keys(): logging.info(f"{m}: {round(metrics[m] * 100, 2)}") def main(): parser = Parser("Trains a model, currenly STLT, LCF, CAF, and CACNF.") train(parser.parse_args()) if __name__ == "__main__": main()
6,221
36.939024
81
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/utils/model_utils.py
import torch def generate_square_subsequent_mask(sz: int) -> torch.Tensor: # https://pytorch.org/docs/stable/_modules/torch/nn/modules/transformer.html#Transformer.generate_square_subsequent_mask mask = ~(torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) return mask
284
34.625
124
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/utils/data_utils.py
from typing import List, Tuple import ffmpeg import numpy as np import torch from PIL import Image from torchvision.transforms import ColorJitter, RandomCrop from torchvision.transforms import functional as TF def load_video(in_filepath: str): """Loads a video from a filepath.""" probe = ffmpeg.probe(in_filepath) video_stream = next( (stream for stream in probe["streams"] if stream["codec_type"] == "video"), None, ) width = int(video_stream["width"]) height = int(video_stream["height"]) out, _ = ( ffmpeg.input(in_filepath) .output("pipe:", format="rawvideo", pix_fmt="rgb24") # https://github.com/kkroening/ffmpeg-python/issues/68#issuecomment-443752014 .global_args("-loglevel", "error") .run(capture_stdout=True) ) video = np.frombuffer(out, np.uint8).reshape([-1, height, width, 3]) return video def sample_train_layout_indices(coord_nr_frames: int, nr_video_frames: int): # https://github.com/joaanna/something_else/blob/master/code/data_utils/data_loader_frames.py#L135 average_duration = nr_video_frames * 1.0 / coord_nr_frames if average_duration > 0: offsets = np.multiply( list(range(coord_nr_frames)), average_duration ) + np.random.uniform(0, average_duration, size=coord_nr_frames) offsets = np.floor(offsets) elif nr_video_frames > coord_nr_frames: offsets = np.sort(np.random.randint(nr_video_frames, size=coord_nr_frames)) else: offsets = np.arange(nr_video_frames) offsets = list(map(int, list(offsets))) return offsets def get_test_layout_indices(coord_nr_frames: int, nr_video_frames: int): # https://github.com/joaanna/something_else/blob/master/code/data_utils/data_loader_frames.py#L148 if nr_video_frames > coord_nr_frames: tick = nr_video_frames * 1.0 / coord_nr_frames offsets = np.array([int(tick / 2.0 + tick * x) for x in range(coord_nr_frames)]) else: offsets = np.arange(nr_video_frames) offsets = list(map(int, list(offsets))) return offsets def sample_appearance_indices( coord_nr_frames: int, nr_video_frames: int, train: bool, sample_rate=2 ): # https://github.com/joaanna/something_else/blob/master/code/data_utils/data_loader_frames.py#L157 d = coord_nr_frames * sample_rate # 16 * 2 if nr_video_frames > d: if train: # random sample offset = np.random.randint(0, nr_video_frames - d) else: # center crop offset = (nr_video_frames - d) // 2 frame_list = list(range(offset, offset + d, sample_rate)) else: # Temporal Augmentation if train: # train if nr_video_frames - 2 < coord_nr_frames: # less frames than needed pos = np.linspace(0, nr_video_frames - 2, coord_nr_frames) else: # take one pos = np.sort( np.random.choice( list(range(nr_video_frames - 2)), coord_nr_frames, replace=False ) ) else: pos = np.linspace(0, nr_video_frames - 2, coord_nr_frames) frame_list = [round(p) for p in pos] # Without max(x, 0) bug when nr_video_frames = 1 frame_list = [int(max(x, 0)) for x in frame_list] return frame_list def pad_sequence(sequences: List[torch.Tensor], pad_tensor: torch.Tensor): num_trailing_dims = len(sequences[0].size()[1:]) max_len = max([s.size(0) for s in sequences]) out_dims = (len(sequences), max_len) + (1,) * num_trailing_dims out_tensor = pad_tensor.repeat(out_dims) for i, tensor in enumerate(sequences): length = tensor.size(0) out_tensor[i, :length, ...] = tensor return out_tensor class IdentityTransform: def __call__(self, image: Image): return image class VideoColorJitter: # Adapted from: https://github.com/pytorch/vision/blob/main/torchvision/transforms/transforms.py#L1140 def __init__(self): ( self.fn_idx, self.brightness_factor, self.contrast_factor, self.saturation_factor, self.hue_factor, ) = ColorJitter.get_params( brightness=(0.75, 1.25), contrast=(0.75, 1.25), saturation=(0.75, 1.25), hue=(-0.1, 0.1), ) def __call__(self, img: Image): for fn_id in self.fn_idx: if fn_id == 0 and self.brightness_factor is not None: img = TF.adjust_brightness(img, self.brightness_factor) elif fn_id == 1 and self.contrast_factor is not None: img = TF.adjust_contrast(img, self.contrast_factor) elif fn_id == 2 and self.saturation_factor is not None: img = TF.adjust_saturation(img, self.saturation_factor) elif fn_id == 3 and self.hue_factor is not None: img = TF.adjust_hue(img, self.hue_factor) return img class ResizeBoxes: # Resize boxes according to the shortest size of the image. Adapted from: # https://github.com/chainer/chainercv/blob/master/chainercv/transforms/bbox/resize_bbox.py def __call__(self, box: List[int], scale_factor: float): out_box = [e * scale_factor for e in box] return out_box class CenterCropBoxes: # Adapted from: # https://github.com/chainer/chainercv/blob/master/chainercv/transforms/bbox/translate_bbox.py def __init__(self, dummy_image, spatial_size: int): self.left = (dummy_image.size[0] - spatial_size) // 2 self.top = (dummy_image.size[1] - spatial_size) // 2 self.height = spatial_size self.width = spatial_size def __call__(self, box: List[int]): out_box = [ box[0] - self.left, box[1] - self.top, box[2] - self.left, box[3] - self.top, ] return out_box class RandomCropBoxes: # Adapted from: # https://github.com/chainer/chainercv/blob/master/chainercv/transforms/bbox/translate_bbox.py def __init__(self, dummy_image, spatial_size): self.top, self.left, self.height, self.width = RandomCrop.get_params( dummy_image, (spatial_size, spatial_size) ) def __call__(self, box: List[int]): out_box = [ box[0] - self.left, box[1] - self.top, box[2] - self.left, box[3] - self.top, ] return out_box def valid_box(box: List[int], frame_size: int): if box[0] >= frame_size and box[2] >= frame_size: return False if box[0] <= 0 and box[2] <= 0: return False if box[1] >= frame_size and box[3] >= frame_size: return False if box[1] <= 0 and box[3] <= 0: return False return True def clamp_box(box: List[int], frame_size: int): out_box = [max(0, min(e, frame_size)) for e in box] return out_box def fix_box(box: List[int], video_size: Tuple[int, int]): # Cast box elements to integers box = [max(0, int(b)) for b in box] # If x1 > x2 or y1 > y2 switch (Hack) if box[0] > box[2]: box[0], box[2] = box[2], box[0] if box[1] > box[3]: box[1], box[3] = box[3], box[1] # Clamp to max size (Hack) if box[0] >= video_size[1]: box[0] = video_size[1] - 1 if box[1] >= video_size[0]: box[1] = video_size[0] - 1 if box[2] >= video_size[1]: box[2] = video_size[1] - 1 if box[3] >= video_size[0]: box[3] = video_size[0] - 1 # Fix if equal (Hack) if box[0] == box[2] and box[0] == 0: box[2] = 1 if box[1] == box[3] and box[1] == 0: box[3] = 1 if box[0] == box[2]: box[0] -= 1 if box[1] == box[3]: box[1] -= 1 return box
7,854
32.857759
106
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/utils/train_inference_utils.py
import logging from typing import Dict import torch from torch import nn, optim def get_device(logger: logging.Logger): device = torch.device("cpu") if torch.cuda.is_available(): device = torch.device("cuda") for i in range(torch.cuda.device_count()): logger.warning(f"{torch.cuda.get_device_properties(f'cuda:{i}')}") logger.warning( f"Current occupied memory: {torch.cuda.memory_allocated(i) * 1e-9} GB" ) logging.warning(f"Using device {device}!!!") return device def get_linear_schedule_with_warmup( optimizer: optim.Optimizer, num_warmup_steps: int, num_training_steps: int ): # https://huggingface.co/transformers/_modules/transformers/optimization.html#get_linear_schedule_with_warmup def lr_lambda(current_step: int): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return max( 0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)), ) return optim.lr_scheduler.LambdaLR(optimizer, lr_lambda) def add_weight_decay(model, weight_decay: float): # https://github.com/rwightman/pytorch-image-models/blob/48371a33b11fc30ca23ed8988619af08902b215b/timm/optim/optim_factory.py#L25 decay = [] no_decay = [] skip_list = {} if hasattr(model, "no_weight_decay"): skip_list = model.no_weight_decay() for name, param in model.named_parameters(): if not param.requires_grad: continue # frozen weights if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: no_decay.append(param) else: decay.append(param) return [ {"params": no_decay, "weight_decay": 0.0}, {"params": decay, "weight_decay": weight_decay}, ] def move_batch_to_device(batch, device): return { key: val.to(device) if isinstance(val, torch.Tensor) else val for key, val in batch.items() } class Criterion(nn.Module): def __init__(self, dataset_name: str): super(Criterion, self).__init__() self.loss_function = ( nn.CrossEntropyLoss() if dataset_name == "something" else nn.BCEWithLogitsLoss() ) def forward(self, logits: Dict[str, torch.Tensor], labels: torch.Tensor): return sum( [self.loss_function(logits[key], labels) for key in logits.keys()] ) / len(logits)
2,556
32.207792
133
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/utils/evaluation.py
import numpy as np from typing import Tuple class EvaluatorSomething: def __init__( self, total_instances: int, total_classes: int, logit_names: Tuple[str] ): self.total_instances = total_instances self.total_classes = total_classes self.logit_names = logit_names self.reset() self.best_acc = 0.0 def reset(self): self.corrects = {} for logit_name in self.logit_names: self.corrects[f"{logit_name}_top1"] = 0 self.corrects[f"{logit_name}_top5"] = 0 def process(self, logits, labels): assert len(logits) == len(self.logit_names) for logit_name in self.logit_names: self.corrects[f"{logit_name}_top1"] += ( (logits[logit_name].cpu().argmax(-1) == labels.cpu()).sum().item() ) self.corrects[f"{logit_name}_top5"] += ( ( logits[logit_name].cpu().topk(k=5).indices == labels.cpu().unsqueeze(1) ) .any(dim=1) .sum() ).item() def evaluate(self): metrics = {} for logit_name in self.logit_names: metrics[f"{logit_name}_top1_accuracy"] = ( self.corrects[f"{logit_name}_top1"] / self.total_instances ) metrics[f"{logit_name}_top5_accuracy"] = ( self.corrects[f"{logit_name}_top5"] / self.total_instances ) return metrics def is_best(self): metrics = self.evaluate() # Get currect accuracy cur_accuracy = sum( [metrics[accuracy_type] for accuracy_type in metrics.keys()] ) / len(metrics) # Validate whether it's the best model if cur_accuracy > self.best_acc: self.best_acc = cur_accuracy return True return False class EvaluatorActionGenome: def __init__( self, total_instances: int, total_classes: int, logit_names: Tuple[str] ): self.total_instances = total_instances self.total_classes = total_classes self.logit_names = logit_names self.reset() self.best_mean_average_precision = 0.0 def reset(self): self.index = 0 self.predictions = np.zeros((self.total_instances, self.total_classes)) self.ground_truths = np.zeros((self.total_instances, self.total_classes)) def process(self, logits, labels): # Action Genome only for STLT so far size = logits["stlt"].shape[0] self.predictions[self.index : self.index + size] = ( logits["stlt"].cpu().sigmoid().numpy() ) self.ground_truths[self.index : self.index + size] = labels.cpu().numpy() self.index += size def evaluate(self): mean_average_precision, _, _ = charades_map( self.predictions, self.ground_truths ) return {"map": mean_average_precision} def is_best(self): metrics = self.evaluate() if metrics["map"] > self.best_mean_average_precision: self.best_mean_average_precision = metrics["map"] return True return False def map(submission_array, gt_array): # https://github.com/gsig/charades-algorithms/blob/master/pytorch/utils/map.py m_aps = [] n_classes = submission_array.shape[1] for oc_i in range(n_classes): sorted_idxs = np.argsort(-submission_array[:, oc_i]) tp = gt_array[:, oc_i][sorted_idxs] == 1 fp = np.invert(tp) n_pos = tp.sum() if n_pos < 0.1: m_aps.append(float("nan")) continue fp.sum() f_pcs = np.cumsum(fp) t_pcs = np.cumsum(tp) prec = t_pcs / (f_pcs + t_pcs).astype(float) avg_prec = 0 for i in range(submission_array.shape[0]): if tp[i]: avg_prec += prec[i] m_aps.append(avg_prec / n_pos.astype(float)) m_aps = np.array(m_aps) m_ap = np.mean(m_aps) w_ap = m_aps * gt_array.sum(axis=0) / gt_array.sum().sum().astype(float) return m_ap, w_ap, m_aps def charades_map(submission_array, gt_array): # https://github.com/gsig/charades-algorithms/blob/master/pytorch/utils/map.py fix = submission_array.copy() empty = np.sum(gt_array, axis=1) == 0 fix[empty, :] = np.NINF return map(fix, gt_array) evaluators_factory = { "something": EvaluatorSomething, "action_genome": EvaluatorActionGenome, }
4,514
31.482014
82
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/modelling/datasets.py
import io import json import math import re import h5py import numpy as np import torch from PIL import Image from torch.utils.data import Dataset from torchvision.transforms import ( Compose, Normalize, RandomCrop, Resize, ToTensor, ) from torchvision.transforms import functional as TF from utils.data_utils import ( IdentityTransform, VideoColorJitter, fix_box, get_test_layout_indices, pad_sequence, sample_appearance_indices, sample_train_layout_indices, ) from modelling.configs import DataConfig class StltDataset(Dataset): def __init__(self, config: DataConfig): self.config = config self.json_file = json.load(open(self.config.dataset_path)) self.labels = json.load(open(self.config.labels_path)) self.videoid2size = json.load(open(self.config.videoid2size_path)) # Find max num objects max_objects = -1 for video in self.json_file: for video_frame in video["frames"]: cur_num_objects = 0 for frame_object in video_frame["frame_objects"]: if frame_object["score"] >= self.config.score_threshold: cur_num_objects += 1 max_objects = max(max_objects, cur_num_objects) self.config.max_num_objects = max_objects def __len__(self): return len(self.json_file) def __getitem__(self, idx: int): video_id = self.json_file[idx]["id"] video_size = torch.tensor(self.videoid2size[video_id]).repeat(2) boxes, categories, scores, frame_types = [], [], [], [] num_frames = len(self.json_file[idx]["frames"]) indices = ( sample_train_layout_indices(self.config.layout_num_frames, num_frames) if self.config.train else get_test_layout_indices(self.config.layout_num_frames, num_frames) ) for index in indices: frame = self.json_file[idx]["frames"][index] # Prepare CLS object frame_types.append( self.config.frame2type["empty"] if len(frame["frame_objects"]) == 0 else self.config.frame2type["regular"] ) frame_boxes = [torch.tensor([0.0, 0.0, 1.0, 1.0])] frame_categories = [self.config.category2id["cls"]] frame_scores = [1.0] # Iterate over the other objects for element in frame["frame_objects"]: if element["score"] < self.config.score_threshold: continue # Prepare box box = [element["x1"], element["y1"], element["x2"], element["y2"]] box = fix_box( box, (video_size[1].item(), video_size[0].item()) ) # Height, Width box = torch.tensor(box) / video_size frame_boxes.append(box) # Prepare category frame_categories.append(self.config.category2id[element["category"]]) # Prepare scores frame_scores.append(element["score"]) # Ensure that everything is of the same length and pad to the max number of objects assert len(frame_boxes) == len(frame_categories) while len(frame_boxes) != self.config.max_num_objects + 1: frame_boxes.append(torch.full((4,), 0.0)) frame_categories.append(0) frame_scores.append(0.0) categories.append(torch.tensor(frame_categories)) scores.append(torch.tensor(frame_scores)) boxes.append(torch.stack(frame_boxes, dim=0)) # Prepare extract element # Boxes extract_box = torch.full((self.config.max_num_objects + 1, 4), 0.0) extract_box[0] = torch.tensor([0.0, 0.0, 1.0, 1.0]) boxes.append(extract_box) # Categories extract_category = torch.full((self.config.max_num_objects + 1,), 0) extract_category[0] = self.config.category2id["cls"] categories.append(extract_category) # Scores extract_score = torch.full((self.config.max_num_objects + 1,), 0.0) extract_score[0] = 1.0 scores.append(extract_score) # Length length = torch.tensor(len(categories)) # Frame types frame_types.append(self.config.frame2type["extract"]) # Get action(s) actions = self.get_actions(self.json_file[idx]) return { "video_id": video_id, "categories": torch.stack(categories, dim=0), "boxes": torch.stack(boxes, dim=0), "scores": torch.stack(scores, dim=0), "frame_types": torch.tensor(frame_types), "lengths": length, "labels": actions, } def get_actions(self, sample): if self.config.dataset_name == "something": actions = torch.tensor( int(self.labels[re.sub("[\[\]]", "", sample["template"])]) ) elif self.config.dataset_name == "action_genome": action_list = [int(action[1:]) for action in sample["actions"]] actions = torch.zeros(len(self.labels), dtype=torch.float) actions[action_list] = 1.0 return actions class AppearanceDataset(Dataset): def __init__(self, config: DataConfig, json_file=None): self.config = config self.json_file = json_file if not self.json_file: self.json_file = json.load(open(self.config.dataset_path)) self.labels = json.load(open(self.config.labels_path)) self.videoid2size = json.load(open(self.config.videoid2size_path)) self.resize = Resize(math.floor(self.config.spatial_size * 1.15)) self.transforms = Compose( [ ToTensor(), Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), ] ) def __len__(self): return len(self.json_file) def open_videos(self): self.videos = h5py.File( self.config.videos_path, "r", libver="latest", swmr=True ) def __getitem__(self, idx: int): if not hasattr(self, "videos"): self.open_videos() video_id = self.json_file[idx]["id"] num_frames = len(self.videos[video_id]) indices = sample_appearance_indices( self.config.appearance_num_frames, num_frames, self.config.train ) # Load all frames raw_video_frames = [ self.resize( Image.open(io.BytesIO(np.array(self.videos[video_id][str(index)]))) ) for index in indices ] augment = IdentityTransform() if self.config.train: augment = VideoColorJitter() top, left, height, width = RandomCrop.get_params( raw_video_frames[0], (self.config.spatial_size, self.config.spatial_size), ) video_frames = [] for i in range(len(raw_video_frames)): frame = raw_video_frames[i] frame = augment(frame) frame = ( TF.crop(frame, top, left, height, width) if self.config.train else TF.center_crop(frame, self.config.spatial_size) ) frame = self.transforms(frame) video_frames.append(frame) video_frames = torch.stack(video_frames, dim=0).transpose(0, 1) # Obtain video label video_label = torch.tensor( int(self.labels[re.sub("[\[\]]", "", self.json_file[idx]["template"])]) ) return { "video_id": video_id, "video_frames": video_frames, "labels": video_label, } class MultimodalDataset(Dataset): def __init__(self, config: DataConfig): self.layout_dataset = StltDataset(config) self.appearance_dataset = AppearanceDataset( config, self.layout_dataset.json_file ) # Making a shallow copy of the labels # for easier interfacing in train.py and inference.py self.labels = self.layout_dataset.labels def __len__(self): return self.layout_dataset.__len__() def __getitem__(self, idx: int): layout_dict = self.layout_dataset[idx] appearance_dict = self.appearance_dataset[idx] # layout_dict and appearance_dict have overlapping video_id and actions return {"layout": layout_dict, "appearance": appearance_dict} datasets_factory = { "appearance": AppearanceDataset, "layout": StltDataset, "multimodal": MultimodalDataset, } class StltCollater: def __init__(self, config: DataConfig): self.config = config def __call__(self, batch): batch = {key: [e[key] for e in batch] for key in batch[0].keys()} # https://github.com/pytorch/pytorch/issues/24816 # Pad categories pad_categories_tensor = torch.full((self.config.max_num_objects + 1,), 0) pad_categories_tensor[0] = self.config.category2id["cls"] batch["categories"] = pad_sequence( batch["categories"], pad_tensor=pad_categories_tensor ) # Hack for padding and using scores only if the dataset is Action Genome :( if self.config.dataset_name == "action_genome": pad_scores_tensor = torch.full((self.config.max_num_objects + 1,), 0.0) pad_scores_tensor[0] = 1.0 batch["scores"] = pad_sequence( batch["scores"], pad_tensor=pad_scores_tensor ) else: del batch["scores"] # Pad boxes pad_boxes_tensor = torch.full((self.config.max_num_objects + 1, 4), 0.0) pad_boxes_tensor[0] = torch.tensor([0.0, 0.0, 1.0, 1.0]) batch["boxes"] = pad_sequence(batch["boxes"], pad_tensor=pad_boxes_tensor) # Pad frame types batch["frame_types"] = pad_sequence( batch["frame_types"], pad_tensor=torch.tensor([self.config.frame2type["pad"]]), ) # Prepare length and labels batch["lengths"] = torch.stack(batch["lengths"], dim=0) batch["labels"] = torch.stack(batch["labels"], dim=0) # Generate mask for the padding of the boxes src_key_padding_mask_boxes = torch.zeros_like( batch["categories"], dtype=torch.bool ) src_key_padding_mask_boxes[torch.where(batch["categories"] == 0)] = True batch["src_key_padding_mask_boxes"] = src_key_padding_mask_boxes # Generate mask for padding of the frames src_key_padding_mask_frames = torch.zeros( batch["frame_types"].size(), dtype=torch.bool ) src_key_padding_mask_frames[ torch.where(batch["frame_types"] == self.config.frame2type["pad"]) ] = True batch["src_key_padding_mask_frames"] = src_key_padding_mask_frames return batch class AppearanceCollater: def __init__(self, config: DataConfig): self.config = config def __call__(self, batch): batch = {key: [e[key] for e in batch] for key in batch[0].keys()} batch["video_frames"] = torch.stack(batch["video_frames"], dim=0) batch["labels"] = torch.stack(batch["labels"], dim=0) return batch class MultiModalCollater: def __init__(self, config: DataConfig): self.config = config self.layout_collater = StltCollater(config) self.appearance_collater = AppearanceCollater(config) def __call__(self, batch): # Layout batch layout_batch = [e["layout"] for e in batch] layout_batch = self.layout_collater(layout_batch) # Appearance batch appearance_batch = [e["appearance"] for e in batch] appearance_batch = self.appearance_collater(appearance_batch) # Combine batches joint_batch = {**layout_batch, **appearance_batch} return joint_batch collaters_factory = { "appearance": AppearanceCollater, "layout": StltCollater, "multimodal": MultiModalCollater, }
12,119
36.06422
95
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/modelling/models.py
from typing import Dict import torch from torch import nn from torch.nn import functional as F from utils.model_utils import generate_square_subsequent_mask from modelling.configs import ( AppearanceModelConfig, MultimodalModelConfig, StltModelConfig, ) from modelling.resnets3d import generate_model class CategoryBoxEmbeddings(nn.Module): def __init__(self, config: StltModelConfig): super(CategoryBoxEmbeddings, self).__init__() self.category_embeddings = nn.Embedding( embedding_dim=config.hidden_size, num_embeddings=config.unique_categories, padding_idx=0, ) self.box_embedding = nn.Linear(4, config.hidden_size) self.score_embeddings = nn.Linear(1, config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, batch: Dict[str, torch.Tensor]) -> torch.Tensor: category_embeddings = self.category_embeddings(batch["categories"]) boxes_embeddings = self.box_embedding(batch["boxes"]) embeddings = category_embeddings + boxes_embeddings if "scores" in batch: score_embeddings = self.score_embeddings(batch["scores"].unsqueeze(-1)) embeddings += score_embeddings embeddings = self.layer_norm(embeddings) embeddings = self.dropout(embeddings) return embeddings class SpatialTransformer(nn.Module): def __init__(self, config: StltModelConfig): super(SpatialTransformer, self).__init__() self.category_box_embeddings = CategoryBoxEmbeddings(config) self.encoder_layer = nn.TransformerEncoderLayer( d_model=config.hidden_size, nhead=config.num_attention_heads, dim_feedforward=config.hidden_size * 4, dropout=config.hidden_dropout_prob, activation="gelu", ) self.transformer = nn.TransformerEncoder( encoder_layer=self.encoder_layer, num_layers=config.num_spatial_layers ) def forward(self, batch: Dict[str, torch.Tensor]): # [Batch size, Num. frames, Num. boxes, Hidden size] cb_embeddings = self.category_box_embeddings(batch) num_frames, num_boxes, hidden_size = cb_embeddings.size()[1:] # [Batch size x Num. frames, Num. boxes, Hidden size] cb_embeddings = cb_embeddings.flatten(0, 1) # [Num. boxes, Batch size x Num. frames, Hidden size] cb_embeddings = cb_embeddings.transpose(0, 1) # [Batch size x Num. frames, Num. boxes] src_key_padding_mask_boxes = batch["src_key_padding_mask_boxes"].flatten(0, 1) # [Num. boxes, Batch size x Num. frames, Hidden size] layout_embeddings = self.transformer( src=cb_embeddings, src_key_padding_mask=src_key_padding_mask_boxes, ) # [Batch size x Num. frames, Num. boxes, Hidden size] layout_embeddings = layout_embeddings.transpose(0, 1) # [Batch size, Num. frames, Num. boxes, Hidden_size] layout_embeddings = layout_embeddings.view( -1, num_frames, num_boxes, hidden_size ) # [Batch size, Num. frames, Hidden size] layout_embeddings = layout_embeddings[:, :, 0, :] return layout_embeddings class FramesEmbeddings(nn.Module): def __init__(self, config: StltModelConfig): super(FramesEmbeddings, self).__init__() self.layout_embedding = SpatialTransformer(config) self.position_embeddings = nn.Embedding( config.layout_num_frames, config.hidden_size ) self.frame_type_embedding = nn.Embedding(5, config.hidden_size, padding_idx=0) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.register_buffer( "position_ids", torch.arange(config.layout_num_frames).expand((1, -1)) ) def forward(self, batch: Dict[str, torch.Tensor]): # [Batch size, Num. frames, Hidden size] layouts_embeddings = self.layout_embedding(batch) # Frame type and position embeddings frame_types_embeddings = self.frame_type_embedding(batch["frame_types"]) num_frames = frame_types_embeddings.size()[1] position_embeddings = self.position_embeddings( self.position_ids[:, :num_frames] ) # Preparing everything together embeddings = layouts_embeddings + position_embeddings + frame_types_embeddings embeddings = self.dropout(self.layer_norm(embeddings)) return embeddings class StltBackbone(nn.Module): def __init__(self, config: StltModelConfig): super(StltBackbone, self).__init__() self.frames_embeddings = FramesEmbeddings(config) encoder_layer = nn.TransformerEncoderLayer( d_model=config.hidden_size, nhead=config.num_attention_heads, dim_feedforward=config.hidden_size * 4, dropout=config.hidden_dropout_prob, activation="gelu", ) # Temporal Transformer self.transformer = nn.TransformerEncoder( encoder_layer=encoder_layer, num_layers=config.num_temporal_layers ) @classmethod def from_pretrained(cls, config: StltModelConfig): model = cls(config) model.load_state_dict(torch.load(config.load_backbone_path, map_location="cpu")) return model def forward(self, batch: Dict[str, torch.Tensor]): # [Batch size, Num. frames, Hidden size] frames_embeddings = self.frames_embeddings(batch) # [Num. frames, Batch size, Hidden size] frames_embeddings = frames_embeddings.transpose(0, 1) # [Num. frames, Num. frames] causal_mask_frames = generate_square_subsequent_mask( frames_embeddings.size()[0] ).to(frames_embeddings.device) # [Num. frames, Batch size, Hidden size] transformer_output = self.transformer( src=frames_embeddings, mask=causal_mask_frames, src_key_padding_mask=batch["src_key_padding_mask_frames"], ) return transformer_output class ClassificationHead(nn.Module): def __init__(self, config: StltModelConfig): super(ClassificationHead, self).__init__() self.fc1 = nn.Linear(config.hidden_size, config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.fc2 = nn.Linear(config.hidden_size, config.num_classes) def forward(self, hidden_state: torch.Tensor): return self.fc2(self.layer_norm(F.gelu(self.fc1(hidden_state)))) class Stlt(nn.Module): def __init__(self, config: StltModelConfig): super(Stlt, self).__init__() self.config = config if config.load_backbone_path is not None: self.backbone = StltBackbone.from_pretrained(config) if config.freeze_backbone: for param in self.backbone.parameters(): param.requires_grad = False else: self.backbone = StltBackbone(config) self.prediction_head = ClassificationHead(config) self.logit_names = ("stlt",) def train(self, mode: bool): super(Stlt, self).train(mode) if self.config.load_backbone_path and self.config.freeze_backbone: self.backbone.train(False) def forward(self, batch: Dict[str, torch.Tensor]): # [Num. frames, Batch size, Hidden size] stlt_output = self.backbone(batch) # [Batch size, Hidden size] batches = torch.arange(batch["categories"].size()[0]).to( batch["categories"].device ) stlt_output = stlt_output[batch["lengths"] - 1, batches, :] logits = (self.prediction_head(stlt_output),) return {k: v for k, v in zip(self.logit_names, logits)} class Resnet3D(nn.Module): def __init__(self, config: AppearanceModelConfig): super(Resnet3D, self).__init__() resnet = generate_model(model_depth=50, n_classes=1139) resnet.load_state_dict( torch.load(config.resnet_model_path, map_location="cpu")["state_dict"] ) self.resnet = torch.nn.Sequential(*(list(resnet.children())[:-2])) for module in self.resnet.modules(): if isinstance(module, nn.BatchNorm3d): module.weight.requires_grad = False module.bias.requires_grad = False if config.num_classes > 0: self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1)) self.classifier = nn.Linear(2048, config.num_classes) self.logit_names = ("resnet3d",) def train(self, mode: bool): super(Resnet3D, self).train(mode) for module in self.resnet.modules(): if isinstance(module, nn.BatchNorm3d): module.train(False) def forward_features(self, batch): return self.resnet(batch["video_frames"]) def forward(self, batch): features = self.forward_features(batch) features = self.avgpool(features).flatten(1) logits = (self.classifier(features),) return {k: v for k, v in zip(self.logit_names, logits)} class TransformerResnet(nn.Module): def __init__(self, config: AppearanceModelConfig): super(TransformerResnet, self).__init__() self.resnet = Resnet3D(config) self.projector = nn.Conv3d( in_channels=2048, out_channels=config.hidden_size, kernel_size=(1, 1, 1) ) encoder_layer = nn.TransformerEncoderLayer( d_model=config.hidden_size, nhead=config.num_attention_heads, dim_feedforward=config.hidden_size * 4, ) self.transformer = nn.TransformerEncoder( encoder_layer=encoder_layer, num_layers=config.num_appearance_layers ) self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) self.pos_embed = nn.Parameter( torch.zeros(config.appearance_num_frames + 1, 1, config.hidden_size) ) self.classifier = nn.Linear(config.hidden_size, config.num_classes) def forward_features(self, batch): # We need the batch size for the CLS token B = batch["video_frames"].shape[0] features = self.resnet.forward_features(batch) # [Batch size, Hidden size, Temporal., Spatial., Spatial.] features = self.projector(features) # [Batch size, Hidden size, Seq. len] features = features.flatten(2) # [Seq. len, Batch size, Hidden size] features = features.permute(2, 0, 1) cls_tokens = self.cls_token.expand( -1, B, -1 ) # stole cls_tokens impl from Ross Wightman thanks features = torch.cat((cls_tokens, features), dim=0) features = features + self.pos_embed # [Seq. len, Batch size, Hidden size] features = self.transformer(src=features) return features def forward(self, batch): # [Seq. len, Batch size, Hidden size] features = self.forward_features(batch) # [Batch size, Hidden size] cls_state = features[0, :, :] logits = (self.classifier(cls_state),) return {k: v for k, v in zip(self.resnet.logit_names, logits)} def no_weight_decay(self): return {"pos_embed", "cls_token"} class FusionHead(nn.Module): def __init__(self, config: MultimodalModelConfig): super(FusionHead, self).__init__() self.fc1 = nn.Linear(config.hidden_size * 2, config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.fc2 = nn.Linear(config.hidden_size, config.num_classes) def forward(self, hidden_state: torch.Tensor): return self.fc2(self.layer_norm(F.gelu(self.fc1(hidden_state)))) class LateConcatenationFusion(nn.Module): # LCF def __init__(self, config: MultimodalModelConfig): super(LateConcatenationFusion, self).__init__() self.layout_branch = StltBackbone(config.stlt_config) self.appearance_branch = TransformerResnet(config.appearance_config) self.classifier = FusionHead(config) self.logit_names = ("lcf",) def forward(self, batch: Dict[str, torch.Tensor]): # [Num. Lay. frames, Batch size, Hidden size] layout_output = self.layout_branch(batch) # [Batch size, Hidden size] batches = torch.arange(batch["categories"].size()[0]).to( batch["categories"].device ) layout_output = layout_output[batch["lengths"] - 1, batches, :] # [Num. App. frames, Batch size, Hidden size] appearance_output = self.appearance_branch.forward_features(batch) # [Batch size, Hidden size] appearance_output = appearance_output[0, :, :] # [Batch size, Hidden size * 2] fused_features = torch.cat((layout_output, appearance_output), dim=-1) logits = (self.classifier(fused_features),) return {k: v for k, v in zip(self.logit_names, logits)} # CAF and CACNF, and related modules class FeedforwardModule(nn.Module): def __init__(self, config: MultimodalModelConfig): super(FeedforwardModule, self).__init__() self.linear1 = nn.Linear(config.hidden_size, config.hidden_size * 4) self.linear2 = nn.Linear(config.hidden_size * 4, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, inputs: torch.Tensor): hidden_states = self.dropout(self.linear2(F.gelu(self.linear1(inputs)))) hidden_states = self.ln(hidden_states + inputs) return hidden_states class SelfAttentionLayer(nn.Module): def __init__(self, config: MultimodalModelConfig): super(SelfAttentionLayer, self).__init__() self.attn = nn.MultiheadAttention( embed_dim=config.hidden_size, num_heads=config.num_attention_heads, dropout=config.hidden_dropout_prob, ) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, inputs, causal_mask=None, key_padding_mask=None): hidden_states = self.attn( inputs, inputs, inputs, key_padding_mask=key_padding_mask, attn_mask=causal_mask, )[0] hidden_states = self.dropout(hidden_states) hidden_states = self.ln(hidden_states + inputs) return hidden_states class CrossAttentionLayer(nn.Module): def __init__(self, config: MultimodalModelConfig): super(CrossAttentionLayer, self).__init__() self.attn = nn.MultiheadAttention( embed_dim=config.hidden_size, num_heads=config.num_attention_heads, dropout=config.hidden_dropout_prob, ) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, inputs, context, context_padding_mask=None): hidden_states = self.attn( inputs, context, context, key_padding_mask=context_padding_mask, )[0] hidden_states = self.dropout(hidden_states) hidden_states = self.ln(hidden_states + inputs) return hidden_states class CrossModalModule(nn.Module): def __init__(self, config: MultimodalModelConfig): super(CrossModalModule, self).__init__() # Cross-attention self.cross_attn = CrossAttentionLayer(config) # Layout-Appearance self-attention self.layout_attn = SelfAttentionLayer(config) self.layout_ffn = FeedforwardModule(config) # Appearance-Layout self-attention self.appearance_attn = SelfAttentionLayer(config) self.appearance_ffn = SelfAttentionLayer(config) def forward( self, layout_hidden_states, appearance_hidden_states, causal_attn_mask_layout, src_key_padding_mask_layout, ): # Cross-attention layout_attn_output = self.cross_attn( layout_hidden_states, appearance_hidden_states, ) appearance_attn_output = self.cross_attn( appearance_hidden_states, layout_hidden_states, src_key_padding_mask_layout, ) # Self-attention layout_attn_output = self.layout_attn( layout_attn_output, causal_mask=causal_attn_mask_layout, key_padding_mask=src_key_padding_mask_layout, ) appearance_attn_output = self.appearance_attn(appearance_attn_output) # Feed-forward layout_output = self.layout_ffn(layout_attn_output) appearance_output = self.appearance_ffn(appearance_attn_output) return layout_output, appearance_output class CrossAttentionFusionBackbone(nn.Module): # Backbone for CAF and CACNF def __init__(self, config: MultimodalModelConfig): super(CrossAttentionFusionBackbone, self).__init__() # Unimodal embeddings self.layout_branch = StltBackbone(config.stlt_config) self.appearance_branch = TransformerResnet(config.appearance_config) # Multimodal embeddings self.mm_fusion = nn.ModuleList( [CrossModalModule(config) for _ in range(config.num_fusion_layers)] ) def forward(self, batch: Dict[str, torch.Tensor]): causal_mask_frames = generate_square_subsequent_mask( batch["categories"].size()[1] ).to(batch["categories"].device) # [Lay. num. frames, Batch size, Hidden size] layout_hidden_states = self.layout_branch(batch) # [App. num. frames, Batch size, Hidden size] appearance_hidden_states = self.appearance_branch.forward_features(batch) # Get hidden states for individual branches # [Batch size, Hidden size] batches = torch.arange(batch["categories"].size()[0]).to( batch["categories"].device ) layout_hidden_state = layout_hidden_states[batch["lengths"] - 1, batches, :] appearance_hidden_state = appearance_hidden_states[0, :, :] # Multimodal fusion for layer in self.mm_fusion: layout_hidden_states, appearance_hidden_states = layer( layout_hidden_states, appearance_hidden_states, causal_mask_frames, batch["src_key_padding_mask_frames"], ) # Get fused hidden state # [Batch size, Hidden size] last_fused_state = torch.cat( ( layout_hidden_states[batch["lengths"] - 1, batches, :], appearance_hidden_states[0, :, :], ), dim=-1, ) return { "layout_hidden_state": layout_hidden_state, "appearance_hidden_state": appearance_hidden_state, "last_fused_state": last_fused_state, } class CrossAttentionFusion(nn.Module): # CAF def __init__(self, config: MultimodalModelConfig): super(CrossAttentionFusion, self).__init__() self.caf_backbone = CrossAttentionFusionBackbone(config) # Classifier self.classifier = FusionHead(config) self.logit_names = ("caf",) def forward(self, batch: Dict[str, torch.Tensor]): cross_attention_fusion_embeddings = self.caf_backbone(batch) # [Batch size, Hidden size * 2] last_fused_state = cross_attention_fusion_embeddings["last_fused_state"] logits = (self.classifier(last_fused_state),) return {k: v for k, v in zip(self.logit_names, logits)} class CrossAttentionCentralNetFusion(nn.Module): # CACNF def __init__(self, config: MultimodalModelConfig): super(CrossAttentionCentralNetFusion, self).__init__() self.config = config if config.load_backbone_path is not None: self.backbone = CrossAttentionFusionBackbone.from_pretrained(config) for param in self.backbone.parameters(): param.requires_grad = False else: self.backbone = CrossAttentionFusionBackbone(config) # Classifiers self.layout_classifier = ClassificationHead(config) self.appearance_classifier = ClassificationHead(config) self.fusion_classifier = FusionHead(config) self.logit_names = ("stlt", "resnet3d", "caf", "ensemble") def train(self, mode: bool): super(CrossAttentionCentralNetFusion, self).train(mode) if self.config.load_backbone_path: self.backbone.train(False) def forward(self, batch: Dict[str, torch.Tensor]): cross_attention_fusion_embeddings = self.backbone(batch) logits = () # Unimodal part # [Batch size, Num. classes] logits += ( self.layout_classifier( cross_attention_fusion_embeddings["layout_hidden_state"] ), ) logits += ( self.appearance_classifier( cross_attention_fusion_embeddings["appearance_hidden_state"] ), ) # Multimodal part # [Batch size, Hidden size * 2] last_fused_state = cross_attention_fusion_embeddings["last_fused_state"] # [Batch size, Num. classes] logits += (self.fusion_classifier(last_fused_state),) # Ensemble logits += (sum(logits) / 3,) return {k: v for k, v in zip(self.logit_names, logits)} models_factory = { "stlt": Stlt, "resnet3d": Resnet3D, "resnet3d-transformer": TransformerResnet, "lcf": LateConcatenationFusion, "caf": CrossAttentionFusion, "cacnf": CrossAttentionCentralNetFusion, }
22,045
38.367857
88
py
revisiting-spatial-temporal-layouts
revisiting-spatial-temporal-layouts-main/src/modelling/resnets3d.py
from functools import partial import torch import torch.nn as nn import torch.nn.functional as F def get_inplanes(): return [64, 128, 256, 512] def conv3x3x3(in_planes, out_planes, stride=1): return nn.Conv3d( in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False ) def conv1x1x1(in_planes, out_planes, stride=1): return nn.Conv3d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1, downsample=None): super().__init__() self.conv1 = conv3x3x3(in_planes, planes, stride) self.bn1 = nn.BatchNorm3d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3x3(planes, planes) self.bn2 = nn.BatchNorm3d(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, in_planes, planes, stride=1, downsample=None): super().__init__() self.conv1 = conv1x1x1(in_planes, planes) self.bn1 = nn.BatchNorm3d(planes) self.conv2 = conv3x3x3(planes, planes, stride) self.bn2 = nn.BatchNorm3d(planes) self.conv3 = conv1x1x1(planes, planes * self.expansion) self.bn3 = nn.BatchNorm3d(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): def __init__( self, block, layers, block_inplanes, n_input_channels=3, conv1_t_size=7, conv1_t_stride=1, no_max_pool=False, shortcut_type="B", widen_factor=1.0, n_classes=400, ): super().__init__() block_inplanes = [int(x * widen_factor) for x in block_inplanes] self.in_planes = block_inplanes[0] self.no_max_pool = no_max_pool self.conv1 = nn.Conv3d( n_input_channels, self.in_planes, kernel_size=(conv1_t_size, 7, 7), stride=(conv1_t_stride, 2, 2), padding=(conv1_t_size // 2, 3, 3), bias=False, ) self.bn1 = nn.BatchNorm3d(self.in_planes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool3d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer( block, block_inplanes[0], layers[0], shortcut_type ) self.layer2 = self._make_layer( block, block_inplanes[1], layers[1], shortcut_type, stride=2, ) self.layer3 = self._make_layer( block, block_inplanes[2], layers[2], shortcut_type, stride=2 ) self.layer4 = self._make_layer( block, block_inplanes[3], layers[3], shortcut_type, stride=2 ) self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1)) self.fc = nn.Linear(block_inplanes[3] * block.expansion, n_classes) for m in self.modules(): if isinstance(m, nn.Conv3d): nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") elif isinstance(m, nn.BatchNorm3d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _downsample_basic_block(self, x, planes, stride): out = F.avg_pool3d(x, kernel_size=1, stride=stride) zero_pads = torch.zeros( out.size(0), planes - out.size(1), out.size(2), out.size(3), out.size(4) ) if isinstance(out.data, torch.cuda.FloatTensor): zero_pads = zero_pads.cuda() out = torch.cat([out.data, zero_pads], dim=1) return out def _make_layer(self, block, planes, blocks, shortcut_type, stride=1): downsample = None if stride != 1 or self.in_planes != planes * block.expansion: if shortcut_type == "A": downsample = partial( self._downsample_basic_block, planes=planes * block.expansion, stride=stride, ) else: downsample = nn.Sequential( conv1x1x1(self.in_planes, planes * block.expansion, stride), nn.BatchNorm3d(planes * block.expansion), ) layers = [] layers.append( block( in_planes=self.in_planes, planes=planes, stride=stride, downsample=downsample, ) ) self.in_planes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.in_planes, planes)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) if not self.no_max_pool: x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x def generate_model(model_depth, **kwargs): assert model_depth in [10, 18, 34, 50, 101, 152, 200] if model_depth == 10: model = ResNet(BasicBlock, [1, 1, 1, 1], get_inplanes(), **kwargs) elif model_depth == 18: model = ResNet(BasicBlock, [2, 2, 2, 2], get_inplanes(), **kwargs) elif model_depth == 34: model = ResNet(BasicBlock, [3, 4, 6, 3], get_inplanes(), **kwargs) elif model_depth == 50: model = ResNet(Bottleneck, [3, 4, 6, 3], get_inplanes(), **kwargs) elif model_depth == 101: model = ResNet(Bottleneck, [3, 4, 23, 3], get_inplanes(), **kwargs) elif model_depth == 152: model = ResNet(Bottleneck, [3, 8, 36, 3], get_inplanes(), **kwargs) elif model_depth == 200: model = ResNet(Bottleneck, [3, 24, 36, 3], get_inplanes(), **kwargs) return model
6,810
28.23176
86
py
AS_Molecule
AS_Molecule-master/base_model/sch.py
# -*- coding:utf-8 -*- import dgl import torch as th import torch.nn as nn from base_model.layers import AtomEmbedding, Interaction, ShiftSoftplus, RBFLayer from torch.nn.modules import PairwiseDistance class SchNetModel(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, device='cpu'): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization device: cpu or gpu with idx """ super(SchNetModel, self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.activation = ShiftSoftplus() self.device = device if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref, device=self.device) if pre_train is None: self.embedding_layer = AtomEmbedding(dim, device=self.device) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train, device=self.device) self.rbf_layer = RBFLayer(0, cutoff, width, device=self.device) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64, output_dim) def set_mean_std(self, mean, std): self.mean_per_atom = th.tensor(mean, device=self.device) self.std_per_atom = th.tensor(std, device=self.device) def forward(self, mol_list): # g_list list of molecules g = dgl.batch([mol.ful_g for mol in mol_list]) g.edata['distance'] = g.edata['distance'].reshape(-1, 1) g.to(self.device) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) atom = self.activation(atom) res = self.atom_dense_layer2(atom) g.ndata["res"] = res if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom res = dgl.mean_nodes(g, "res") return res if __name__ == "__main__": g = dgl.DGLGraph() g.add_nodes(2) g.add_edges([0, 0, 1, 1], [1, 0, 1, 0]) g.edata["distance"] = th.tensor([1.0, 3.0, 2.0, 4.0]).reshape(-1, 1) g.ndata["node_type"] = th.LongTensor([1, 2]) model = SchNetModel(dim=2) atom = model(g) print(atom)
3,495
31.981132
81
py
AS_Molecule
AS_Molecule-master/base_model/train_base.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * def train(args, train_dataset, test_dataset, model, optimizer, writer, device): print("start") train_loader = DataLoader(dataset=train_dataset, batch_size=args.batchsize, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) test_loader = DataLoader(dataset=test_dataset, batch_size=args.batchsize * 2, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) print(model) print(train_dataset.mean.item(), train_dataset.std.item()) # if model.name in ["MGCN", "SchNet"]: if args.multi_gpu: model.module.set_mean_std(train_dataset.mean, train_dataset.std) else: model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() init_lr = args.lr info = {'train_loss': [], 'train_mae': [], 'test_loss': [], 'test_mae': []} for epoch in range(args.epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) # if loss>1e3: # print('loss more than 1e3') optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) if idx % 50 == 0 and args.use_tb: writer.add_scalar( 'training_loss', mse_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) writer.add_scalar( 'training_mae', mae_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) print('training loss {} mae {}'.format(mse_meter.value()[0], mae_meter.value()[0])) loss_test, mae_test = test(args, test_loader, model, device) print( "Epoch {:2d}, training: loss: {:.7f}, mae: {:.7f} test: loss{:.7f}, mae:{:.7f}" .format(epoch, mse_meter.value()[0], mae_meter.value()[0], loss_test, mae_test)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 2 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) info['test_loss'].append(loss_test) info['test_mae'].append(mae_test) if args.use_tb: writer.add_scalar('testing_loss', loss_test, epoch) writer.add_scalar('testing_mae', mae_test, epoch) return info def test(args, test_loader, model, device): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 400 args.batchsize = 32 args.use_tb = False args.dataset = 'qm9' args.device = 1 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'U0' print(args) logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') train_set, test_set = MoleDataset(prop_name=args.prop_name), MoleDataset( prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol( config.test_pkl[args.dataset]) device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None atom_ref = get_atom_ref(args.prop_name) # atom_ref = None model = SchNetModel(dim=128, n_conv=4, cutoff=30.0, width=0.1, norm=False, output_dim=1, atom_ref=atom_ref) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) if args.multi_gpu: model = DataParallel( model, device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args, train_set, test_set, model, optimizer, writer, device) if args.save_model: torch.save( { 'model_state_dict': model.state_dict(), 'optimizier_state_dict': optimizer.state_dict(), 'info': info, }, config.save_model_path(args.dataset))
6,194
33.226519
91
py
AS_Molecule
AS_Molecule-master/base_model/layers.py
import torch as th import numpy as np import torch.nn as nn import dgl.function as fn from torch.nn import Softplus class AtomEmbedding(nn.Module): """ Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. """ def __init__(self, dim=128, type_num=100, pre_train=None, device='cpu'): """ Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings """ super(AtomEmbedding, self).__init__() self._dim = dim self._type_num = type_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(type_num, dim, padding_idx=0) self.embedding.to(device) def forward(self, g, p_name="node"): """Input type is dgl graph""" atom_list = g.ndata["nodes"] g.ndata[p_name] = self.embedding(atom_list) return g.ndata[p_name] class EdgeEmbedding(nn.Module): """ Convert the edge to embedding. The edge links same pair of atoms share the same initial embedding. """ def __init__(self, dim=128, edge_num=3000, pre_train=None): """ Randomly init the edge embeddings. Args: dim: the dim of embeddings edge_num: the maximum type of edges pre_train: the pre_trained embeddings """ super(EdgeEmbedding, self).__init__() self._dim = dim self._edge_num = edge_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(edge_num, dim, padding_idx=0) def generate_edge_type(self, edges): """ Generate the edge type based on the src&dst atom type of the edge. Note that C-O and O-C are the same edge type. To map a pair of nodes to one number, we use an unordered pairing function here See more detail in this disscussion: https://math.stackexchange.com/questions/23503/create-unique-number-from-2-numbers Note that, the edge_num should larger than the square of maximum atomic number in the dataset. """ atom_type_x = edges.src["node_type"] atom_type_y = edges.dst["node_type"] return { "type": atom_type_x * atom_type_y + (th.abs(atom_type_x - atom_type_y) - 1)**2 / 4 } def forward(self, g, p_name="edge_f"): g.apply_edges(self.generate_edge_type) g.edata[p_name] = self.embedding(g.edata["type"]) return g.edata[p_name] class ShiftSoftplus(Softplus): """ Shiftsoft plus activation function: 1/beta * (log(1 + exp**(beta * x)) - log(shift)) """ def __init__(self, beta=1, shift=2, threshold=20): super().__init__(beta, threshold) self.shift = shift self.softplus = Softplus(beta, threshold) def forward(self, input): return self.softplus(input) - np.log(float(self.shift)) class RBFLayer(nn.Module): """ Radial basis functions Layer. e(d) = exp(- gamma * ||d - mu_k||^2) default settings: gamma = 10 0 <= mu_k <= 30 for k=1~300 """ def __init__(self, low=0, high=30, gap=0.1, dim=1, device='cpu'): super(RBFLayer, self).__init__() self._low = low self._high = high self._gap = gap self._dim = dim self._n_centers = int(np.ceil((high - low) / gap)) centers = np.linspace(low, high, self._n_centers) self.centers = nn.Parameter(th.Tensor(centers), requires_grad=False) self._fan_out = self._dim * self._n_centers self._gap = centers[1] - centers[0] def dis2rbf(self, edges): dist = edges.data["distance"] radial = dist - self.centers coef = float(-1 / self._gap) rbf = th.exp(coef * (radial**2)) return {"rbf": rbf} def forward(self, g): """Convert distance scalar to rbf vector""" g.apply_edges(self.dis2rbf) return g.edata["rbf"] class CFConv(nn.Module): """ The continuous-filter convolution layer in SchNet. One CFConv contains one rbf layer and three linear layer (two of them have activation funct). """ def __init__(self, rbf_dim, dim=64, act="sp"): """ Args: rbf_dim: the dimsion of the RBF layer dim: the dimension of linear layers act: activation function (default shifted softplus) """ super(CFConv, self).__init__() self._rbf_dim = rbf_dim self._dim = dim self.linear_layer1 = nn.Linear(self._rbf_dim, self._dim) self.linear_layer2 = nn.Linear(self._dim, self._dim) if act == "sp": self.activation = nn.Softplus(beta=0.5, threshold=14) else: self.activation = act def update_edge(self, edges): rbf = edges.data["rbf"] h = self.linear_layer1(rbf) h = self.activation(h) h = self.linear_layer2(h) return {"h": h} def forward(self, g): g.apply_edges(self.update_edge) g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), reduce_func=fn.sum('neighbor_info', 'new_node')) return g.ndata["new_node"] class Interaction(nn.Module): """ The interaction layer in the SchNet model. """ def __init__(self, rbf_dim, dim): super(Interaction, self).__init__() self._node_dim = dim self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=False) self.cfconv = CFConv(rbf_dim, dim, act=self.activation) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) def forward(self, g): g.ndata["new_node"] = self.node_layer1(g.ndata["node"]) cf_node = self.cfconv(g) cf_node_1 = self.node_layer2(cf_node) cf_node_1a = self.activation(cf_node_1) new_node = self.node_layer3(cf_node_1a) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] class VEConv(nn.Module): """ The Vertex-Edge convolution layer in MGCN which take edge & vertex features in consideratoin at the same time. """ def __init__(self, rbf_dim, dim=64, update_edge=True): """ Args: rbf_dim: the dimension of the RBF layer dim: the dimension of linear layers update_edge: whether update the edge emebedding in each conv-layer """ super().__init__() self._rbf_dim = rbf_dim self._dim = dim self._update_edge = update_edge self.linear_layer1 = nn.Linear(self._rbf_dim, self._dim) self.linear_layer2 = nn.Linear(self._dim, self._dim) self.linear_layer3 = nn.Linear(self._dim, self._dim) self.activation = nn.Softplus(beta=0.5, threshold=14) def update_rbf(self, edges): rbf = edges.data["rbf"] h = self.linear_layer1(rbf) h = self.activation(h) h = self.linear_layer2(h) return {"h": h} def update_edge(self, edges): edge_f = edges.data["edge_f"] h = self.linear_layer3(edge_f) return {"edge_f": h} def forward(self, g): g.apply_edges(self.update_rbf) if self._update_edge: g.apply_edges(self.update_edge) g.update_all(message_func=[ fn.u_mul_e("new_node", "h", "m_0"), fn.copy_e("edge_f", "m_1") ], reduce_func=[ fn.sum("m_0", "new_node_0"), fn.sum("m_1", "new_node_1") ]) g.ndata["new_node"] = g.ndata.pop("new_node_0") + g.ndata.pop( "new_node_1") return g.ndata["new_node"] class MultiLevelInteraction(nn.Module): """ The multilevel interaction in the MGCN model. """ def __init__(self, rbf_dim, dim): super().__init__() self._atom_dim = dim self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=True) self.edge_layer1 = nn.Linear(dim, dim, bias=True) self.conv_layer = VEConv(rbf_dim, dim) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) def forward(self, g, level=1): g.ndata["new_node"] = self.node_layer1(g.ndata["node_%s" % (level - 1)]) node = self.conv_layer(g) g.edata["edge_f"] = self.activation(self.edge_layer1( g.edata["edge_f"])) node_1 = self.node_layer2(node) node_1a = self.activation(node_1) new_node = self.node_layer3(node_1a) g.ndata["node_%s" % (level)] = g.ndata["node_%s" % (level - 1)] + new_node return g.ndata["node_%s" % (level)]
9,374
32.127208
90
py
AS_Molecule
AS_Molecule-master/base_model/schmodel.py
import torch as th import numpy as np import torch.nn as nn import dgl.function as fn from torch.nn import Softplus import dgl #cannot first write device in model class AtomEmbedding(nn.Module): """ Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. """ def __init__(self, dim=128, type_num=100, pre_train=None): """ Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings """ super(AtomEmbedding, self).__init__() self._dim = dim self._type_num = type_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train) else: self.embedding = nn.Embedding(type_num, dim, padding_idx=0) def forward(self, g, p_name="node"): """Input type is dgl graph""" atom_list = g.ndata["nodes"] g.ndata[p_name] = self.embedding(atom_list) return g.ndata[p_name] class EdgeEmbedding(nn.Module): """ Convert the edge to embedding. The edge links same pair of atoms share the same initial embedding. """ def __init__(self, dim=128, edge_num=3000, pre_train=None): """ Randomly init the edge embeddings. Args: dim: the dim of embeddings edge_num: the maximum type of edges pre_train: the pre_trained embeddings """ super(EdgeEmbedding, self).__init__() self._dim = dim self._edge_num = edge_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(edge_num, dim, padding_idx=0) def generate_edge_type(self, edges): """ Generate the edge type based on the src&dst atom type of the edge. Note that C-O and O-C are the same edge type. To map a pair of nodes to one number, we use an unordered pairing function here See more detail in this disscussion: https://math.stackexchange.com/questions/23503/create-unique-number-from-2-numbers Note that, the edge_num should larger than the square of maximum atomic number in the dataset. """ atom_type_x = edges.src["node_type"] atom_type_y = edges.dst["node_type"] return { "type": atom_type_x * atom_type_y + (th.abs(atom_type_x - atom_type_y) - 1)**2 / 4 } def forward(self, g, p_name="edge_f"): g.apply_edges(self.generate_edge_type) g.edata[p_name] = self.embedding(g.edata["type"]) return g.edata[p_name] class ShiftSoftplus(Softplus): """ Shiftsoft plus activation function: 1/beta * (log(1 + exp**(beta * x)) - log(shift)) """ def __init__(self, beta=1, shift=2, threshold=20): super().__init__(beta, threshold) self.shift = shift self.softplus = Softplus(beta, threshold) def forward(self, input): return self.softplus(input) - np.log(float(self.shift)) class RBFLayer(nn.Module): """ Radial basis functions Layer. e(d) = exp(- gamma * ||d - mu_k||^2) default settings: gamma = 10 0 <= mu_k <= 30 for k=1~300 """ def __init__(self, low=0, high=30, gap=0.1, dim=1): super(RBFLayer, self).__init__() self._low = low self._high = high self._gap = gap self._dim = dim self._n_centers = int(np.ceil((high - low) / gap)) centers = np.linspace(low, high, self._n_centers) self.centers = nn.Parameter(th.Tensor(centers), requires_grad=False) self._fan_out = self._dim * self._n_centers self._gap = centers[1] - centers[0] def dis2rbf(self, edges): dist = edges.data["distance"] radial = dist - self.centers coef = float(-1 / self._gap) rbf = th.exp(coef * (radial**2)) return {"rbf": rbf} def forward(self, g): """Convert distance scalar to rbf vector""" g.apply_edges(self.dis2rbf) return g.edata["rbf"] class CFConv(nn.Module): """ The continuous-filter convolution layer in SchNet. One CFConv contains one rbf layer and three linear layer (two of them have activation funct). """ def __init__(self, rbf_dim, dim=64, act="sp"): """ Args: rbf_dim: the dimsion of the RBF layer dim: the dimension of linear layers act: activation function (default shifted softplus) """ super(CFConv, self).__init__() self._rbf_dim = rbf_dim self._dim = dim self.linear_layer1 = nn.Linear(self._rbf_dim, self._dim) self.linear_layer2 = nn.Linear(self._dim, self._dim) if act == "sp": self.activation = nn.Softplus(beta=0.5, threshold=14) else: self.activation = act def update_edge(self, edges): rbf = edges.data["rbf"] h = self.linear_layer1(rbf) h = self.activation(h) h = self.linear_layer2(h) return {"h": h} def forward(self, g): g.apply_edges(self.update_edge) g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), reduce_func=fn.sum('neighbor_info', 'new_node')) return g.ndata["new_node"] class Interaction(nn.Module): """ The interaction layer in the SchNet model. """ def __init__(self, rbf_dim, dim): super(Interaction, self).__init__() self._node_dim = dim self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=False) self.cfconv = CFConv(rbf_dim, dim, act=self.activation) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) self.bn1 = nn.BatchNorm1d(dim) self.bn2 = nn.BatchNorm1d(dim) self.bn3 = nn.BatchNorm1d(dim) def forward(self, g): g.ndata["new_node"] = self.bn1(self.node_layer1(g.ndata["node"])) cf_node = self.cfconv(g) cf_node_1 = self.bn2(self.node_layer2(cf_node)) cf_node_1a = self.activation(cf_node_1) new_node = self.bn3(self.node_layer3(cf_node_1a)) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] '''Original Schnet''' class SchInteraction(nn.Module): """ The interaction layer in the SchNet model. """ def __init__(self, rbf_dim, dim): super(SchInteraction, self).__init__() self._node_dim = dim self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=False) self.cfconv = CFConv(rbf_dim, dim, act=self.activation) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) self.bn1 = nn.BatchNorm1d(dim) self.bn2 = nn.BatchNorm1d(dim) self.bn3 = nn.BatchNorm1d(dim) def forward(self, g): g.ndata["new_node"] = self.bn1(self.node_layer1(g.ndata["node"])) cf_node = self.cfconv(g) cf_node_1 = self.bn2(self.node_layer2(cf_node)) cf_node_1a = self.activation(cf_node_1) new_node = self.bn3(self.node_layer3(cf_node_1a)) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] class SchNet(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__( self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(SchNet, self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList([ SchInteraction(self.rbf_layer._fan_out, dim) for i in range(n_conv) ]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64, 1) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) atom = self.activation(atom) res = self.atom_dense_layer2(atom) g.ndata["res"] = res if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom res = dgl.mean_nodes(g, "res") return res class SchNetModel(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__( self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(SchNetModel, self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64, 64) self.regressor = nn.Linear(64, 1) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) atom = self.activation(atom) atom = self.activation(self.atom_dense_layer2(atom)) res = self.regressor(atom) g.ndata["res"] = res if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom res = dgl.sum_nodes(g, "res") return res if __name__ == "__main__": pass
12,889
30.985112
90
py
AS_Molecule
AS_Molecule-master/bayes_al/mm_sch.py
#!/usr/bin/env python #-*- coding:utf-8 _*- import torch as th import numpy as np import torch.nn as nn import dgl.function as fn from torch.nn import Softplus import random import dgl from torch.distributions.categorical import Categorical '''Message Masking Schnet, An attempt in one of my own models Masking some of the interactions(often the interactions are redundant) in the model at inference mode (not forward), and calculate the variance due to such perbulence It is more like a kind of consistency based method rather than Bayes based method ''' #cannot first write device in model class AtomEmbedding(nn.Module): """ Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. """ def __init__(self, dim=128, type_num=100, pre_train=None): """ Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings """ super(AtomEmbedding, self).__init__() self._dim = dim self._type_num = type_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(type_num, dim, padding_idx=0) def forward(self, g, p_name="node"): """Input type is dgl graph""" atom_list = g.ndata["nodes"] g.ndata[p_name] = self.embedding(atom_list) return g.ndata[p_name] class EdgeEmbedding(nn.Module): """ Convert the edge to embedding. The edge links same pair of atoms share the same initial embedding. """ def __init__(self, dim=128, edge_num=3000, pre_train=None): """ Randomly init the edge embeddings. Args: dim: the dim of embeddings edge_num: the maximum type of edges pre_train: the pre_trained embeddings """ super(EdgeEmbedding, self).__init__() self._dim = dim self._edge_num = edge_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(edge_num, dim, padding_idx=0) def generate_edge_type(self, edges): """ Generate the edge type based on the src&dst atom type of the edge. Note that C-O and O-C are the same edge type. To map a pair of nodes to one number, we use an unordered pairing function here See more detail in this disscussion: https://math.stackexchange.com/questions/23503/create-unique-number-from-2-numbers Note that, the edge_num should larger than the square of maximum atomic number in the dataset. """ atom_type_x = edges.src["node_type"] atom_type_y = edges.dst["node_type"] return { "type": atom_type_x * atom_type_y + (th.abs(atom_type_x - atom_type_y) - 1)**2 / 4 } def forward(self, g, p_name="edge_f"): g.apply_edges(self.generate_edge_type) g.edata[p_name] = self.embedding(g.edata["type"]) return g.edata[p_name] class ShiftSoftplus(Softplus): """ Shiftsoft plus activation function: 1/beta * (log(1 + exp**(beta * x)) - log(shift)) """ def __init__(self, beta=1, shift=2, threshold=20): super().__init__(beta, threshold) self.shift = shift self.softplus = Softplus(beta, threshold) def forward(self, input): return self.softplus(input) - np.log(float(self.shift)) class RBFLayer(nn.Module): """ Radial basis functions Layer. e(d) = exp(- gamma * ||d - mu_k||^2) default settings: gamma = 10 0 <= mu_k <= 30 for k=1~300 """ def __init__(self, low=0, high=30, gap=0.1, dim=1): super(RBFLayer, self).__init__() self._low = low self._high = high self._gap = gap self._dim = dim self._n_centers = int(np.ceil((high - low) / gap)) centers = np.linspace(low, high, self._n_centers) self.centers = nn.Parameter(th.Tensor(centers), requires_grad=False) self._fan_out = self._dim * self._n_centers self._gap = centers[1] - centers[0] def dis2rbf(self, edges): dist = edges.data["distance"] radial = dist - self.centers coef = float(-1 / self._gap) rbf = th.exp(coef * (radial**2)) return {"rbf": rbf} def forward(self, g): """Convert distance scalar to rbf vector""" g.apply_edges(self.dis2rbf) return g.edata["rbf"] '''Message Masking on this module''' class CFConv(nn.Module): """ The continuous-filter convolution layer in SchNet. One CFConv contains one rbf layer and three linear layer (two of them have activation funct). """ def __init__(self, rbf_dim, dim=64, act="sp", mask_rate=0.2): """ Args: rbf_dim: the dimsion of the RBF layer dim: the dimension of linear layers act: activation function (default shifted softplus) """ super(CFConv, self).__init__() self._rbf_dim = rbf_dim self._dim = dim self._rbf_threshold = 1e-2 self.mask_rate = mask_rate self.linear_layer1 = nn.Linear(self._rbf_dim, self._dim) self.linear_layer2 = nn.Linear(self._dim, self._dim) if act == "sp": self.activation = nn.Softplus(beta=0.5, threshold=14) else: self.activation = act def update_edge(self, edges): rbf = edges.data["rbf"] h = self.linear_layer1(rbf) h = self.activation(h) h = self.linear_layer2(h) return {"h": h} def msk_update_edge(self, edges): rbf = edges.data["rbf"] valid_msg_id = th.nonzero(rbf.max(dim=1)[0] > 1e-2).squeeze() # msk_d = Categorical(th.ones(valid_msg_id.shape[0])) # # msk_msg_id = msk_d.sample_n(int(self.mask_rate*valid_msg_id.shape[0])) # msk_msg_id = valid_msg_id[th.nonzero(th.bernoulli(self.mask_rate*th.ones(valid_msg_id.shape[0]))).squeeze()] msk_msg_id = valid_msg_id[th.randint( 0, valid_msg_id.shape[0], [int(self.mask_rate * valid_msg_id.shape[0])])] h = self.linear_layer1(rbf) h = self.activation(h) h = self.linear_layer2(h) h[msk_msg_id] = 0 return {"h": h} def forward(self, g): g.apply_edges(self.update_edge) g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), reduce_func=fn.sum('neighbor_info', 'new_node')) return g.ndata["new_node"] def message_masking_inference(self, g): g.apply_edges(self.msk_update_edge) g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), reduce_func=fn.sum('neighbor_info', 'new_node')) return g.ndata["new_node"] class MM_Interaction(nn.Module): """ The interaction layer in the SchNet model. """ def __init__(self, rbf_dim, dim, mask_rate=0.2): super(MM_Interaction, self).__init__() self._node_dim = dim self.mask_rate = mask_rate self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=False) self.cfconv = CFConv(rbf_dim, dim, act=self.activation) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) self.bn1 = nn.BatchNorm1d(dim) self.bn2 = nn.BatchNorm1d(dim) self.bn3 = nn.BatchNorm1d(dim) def forward(self, g): g.ndata["new_node"] = self.bn1(self.node_layer1(g.ndata["node"])) cf_node = self.cfconv(g) cf_node_1 = self.bn2(self.node_layer2(cf_node)) cf_node_1a = self.activation(cf_node_1) new_node = self.bn3(self.node_layer3(cf_node_1a)) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] def message_masking_inference(self, g): g.ndata["new_node"] = self.bn1(self.node_layer1(g.ndata["node"])) cf_node = self.cfconv.message_masking_inference(g) cf_node_1 = self.bn2(self.node_layer2(cf_node)) cf_node_1a = self.activation(cf_node_1) new_node = self.bn3(self.node_layer3(cf_node_1a)) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] class MM_SchNetModel(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, mask_rate=0.2): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(MM_SchNetModel, self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.activation = ShiftSoftplus() self.mask_rate = mask_rate if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList([ MM_Interaction(self.rbf_layer._fan_out, dim, self.mask_rate) for i in range(n_conv) ]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64, output_dim) self.final_bn = nn.BatchNorm1d(64) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) atom = self.activation(atom) res = self.atom_dense_layer2(atom) g.ndata["res"] = res if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom res = dgl.mean_nodes(g, "res") return res def inference(self, g): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx].message_masking_inference(g) atom = self.atom_dense_layer1(g.ndata["node"]) atom = self.activation(atom) res = self.atom_dense_layer2(atom) g.ndata["res"] = res if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom res = dgl.mean_nodes(g, "res") return res if __name__ == "__main__": pass
12,338
32.348649
118
py
AS_Molecule
AS_Molecule-master/bayes_al/msk_sch.py
#!/usr/bin/env python #-*- coding:utf-8 _*- import torch as th import numpy as np import torch.nn as nn import dgl.function as fn from torch.nn import Softplus import random import dgl from torch.distributions.categorical import Categorical '''Message Masking Schnet but mask message when training and testing ''' #cannot first write device in model class AtomEmbedding(nn.Module): """ Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. """ def __init__(self, dim=128, type_num=100, pre_train=None): """ Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings """ super(AtomEmbedding, self).__init__() self._dim = dim self._type_num = type_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(type_num, dim, padding_idx=0) def forward(self, g, p_name="node"): """Input type is dgl graph""" atom_list = g.ndata["nodes"] g.ndata[p_name] = self.embedding(atom_list) return g.ndata[p_name] class EdgeEmbedding(nn.Module): """ Convert the edge to embedding. The edge links same pair of atoms share the same initial embedding. """ def __init__(self, dim=128, edge_num=3000, pre_train=None): """ Randomly init the edge embeddings. Args: dim: the dim of embeddings edge_num: the maximum type of edges pre_train: the pre_trained embeddings """ super(EdgeEmbedding, self).__init__() self._dim = dim self._edge_num = edge_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(edge_num, dim, padding_idx=0) def generate_edge_type(self, edges): """ Generate the edge type based on the src&dst atom type of the edge. Note that C-O and O-C are the same edge type. To map a pair of nodes to one number, we use an unordered pairing function here See more detail in this disscussion: https://math.stackexchange.com/questions/23503/create-unique-number-from-2-numbers Note that, the edge_num should larger than the square of maximum atomic number in the dataset. """ atom_type_x = edges.src["node_type"] atom_type_y = edges.dst["node_type"] return { "type": atom_type_x * atom_type_y + (th.abs(atom_type_x - atom_type_y) - 1)**2 / 4 } def forward(self, g, p_name="edge_f"): g.apply_edges(self.generate_edge_type) g.edata[p_name] = self.embedding(g.edata["type"]) return g.edata[p_name] class ShiftSoftplus(Softplus): """ Shiftsoft plus activation function: 1/beta * (log(1 + exp**(beta * x)) - log(shift)) """ def __init__(self, beta=1, shift=2, threshold=20): super().__init__(beta, threshold) self.shift = shift self.softplus = Softplus(beta, threshold) def forward(self, input): return self.softplus(input) - np.log(float(self.shift)) class RBFLayer(nn.Module): """ Radial basis functions Layer. e(d) = exp(- gamma * ||d - mu_k||^2) default settings: gamma = 10 0 <= mu_k <= 30 for k=1~300 """ def __init__(self, low=0, high=30, gap=0.1, dim=1): super(RBFLayer, self).__init__() self._low = low self._high = high self._gap = gap self._dim = dim self._n_centers = int(np.ceil((high - low) / gap)) centers = np.linspace(low, high, self._n_centers) self.centers = nn.Parameter(th.Tensor(centers), requires_grad=False) self._fan_out = self._dim * self._n_centers self._gap = centers[1] - centers[0] def dis2rbf(self, edges): dist = edges.data["distance"] radial = dist - self.centers coef = float(-1 / self._gap) rbf = th.exp(coef * (radial**2)) return {"rbf": rbf} def forward(self, g): """Convert distance scalar to rbf vector""" g.apply_edges(self.dis2rbf) return g.edata["rbf"] '''Message Masking on this module''' class CFConv(nn.Module): """ The continuous-filter convolution layer in SchNet. One CFConv contains one rbf layer and three linear layer (two of them have activation funct). """ def __init__(self, rbf_dim, dim=64, act="sp", mask_rate=0.2): """ Args: rbf_dim: the dimsion of the RBF layer dim: the dimension of linear layers act: activation function (default shifted softplus) """ super(CFConv, self).__init__() self._rbf_dim = rbf_dim self._dim = dim self._rbf_threshold = 1e-2 self.mask_rate = mask_rate self.linear_layer1 = nn.Linear(self._rbf_dim, self._dim) self.linear_layer2 = nn.Linear(self._dim, self._dim) if act == "sp": self.activation = nn.Softplus(beta=0.5, threshold=14) else: self.activation = act def update_edge(self, edges): rbf = edges.data["rbf"] valid_msg_id = th.nonzero(rbf.max(dim=1)[0] > 1e-2).squeeze() msk_msg_id = valid_msg_id[th.randint( 0, valid_msg_id.shape[0], [int(self.mask_rate * valid_msg_id.shape[0])])] h = self.linear_layer1(rbf) h = self.activation(h) h = self.linear_layer2(h) h[msk_msg_id] = 0 return {"h": h} # def msk_update_edge(self,edges): # rbf = edges.data["rbf"] # # valid_msg_id = th.nonzero(rbf.max(dim=1)[0] > 1e-2).squeeze() # # # msk_d = Categorical(th.ones(valid_msg_id.shape[0])) # # # # msk_msg_id = msk_d.sample_n(int(self.mask_rate*valid_msg_id.shape[0])) # # msk_msg_id = valid_msg_id[th.nonzero(th.bernoulli(self.mask_rate*th.ones(valid_msg_id.shape[0]))).squeeze()] # msk_msg_id = valid_msg_id[th.randint(0,valid_msg_id.shape[0],[int(self.mask_rate*valid_msg_id.shape[0])])] # # h = self.linear_layer1(rbf) # h = self.activation(h) # h = self.linear_layer2(h) # # h[msk_msg_id] = 0 # return {"h": h} def forward(self, g): g.apply_edges(self.update_edge) g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), reduce_func=fn.sum('neighbor_info', 'new_node')) return g.ndata["new_node"] # def message_masking_inference(self,g): # g.apply_edges(self.msk_update_edge) # # g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), # reduce_func=fn.sum('neighbor_info', 'new_node')) # return g.ndata["new_node"] class MM_Interaction(nn.Module): """ The interaction layer in the SchNet model. """ def __init__(self, rbf_dim, dim, mask_rate=0.2): super(MM_Interaction, self).__init__() self._node_dim = dim self.mask_rate = mask_rate self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=False) self.cfconv = CFConv(rbf_dim, dim, act=self.activation) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) def forward(self, g): g.ndata["new_node"] = self.node_layer1(g.ndata["node"]) cf_node = self.cfconv(g) cf_node_1 = self.node_layer2(cf_node) cf_node_1a = self.activation(cf_node_1) new_node = self.node_layer3(cf_node_1a) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] # def message_masking_inference(self,g): # g.ndata["new_node"] = self.node_layer1(g.ndata["node"]) # cf_node = self.cfconv.message_masking_inference(g) # cf_node_1 = self.node_layer2(cf_node) # cf_node_1a = self.activation(cf_node_1) # new_node = self.node_layer3(cf_node_1a) # g.ndata["node"] = g.ndata["node"] + new_node # return g.ndata["node"] class Msk_SchNetModel(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, mask_rate=0.2): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(Msk_SchNetModel, self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.activation = ShiftSoftplus() self.mask_rate = mask_rate if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList([ MM_Interaction(self.rbf_layer._fan_out, dim, self.mask_rate) for i in range(n_conv) ]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64, output_dim) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) atom = self.activation(atom) res = self.atom_dense_layer2(atom) g.ndata["res"] = res if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom res = dgl.mean_nodes(g, "res") return res # def inference(self,g): # # g_list list of molecules # # g.edata['distance'] = g.edata['distance'].reshape(-1, 1) # # self.embedding_layer(g) # if self.atom_ref is not None: # self.e0(g, "e0") # self.rbf_layer(g) # for idx in range(self.n_conv): # self.conv_layers[idx].message_masking_inference(g) # # atom = self.atom_dense_layer1(g.ndata["node"]) # atom = self.activation(atom) # res = self.atom_dense_layer2(atom) # g.ndata["res"] = res # # if self.atom_ref is not None: # g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] # # if self.norm: # g.ndata["res"] = g.ndata[ # "res"] * self.std_per_atom + self.mean_per_atom # res = dgl.mean_nodes(g, "res") # return res if __name__ == "__main__": pass
12,232
32.332425
120
py
AS_Molecule
AS_Molecule-master/bayes_al/bald.py
import torch import numpy as np import time class Bayes_sampler(object): def __init__(self, args, total_data_num, batch_data_num, init_ids): self.args = args self.total_data_num = total_data_num self.batch_data_num = batch_data_num self.data_ids = np.delete(np.arange(self.total_data_num, dtype=int), init_ids) #data unselected # query by TODO: the calculation of variance need to be checked def query(self, preds): time0 = time.time() preds_unlabeled = preds[self.data_ids] variance = np.std(preds_unlabeled, axis=1) vars_ids = np.stack([variance, np.arange(0, len(variance))], axis=0) queries = vars_ids[:, vars_ids[0].argsort()] query_ids = queries[1].astype(int)[ -self.batch_data_num:] # query id according to new dataset # query_data_ids = queries[2].astype(int)[-self.batchnum:] #query id according to origin dataset(whole) new_batch_ids = self.data_ids[query_ids] self.data_ids = np.delete(self.data_ids, query_ids) # del from unlabeled print('query new data {}'.format(time.time() - time0)) return new_batch_ids # time0 = time.time() # variance = np.std(preds, axis=1).squeeze() # vars_ids = np.stack([variance, np.arange(0, len(variance))], axis=0) # queries = vars_ids[:, vars_ids[0].argsort()] # query_ids = queries[1].astype(int)[-self.batch_data_num:] # query id according to new dataset # # query_data_ids = queries[2].astype(int)[-self.batchnum:] #query id according to origin dataset(whole) # query_data_ids = self.data_ids[query_ids] # self.data_ids = np.delete(self.data_ids, query_ids) # del from unlabeled # print('query new data {}'.format(time.time() - time0)) # return query_data_ids
1,922
48.307692
119
py
AS_Molecule
AS_Molecule-master/bayes_al/mc_sch.py
import torch as th import numpy as np import torch.nn as nn import dgl.function as fn from torch.nn import Softplus import dgl '''Monte Carlo Dropout Schnet for active learning''' #cannot first write device in model class AtomEmbedding(nn.Module): """ Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. """ def __init__(self, dim=128, type_num=100, pre_train=None): """ Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings """ super(AtomEmbedding, self).__init__() self._dim = dim self._type_num = type_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(type_num, dim, padding_idx=0) def forward(self, g, p_name="node"): """Input type is dgl graph""" atom_list = g.ndata["nodes"] g.ndata[p_name] = self.embedding(atom_list) return g.ndata[p_name] class EdgeEmbedding(nn.Module): """ Convert the edge to embedding. The edge links same pair of atoms share the same initial embedding. """ def __init__(self, dim=128, edge_num=3000, pre_train=None): """ Randomly init the edge embeddings. Args: dim: the dim of embeddings edge_num: the maximum type of edges pre_train: the pre_trained embeddings """ super(EdgeEmbedding, self).__init__() self._dim = dim self._edge_num = edge_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(edge_num, dim, padding_idx=0) def generate_edge_type(self, edges): """ Generate the edge type based on the src&dst atom type of the edge. Note that C-O and O-C are the same edge type. To map a pair of nodes to one number, we use an unordered pairing function here See more detail in this disscussion: https://math.stackexchange.com/questions/23503/create-unique-number-from-2-numbers Note that, the edge_num should larger than the square of maximum atomic number in the dataset. """ atom_type_x = edges.src["node_type"] atom_type_y = edges.dst["node_type"] return { "type": atom_type_x * atom_type_y + (th.abs(atom_type_x - atom_type_y) - 1)**2 / 4 } def forward(self, g, p_name="edge_f"): g.apply_edges(self.generate_edge_type) g.edata[p_name] = self.embedding(g.edata["type"]) return g.edata[p_name] class ShiftSoftplus(Softplus): """ Shiftsoft plus activation function: 1/beta * (log(1 + exp**(beta * x)) - log(shift)) """ def __init__(self, beta=1, shift=2, threshold=20): super().__init__(beta, threshold) self.shift = shift self.softplus = Softplus(beta, threshold) def forward(self, input): return self.softplus(input) - np.log(float(self.shift)) class RBFLayer(nn.Module): """ Radial basis functions Layer. e(d) = exp(- gamma * ||d - mu_k||^2) default settings: gamma = 10 0 <= mu_k <= 30 for k=1~300 """ def __init__(self, low=0, high=30, gap=0.1, dim=1): super(RBFLayer, self).__init__() self._low = low self._high = high self._gap = gap self._dim = dim self._n_centers = int(np.ceil((high - low) / gap)) centers = np.linspace(low, high, self._n_centers) self.centers = nn.Parameter(th.Tensor(centers), requires_grad=False) self._fan_out = self._dim * self._n_centers self._gap = centers[1] - centers[0] def dis2rbf(self, edges): dist = edges.data["distance"] radial = dist - self.centers coef = float(-1 / self._gap) rbf = th.exp(coef * (radial**2)) return {"rbf": rbf} def forward(self, g): """Convert distance scalar to rbf vector""" g.apply_edges(self.dis2rbf) return g.edata["rbf"] class MC_CFConv(nn.Module): """ The continuous-filter convolution layer in SchNet. One CFConv contains one rbf layer and three linear layer (two of them have activation funct). """ def __init__(self, rbf_dim, dropout=0.05, dim=64, act="sp"): """ Args: rbf_dim: the dimsion of the RBF layer dim: the dimension of linear layers act: activation function (default shifted softplus) """ super(MC_CFConv, self).__init__() self._rbf_dim = rbf_dim self._dim = dim self._dropout = dropout self.linear_layer1 = nn.Linear(self._rbf_dim, self._dim) self.linear_layer2 = nn.Linear(self._dim, self._dim) if act == "sp": self.activation = nn.Softplus(beta=0.5, threshold=14) else: self.activation = act # additional MC dropout self.mc_drop1 = nn.Dropout(self._dropout) self.mc_drop2 = nn.Dropout(self._dropout) def update_edge(self, edges): rbf = edges.data["rbf"] h = self.mc_drop1(self.linear_layer1(rbf)) h = self.activation(h) h = self.mc_drop2(self.linear_layer2(h)) return {"h": h} def forward(self, g): g.apply_edges(self.update_edge) g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), reduce_func=fn.sum('neighbor_info', 'new_node')) return g.ndata["new_node"] class MC_Interaction(nn.Module): """ The interaction layer in the SchNet model. """ def __init__(self, rbf_dim, dim, dropout=0.05): super(MC_Interaction, self).__init__() self._node_dim = dim self._dropout = dropout self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=False) self.cfconv = MC_CFConv(rbf_dim, dim=dim, dropout=self._dropout, act=self.activation) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) #additional dropouts self.mc_drop1 = nn.Dropout(self._dropout) self.mc_drop2 = nn.Dropout(self._dropout) self.mc_drop3 = nn.Dropout(self._dropout) self.bn1 = nn.BatchNorm1d(dim) self.bn2 = nn.BatchNorm1d(dim) self.bn3 = nn.BatchNorm1d(dim) def forward(self, g): g.ndata["new_node"] = self.mc_drop1( self.bn1(self.node_layer1(g.ndata["node"]))) cf_node = self.cfconv(g) cf_node_1 = self.mc_drop2(self.bn2(self.node_layer2(cf_node))) cf_node_1a = self.activation(cf_node_1) new_node = self.mc_drop3(self.bn3(self.node_layer3(cf_node_1a))) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] class MC_SchNetModel(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, dropout=0.05): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(MC_SchNetModel, self).__init__() self.name = "SchNet" self._dim = dim self.dropout = dropout self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList([ MC_Interaction(self.rbf_layer._fan_out, dim, self.dropout) for i in range(n_conv) ]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64, output_dim) self.atom_drop1 = nn.Dropout(self.dropout) self.atom_drop2 = nn.Dropout(self.dropout) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_drop1(self.atom_dense_layer1(g.ndata["node"])) atom = self.activation(atom) res = self.atom_drop2(self.atom_dense_layer2(atom)) g.ndata["res"] = res if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom res = dgl.mean_nodes(g, "res") return res
10,229
32.762376
90
py
AS_Molecule
AS_Molecule-master/bayes_al/bayes_learn.py
import torch import sys import torch.nn as nn from torch.utils.data import DataLoader import time import random from torchnet import meter sys.path.append('..') from bayes_al.bald import Bayes_sampler from config import * from utils.funcs import * from tensorboardX import SummaryWriter from bayes_al.mc_sch import MC_SchNetModel # K_center AL #load the whole dataset def get_preds(args, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize, collate_fn=batcher, shuffle=False, num_workers=args.workers) model.to(device) model.train() model.set_mean_std(dataset.mean, dataset.std) preds = [] pred = [] with torch.no_grad(): for idx, (mols, _) in enumerate(dataloader): pred = torch.zeros(len(mols), args.mc_sampling_num) g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) for i in range(args.mc_sampling_num): pred[:, i] = model(g).squeeze() preds.append(pred) preds = torch.cat(preds, dim=0).cpu().numpy() #torch tensor print('inference {}'.format(time.time() - time0)) return preds def finetune(args, train_dataset, model, optimizer, writer, info, device, iter): train_loader = DataLoader(dataset=train_dataset, batch_size=args.batchsize, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) print('start finetuning with label numbers {}'.format(len(train_dataset))) print('dataset mean {} std {}'.format(train_dataset.mean.item(), train_dataset.std.item())) # if model.name in ["MGCN", "SchNet"]: model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) # optimizer = optimizer_(model.parameters(), lr=args.lr) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() total_epochs = iter * args.bald_ft_epochs # info = {'train_loss': [], # 'train_mae': [], # 'total_epochs':[]} for epoch in range(args.bald_ft_epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() # use SchEmbedding model loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) print("Epoch {:2d}/{:2d}, training: loss: {:.7f}, mae: {:.7f}".format( epoch, total_epochs + epoch, mse_meter.value()[0], mae_meter.value()[0])) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) info['total_epochs'].append(total_epochs + epoch) if args.use_tb: writer.add_scalar('train_loss', mse_meter.value()[0], total_epochs + epoch) writer.add_scalar('train_mae', mae_meter.value()[0], total_epochs + epoch) # if args.use_tb: # writer.add_scalar('testing_loss',loss_test,epoch) # writer.add_scalar('testing_mae',mae_test,epoch) return info def test(args, test_set, model, device): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() model.to(device) test_loader = DataLoader(dataset=test_set, batch_size=args.batchsize, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) model.set_mean_std(test_set.mean, test_set.std) with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def bald_learn(args, config, train_dataset, test_dataset, model, optimizer, writer, device, test_freq): ac_info = [] label_rates = [] print('start k-center active learning ') t_iterations = int((len(train_dataset) - args.init_data_num) / args.batch_data_num) #discard tail data total_data_num = t_iterations * args.batch_data_num + args.init_data_num train_ids = random.sample(range(total_data_num), args.init_data_num) # K_center_sampler = K_center(args,total_data_num,args.batch_data_num,train_ids) bald_sampler = Bayes_sampler(args, total_data_num, args.batch_data_num, train_ids) train_info = {'total_epochs': [], 'train_loss': [], 'train_mae': []} # initialization training train_mols = [train_dataset.mols[i] for i in train_ids] train_subset = MoleDataset(mols=train_mols) train_info = finetune(args, train_subset, model, optimizer, writer, train_info, device, 0) for iter in range(1, t_iterations + 1): embeddings = get_preds(args, model, train_dataset, device) query_ids = bald_sampler.query(embeddings) train_mols.extend([train_dataset.mols[i] for i in query_ids]) train_subset = MoleDataset(mols=train_mols) label_rate = len(train_subset) / total_data_num label_rates.append(label_rate) #finetuning train_info = finetune(args, train_subset, model, optimizer, writer, train_info, device, iter) if iter % args.test_freq == 0: testing_mse, testing_mae = test(args, test_dataset, model, device) print('labels ratio {} number {} test mae {}'.format( label_rate, len(train_subset), testing_mae)) ac_info.append( (train_info['train_loss'][-1], train_info['train_mae'][-1], testing_mse, testing_mae)) if args.use_tb: writer.add_scalar('test_mae', testing_mae, label_rate) if args.save_model: torch.save( { 'info_train': train_info, 'testing_mae': testing_mae, 'model': model.state_dict(), 'data_ids': bald_sampler.data_ids }, config.save_model_path(args.dataset + 'k_center_ac')) ac_results = dict(zip(label_rates, ac_info)) return ac_results if __name__ == "__main__": config = Global_Config() args = make_args() args.use_default = False if args.use_default is False: args.batchsize = 64 args.epochs = 300 args.use_tb = False args.dataset = 'qm9' args.device = 0 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.lr = 1e-3 args.init_data_num = 5000 args.bald_ft_epochs = 10 args.batch_data_num = 1000 args.test_freq = 1 args.mc_sampling_num = 50 print(args) logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') result_path = config.PATH + '/datasets/k_center/' + args.dataset + time.strftime( '_%m%d_%H_%M.txt') train_set, test_set = MoleDataset(prop_name=args.prop_name), MoleDataset( prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol( config.test_pkl[args.dataset]) device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None model = MC_SchNetModel(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) print(model) optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) # label_rates = np.arange(75, 105, 5) / 100 # the first will not be trained results = bald_learn(args, config, train_set, test_set, model, optimizer, writer, device, args.test_freq) with open(result_path, 'w') as fp: for key in results.keys(): fp.write( str(key) + '\t' + ''.join([str(i) + '\t' for i in results[key]]) + '\n') print('test success')
9,316
36.268
85
py
AS_Molecule
AS_Molecule-master/baseline/active-learning/utils/utils.py
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility functions for run_experiment.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import os import pickle import sys import numpy as np import scipy from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV from sklearn.svm import LinearSVC from sklearn.svm import SVC from tensorflow import gfile from utils.kernel_block_solver import BlockKernelSolver from utils.small_cnn import SmallCNN from utils.allconv import AllConv class Logger(object): """Logging object to write to file and stdout.""" def __init__(self, filename): self.terminal = sys.stdout self.log = gfile.GFile(filename, "w") def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): self.terminal.flush() def flush_file(self): self.log.flush() def create_checker_unbalanced(split, n, grid_size): """Creates a dataset with two classes that occupy one color of checkboard. Args: split: splits to use for class imbalance. n: number of datapoints to sample. grid_size: checkerboard size. Returns: X: 2d features. y: binary class. """ y = np.zeros(0) X = np.zeros((0, 2)) for i in range(grid_size): for j in range(grid_size): label = 0 n_0 = int(n/(grid_size*grid_size) * split[0] * 2) if (i-j) % 2 == 0: label = 1 n_0 = int(n/(grid_size*grid_size) * split[1] * 2) x_1 = np.random.uniform(i, i+1, n_0) x_2 = np.random.uniform(j, j+1, n_0) x = np.vstack((x_1, x_2)) x = x.T X = np.concatenate((X, x)) y_0 = label * np.ones(n_0) y = np.concatenate((y, y_0)) return X, y def flatten_X(X): shape = X.shape flat_X = X if len(shape) > 2: flat_X = np.reshape(X, (shape[0], np.product(shape[1:]))) return flat_X def get_mldata(data_dir, name): """Loads data from data_dir. Looks for the file in data_dir. Assumes that data is in pickle format with dictionary fields data and target. Args: data_dir: directory to look in name: dataset name, assumes data is saved in the save_dir with filename <name>.pkl Returns: data and targets Raises: NameError: dataset not found in data folder. """ dataname = name if dataname == "checkerboard": X, y = create_checker_unbalanced(split=[1./5, 4./5], n=10000, grid_size=4) else: filename = os.path.join(data_dir, dataname + ".pkl") if not gfile.Exists(filename): raise NameError("ERROR: dataset not available") data = pickle.load(gfile.GFile(filename, "r")) X = data["data"] y = data["target"] if "keras" in dataname: X = X / 255 y = y.flatten() return X, y def filter_data(X, y, keep=None): """Filters data by class indicated in keep. Args: X: train data y: train targets keep: defaults to None which will keep everything, otherwise takes a list of classes to keep Returns: filtered data and targets """ if keep is None: return X, y keep_ind = [i for i in range(len(y)) if y[i] in keep] return X[keep_ind], y[keep_ind] def get_class_counts(y_full, y): """Gets the count of all classes in a sample. Args: y_full: full target vector containing all classes y: sample vector for which to perform the count Returns: count of classes for the sample vector y, the class order for count will be the same as long as same y_full is fed in """ classes = np.unique(y_full) classes = np.sort(classes) unique, counts = np.unique(y, return_counts=True) complete_counts = [] for c in classes: if c not in unique: complete_counts.append(0) else: index = np.where(unique == c)[0][0] complete_counts.append(counts[index]) return np.array(complete_counts) def flip_label(y, percent_random): """Flips a percentage of labels for one class to the other. Randomly sample a percent of points and randomly label the sampled points as one of the other classes. Does not introduce bias. Args: y: labels of all datapoints percent_random: percent of datapoints to corrupt the labels Returns: new labels with noisy labels for indicated percent of data """ classes = np.unique(y) y_orig = copy.copy(y) indices = range(y_orig.shape[0]) np.random.shuffle(indices) sample = indices[0:int(len(indices) * 1.0 * percent_random)] fake_labels = [] for s in sample: label = y[s] class_ind = np.where(classes == label)[0][0] other_classes = np.delete(classes, class_ind) np.random.shuffle(other_classes) fake_label = other_classes[0] assert fake_label != label fake_labels.append(fake_label) y[sample] = np.array(fake_labels) assert all(y[indices[len(sample):]] == y_orig[indices[len(sample):]]) return y def get_model(method, seed=13): """Construct sklearn model using either logistic regression or linear svm. Wraps grid search on regularization parameter over either logistic regression or svm, returns constructed model Args: method: string indicating scikit method to use, currently accepts logistic and linear svm. seed: int or rng to use for random state fed to scikit method Returns: scikit learn model """ # TODO(lishal): extend to include any scikit model that implements # a decision function. # TODO(lishal): for kernel methods, currently using default value for gamma # but should probably tune. if method == "logistic": model = LogisticRegression(random_state=seed, multi_class="multinomial", solver="lbfgs", max_iter=200) params = {"C": [10.0**(i) for i in range(-4, 5)]} elif method == "logistic_ovr": model = LogisticRegression(random_state=seed) params = {"C": [10.0**(i) for i in range(-5, 4)]} elif method == "linear_svm": model = LinearSVC(random_state=seed) params = {"C": [10.0**(i) for i in range(-4, 5)]} elif method == "kernel_svm": model = SVC(random_state=seed) params = {"C": [10.0**(i) for i in range(-4, 5)]} elif method == "kernel_ls": model = BlockKernelSolver(random_state=seed) params = {"C": [10.0**(i) for i in range(-6, 1)]} elif method == "small_cnn": # Model does not work with weighted_expert or simulate_batch model = SmallCNN(random_state=seed) return model elif method == "allconv": # Model does not work with weighted_expert or simulate_batch model = AllConv(random_state=seed) return model else: raise NotImplementedError("ERROR: " + method + " not implemented") model = GridSearchCV(model, params, cv=3) return model def calculate_entropy(batch_size, y_s): """Calculates KL div between training targets and targets selected by AL. Args: batch_size: batch size of datapoints selected by AL y_s: vector of datapoints selected by AL. Assumes that the order of the data is the order in which points were labeled by AL. Also assumes that in the offline setting y_s will eventually overlap completely with original training targets. Returns: entropy between actual distribution of classes and distribution of samples selected by AL """ n_batches = int(np.ceil(len(y_s) * 1.0 / batch_size)) counts = get_class_counts(y_s, y_s) true_dist = counts / (len(y_s) * 1.0) entropy = [] for b in range(n_batches): sample = y_s[b * batch_size:(b + 1) * batch_size] counts = get_class_counts(y_s, sample) sample_dist = counts / (1.0 * len(sample)) entropy.append(scipy.stats.entropy(true_dist, sample_dist)) return entropy def get_train_val_test_splits(X, y, max_points, seed, confusion, seed_batch, split=(2./3, 1./6, 1./6)): """Return training, validation, and test splits for X and y. Args: X: features y: targets max_points: # of points to use when creating splits. seed: seed for shuffling. confusion: labeling noise to introduce. 0.1 means randomize 10% of labels. seed_batch: # of initial datapoints to ensure sufficient class membership. split: percent splits for train, val, and test. Returns: indices: shuffled indices to recreate splits given original input data X. y_noise: y with noise injected, needed to reproduce results outside of run_experiments using original data. """ np.random.seed(seed) X_copy = copy.copy(X) y_copy = copy.copy(y) # Introduce labeling noise y_noise = flip_label(y_copy, confusion) indices = np.arange(len(y)) if max_points is None: max_points = len(y_noise) else: max_points = min(len(y_noise), max_points) train_split = int(max_points * split[0]) val_split = train_split + int(max_points * split[1]) assert seed_batch <= train_split # Do this to make sure that the initial batch has examples from all classes min_shuffle = 3 n_shuffle = 0 y_tmp = y_noise # Need at least 4 obs of each class for 2 fold CV to work in grid search step while (any(get_class_counts(y_tmp, y_tmp[0:seed_batch]) < 4) or n_shuffle < min_shuffle): np.random.shuffle(indices) y_tmp = y_noise[indices] n_shuffle += 1 X_train = X_copy[indices[0:train_split]] X_val = X_copy[indices[train_split:val_split]] X_test = X_copy[indices[val_split:max_points]] y_train = y_noise[indices[0:train_split]] y_val = y_noise[indices[train_split:val_split]] y_test = y_noise[indices[val_split:max_points]] # Make sure that we have enough observations of each class for 2-fold cv assert all(get_class_counts(y_noise, y_train[0:seed_batch]) >= 4) # Make sure that returned shuffled indices are correct assert all(y_noise[indices[0:max_points]] == np.concatenate((y_train, y_val, y_test), axis=0)) return (indices[0:max_points], X_train, y_train, X_val, y_val, X_test, y_test, y_noise)
10,503
30.169139
79
py
AS_Molecule
AS_Molecule-master/baseline/active-learning/utils/create_data.py
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Make datasets and save specified directory. Downloads datasets using scikit datasets and can also parse csv file to save into pickle format. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from io import BytesIO import os import pickle import StringIO import tarfile import urllib2 import keras.backend as K from keras.datasets import cifar10 from keras.datasets import cifar100 from keras.datasets import mnist import numpy as np import pandas as pd from sklearn.datasets import fetch_20newsgroups_vectorized from sklearn.datasets import fetch_mldata from sklearn.datasets import load_breast_cancer from sklearn.datasets import load_iris import sklearn.datasets.rcv1 from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from absl import app from absl import flags from tensorflow import gfile flags.DEFINE_string('save_dir', '/tmp/data', 'Where to save outputs') flags.DEFINE_string('datasets', '', 'Which datasets to download, comma separated.') FLAGS = flags.FLAGS class Dataset(object): def __init__(self, X, y): self.data = X self.target = y def get_csv_data(filename): """Parse csv and return Dataset object with data and targets. Create pickle data from csv, assumes the first column contains the targets Args: filename: complete path of the csv file Returns: Dataset object """ f = gfile.GFile(filename, 'r') mat = [] for l in f: row = l.strip() row = row.replace('"', '') row = row.split(',') row = [float(x) for x in row] mat.append(row) mat = np.array(mat) y = mat[:, 0] X = mat[:, 1:] data = Dataset(X, y) return data def get_wikipedia_talk_data(): """Get wikipedia talk dataset. See here for more information about the dataset: https://figshare.com/articles/Wikipedia_Detox_Data/4054689 Downloads annotated comments and annotations. """ ANNOTATED_COMMENTS_URL = 'https://ndownloader.figshare.com/files/7554634' ANNOTATIONS_URL = 'https://ndownloader.figshare.com/files/7554637' def download_file(url): req = urllib2.Request(url) response = urllib2.urlopen(req) return response # Process comments comments = pd.read_table( download_file(ANNOTATED_COMMENTS_URL), index_col=0, sep='\t') # remove newline and tab tokens comments['comment'] = comments['comment'].apply( lambda x: x.replace('NEWLINE_TOKEN', ' ')) comments['comment'] = comments['comment'].apply( lambda x: x.replace('TAB_TOKEN', ' ')) # Process labels annotations = pd.read_table(download_file(ANNOTATIONS_URL), sep='\t') # labels a comment as an atack if the majority of annoatators did so labels = annotations.groupby('rev_id')['attack'].mean() > 0.5 # Perform data preprocessing, should probably tune these hyperparameters vect = CountVectorizer(max_features=30000, ngram_range=(1, 2)) tfidf = TfidfTransformer(norm='l2') X = tfidf.fit_transform(vect.fit_transform(comments['comment'])) y = np.array(labels) data = Dataset(X, y) return data def get_keras_data(dataname): """Get datasets using keras API and return as a Dataset object.""" if dataname == 'cifar10_keras': train, test = cifar10.load_data() elif dataname == 'cifar100_coarse_keras': train, test = cifar100.load_data('coarse') elif dataname == 'cifar100_keras': train, test = cifar100.load_data() elif dataname == 'mnist_keras': train, test = mnist.load_data() else: raise NotImplementedError('dataset not supported') X = np.concatenate((train[0], test[0])) y = np.concatenate((train[1], test[1])) if dataname == 'mnist_keras': # Add extra dimension for channel num_rows = X.shape[1] num_cols = X.shape[2] X = X.reshape(X.shape[0], 1, num_rows, num_cols) if K.image_data_format() == 'channels_last': X = X.transpose(0, 2, 3, 1) y = y.flatten() data = Dataset(X, y) return data # TODO(lishal): remove regular cifar10 dataset and only use dataset downloaded # from keras to maintain image dims to create tensor for tf models # Requires adding handling in run_experiment.py for handling of different # training methods that require either 2d or tensor data. def get_cifar10(): """Get CIFAR-10 dataset from source dir. Slightly redundant with keras function to get cifar10 but this returns in flat format instead of keras numpy image tensor. """ url = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def download_file(url): req = urllib2.Request(url) response = urllib2.urlopen(req) return response response = download_file(url) tmpfile = BytesIO() while True: # Download a piece of the file from the connection s = response.read(16384) # Once the entire file has been downloaded, tarfile returns b'' # (the empty bytes) which is a falsey value if not s: break # Otherwise, write the piece of the file to the temporary file. tmpfile.write(s) response.close() tmpfile.seek(0) tar_dir = tarfile.open(mode='r:gz', fileobj=tmpfile) X = None y = None for member in tar_dir.getnames(): if '_batch' in member: filestream = tar_dir.extractfile(member).read() batch = pickle.load(StringIO.StringIO(filestream)) if X is None: X = np.array(batch['data'], dtype=np.uint8) y = np.array(batch['labels']) else: X = np.concatenate((X, np.array(batch['data'], dtype=np.uint8))) y = np.concatenate((y, np.array(batch['labels']))) data = Dataset(X, y) return data def get_mldata(dataset): # Use scikit to grab datasets and save them save_dir. save_dir = FLAGS.save_dir filename = os.path.join(save_dir, dataset[1]+'.pkl') if not gfile.Exists(save_dir): gfile.MkDir(save_dir) if not gfile.Exists(filename): if dataset[0][-3:] == 'csv': data = get_csv_data(dataset[0]) elif dataset[0] == 'breast_cancer': data = load_breast_cancer() elif dataset[0] == 'iris': data = load_iris() elif dataset[0] == 'newsgroup': # Removing header information to make sure that no newsgroup identifying # information is included in data data = fetch_20newsgroups_vectorized(subset='all', remove=('headers')) tfidf = TfidfTransformer(norm='l2') X = tfidf.fit_transform(data.data) data.data = X elif dataset[0] == 'rcv1': sklearn.datasets.rcv1.URL = ( 'http://www.ai.mit.edu/projects/jmlr/papers/' 'volume5/lewis04a/a13-vector-files/lyrl2004_vectors') sklearn.datasets.rcv1.URL_topics = ( 'http://www.ai.mit.edu/projects/jmlr/papers/' 'volume5/lewis04a/a08-topic-qrels/rcv1-v2.topics.qrels.gz') data = sklearn.datasets.fetch_rcv1( data_home='/tmp') elif dataset[0] == 'wikipedia_attack': data = get_wikipedia_talk_data() elif dataset[0] == 'cifar10': data = get_cifar10() elif 'keras' in dataset[0]: data = get_keras_data(dataset[0]) else: try: data = fetch_mldata(dataset[0]) except: raise Exception('ERROR: failed to fetch data from mldata.org') X = data.data y = data.target if X.shape[0] != y.shape[0]: X = np.transpose(X) assert X.shape[0] == y.shape[0] data = {'data': X, 'target': y} pickle.dump(data, gfile.GFile(filename, 'w')) def main(argv): del argv # Unused. # First entry of tuple is mldata.org name, second is the name that we'll use # to reference the data. datasets = [('mnist (original)', 'mnist'), ('australian', 'australian'), ('heart', 'heart'), ('breast_cancer', 'breast_cancer'), ('iris', 'iris'), ('vehicle', 'vehicle'), ('wine', 'wine'), ('waveform ida', 'waveform'), ('german ida', 'german'), ('splice ida', 'splice'), ('ringnorm ida', 'ringnorm'), ('twonorm ida', 'twonorm'), ('diabetes_scale', 'diabetes'), ('mushrooms', 'mushrooms'), ('letter', 'letter'), ('dna', 'dna'), ('banana-ida', 'banana'), ('letter', 'letter'), ('dna', 'dna'), ('newsgroup', 'newsgroup'), ('cifar10', 'cifar10'), ('cifar10_keras', 'cifar10_keras'), ('cifar100_keras', 'cifar100_keras'), ('cifar100_coarse_keras', 'cifar100_coarse_keras'), ('mnist_keras', 'mnist_keras'), ('wikipedia_attack', 'wikipedia_attack'), ('rcv1', 'rcv1')] if FLAGS.datasets: subset = FLAGS.datasets.split(',') datasets = [d for d in datasets if d[1] in subset] for d in datasets: print(d[1]) get_mldata(d) if __name__ == '__main__': app.run(main)
9,340
31.775439
79
py
AS_Molecule
AS_Molecule-master/baseline/active-learning/utils/allconv.py
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implements allconv model in keras using tensorflow backend.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import keras import keras.backend as K from keras.layers import Activation from keras.layers import Conv2D from keras.layers import Dropout from keras.layers import GlobalAveragePooling2D from keras.models import Sequential import numpy as np import tensorflow as tf class AllConv(object): """allconv network that matches sklearn api.""" def __init__(self, random_state=1, epochs=50, batch_size=32, solver='rmsprop', learning_rate=0.001, lr_decay=0.): # params self.solver = solver self.epochs = epochs self.batch_size = batch_size self.learning_rate = learning_rate self.lr_decay = lr_decay # data self.encode_map = None self.decode_map = None self.model = None self.random_state = random_state self.n_classes = None def build_model(self, X): # assumes that data axis order is same as the backend input_shape = X.shape[1:] np.random.seed(self.random_state) tf.set_random_seed(self.random_state) model = Sequential() model.add(Conv2D(96, (3, 3), padding='same', input_shape=input_shape, name='conv1')) model.add(Activation('relu')) model.add(Conv2D(96, (3, 3), name='conv2', padding='same')) model.add(Activation('relu')) model.add(Conv2D(96, (3, 3), strides=(2, 2), padding='same', name='conv3')) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Conv2D(192, (3, 3), name='conv4', padding='same')) model.add(Activation('relu')) model.add(Conv2D(192, (3, 3), name='conv5', padding='same')) model.add(Activation('relu')) model.add(Conv2D(192, (3, 3), strides=(2, 2), name='conv6', padding='same')) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Conv2D(192, (3, 3), name='conv7', padding='same')) model.add(Activation('relu')) model.add(Conv2D(192, (1, 1), name='conv8', padding='valid')) model.add(Activation('relu')) model.add(Conv2D(10, (1, 1), name='conv9', padding='valid')) model.add(GlobalAveragePooling2D()) model.add(Activation('softmax', name='activation_top')) model.summary() try: optimizer = getattr(keras.optimizers, self.solver) except: raise NotImplementedError('optimizer not implemented in keras') # All optimizers with the exception of nadam take decay as named arg try: opt = optimizer(lr=self.learning_rate, decay=self.lr_decay) except: opt = optimizer(lr=self.learning_rate, schedule_decay=self.lr_decay) model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy']) # Save initial weights so that model can be retrained with same # initialization self.initial_weights = copy.deepcopy(model.get_weights()) self.model = model def create_y_mat(self, y): y_encode = self.encode_y(y) y_encode = np.reshape(y_encode, (len(y_encode), 1)) y_mat = keras.utils.to_categorical(y_encode, self.n_classes) return y_mat # Add handling for classes that do not start counting from 0 def encode_y(self, y): if self.encode_map is None: self.classes_ = sorted(list(set(y))) self.n_classes = len(self.classes_) self.encode_map = dict(zip(self.classes_, range(len(self.classes_)))) self.decode_map = dict(zip(range(len(self.classes_)), self.classes_)) mapper = lambda x: self.encode_map[x] transformed_y = np.array(map(mapper, y)) return transformed_y def decode_y(self, y): mapper = lambda x: self.decode_map[x] transformed_y = np.array(map(mapper, y)) return transformed_y def fit(self, X_train, y_train, sample_weight=None): y_mat = self.create_y_mat(y_train) if self.model is None: self.build_model(X_train) # We don't want incremental fit so reset learning rate and weights K.set_value(self.model.optimizer.lr, self.learning_rate) self.model.set_weights(self.initial_weights) self.model.fit( X_train, y_mat, batch_size=self.batch_size, epochs=self.epochs, shuffle=True, sample_weight=sample_weight, verbose=0) def predict(self, X_val): predicted = self.model.predict(X_val) return predicted def score(self, X_val, val_y): y_mat = self.create_y_mat(val_y) val_acc = self.model.evaluate(X_val, y_mat)[1] return val_acc def decision_function(self, X): return self.predict(X) def transform(self, X): model = self.model inp = [model.input] activations = [] # Get activations of the last conv layer. output = [layer.output for layer in model.layers if layer.name == 'conv9'][0] func = K.function(inp + [K.learning_phase()], [output]) for i in range(int(X.shape[0]/self.batch_size) + 1): minibatch = X[i * self.batch_size : min(X.shape[0], (i+1) * self.batch_size)] list_inputs = [minibatch, 0.] # Learning phase. 0 = Test mode (no dropout or batch normalization) layer_output = func(list_inputs)[0] activations.append(layer_output) output = np.vstack(tuple(activations)) output = np.reshape(output, (output.shape[0],np.product(output.shape[1:]))) return output def get_params(self, deep = False): params = {} params['solver'] = self.solver params['epochs'] = self.epochs params['batch_size'] = self.batch_size params['learning_rate'] = self.learning_rate params['weight_decay'] = self.lr_decay if deep: return copy.deepcopy(params) return copy.copy(params) def set_params(self, **parameters): for parameter, value in parameters.items(): setattr(self, parameter, value) return self
6,553
32.269036
80
py
AS_Molecule
AS_Molecule-master/baseline/active-learning/utils/small_cnn.py
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implements Small CNN model in keras using tensorflow backend.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import keras import keras.backend as K from keras.layers import Activation from keras.layers import Conv2D from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.layers import MaxPooling2D from keras.models import Sequential import numpy as np import tensorflow as tf class SmallCNN(object): """Small convnet that matches sklearn api. Implements model from https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py Adapts for inputs of variable size, expects data to be 4d tensor, with # of obserations as first dimension and other dimensions to correspond to length width and # of channels in image. """ def __init__(self, random_state=1, epochs=50, batch_size=32, solver='rmsprop', learning_rate=0.001, lr_decay=0.): # params self.solver = solver self.epochs = epochs self.batch_size = batch_size self.learning_rate = learning_rate self.lr_decay = lr_decay # data self.encode_map = None self.decode_map = None self.model = None self.random_state = random_state self.n_classes = None def build_model(self, X): # assumes that data axis order is same as the backend input_shape = X.shape[1:] np.random.seed(self.random_state) tf.set_random_seed(self.random_state) model = Sequential() model.add(Conv2D(32, (3, 3), padding='same', input_shape=input_shape, name='conv1')) model.add(Activation('relu')) model.add(Conv2D(32, (3, 3), name='conv2')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3, 3), padding='same', name='conv3')) model.add(Activation('relu')) model.add(Conv2D(64, (3, 3), name='conv4')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512, name='dense1')) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(self.n_classes, name='dense2')) model.add(Activation('softmax')) try: optimizer = getattr(keras.optimizers, self.solver) except: raise NotImplementedError('optimizer not implemented in keras') # All optimizers with the exception of nadam take decay as named arg try: opt = optimizer(lr=self.learning_rate, decay=self.lr_decay) except: opt = optimizer(lr=self.learning_rate, schedule_decay=self.lr_decay) model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy']) # Save initial weights so that model can be retrained with same # initialization self.initial_weights = copy.deepcopy(model.get_weights()) self.model = model def create_y_mat(self, y): y_encode = self.encode_y(y) y_encode = np.reshape(y_encode, (len(y_encode), 1)) y_mat = keras.utils.to_categorical(y_encode, self.n_classes) return y_mat # Add handling for classes that do not start counting from 0 def encode_y(self, y): if self.encode_map is None: self.classes_ = sorted(list(set(y))) self.n_classes = len(self.classes_) self.encode_map = dict(zip(self.classes_, range(len(self.classes_)))) self.decode_map = dict(zip(range(len(self.classes_)), self.classes_)) mapper = lambda x: self.encode_map[x] transformed_y = np.array(map(mapper, y)) return transformed_y def decode_y(self, y): mapper = lambda x: self.decode_map[x] transformed_y = np.array(map(mapper, y)) return transformed_y def fit(self, X_train, y_train, sample_weight=None): y_mat = self.create_y_mat(y_train) if self.model is None: self.build_model(X_train) # We don't want incremental fit so reset learning rate and weights K.set_value(self.model.optimizer.lr, self.learning_rate) self.model.set_weights(self.initial_weights) self.model.fit( X_train, y_mat, batch_size=self.batch_size, epochs=self.epochs, shuffle=True, sample_weight=sample_weight, verbose=0) def predict(self, X_val): predicted = self.model.predict(X_val) return predicted def score(self, X_val, val_y): y_mat = self.create_y_mat(val_y) val_acc = self.model.evaluate(X_val, y_mat)[1] return val_acc def decision_function(self, X): return self.predict(X) def transform(self, X): model = self.model inp = [model.input] activations = [] # Get activations of the first dense layer. output = [layer.output for layer in model.layers if layer.name == 'dense1'][0] func = K.function(inp + [K.learning_phase()], [output]) for i in range(int(X.shape[0]/self.batch_size) + 1): minibatch = X[i * self.batch_size : min(X.shape[0], (i+1) * self.batch_size)] list_inputs = [minibatch, 0.] # Learning phase. 0 = Test mode (no dropout or batch normalization) layer_output = func(list_inputs)[0] activations.append(layer_output) output = np.vstack(tuple(activations)) return output def get_params(self, deep = False): params = {} params['solver'] = self.solver params['epochs'] = self.epochs params['batch_size'] = self.batch_size params['learning_rate'] = self.learning_rate params['weight_decay'] = self.lr_decay if deep: return copy.deepcopy(params) return copy.copy(params) def set_params(self, **parameters): for parameter, value in parameters.items(): setattr(self, parameter, value) return self
6,485
31.43
75
py
AS_Molecule
AS_Molecule-master/qbc_learn/test_manager.py
from torch.multiprocessing import Manager,Queue,Process import numpy as np def tar(share,i): share[i][0] = i if __name__ == "__main__": manager = Manager() share = manager.list([np.zeros(4),np.zeros(4),np.zeros(4)]) ps = [] for i in range(3): p = Process(target=tar,args=(share,i)) p.start() ps.append(p) for p in ps: p.join() print(share)
403
20.263158
63
py
AS_Molecule
AS_Molecule-master/qbc_learn/qbc.py
import torch from utils.funcs import * import numpy as np from torch.utils.data import DataLoader import torch.nn as nn from torchnet import meter from copy import deepcopy import torch.multiprocessing as mp # from torch.multiprocessing import Manager,Queue,Process,Pipe,Lock from config import * import time # from base_model.sch import SchNetModel from qbc_learn.model import SchNetModel from tensorboardX import SummaryWriter # torch.multiprocessing.set_start_method('spawn') torch.multiprocessing.set_sharing_strategy('file_system') import sys import torch from torch.utils.data import dataloader from torch.multiprocessing import reductions from multiprocessing.reduction import ForkingPickler default_collate_func = dataloader.default_collate def default_collate_override(batch): dataloader._use_shared_memory = False return default_collate_func(batch) setattr(dataloader, 'default_collate', default_collate_override) for t in torch._storage_classes: if sys.version_info[0] == 2: if t in ForkingPickler.dispatch: del ForkingPickler.dispatch[t] else: if t in ForkingPickler._extra_reducers: del ForkingPickler._extra_reducers[t] class Commitee(): def __init__(self,args,dataset_dir,model_num, batch_data_num,dataset_num): self.model_num = model_num self.batchnum = batch_data_num #different from batchsize self.data_ids = np.arange(0,dataset_num,dtype=int) #now unlabeled data self.args = args self.dataset_dir = dataset_dir self.prop_name = args.prop_name def query_dataset(self): time0 = time.time() query_dataset = FMolDataSet(self.dataset_dir,self.prop_name,self.data_ids) print('get query set time {}'.format(time.time()-time0)) return query_dataset # build query datasets for vars, mols: the whole training dataset def query_ids(self,preds): # selection time0 = time.time() vars = np.std(preds, axis=0).squeeze() vars_ids = np.stack([vars,np.arange(0,len(vars))],axis=0) queries = vars_ids[:,vars_ids[0].argsort()] query_ids = queries[1].astype(int)[-self.batchnum:] #query id according to new dataset # query_data_ids = queries[2].astype(int)[-self.batchnum:] #query id according to origin dataset(whole) query_data_ids = self.data_ids[query_ids] self.data_ids = np.delete(self.data_ids, query_ids) #del from unlabeled print('query new data {}'.format(time.time()-time0)) return query_data_ids #inference all data with mp models #shares {'args':..'dataset':..,'preds':..} #queue {'model':.,'model_id':..} def get_preds(args,dataset,queue,rt_queue,device): torch.cuda.set_device(device) time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize, collate_fn=batcher,shuffle=False, num_workers=args.workers) print('building subprocess dataset {}'.format(time.time()-time0)) time0 = time.time() while not queue.empty(): target = queue.get() model, model_id = target['model'], target['model_id'] model.to(device) model.set_mean_std(dataset.mean,dataset.std) preds = [] with torch.no_grad(): for idx, (mols,_) in enumerate(dataloader): pred = model(mols,device) preds.append(pred.cpu().numpy()) rt_queue[model_id] = np.concatenate(preds,axis=0) print('inferencing {}'.format(time.time()-time0)) return #finetune with multiprocessing #iter: iteration id choosing batch; m_id: model id #shares {'dataset':..,'args'....} #tar_queue({ 'model':..,'info':corresponds to model_id,'model_id}) return_dict[{'model':[],'info':[]}] def finetune(args,train_dataset,tar_queue,return_models,optimizer_,device,iter): # torch.cuda.set_device(device) while not tar_queue.empty(): target = tar_queue.get() m_id = target['model_id'] model = target['model'] info = target['info'] train_loader = DataLoader(dataset=train_dataset,batch_size=args.batchsize,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) total_epochs = iter*args.qbc_ft_epochs if m_id == 0: print('Finetuning with label numbers {}'.format(len(train_dataset))) print('Iter {} Total epochs {}'.format(iter,total_epochs) ) print('dataset mean {} std {}'.format(train_dataset.mean.item(), train_dataset.std.item())) model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) optimizer = optimizer_(model.parameters(),lr=args.lr) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() for epoch in range(args.qbc_ft_epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): label = label.to(device) res = model(mols,device).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) if m_id == 0: print("Epoch {:2d}/ {}, training: loss: {:.7f}, mae: {:.7f} cuda {}".format(epoch,epoch+total_epochs,mse_meter.value()[0],mae_meter.value()[0],device)) info['total_epoch'].append(epoch+total_epochs) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) #return finetuned model model.to(torch.device('cpu')) return_models[m_id] = {'model':model,'info':info} return def qbc_test(args, test_set, models, device,use_all): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() test_models = models if use_all else [models[0]] test_loader = DataLoader(dataset=test_set,batch_size=args.batchsize,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) loss_mat = np.zeros([len(test_models),len(test_loader)]) mae_mat = np.zeros([len(test_models),len(test_loader)]) with torch.no_grad(): for i in range(len(test_models)): test_models[i].to(device) test_models[i].eval() for idx, (mols, label) in enumerate(test_loader): label = label.to(device) res = test_models[i](mols,device).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) loss_mat[i,idx*args.batchsize:idx*args.batchsize+len(mols)] = loss.cpu().numpy() mae_mat[i,idx*args.batchsize:idx*args.batchsize+len(mols)] = mae.cpu().numpy() mse = loss_mat.mean() mae = mae_mat.mean() return mse, mae #models:[model] #results:{'data num':[],'mae'[]} def qbc_active_learning(args,config,train_set,test_set,models,optimizer_,writer,process_num,test_freq): devices = [torch.device('cuda:'+str(i) if torch.cuda.is_available() else 'cpu') for i in range(process_num)] commitee = Commitee(args,train_set.dir,len(models),args.batch_data_num,len(train_set)) model_num = len(models) traindata_num = len(train_set) t_iterations = int(len(train_set)/args.batch_data_num) #discard tails train_ids = [] #currently not use inits manager = mp.Manager() return_models = manager.list([{'model':[],'info':{'total_epoch':[],'train_loss':[],'train_mae':[]}} for _ in range(model_num)]) ac_results = {'label_rate':[],'data_num':[],'test_mae':[]} print('start active learning QBC') for iter in range(t_iterations): #inference print('getting query dataset...') time0 = time.time() query_subset = commitee.query_dataset() preds = manager.list([[] for _ in range(model_num)]) print('building share objects {} datasetid {}'.format(time.time()-time0,id(query_subset))) queue_q = mp.Queue() for i in range(model_num): queue_q.put({'model':models[i],'model_id':i}) processes_q = [] print('building inference process...{}'.format(time.time()-time0)) for i in range(process_num): time0 = time.time() p = mp.Process(target=get_preds,args=(args,query_subset,queue_q,preds,devices[i])) p.start() processes_q.append(p) print('subprocess build {}'.format(time.time()-time0)) for p in processes_q: p.join() preds = np.stack(preds,axis=0) #query print('quering new labeled data...') query_ids = commitee.query_ids(preds) train_ids.extend(query_ids) print(len(set(list(train_ids)))) # print(set('training idddddd num{}'.format(len(set(train_ids))))) train_subset = FMolDataSet(train_set.dir,args.prop_name,train_ids) data_num = len(train_subset) label_rate = data_num / traindata_num #finetuning queue_t = mp.Queue() for i in range(model_num): #put models to queue info = {'total_epoch':[],'train_loss':[],'train_mae':[]} queue_t.put({'model':models[i],'info':info,'model_id':i}) processes_t = [] print('building finetuning process...') for i in range(process_num): p = mp.Process(target=finetune,args=(args,train_subset,queue_t,return_models,optimizer_,devices[i],iter)) p.start() processes_t.append(p) for p in processes_t: p.join() models = [return_models[i]['model'] for i in range(model_num)] print('finetuning finish with {} data, label rate {}'.format(len(train_subset),len(train_subset)/traindata_num)) if args.use_tb: total_epochs = return_models[0]['info']['total_epoch'][-1] writer.add_scalar('training_loss', return_models[0]['info']['train_loss'][-1], total_epochs) writer.add_scalar('training_mae', return_models[0]['info']['train_mae'][-1], total_epochs) if (iter+1)%test_freq == 0: #save the model after test _, test_mae = qbc_test(args,test_set,models,devices[0],use_all=args.test_use_all) ac_results['data_num'].append(data_num) ac_results['label_rate'].append(label_rate) ac_results['test_mae'].append(test_mae) print('test mae {} train data num {} label rate {}'.format(test_mae,data_num,label_rate)) if args.use_tb: writer.add_scalar('test_mae',test_mae,label_rate) if args.save_model: #currently no training info torch.save({'test_mae':test_mae,'models_state_dict':[model.state_dict() for model in models]}, config.save_model_path(args.dataset+'qbc_ac')) return ac_results if __name__ =="__main__": config = Global_Config() args = make_args() if args.use_default is False: args.batchsize = 32 args.epochs = 600 args.use_tb = False args.dataset = 'OPV' args.device = 1 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.lr = 1e-3 args.workers = 10 args.qbc_ft_epochs = 10 args.init_data_num = 2000 args.batch_data_num = 500 args.model_num = 8 args.process_num = 4 args.test_freq = 10 if args.process_num>torch.cuda.device_count(): print('process can not be more than gpu num {}'.format(torch.cuda.device_count())) args.process_num = torch.cuda.device_count() print(args) logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') result_path = config.PATH + '/datasets/qbc/' + args.dataset + time.strftime('_%m%d_%H_%M.txt') train_set, test_set = FMolDataSet(config.mols_dir['qm9'],prop_name=args.prop_name), MoleDataset(prop_name=args.prop_name) # train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol(config.test_pkl[args.dataset]) test_set.load_mol(config.test_pkl[args.dataset]) print('loading data success') mp = mp.get_context('forkserver') #init models models = [] for i in range(args.model_num): models.append(SchNetModel(dim=96, n_conv=4,cutoff=30.0, width=0.1, norm=True, output_dim=1)) print(models[-1]) optimizer_ = torch.optim.Adam if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None results = qbc_active_learning(args,config,train_set,test_set,models,optimizer_,writer,process_num=args.process_num,test_freq=args.test_freq) with open(result_path,'w') as fp: for i in range(len(results['data_num'])): fp.write(str(results['data_num'][i])+'\t'+str(results['test_mae'][i])+'\n') fp.write(str(args)) print('test success') # class Commitee(): # def __init__(self,args,model_num, batch_data_num,dataset_num): # self.model_num = model_num # self.batchnum = batch_data_num #different from batchsize # self.data_ids = np.arange(0,dataset_num,dtype=int) #now unlabeled data # self.args = args # # def query_dataset(self,mols): # time0 = time.time() # query_dataset = MoleDataset(mols=[mols[i] for i in self.data_ids]) # print('get query set time {}'.format(time.time()-time0)) # return query_dataset # # # build query datasets for vars, mols: the whole training dataset # def query_ids(self,mols,preds): # # selection # time0 = time.time() # vars = np.std(preds, axis=0).squeeze() # vars_ids = np.stack([vars,np.arange(0,len(vars)),deepcopy(self.data_ids)],axis=0) # # queries = vars_ids[:,vars_ids[0].argsort()] # query_ids = queries[1].astype(int)[-self.batchnum:] #query id according to new dataset # query_data_ids = queries[2].astype(int)[-self.batchnum:] #query id according to origin dataset(whole) # self.data_ids = np.delete(self.data_ids, query_data_ids) #del from unlabeled # # print('query_id',query_ids) # # print('data id',self.data_ids) # mols_query = [mols[i] for i in query_ids] # newly added mols # print('query new data {}'.format(time.time()-time0)) # return mols_query # #finetune with multiprocessing # #iter: iteration id choosing batch; m_id: model id # #shares {'dataset':..,'args'....} # #tar_queue({ 'model':..,'info':corresponds to model_id,'model_id}) return_dict[{'model':[],'info':[]}] # def finetune(shares,tar_queue,return_models,optimizer_,device,iter): # # torch.cuda.set_device(device) # args = shares['args'] # train_dataset = shares['dataset'] # while not tar_queue.empty(): # target = tar_queue.get() # m_id = target['model_id'] # model = target['model'] # info = target['info'] # train_loader = DataLoader(dataset=train_dataset,batch_size=args.batchsize,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) # total_epochs = iter*args.qbc_ft_epochs # if m_id == 0: # print('Finetuning with label numbers {}'.format(len(train_dataset))) # print('Iter {} Total epochs {}'.format(iter,total_epochs) ) # print('dataset mean {} std {}'.format(train_dataset.mean.item(), train_dataset.std.item())) # model.set_mean_std(train_dataset.mean, train_dataset.std) # model.to(device) # optimizer = optimizer_(model.parameters(),lr=args.lr) # loss_fn = nn.MSELoss() # MAE_fn = nn.L1Loss() # mse_meter = meter.AverageValueMeter() # mae_meter = meter.AverageValueMeter() # for epoch in range(args.qbc_ft_epochs): # mse_meter.reset() # mae_meter.reset() # model.train() # for idx, (mols, label) in enumerate(train_loader): # label = label.to(device) # res = model(mols,device).squeeze() # loss = loss_fn(res, label) # mae = MAE_fn(res, label) # optimizer.zero_grad() # loss.backward() # optimizer.step() # mae_meter.add(mae.detach().item()) # mse_meter.add(loss.detach().item()) # if m_id == 0: # print("Epoch {:2d}/ {}, training: loss: {:.7f}, mae: {:.7f} cuda {}".format(epoch,epoch+total_epochs,mse_meter.value()[0],mae_meter.value()[0],device)) # info['total_epoch'].append(epoch+total_epochs) # info['train_loss'].append(mse_meter.value()[0]) # info['train_mae'].append(mae_meter.value()[0]) # #return finetuned model # model.to(torch.device('cpu')) # return_models[m_id] = {'model':model,'info':info} # return # #models:[model] # #results:{'data num':[],'mae'[]} # def qbc_active_learning(args,config,train_set,test_set,models,optimizer_,writer,process_num,test_freq): # devices = [torch.device('cuda:'+str(i) if torch.cuda.is_available() else 'cpu') for i in range(process_num)] # # # commitee = Commitee(args,train_set.dir,len(models),args.batch_data_num,len(train_set)) # model_num = len(models) # traindata_num = len(train_set) # t_iterations = int(len(train_set)/args.batch_data_num) #discard tails # train_mols = [] #currently not use inits # manager = mp.Manager() # # return_models = manager.list([{'model':[],'info':{'total_epoch':[],'train_loss':[],'train_mae':[]}} for _ in range(model_num)]) # ac_results = {'label_rate':[],'data_num':[],'test_mae':[]} # print('start active learning QBC') # for iter in range(t_iterations): # #inference # print('getting query dataset...') # time0 = time.time() # query_subset = commitee.query_dataset() # preds = manager.list([[] for _ in range(model_num)]) # # query_loader = DataLoader(dataset=query_subset, batch_size=args.batchsize, collate_fn=batcher, shuffle=args.shuffle,num_workers=args.workers) # # # sharing_vars_q = manager.dict({'dataset':query_subset,'args':args}) #59s on 10000 data # # sharing_vars_q = manager.list(query_subset.mols) #30s on 10000 data # # sharing_vars_q = manager.dict({'args':args}) # print('building share objects {} datasetid {}'.format(time.time()-time0,id(query_subset))) # queue_q = mp.Queue() # for i in range(model_num): # queue_q.put({'model':models[i],'model_id':i}) # processes_q = [] # print('building inference process...{}'.format(time.time()-time0)) # for i in range(process_num): # time0 = time.time() # p = mp.Process(target=get_preds,args=(args,query_subset,queue_q,preds,devices[i],query_subset)) # p.start() # processes_q.append(p) # print('subprocess build {}'.format(time.time()-time0)) # for p in processes_q: # p.join() # preds = np.stack(preds,axis=0) # #query # print('quering new labeled data...') # query_mols = commitee.query_ids(train_set.mols,preds) # train_mols.extend(query_mols) # train_subset = MoleDataset(mols=train_mols) # data_num = len(train_subset) # label_rate = data_num / traindata_num # #finetuning # sharing_vars_t = manager.dict({'dataset': train_subset,'args':args}) # queue_t = mp.Queue() # for i in range(model_num): #put models to queue # info = {'total_epoch':[],'train_loss':[],'train_mae':[]} # queue_t.put({'model':models[i],'info':info,'model_id':i}) # processes_t = [] # print('building finetuning process...') # for i in range(process_num): # p = mp.Process(target=finetune,args=(sharing_vars_t,queue_t,return_models,optimizer_,devices[i],iter)) # p.start() # processes_t.append(p) # print('Finetuning on device id {}'.format(i)) # for p in processes_t: # p.join() # models = [return_models[i]['model'] for i in range(model_num)] # print('finetuning finish with {} data, label rate {}'.format(len(train_subset),len(train_subset)/traindata_num)) # # if (iter+1)%test_freq == 0: #save the model after test # _, test_mae = qbc_test(args,test_set,models,devices[0],use_all=args.test_use_all) # ac_results['data_num'].append(data_num) # ac_results['label_rate'].append(label_rate) # ac_results['test_mae'].append(test_mae) # print('test mae {} train data num {} label rate {}'.format(test_mae,data_num,label_rate)) # if args.use_tb: # total_epochs = return_models[0]['info']['total_epoch'][-1] # writer.add_scalar('test_mae',test_mae,label_rate) # writer.add_scalar('training_loss',return_models[0]['info']['train_loss'][-1],total_epochs) # writer.add_scalar('training_mae',return_models[0]['info']['train_mae'][-1],total_epochs) # if args.save_model: #currently no training info # torch.save({ # 'test_mae':test_mae, # 'models_state_dict':[model.state_dict() for model in models] # },config.save_model_path(args.dataset+'qbc_ac')) # return ac_results
21,688
43.173116
169
py
AS_Molecule
AS_Molecule-master/qbc_learn/test_procon.py
# import torch.multiprocessing as mp from utils.funcs import Molecule import numpy as np from torch.multiprocessing import Process, Queue, Lock import torch import random import time import os class TestClass(): def __init__(self,tensor,arr=np.zeros([3])): self.t = tensor self.p = arr # Producer function that places data on the Queue def producer(queue, lock, names): # Synchronize access to the console # with lock: # print('Starting producer => {}'.format(os.getpid())) print('Starting producer => {}'.format(os.getpid())) # Place our names on the Queue for name in names: # time.sleep(random.randint(0, 10)) queue.put(name) # Synchronize access to the console # with lock: # print('Producer {} exiting...'.format(os.getpid())) print('Producer {} exiting...'.format(os.getpid())) # The consumer function takes data off of the Queue def consumer(queue, lock): # Synchronize access to the console # with lock: # print('Starting consumer => {}'.format(os.getpid())) # print('Starting consumer => {}'.format(os.getpid())) # Run indefinitely while True: # time.sleep(random.randint(0, 10)) # If the queue is empty, queue.get() will block until the queue has data name = queue.get() if name is None: print('None') # Synchronize access to the console # with lock: # print('{} got {}'.format(os.getpid(), name)) print('{} got {}'.format(os.getpid(), name)) if __name__ == '__main__': # Some lists with our favorite characters # names = [[TestClass(torch.Tensor([i+j])) for i in range(3)] for j in range(2)] names = [['Master Shake', 'Meatwad', 'Frylock', 'Carl'], ['Early', 'Rusty', 'Sheriff', 'Granny', 'Lil'], ['Rick', 'Morty', 'Jerry', 'Summer', 'Beth']] # Create the Queue object queue = Queue() # Create a lock object to synchronize resource access lock = Lock() producers = [] consumers = [] for n in names: # Create our producer processes by passing the producer function and it's arguments producers.append(Process(target=producer, args=(queue, lock, n))) # Create consumer processes for i in range(len(names) * 2): p = Process(target=consumer, args=(queue, lock)) # This is critical! The consumer function has an infinite loop # Which means it will never exit unless we set daemon to true p.daemon = True consumers.append(p) # Start the producers and consumer # The Python VM will launch new independent processes for each Process object for p in producers: p.start() for c in consumers: c.start() # Like threading, we have a join() method that synchronizes our program for p in producers: p.join() print('Parent process exiting...')
2,932
29.873684
91
py
AS_Molecule
AS_Molecule-master/qbc_learn/model.py
import torch as th import numpy as np import torch.nn as nn import dgl.function as fn from torch.nn import Softplus import dgl #cannot first write device in model class AtomEmbedding(nn.Module): """ Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. """ def __init__(self, dim=128, type_num=100, pre_train=None): """ Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings """ super(AtomEmbedding,self).__init__() self._dim = dim self._type_num = type_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(type_num, dim, padding_idx=0) def forward(self, g, p_name="node"): """Input type is dgl graph""" atom_list = g.ndata["nodes"] g.ndata[p_name] = self.embedding(atom_list) return g.ndata[p_name] class EdgeEmbedding(nn.Module): """ Convert the edge to embedding. The edge links same pair of atoms share the same initial embedding. """ def __init__(self, dim=128, edge_num=3000, pre_train=None): """ Randomly init the edge embeddings. Args: dim: the dim of embeddings edge_num: the maximum type of edges pre_train: the pre_trained embeddings """ super(EdgeEmbedding,self).__init__() self._dim = dim self._edge_num = edge_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(edge_num, dim, padding_idx=0) def generate_edge_type(self, edges): """ Generate the edge type based on the src&dst atom type of the edge. Note that C-O and O-C are the same edge type. To map a pair of nodes to one number, we use an unordered pairing function here See more detail in this disscussion: https://math.stackexchange.com/questions/23503/create-unique-number-from-2-numbers Note that, the edge_num should larger than the square of maximum atomic number in the dataset. """ atom_type_x = edges.src["node_type"] atom_type_y = edges.dst["node_type"] return { "type": atom_type_x * atom_type_y + (th.abs(atom_type_x - atom_type_y) - 1)**2 / 4 } def forward(self, g, p_name="edge_f"): g.apply_edges(self.generate_edge_type) g.edata[p_name] = self.embedding(g.edata["type"]) return g.edata[p_name] class ShiftSoftplus(Softplus): """ Shiftsoft plus activation function: 1/beta * (log(1 + exp**(beta * x)) - log(shift)) """ def __init__(self, beta=1, shift=2, threshold=20): super().__init__(beta, threshold) self.shift = shift self.softplus = Softplus(beta, threshold) def forward(self, input): return self.softplus(input) - np.log(float(self.shift)) class RBFLayer(nn.Module): """ Radial basis functions Layer. e(d) = exp(- gamma * ||d - mu_k||^2) default settings: gamma = 10 0 <= mu_k <= 30 for k=1~300 """ def __init__(self, low=0, high=30, gap=0.1, dim=1): super(RBFLayer,self).__init__() self._low = low self._high = high self._gap = gap self._dim = dim self._n_centers = int(np.ceil((high - low) / gap)) centers = np.linspace(low, high, self._n_centers) self.centers = nn.Parameter(th.Tensor(centers), requires_grad=False) self._fan_out = self._dim * self._n_centers self._gap = centers[1] - centers[0] def dis2rbf(self, edges): dist = edges.data["distance"] radial = dist - self.centers coef = float(-1 / self._gap) rbf = th.exp(coef * (radial**2)) return {"rbf": rbf} def forward(self, g): """Convert distance scalar to rbf vector""" g.apply_edges(self.dis2rbf) return g.edata["rbf"] class CFConv(nn.Module): """ The continuous-filter convolution layer in SchNet. One CFConv contains one rbf layer and three linear layer (two of them have activation funct). """ def __init__(self, rbf_dim, dim=64, act="sp"): """ Args: rbf_dim: the dimsion of the RBF layer dim: the dimension of linear layers act: activation function (default shifted softplus) """ super(CFConv,self).__init__() self._rbf_dim = rbf_dim self._dim = dim self.linear_layer1 = nn.Linear(self._rbf_dim, self._dim) self.linear_layer2 = nn.Linear(self._dim, self._dim) if act == "sp": self.activation = nn.Softplus(beta=0.5, threshold=14) else: self.activation = act def update_edge(self, edges): rbf = edges.data["rbf"] h = self.linear_layer1(rbf) h = self.activation(h) h = self.linear_layer2(h) return {"h": h} def forward(self, g): g.apply_edges(self.update_edge) g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), reduce_func=fn.sum('neighbor_info', 'new_node')) return g.ndata["new_node"] class Interaction(nn.Module): """ The interaction layer in the SchNet model. """ def __init__(self, rbf_dim, dim): super(Interaction,self).__init__() self._node_dim = dim self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=False) self.cfconv = CFConv(rbf_dim, dim, act=self.activation) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) def forward(self, g): g.ndata["new_node"] = self.node_layer1(g.ndata["node"]) cf_node = self.cfconv(g) cf_node_1 = self.node_layer2(cf_node) cf_node_1a = self.activation(cf_node_1) new_node = self.node_layer3(cf_node_1a) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] class SchNetModel(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(SchNetModel,self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64, output_dim) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, mol_list, device): # g_list list of molecules g = dgl.batch([mol.ful_g for mol in mol_list]) g.edata['distance'] = g.edata['distance'].reshape(-1,1) g.to(device) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) atom = self.activation(atom) res = self.atom_dense_layer2(atom) g.ndata["res"] = res if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom res = dgl.mean_nodes(g, "res") return res
9,267
31.069204
90
py
AS_Molecule
AS_Molecule-master/geo_al/k_center.py
import numpy as np import torch import multiprocessing as mp import time from utils.funcs import * import random import math class K_center(object): def __init__(self, args, total_data_num, batch_data_num, init_ids): self.args = args self.total_data_num = total_data_num self.batch_data_num = batch_data_num self.data_ids = np.delete(np.arange(self.total_data_num, dtype=int), init_ids) #data unselected self.core_ids = init_ids # metric: function calculates distance of embeddings #embeddings: np n*ebd def query(self, embeddings, process_num=10): time0 = time.time() new_batch = [] # pool = mp.Pool(process_num) for id in range(self.batch_data_num): un_embeddings = embeddings[self.data_ids] core_embeddings = embeddings[self.core_ids] minimal_cover_dist = torch.zeros(len(self.data_ids)).to( un_embeddings.device) chunk_ids = chunks(range(un_embeddings.size(0)), int(math.sqrt(un_embeddings.size(0)))) un_ebd_a = torch.sum(un_embeddings**2, dim=1) c_ebd_b = torch.sum(core_embeddings**2, dim=1) for i in range(len(chunk_ids)): # minimal_cover_dist[i] = torch.min(torch.norm(un_embeddings[i]-core_embeddings,p=2,dim=1,keepdim=False)) minimal_cover_dist[chunk_ids[i]] = torch.min( c_ebd_b - 2 * un_embeddings[chunk_ids[i]] @ core_embeddings.t(), dim=1)[0] core_point_id = torch.argmax( minimal_cover_dist + un_ebd_a).cpu().numpy() #id in data_ids new_batch.append(self.data_ids[core_point_id]) self.data_ids = np.delete(self.data_ids, core_point_id) # print(id) self.core_ids = np.sort(np.concatenate([self.core_ids, new_batch])) print('query new data {}'.format(time.time() - time0)) return new_batch def random_query(self): new_batch_ids = np.sort( random.sample(list(self.data_ids), self.batch_data_num)) self.data_ids = np.delete(self.data_ids, new_batch_ids) return new_batch_ids # @numba.jit(nopython=True) # def add(l:np.ndarray,m:np.ndarray): # for i in range(l.shape[0]): # q = np.zeros(m.shape[0]) # for j in range(m.shape[0]): # q[j] = np.sqrt(np.dot(l[i]-m[j],l[i]-m[j])) # # np.min(np.sqrt(np.einsum('ij,ij->i',l[i] - m,l[i]-m))) # return # # @numba.jit() # def add_t(l:torch.tensor,m:torch.tensor): # for i in range(l.shape[0]): # torch.min(torch.norm(l[i] - m, p=2, dim=1, keepdim=False)) # return # def mini_dist(u_embeddings,core_embeddings): # return np.min(np.linalg.norm(u_embeddings - core_embeddings,ord=2,axis=1,keepdims=False)) # test code if __name__ == "__main__": sampler = K_center(None, 110000, 20, np.arange(10000, dtype=int)) l = torch.Tensor(np.random.randn(110000, 64)).cuda(0) # un_embeddings = torch.Tensor(np.random.randn(50000,64)).cuda(0) # core_embeddings = torch.Tensor(np.random.randn(50000,64)).cuda(0) # l = torch.Tensor(np.random.randn(100000,64)) # m = torch.Tensor(np.random.randn(1000,64)) # l = np.random.randn(100000,64) # m = np.random.randn(1000,64) # d = torch.zeros(100000).cuda(0) # q = np.zeros(100000) time0 = time.time() # chunk_ids = chunks(range(un_embeddings.size(0)),int(math.sqrt(un_embeddings.size(0)))) # # for i in range(len(chunk_ids)): # d[chunk_ids[i]] = torch.max(un_embeddings[chunk_ids[i]]@core_embeddings.t(),dim=1)[0] # for i in range(l.shape[0]): # torch.min(torch.norm(l[i] - m, p=2, dim=1, keepdim=False)) # np.min(np.linalg.norm(l[i]-m,ord=2,axis=1)) # [torch.min(torch.norm(l[i]-m,p=2,dim=1,keepdim=False)) for i in range(l.shape[0])] # add(l,m) # add_t(l,m) #time 100000+1000 *64 # GPU(torch) CPU(numpy) CPU(torch) # for python 7.38 23.15 17.63 # list compression # for numba sampler.query(l) print(time.time() - time0)
4,262
36.069565
121
py
AS_Molecule
AS_Molecule-master/geo_al/embedding_model.py
import torch as th import torch.nn as nn import numpy as np import dgl import dgl.function as fn from torch.nn import Softplus #cannot first write device in model class AtomEmbedding(nn.Module): """ Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. """ def __init__(self, dim=128, type_num=100, pre_train=None): """ Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings """ super(AtomEmbedding, self).__init__() self._dim = dim self._type_num = type_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(type_num, dim, padding_idx=0) def forward(self, g, p_name="node"): """Input type is dgl graph""" atom_list = g.ndata["nodes"] g.ndata[p_name] = self.embedding(atom_list) return g.ndata[p_name] class EdgeEmbedding(nn.Module): """ Convert the edge to embedding. The edge links same pair of atoms share the same initial embedding. """ def __init__(self, dim=128, edge_num=3000, pre_train=None): """ Randomly init the edge embeddings. Args: dim: the dim of embeddings edge_num: the maximum type of edges pre_train: the pre_trained embeddings """ super(EdgeEmbedding, self).__init__() self._dim = dim self._edge_num = edge_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(edge_num, dim, padding_idx=0) def generate_edge_type(self, edges): """ Generate the edge type based on the src&dst atom type of the edge. Note that C-O and O-C are the same edge type. To map a pair of nodes to one number, we use an unordered pairing function here See more detail in this disscussion: https://math.stackexchange.com/questions/23503/create-unique-number-from-2-numbers Note that, the edge_num should larger than the square of maximum atomic number in the dataset. """ atom_type_x = edges.src["node_type"] atom_type_y = edges.dst["node_type"] return { "type": atom_type_x * atom_type_y + (th.abs(atom_type_x - atom_type_y) - 1)**2 / 4 } def forward(self, g, p_name="edge_f"): g.apply_edges(self.generate_edge_type) g.edata[p_name] = self.embedding(g.edata["type"]) return g.edata[p_name] class ShiftSoftplus(Softplus): """ Shiftsoft plus activation function: 1/beta * (log(1 + exp**(beta * x)) - log(shift)) """ def __init__(self, beta=1, shift=2, threshold=20): super().__init__(beta, threshold) self.shift = shift self.softplus = Softplus(beta, threshold) def forward(self, input): return self.softplus(input) - np.log(float(self.shift)) class RBFLayer(nn.Module): """ Radial basis functions Layer. e(d) = exp(- gamma * ||d - mu_k||^2) default settings: gamma = 10 0 <= mu_k <= 30 for k=1~300 """ def __init__(self, low=0, high=30, gap=0.1, dim=1): super(RBFLayer, self).__init__() self._low = low self._high = high self._gap = gap self._dim = dim self._n_centers = int(np.ceil((high - low) / gap)) centers = np.linspace(low, high, self._n_centers) self.centers = nn.Parameter(th.Tensor(centers), requires_grad=False) self._fan_out = self._dim * self._n_centers self._gap = centers[1] - centers[0] def dis2rbf(self, edges): dist = edges.data["distance"] radial = dist - self.centers coef = float(-1 / self._gap) rbf = th.exp(coef * (radial**2)) return {"rbf": rbf} def forward(self, g): """Convert distance scalar to rbf vector""" g.apply_edges(self.dis2rbf) return g.edata["rbf"] class CFConv(nn.Module): """ The continuous-filter convolution layer in SchNet. One CFConv contains one rbf layer and three linear layer (two of them have activation funct). """ def __init__(self, rbf_dim, dim=64, act="sp"): """ Args: rbf_dim: the dimsion of the RBF layer dim: the dimension of linear layers act: activation function (default shifted softplus) """ super(CFConv, self).__init__() self._rbf_dim = rbf_dim self._dim = dim self.linear_layer1 = nn.Linear(self._rbf_dim, self._dim) self.linear_layer2 = nn.Linear(self._dim, self._dim) if act == "sp": self.activation = nn.Softplus(beta=0.5, threshold=14) else: self.activation = act def update_edge(self, edges): rbf = edges.data["rbf"] h = self.linear_layer1(rbf) h = self.activation(h) h = self.linear_layer2(h) return {"h": h} def forward(self, g): g.apply_edges(self.update_edge) g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), reduce_func=fn.sum('neighbor_info', 'new_node')) return g.ndata["new_node"] class Interaction(nn.Module): """ The interaction layer in the SchNet model. """ def __init__(self, rbf_dim, dim): super(Interaction, self).__init__() self._node_dim = dim self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=False) self.cfconv = CFConv(rbf_dim, dim, act=self.activation) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) def forward(self, g): g.ndata["new_node"] = self.node_layer1(g.ndata["node"]) cf_node = self.cfconv(g) cf_node_1 = self.node_layer2(cf_node) cf_node_1a = self.activation(cf_node_1) new_node = self.node_layer3(cf_node_1a) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] class SchEmbedding(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__( self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(SchEmbedding, self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64, output_dim) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g): # g_list list of molecules # g = dgl.batch([mol.ful_g for mol in mol_list]) g.edata['distance'] = g.edata['distance'].reshape(-1, 1) # g.to(device) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom preds = self.atom_dense_layer2(dgl.mean_nodes(g, "res")) return preds def inference(self, g): # g_list list of molecules # g = dgl.batch([mol.ful_g for mol in mol_list]) g.edata['distance'] = g.edata['distance'].reshape(-1, 1) # g.to(device) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom res = dgl.mean_nodes(g, "atom") # atom = self.activation(atom) # g.ndata["res"] = atom # # if self.atom_ref is not None: # g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] # # if self.norm: # g.ndata["res"] = g.ndata[ # "res"] * self.std_per_atom + self.mean_per_atom # preds = self.atom_dense_layer2(dgl.mean_nodes(g, "res")) return res
10,204
31.603834
90
py
AS_Molecule
AS_Molecule-master/geo_al/k_center_cifar10.py
import torch.nn as nn import torch from geo_al.k_center import K_center from config import * from utils.funcs import * from torch.utils.data import DataLoader import torch.utils as utils import time import random from torchnet import meter from tensorboardX import SummaryWriter from geo_al.cnn import * class CNN_Cifar(nn.Module): def __init__(self): super(CNN_Cifar, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(in_channels=3, out_channels=30, kernel_size=5, stride=1, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(2)) self.conv2 = nn.Sequential( nn.Conv2d(30, 40, 5, 1, 2), nn.ReLU(inplace=True), nn.MaxPool2d(2), ) self.conv3 = nn.Sequential( nn.Conv2d(40, 80, 4, 2, 1), nn.ReLU(inplace=True), nn.MaxPool2d(2), ) self.linear = nn.Linear(80 * 2 * 2, 100) self.out = nn.Linear(100, 10) def forward(self, x): x = x.view(-1, 3, 32, 32) x = self.conv1(x) #10*16*16 x = self.conv2(x) #20*8*8 x = self.conv3(x) # 2*2 x = x.view(x.size(0), -1) x = self.linear(x) #100 x = self.out(x) #10 return x # K_center AL #load the whole dataset # slightly different from qm9/opv def get_preds(args, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize, shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) #ignore when using cifar10 embeddings = [] with torch.no_grad(): for idx, (data, _) in enumerate(dataloader): data = data.to(device) embedding = model(data) embeddings.append(embedding) embeddings = torch.cat(embeddings, dim=0) print('inference {}'.format(time.time() - time0)) return embeddings #difference: # mae--> acc #mols-->data or img # model has no attributes set mean std #loss Cross entropy def finetune(args, train_dataset, model, optimizer, writer, info, device, iter): train_loader = DataLoader(dataset=train_dataset, batch_size=args.batchsize, shuffle=args.shuffle, num_workers=args.workers) #collate no need print('start finetuning with label numbers {}'.format(len(train_dataset))) # print('dataset mean {} std {}'.format(train_dataset.mean.item(), train_dataset.std.item())) # if model.name in ["MGCN", "SchNet"]: # model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) # optimizer = optimizer_(model.parameters(), lr=args.lr) loss_fn = nn.CrossEntropyLoss( ) # loss_fn = nn.MSELoss() # MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter( ) # mae_meter = meter.AverageValueMeter() acc_meter = meter.ConfusionMeter(10) total_epochs = iter * args.k_center_ft_epochs for epoch in range(args.k_center_ft_epochs): mse_meter.reset() acc_meter.reset() model.train() for idx, (datas, label) in enumerate(train_loader): datas = datas.to(device) label = label.to(device) scores = model(datas).squeeze() # use CNN_Cifar out_classes = torch.argmax(scores, 1) target_digit = torch.argmax(label, 1) loss = loss_fn(scores, target_digit) # mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() acc_meter.add(out_classes, target_digit) mse_meter.add(loss.detach().item()) acc = 100 * sum(acc_meter.value()[i, i] for i in range(10)) / acc_meter.value().sum( ) # mae_meter.add(mae.detach().item()) print("Epoch {:2d}/{:2d}, training: loss: {:.7f}, acc: {:.7f}".format( epoch, total_epochs + epoch, mse_meter.value()[0], acc)) info['train_loss'].append(mse_meter.value()[0]) info['train_acc'].append(acc) info['total_epochs'].append(total_epochs + epoch) if args.use_tb: writer.add_scalar('train_loss', mse_meter.value()[0], total_epochs + epoch) writer.add_scalar('train_acc', acc, total_epochs + epoch) # if args.use_tb: # writer.add_scalar('testing_loss',loss_test,epoch) # writer.add_scalar('testing_mae',mae_test,epoch) return info def test(args, test_set, model, device): loss_fn = nn.CrossEntropyLoss() # MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter( ) # mae_meter = meter.AverageValueMeter() acc_meter = meter.ConfusionMeter(10) model.eval() model.to(device) test_loader = DataLoader(dataset=test_set, batch_size=args.batchsize, shuffle=args.shuffle, num_workers=args.workers) # model.set_mean_std(test_set.mean,test_set.std) with torch.no_grad(): for idx, (datas, label) in enumerate(test_loader): label = label.to(device) datas = datas.to(device) scores = model(datas).squeeze() out_classes = torch.argmax(scores, 1) target_digit = torch.argmax(label, 1) loss = loss_fn(scores, target_digit) # acc_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) acc_meter.add(out_classes, target_digit) acc = 100 * sum(acc_meter.value()[i, i] for i in range(10)) / acc_meter.value().sum() return mse_meter.value()[0], acc # Cifar 10 is small and allow us to retraining the whole NN def k_center_learn(args, config, train_datas, test_datas, model, optimizer_, writer, device): ac_info = [] label_rates = [] if args.query_method is 'k_center': print('start k-center active learning ') else: print('start random sampling ') t_iterations = int((train_datas[0].shape[0] - args.init_data_num) / args.batch_data_num) #discard tail data total_data_num = t_iterations * args.batch_data_num + args.init_data_num train_ids = random.sample(range(total_data_num), args.init_data_num) K_center_sampler = K_center(args, total_data_num, args.batch_data_num, train_ids) train_info = {'total_epochs': [], 'train_loss': [], 'train_acc': []} train_dataset, test_dataset = Cifar(*train_datas), Cifar(*test_datas) # initialization training train_subdatas = train_datas[0][train_ids], train_datas[1][train_ids] train_subset = Cifar(*train_subdatas) optimizer = optimizer_(model.parameters(), lr=args.lr) train_info = finetune(args, train_subset, model, optimizer, writer, train_info, device, 0) for iter in range(1, t_iterations + 1): embeddings = get_preds(args, model, train_dataset, device) if args.query_method is 'k_center': query_ids = K_center_sampler.query(embeddings) else: query_ids = K_center_sampler.random_query() # train_subdatas.extend([train_dataset.mols[i] for i in query_ids]) train_subdatas = torch.cat([ train_subdatas[0], train_datas[0][query_ids] ]), torch.cat([train_subdatas[1], train_datas[1][query_ids]]) train_subset = Cifar(*train_subdatas) label_rate = len(train_subset) / total_data_num #finetuning if args.init_model: #completely reinitialize the model model = CNN_Cifar() optimizer = optimizer_(model.parameters(), lr=args.lr) train_info = finetune(args, train_subset, model, optimizer, writer, train_info, device, iter) if iter % args.test_freq == 0: testing_mse, testing_acc = test(args, test_dataset, model, device) print('labels ratio {} number {} test acc {}'.format( label_rate, len(train_subset), testing_acc)) ac_info.append( (train_info['train_loss'][-1], train_info['train_acc'][-1], testing_mse, testing_acc)) label_rates.append(label_rate) if args.use_tb: writer.add_scalar('test_acc', testing_acc, label_rate) if args.save_model: torch.save( { 'info_train': train_info, 'testing_acc': testing_acc, 'model': model.state_dict(), 'data_ids': K_center_sampler.data_ids }, config.save_model_path(args.dataset + 'k_center_ac')) ac_results = dict(zip(label_rates, ac_info)) return ac_results if __name__ == "__main__": config = Global_Config() args = make_args() # for cifar10 configuration 50000:10000 if args.use_default is False: args.batchsize = 50 args.epochs = 300 args.use_tb = False args.dataset = 'cifar10' args.device = 1 args.save_model = False args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.lr = 5e-4 args.init_data_num = 5000 args.k_center_ft_epochs = 5 args.batch_data_num = 100 args.test_freq = 2 args.init_model = False args.query_method = 'k_center' optimizer_ = torch.optim.Adam print(args) logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') result_path_k_center = config.PATH + '/datasets/k_center/' + args.dataset + time.strftime( '_%m%d_%H_%M.txt') result_path_random = config.PATH + '/datasets/rd/' + args.dataset + time.strftime( '_%m%d_%H_%M.txt') # train_set, test_set = MoleDataset(prop_name=args.prop_name), MoleDataset(prop_name=args.prop_name) # train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol(config.test_pkl[args.dataset]) train_imgs, test_imgs = pickle.load( open(config.train_pkl['cifar10'], 'rb')), pickle.load(open(config.test_pkl['cifar10'], 'rb')) device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='cifar10') else: writer = None # model = SchEmbedding(dim=32, n_conv=4, cutoff=5.0, width=0.5, norm=True, output_dim=1) model = ResNet(10) print(model) # optimizer = optimizer_(model.parameters(),lr=args.lr) # label_rates = np.arange(75, 105, 5) / 100 # the first will not be trained # print('start k center active learning') # results_k_center = k_center_learn(args, config, train_imgs, test_imgs, model, optimizer_, writer, device) #notice the optimizer_ print('start') args.query_method = 'random' model = ResNet(10) results_random = k_center_learn(args, config, train_imgs, test_imgs, model, optimizer_, writer, device) # with open(result_path_k_center, 'w') as fp: # for key in results_k_center.keys(): # fp.write(str(key) + '\t' + ''.join([str(i) + '\t' for i in results_k_center[key]]) + '\n') with open(result_path_random, 'w') as fp: for key in results_random.keys(): fp.write( str(key) + '\t' + ''.join([str(i) + '\t' for i in results_random[key]]) + '\n') print('test success')
11,901
39.209459
136
py
AS_Molecule
AS_Molecule-master/geo_al/geo_learn.py
import torch import torch.nn as nn from geo_al.embedding_model import SchEmbedding from geo_al.k_center import K_center from config import * from utils.funcs import * from torch.utils.data import DataLoader import time import random from torchnet import meter from tensorboardX import SummaryWriter # K_center AL #load the whole dataset def get_preds(args, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize, collate_fn=batcher, shuffle=False, num_workers=args.workers) model.to(device) model.set_mean_std(dataset.mean, dataset.std) embeddings = [] with torch.no_grad(): for idx, (mols, _) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.inference(g) embeddings.append(embedding) embeddings = torch.cat(embeddings, dim=0) print('inference {}'.format(time.time() - time0)) return embeddings def finetune(args, train_dataset, model, optimizer, writer, info, device, iter): train_loader = DataLoader(dataset=train_dataset, batch_size=args.batchsize, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) print('start finetuning with label numbers {}'.format(len(train_dataset))) print('dataset mean {} std {}'.format(train_dataset.mean.item(), train_dataset.std.item())) # if model.name in ["MGCN", "SchNet"]: model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) # optimizer = optimizer_(model.parameters(), lr=args.lr) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() total_epochs = iter * args.k_center_ft_epochs # info = {'train_loss': [], # 'train_mae': [], # 'total_epochs':[]} for epoch in range(args.k_center_ft_epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): label = label.to(device) g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) res = model(g)[0].squeeze() # use SchEmbedding model loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) print("Epoch {:2d}/{:2d}, training: loss: {:.7f}, mae: {:.7f}".format( epoch, total_epochs + epoch, mse_meter.value()[0], mae_meter.value()[0])) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) info['total_epochs'].append(total_epochs + epoch) if args.use_tb: writer.add_scalar('train_loss', mse_meter.value()[0], total_epochs + epoch) writer.add_scalar('train_mae', mae_meter.value()[0], total_epochs + epoch) # if args.use_tb: # writer.add_scalar('testing_loss',loss_test,epoch) # writer.add_scalar('testing_mae',mae_test,epoch) return info def test(args, test_set, model, device): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() model.to(device) test_loader = DataLoader(dataset=test_set, batch_size=args.batchsize, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) model.set_mean_std(test_set.mean, test_set.std) with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): label = label.to(device) g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) res = model(g)[0].squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def k_center_learn(args, config, train_dataset, test_dataset, model, optimizer, writer, device, test_freq): ac_info = [] label_rates = [] print('start k-center active learning ') t_iterations = int((len(train_dataset) - args.init_data_num) / args.batch_data_num) #discard tail data total_data_num = t_iterations * args.batch_data_num + args.init_data_num train_ids = random.sample(range(total_data_num), args.init_data_num) K_center_sampler = K_center(args, total_data_num, args.batch_data_num, train_ids) train_info = {'total_epochs': [], 'train_loss': [], 'train_mae': []} # initialization training train_mols = [train_dataset.mols[i] for i in train_ids] train_subset = MoleDataset(mols=train_mols) train_info = finetune(args, train_subset, model, optimizer, writer, train_info, device, 0) for iter in range(1, t_iterations + 1): embeddings = get_preds(args, model, train_dataset, device) query_ids = K_center_sampler.query(embeddings) train_mols.extend([train_dataset.mols[i] for i in query_ids]) train_subset = MoleDataset(mols=train_mols) label_rate = len(train_subset) / total_data_num label_rates.append(label_rate) #finetuning train_info = finetune(args, train_subset, model, optimizer, writer, train_info, device, iter) if iter % args.test_freq == 0: testing_mse, testing_mae = test(args, test_dataset, model, device) print('labels ratio {} number {} test mae {}'.format( label_rate, len(train_subset), testing_mae)) ac_info.append( (train_info['train_loss'][-1], train_info['train_mae'][-1], testing_mse, testing_mae)) if args.use_tb: writer.add_scalar('test_mae', testing_mae, label_rate) if args.save_model: torch.save( { 'info_train': train_info, 'testing_mae': testing_mae, 'model': model.state_dict(), 'data_ids': K_center_sampler.data_ids }, config.save_model_path(args.dataset + 'k_center_ac')) ac_results = dict(zip(label_rates, ac_info)) return ac_results if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.batchsize = 64 args.epochs = 300 args.use_tb = False args.dataset = 'qm9' args.device = 2 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.lr = 1e-3 args.init_data_num = 1000 args.k_center_ft_epochs = 20 args.batch_data_num = 2000 args.test_freq = 1 print(args) logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') result_path = config.PATH + '/datasets/k_center/' + args.dataset + time.strftime( '_%m%d_%H_%M.txt') train_set, test_set = MoleDataset(prop_name=args.prop_name), MoleDataset( prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol( config.test_pkl[args.dataset]) device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None model = SchEmbedding(dim=96, n_conv=4, cutoff=30, width=0.1, norm=True, output_dim=1) print(model) optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) # label_rates = np.arange(75, 105, 5) / 100 # the first will not be trained results = k_center_learn(args, config, train_set, test_set, model, optimizer, writer, device, args.test_freq) with open(result_path, 'w') as fp: for key in results.keys(): fp.write( str(key) + '\t' + ''.join([str(i) + '\t' for i in results[key]]) + '\n') print('test success')
9,014
36.252066
85
py
AS_Molecule
AS_Molecule-master/geo_al/dist_test.py
import numpy as np import time from multiprocessing import Pool import torch from geo_al.k_center import K_center if __name__ == "__main__": l = torch.randn(50000, 320) g = torch.randn(50000, 320) l = l.cuda(0) g = g.cuda(0) m = torch.zeros(l.size(0)) time0 = time.time() for i in range(l.size(0)): m[i] = torch.min(torch.norm(l[i] - g, p=2, dim=1)) print('cost', time.time() - time0)
427
22.777778
58
py
AS_Molecule
AS_Molecule-master/single_model_al/wsl_al.py
import torch import torch.nn as nn from torch.utils.data import DataLoader import time import random import numpy as np import sys from tensorboardX import SummaryWriter sys.path.append('..') from pre_training.wsch import WSchnet, Semi_Schnet from single_model_al.sampler import AL_sampler, Inferencer, check_point_test, save_cpt_xlsx, Weakly_Supervised_Trainer, get_preds_w from utils.funcs import MoleDataset, k_center, SelfMolDataSet, k_medoid, get_atom_ref from config import Global_Config, make_args '''Weakly supervised learning for active learning on graphs''' def active_learning(input): args = input['args'] config = input['config'] train_dataset = input['train_dataset'] test_dataset = input['test_dataset'] model_l = input['model'] writer = input['writer'] device = input['device'] ft_method = input['ft_method'] cpt_data_nums = input['checkpoint_data_num'] al_settings = input['al_settings'] result_path = input['result_path'] cpt_path = input['cpt_path'] checkpoint_epochs_num = input['checkpoint_epochs_num'] # al_method = input['al_method'] # val_dataset = input['val_dataset'] # test_freq = input['test_freq'] # ft_epochs = input['ft_epochs'] print('start weakly supervised active learning') al_method = 'k_center' cpk_test_iter = 0 ac_info = [] ac_results = [] cpk_train_mae = [] cpk_test_mae = [] label_rates = [] train_info = {'total_epochs': [], 'train_loss': [], 'train_mae': []} p_labels = torch.zeros(len(train_dataset)).long() t_iterations = int((len(train_dataset) - args.init_data_num) / args.batch_data_num) + 1 # discard tail data total_data_num = (t_iterations - 1) * args.batch_data_num + args.init_data_num # train_ids = random.sample(range(len(train_dataset)), args.init_data_num) # record total data not discard dataset_s = SelfMolDataSet(mols=train_dataset.mols, level='w', prop_name=args.prop_name) # al_inferencer = Inferencer(args,al_method) al_trainer = Weakly_Supervised_Trainer(args, al_settings) # al_trainer = Trainer(args, t_iterations, method=ft_method, ft_epochs=ft_epochs) al_trainer.run(model_l, dataset_s, optimizer, device, writer, None, level='g') preds = get_preds_w(args, model_l, dataset_s, device) # train_ids = k_center(preds.cpu(),args.init_data_num) train_ids = k_medoid(preds.cpu(), args.init_data_num, al_settings['iters'], None, show_stats=True) al_sampler = AL_sampler(args, len(train_dataset), args.batch_data_num, train_ids, al_method) # initialization training # train_mols = [train_dataset.mols[i] for i in train_ids] # train_subset = MoleDataset(mols=train_mols) # input['train_dataset'] = train_subset input['info'] = train_info for iters in range(0, t_iterations): expect_data_num = args.init_data_num + iters * args.batch_data_num label_rate = expect_data_num / total_data_num labeled_ids = al_sampler.get_label_ids() unlabeled_ids = al_sampler.get_unlabeled_ids() # Do checkpoint_test # tune hyperparameters of checkpoint model outside ! if expect_data_num in cpt_data_nums: train_ckpset = MoleDataset( mols=[train_dataset.mols[i] for i in labeled_ids], prop_name=args.prop_name) print('start checkpoint testing iter {} with labels {}'.format( cpk_test_iter, len(train_ckpset))) model_h, cpk_mae_train, cpk_mae_test = check_point_test( al_settings, train_ckpset, test_dataset, model_l, checkpoint_epochs_num[cpk_test_iter], device) cpk_train_mae.append(cpk_mae_train) cpk_test_mae.append(cpk_mae_test) save_cpt_xlsx(cpt_path, cpt_data_nums, cpk_train_mae, cpk_test_mae) print('checkpoint test record save success') # exit when the maximum checkpoint data number is reached if expect_data_num >= np.max(cpt_data_nums): return ac_results else: # generate pesudo labels for next iteration p_labels = al_trainer.generate_p_labels( model_h, train_dataset, labeled_ids, unlabeled_ids, args.prop_name, device) cpk_test_iter += 1 train_info = al_trainer.run(model_l, dataset_s, optimizer, device, writer, p_labels, level='w') preds = get_preds_w(args, model_l, dataset_s, device) new_batch_ids = al_sampler.query(preds) # train_subset_ids = al_sampler.generate_subset(new_batch_ids) # train_subset = MoleDataset(mols=[train_dataset.mols[i] for i in train_subset_ids]) # input['train_dataset'] = train_subset input['info'] = train_info # record results if iters % args.test_freq == 0: # # testing_mse, testing_mae = al_trainer.test(test_dataset, model, device) print('labels ratio {} '.format(label_rate)) # label_rates.append(label_rate) # ac_info.append((train_info['train_loss'][-1], train_info['train_mae'][-1], testing_mse, testing_mae)) # if args.use_tb: # writer.add_scalar('test_mae', testing_mae, label_rate) if args.save_model: torch.save( { 'info_train': train_info, # 'testing_mae': testing_mae, 'model': model.state_dict(), 'data_ids': al_sampler.get_label_ids() }, config.save_model_path(args.dataset + al_method + '_' + ft_method)) '''result file description: label_rate train_loss train_mae test_mae ''' ac_results = dict(zip(label_rates, ac_info)) with open(result_path, 'w') as fp: for key in ac_results.keys(): fp.write( str(key) + '\t' + ''.join([str(i) + '\t' for i in ac_results[key]]) + '\n') print('save success') return ac_results if __name__ == "__main__": config = Global_Config() args = make_args() # # al_method = 'random' # ft_method = 'by_valid' # ft_epochs = 2 al_method = args.al_method ft_method = args.ft_method ft_epochs = args.ft_epochs checkpoint_data_num = [ 5000, 10000, 20000, 30000, 40000, 50000, 60000, 70000 ] # checkpoint_epochs_num = [1500, 1000 ,1000 ,1000 ,600 ,400 ,300 ,300] checkpoint_epochs_num = [800, 500, 500, 500, 400, 200, 200, 200] # checkpoint_epochs_num = [2,2,2,2,2,2,2,2] al_settings = { 'dim': 96, 'n_conv': 4, 'cutoff': 30.0, 'width': 0.1, 'norm': False, 'output_dim': 1, 'atom_ref': get_atom_ref(args.prop_name), 'pre_train': None, 'lr': 1e-3, 'epochs': 150, 'batch_size': 64, 'n_patience': 55, 'cls_method': 'ot', 'prop_bins': 25, 'cls_num': 100, 'cls_epochs': 6, 'iters': 6, 'init_method': 'k_medroids', } # Attention we found normalize will hurt the performance of optimal transport ???***** print(args) logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') result_path = config.PATH + '/datasets/s_al/' + args.dataset + '_' + al_method + '_' + ft_method + time.strftime( '_%m%d_%H_%M.txt') checkpoint_test_path = config.PATH + '/datasets/s_al/' + args.dataset + '_' + al_method + time.strftime( '_%m%d_%H_%M_cpt.xlsx') train_set, valid_set, test_set = MoleDataset( prop_name=args.prop_name), MoleDataset( prop_name=args.prop_name), MoleDataset(prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), valid_set.load_mol( config.valid_pkl[args.dataset]), test_set.load_mol( config.test_pkl[args.dataset]) device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None # atom_ref = get_atom_ref(args.prop_name) # model = WSchnet(dim=256, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1,props_bins=al_settings['prop_bins'],cls_dim=al_settings['cls_num']) model = Semi_Schnet(dim=96, n_conv=4, cutoff=30.0, cls_dim=al_settings['cls_num'], width=0.1, norm=False, output_dim=1, edge_bins=150, mask_n_ratio=args.mask_n_ratio, mask_msg_ratio=0, props_bins=al_settings['prop_bins'], atom_ref=al_settings['atom_ref']) optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) print(model) print(optimizer) input = { 'args': args, 'config': config, 'train_dataset': train_set, 'test_dataset': test_set, 'val_dataset': valid_set, 'model': model, 'optimizer': optimizer, 'writer': writer, 'device': device, 'test_freq': args.test_freq, 'al_method': al_method, 'ft_method': ft_method, 'ft_epochs': ft_epochs, 'checkpoint_data_num': checkpoint_data_num, 'checkpoint_epochs_num': checkpoint_epochs_num, 'al_settings': al_settings, 'result_path': result_path, 'cpt_path': checkpoint_test_path } results = active_learning(input) print('test success')
10,450
37.707407
156
py
AS_Molecule
AS_Molecule-master/single_model_al/sampler.py
import torch import numpy as np import random import torch.nn as nn import time from copy import deepcopy import math from torch.utils.data import DataLoader from torchnet import meter from torch.optim import Adam import pandas as pd import sys import ot import torch.nn.functional as F import copy sys.path.append('..') from base_model.schmodel import SchNetModel from utils.funcs import * class AL_sampler(object): '''A unified sampler class for all single model based active learning algorithms __init__---------- args:args total_data_num: total_data_num of the dataset init_ids: the initial training data when AL starts batch_data_num: num of datas to label each iteration method: AL sampling method in 'random','k_center','bayes' query------------- inputs: the output of the inference process (torch: Tensor) output: the data ids of new batch data ''' def __init__(self, args, total_data_num, batch_data_num, init_ids=None, method='random'): self.args = args self.total_data_num = total_data_num self.batch_data_num = batch_data_num self.data_mix = args.data_mix self.data_mixing_rate = args.data_mixing_rate self.label_ids = init_ids if init_ids != None else [] # labelled ids self.data_ids = np.delete(np.arange(self.total_data_num, dtype=int), init_ids) #data unselected self.al_method = method if method == 'k_center': self.core_ids = init_ids def get_label_ids(self): return self.label_ids def get_unlabeled_ids(self): return self.data_ids # inputs: tensor of embeddings def query(self, inputs): new_batch_ids = [] if self.al_method == 'random': new_batch_ids = self._random_query() elif self.al_method == 'k_center': new_batch_ids = self._k_center_query(inputs) elif self.al_method == 'bayes': new_batch_ids = self._bayes_query(inputs) elif self.al_method == 'msg_mask': new_batch_ids = self._msg_mask_query(inputs) elif self.al_method == 'k_medroids': new_batch_ids = self._k_medroids_query(inputs) else: raise ValueError # add the new batch ids to label_ids self.label_ids.extend(new_batch_ids) return new_batch_ids # def generate_subset(self,new_batch_ids): # if self.data_mix: # subset_ids = deepcopy(random.sample(self.label_ids,int(self.data_mixing_rate*len(self.label_ids)))) # subset_ids.extend(list(new_batch_ids)) # else: # subset_ids = deepcopy(self.label_ids) # subset_ids.extend(list(new_batch_ids)) # return subset_ids def _random_query(self): query_ids = random.sample(range(len(self.data_ids)), self.batch_data_num) new_batch_ids = self.data_ids[query_ids] self.data_ids = np.delete(self.data_ids, query_ids) return new_batch_ids # accelerated k center def _k_center_query(self, inputs): time0 = time.time() new_batch_ids_ = [] new_batch_ids = [] # calculate the minimum dist using a chunked way un_embeddings = inputs[self.data_ids] core_embeddings = inputs[ self.core_ids] # core point is the data already choosen min_dist = 1e5 * torch.ones(self.total_data_num).to( un_embeddings.device) min_dist[self.core_ids] = 0 chunk_ids = chunks(range(un_embeddings.size(0)), int(math.sqrt(un_embeddings.size(0)))) un_ebd_a = torch.sum(un_embeddings**2, dim=1) c_ebd_b = torch.sum(core_embeddings**2, dim=1) for i in range(len(chunk_ids)): min_dist[self.data_ids[ chunk_ids[i]]] = un_ebd_a[chunk_ids[i]] + torch.min( c_ebd_b - 2 * un_embeddings[chunk_ids[i]] @ core_embeddings.t(), dim=1)[0] for id in range(self.batch_data_num): new_point_id_ = int(torch.argmax( min_dist[self.data_ids])) # id relative to query_data_ids new_point_id = self.data_ids[new_point_id_] new_batch_ids_.append(new_point_id_) new_batch_ids.append(new_point_id) distance_new = torch.sum((inputs[new_point_id] - inputs)**2, dim=1) min_dist = torch.min(torch.stack([min_dist, distance_new], dim=0), dim=0)[0] # print(id) self.core_ids = np.sort(np.concatenate([self.core_ids, new_batch_ids])) self.data_ids = np.delete(self.data_ids, new_batch_ids_) print('query new data {}'.format(time.time() - time0)) return new_batch_ids def _k_medroids_query(self, inputs): time0 = time.time() un_embeddings = inputs[self.data_ids] new_batch_ids_ = k_medoids_pp(un_embeddings, self.batch_data_num, 10, show_stats=True) new_batch_ids = self.data_ids[new_batch_ids_] self.data_ids = np.delete(self.data_ids, new_batch_ids_) print('query new data {}'.format(time.time() - time0)) return new_batch_ids def _variance_query(self, preds): time0 = time.time() preds_unlabeled = preds[self.data_ids] variance = torch.std(preds_unlabeled, dim=1).cpu().numpy().squeeze() vars_ids = np.stack([variance, np.arange(0, len(variance))], axis=0) queries = vars_ids[:, vars_ids[0].argsort()] query_ids = queries[1].astype(int)[ -self.batch_data_num:] # query id according to new dataset # query_data_ids = queries[2].astype(int)[-self.batchnum:] #query id according to origin dataset(whole) new_batch_ids = self.data_ids[query_ids] self.data_ids = np.delete(self.data_ids, query_ids) # del from unlabeled print('query new data {}'.format(time.time() - time0)) return new_batch_ids def _bayes_query(self, inputs): return self._variance_query(inputs) def _msg_mask_query(self, inputs): return self._variance_query(inputs) class Inferencer(object): '''A unified class for inference the model before active learning sampling __init__------------ method: AL method in 'random' 'bayes' 'k_center' run------------ model: the inputs model like Schnet or MC_schnet dataset: the data set( class inherited from torch: Dataset) device: device Output: the inputs for AL sampling(eg. variance for Bayes AL method) ''' def __init__(self, args, method='random'): self.args = args self.method = method def run(self, model, dataset, device): output = [] if self.method == 'random': output = self._random_inference() elif self.method == 'k_center': output = self._k_center_inference(model, dataset, device) elif self.method == 'bayes': output = self._bayes_inference(model, dataset, device) elif self.method in ['dropout', 'msg_mask']: output = self._perbulence_inference(model, dataset, device) else: raise ValueError return output # random method does not need inference def _random_inference(self): pass def _k_center_inference(self, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=self.args.batchsize, collate_fn=batcher, shuffle=False, num_workers=self.args.workers) model.to(device) model.set_mean_std(dataset.mean, dataset.std) scores = [] with torch.no_grad(): for idx, (mols, _) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) res = model.inference(g) scores.append(res) scores = torch.cat(scores, dim=0) print('inference {}'.format(time.time() - time0)) return scores def _bayes_inference(self, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=self.args.batchsize * 13, collate_fn=batcher, shuffle=False, num_workers=self.args.workers) model.to(device) model.train() model.set_mean_std(dataset.mean, dataset.std) preds = [] with torch.no_grad(): for idx, (mols, _) in enumerate(dataloader): pred = torch.zeros(len(mols), self.args.mc_sampling_num) g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) for i in range(self.args.mc_sampling_num): pred[:, i] = model(g).squeeze() preds.append(pred) preds = torch.cat(preds, dim=0) # torch tensor print('inference {}'.format(time.time() - time0)) return preds def _perbulence_inference(self, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=self.args.batchsize * 13, collate_fn=batcher, shuffle=False, num_workers=self.args.workers) model.to(device) model.train() model.set_mean_std(dataset.mean, dataset.std) preds = [] with torch.no_grad(): for idx, (mols, _) in enumerate(dataloader): pred = torch.zeros(len(mols), self.args.mc_sampling_num) g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) for i in range(self.args.mc_sampling_num): pred[:, i] = model.inference(g).squeeze() preds.append(pred) preds = torch.cat(preds, dim=0) # torch tensor print('inference {}'.format(time.time() - time0)) return preds class Trainer(object): '''class for finetuning the neural network method: how the finetuning method stops 1. fixed_epochs: finetune only fixed epochs 2. varying_epochs: finetune epochs are decided by an inputs list 3. by_valid: finetune stops when MAE on validation set increases ''' def __init__(self, args, total_iters, method='fixed_epochs', ft_epochs=None): self.args = args self.method = method self.total_iters = total_iters self.iter = 0 self.total_epochs = 0 if self.method == 'fixed_epochs': if type(ft_epochs) is not int: print( 'fixed epochs finetuning requires a parameter ft_epochs: int' ) raise ValueError else: self.ft_epochs = [ft_epochs] * self.total_iters elif self.method == 'varying_epochs': if type(ft_epochs) is not list: print( 'varying epochs finetuning requires a parameter ft_epochs: list' ) raise ValueError elif len(ft_epochs) != self.total_iters: print('epochs list size not match') raise ValueError else: self.ft_epochs = ft_epochs elif self.method == 'by_valid': pass else: print('method not exists') raise ValueError # augments: # info: a dict contains the training information # ft_epochs: list of ft_epochs def finetune(self, inputs): # def finetune(self,train_dataset,model,optimizer,writer,info,device): train_dataset = inputs['train_dataset'] model = inputs['model'] optimizer = inputs['optimizer'] writer = inputs['writer'] info = inputs['info'] device = inputs['device'] if 'val_dataset' in inputs.keys(): val_dataset = inputs['val_dataset'] else: val_dataset = None if self.method in ('fixed_epochs', 'varying_epochs'): info = self._ft_with_known_epochs(train_dataset, model, optimizer, writer, info, device) elif self.method in ('by_valid', ): if val_dataset is None: raise ValueError info = self._ft_by_valid_datas(train_dataset, val_dataset, model, optimizer, writer, info, device) else: raise ValueError return info def test(self, test_dataset, model, device): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() model.to(device) test_loader = DataLoader(dataset=test_dataset, batch_size=self.args.batchsize, collate_fn=batcher, shuffle=self.args.shuffle, num_workers=self.args.workers) model.set_mean_std(test_dataset.mean, test_dataset.std) with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def _ft_with_known_epochs(self, train_dataset, model, optimizer, writer, info, device): train_loader = DataLoader(dataset=train_dataset, batch_size=self.args.batchsize, collate_fn=batcher, shuffle=self.args.shuffle, num_workers=self.args.workers) print('start finetuning with label numbers {} at iteration {}'.format( len(train_dataset), self.iter)) print('dataset mean {} std {}'.format(train_dataset.mean.item(), train_dataset.std.item())) model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) # optimizer = optimizer_(model.parameters(), lr=args.lr) ft_epochs = self.ft_epochs[self.iter] self.total_epochs += ft_epochs self.iter += 1 loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() for epoch in range(ft_epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() # use SchEmbedding model loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) print("Epoch {:2d}/{:2d}, training: loss: {:.7f}, mae: {:.7f}". format(epoch, self.total_epochs, mse_meter.value()[0], mae_meter.value()[0])) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) info['total_epochs'].append(self.total_epochs) if self.args.use_tb: writer.add_scalar('train_loss', mse_meter.value()[0], self.total_epochs) writer.add_scalar('train_mae', mae_meter.value()[0], self.total_epochs) return info def _ft_by_valid_datas(self, train_dataset, val_dataset, model, optimizer, writer, info, device): train_loader = DataLoader(dataset=train_dataset, batch_size=self.args.batchsize, collate_fn=batcher, shuffle=self.args.shuffle, num_workers=self.args.workers) print('start finetuning with label numbers {} at iteration {}'.format( len(train_dataset), self.iter)) print('dataset mean {} std {}'.format(train_dataset.mean.item(), train_dataset.std.item())) model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) # optimizer = optimizer_(model.parameters(), lr=args.lr) epoch = 0 self.iter += 1 loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() mae_valid = [1e10] #inits while True: # test or valid _, valid_mae = self.test(val_dataset, model, device) if valid_mae > mae_valid[-1]: break else: self.total_epochs += 1 mae_valid.append(valid_mae) epoch += 1 mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() # use SchEmbedding model loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) print( "Epoch {:2d}/{:2d}, training: loss: {:.7f}, mae: {:.7f} validing mae {:.7f}" .format(epoch, self.total_epochs, mse_meter.value()[0], mae_meter.value()[0], valid_mae)) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) info['total_epochs'].append(self.total_epochs) if self.args.use_tb: writer.add_scalar('train_loss', mse_meter.value()[0], self.total_epochs) writer.add_scalar('train_mae', mae_meter.value()[0], self.total_epochs) return info class Weakly_Supervised_Trainer(object): def __init__(self, args, wal_settings): self.args = args self.wal_settings = wal_settings self.cls_tags = 0 self.iters = 0 self.method = wal_settings['cls_method'] def run(self, model, dataset, optimizer, device, writer=None, p_labels=None, level='g'): if self.method == 'k_means': self._run_kmeans(model, dataset, optimizer, device, writer, p_labels, level) elif self.method == 'ot': self._run_ot(model, dataset, optimizer, device, writer, p_labels, level) else: raise ValueError def _run_kmeans(self, model, dataset, optimizer, device, writer=None, p_labels=None, level='g'): settings = self.wal_settings train_loader = DataLoader(dataset=dataset, batch_size=self.args.batchsize, collate_fn=batcher_g, shuffle=self.args.shuffle, num_workers=self.args.workers) model.to(device) if p_labels is not None: p_labels = p_labels.to(device) loss_fn = nn.CrossEntropyLoss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() p_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter( 100 ) # clustering num might be too big, do not use confusion matrix p_acc_meter = meter.ConfusionMeter(settings['prop_bins']) c_acc_meter = AccMeter(settings['cls_num']) init_lr = self.args.lr info = { 'n_loss': [], 'n_acc': [], 'c_loss': [], 'c_acc': [], 'p_loss': [], 'p_acc': [] } cls_tags = 0 for epoch in range(self.args.ft_epochs): n_loss_meter.reset() c_loss_meter.reset() p_loss_meter.reset() n_acc_meter.reset() c_acc_meter.reset() p_acc_meter.reset() model.train() # prepare pesudo labels via k means if epoch % settings['cls_epochs'] == 0: feats_all = get_preds_w(self.args, model, dataset, device) if self.iters == 0: cls_tags = k_means(feats_all.cpu(), settings['cls_num'], settings['iters'], inits=settings['init_method'], show_stats=True) self.cls_tags = cls_tags else: cls_tags = k_means(feats_all.cpu(), settings['cls_num'], settings['iters'], inits='random', show_stats=True) #****** self.cls_tags = cls_tags model.re_init_head() for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) # Mask node features mask = torch.randint( 0, g.number_of_nodes(), [int(self.args.mask_n_ratio * g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 # make pesudo labels vis k means cls_labels = cls_tags[list(ids)].to(device) atom_preds, cls_preds, prop_preds = model(g) n_pred_cls = torch.argmax(atom_preds, dim=1) c_pred_cls = torch.argmax(cls_preds, dim=1) p_pred_cls = torch.argmax(prop_preds, dim=1) n_loss = loss_fn(atom_preds[mask], n_label[mask]) c_loss = loss_fn(cls_preds, cls_labels) p_loss = torch.Tensor([0.]).to(device) if level == 'w': p_loss = loss_fn(prop_preds, p_labels[list(ids)]) loss = c_loss + n_loss + p_loss optimizer.zero_grad() loss.backward() optimizer.step() n_loss_meter.add(n_loss.detach().item()) c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, n_label) c_acc_meter.add(c_pred_cls, cls_labels) p_loss_meter.add(p_loss.detach().item()) p_acc_meter.add(p_pred_cls, p_labels[list( ids)]) if p_labels is not None else p_acc_meter.add( p_pred_cls, torch.zeros_like(p_pred_cls).long()) if idx % 50 == 0 and self.args.use_tb: acc = 100 * sum( n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() writer.add_scalar( 'n_train_loss', n_loss_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) writer.add_scalar( 'n_train_acc', acc, int((idx + 1 + epoch * len(train_loader)) / 50)) print('training loss {} acc {}'.format( n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() p_acc = 100 * sum(p_acc_meter.value()[i, i] for i in range( settings['prop_bins'])) / p_acc_meter.value().sum() print( "Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} acc: {:.7f} props: loss {} acc {} level {}" .format(epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0], 100 * c_acc_meter.value(), p_loss_meter.value()[0], p_acc, level)) if (epoch + 1) % 100 == 0: init_lr = init_lr * 0.75 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(n_acc) info['c_loss'].append(c_loss_meter.value()[0]) info['c_acc'].append(100 * c_acc_meter.value()) info['p_loss'].append(p_loss_meter.value()[0]) info['p_acc'].append(p_acc) self.iters += 1 return info def _run_ot(self, model, dataset, optimizer, device, writer=None, p_labels=None, level='g'): settings = self.wal_settings train_loader = DataLoader(dataset=dataset, batch_size=self.args.batchsize, collate_fn=batcher_g, shuffle=self.args.shuffle, num_workers=self.args.workers) model.to(device) if p_labels is not None: p_labels = p_labels.to(device) loss_fn = nn.CrossEntropyLoss() MSE_fn = nn.MSELoss() MAE_fn = nn.L1Loss() loss_meter = meter.AverageValueMeter() n_loss_meter = meter.AverageValueMeter() e_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() p_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter( 100 ) # clustering num might be too big, do not use confusion matrix e_acc_meter = meter.ConfusionMeter(150) p_mae_meter = meter.AverageValueMeter() c_acc_meter = AccMeter(settings['cls_num']) init_lr = self.args.lr info = { 'n_loss': [], 'n_acc': [], 'c_loss': [], 'c_acc': [], 'p_loss': [], 'p_mae': [] } cls_tags = 0 edge_bins = torch.linspace(0, 30, 150).to(device) # 0.2 per bin K = settings['cls_num'] N = len(dataset) # q = np.ones(K)/K # cls distribution # p = np.ones(N)/N # instance distribution # C = np.ones([N, K]) * np.log(K) / N # prob_tensor (cost function) # Q = np.ones([N, K]) / (K * N) # the tag is a prob distribution # # Now I replace it by a normal distribution 4 is decided by 100000*Gauss(4)~10 q = np.exp(-(np.linspace(-4, 4, K)**2) / 2) / (np.sqrt(2 * np.pi)) q = q / q.sum() p = torch.ones(N) / N # C = np.ones([N, K]) * np.log(K) / N # cost matrix Q = np.copy(np.tile(q, (N, 1))) / N # joint distribution model.set_mean_std(torch.zeros([1]), torch.ones([1])) for epoch in range(self.args.ft_epochs): loss_meter.reset() n_loss_meter.reset() e_loss_meter.reset() c_loss_meter.reset() p_loss_meter.reset() n_acc_meter.reset() e_acc_meter.reset() c_acc_meter.reset() p_mae_meter.reset() model.train() # prepare pesudo labels via optimal transport if epoch % settings['cls_epochs'] == 1: time0 = time.time() # Q = ot.sinkhorn(p, q, C, 0.04) print('optimal transport finished {}'.format(time.time() - time0)) for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) # make pesudo labels vis optimal transport cls_labels = torch.tensor( np.argmax(Q[list(ids)], axis=1), requires_grad=False).to(device).long() atom, atom_preds, edge_preds, ( src, dst, edge_ids), cls_preds, embeddings_g, prop_preds = model(g) edge_dist = torch.clone( g.edata['distance'][edge_ids]).requires_grad_(False) edge_labels = torch.argmin(torch.abs(edge_dist - edge_bins), dim=1).long() node_labels = n_label[src] n_pred_cls = torch.argmax(atom_preds, dim=1) e_pred_cls = torch.argmax(edge_preds, dim=1) c_pred_cls = torch.argmax(cls_preds, dim=1) cls_logits = torch.log(F.softmax(cls_preds, dim=1)) n_loss = loss_fn(atom_preds, node_labels) e_loss = loss_fn(edge_preds, edge_labels) c_loss = loss_fn(cls_preds, cls_labels) p_loss = torch.Tensor([0.]).to(device) if level == 'w': p_loss = MSE_fn(prop_preds, p_labels[list(ids)]) p_mae = MAE_fn(prop_preds, p_labels[list(ids)]) # loss = c_loss + n_loss + e_loss + p_loss* 5e4 # For AB study # loss = n_loss + e_loss + p_loss* 4e4 # For vanilla k center loss = p_loss * 5e4 if level == 'w': optimizer.zero_grad() loss.backward() optimizer.step() # optimizer.zero_grad() # loss.backward() # optimizer.step() C[idx * self.args.batchsize:idx * self.args.batchsize + len(mols)] = -cls_logits.detach().cpu().numpy() loss_meter.add(loss.detach().item()) n_loss_meter.add(n_loss.detach().item()) e_loss_meter.add(e_loss.detach().item()) c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, node_labels) e_acc_meter.add(e_pred_cls, edge_labels) c_acc_meter.add(c_pred_cls, cls_labels) p_loss_meter.add(p_loss.detach().item()) p_mae_meter.add(p_mae.detach().item( )) if p_labels is not None else p_mae_meter.add(0) # n_loss_test, n_acc_test= test(args,test_loader,model,device) n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() e_acc = 100 * sum(e_acc_meter.value()[i, i] for i in range(150)) / e_acc_meter.value().sum() print( "Epoch {:2d}, training: loss: {:.7f}, node {:.4f} acc: {:.4f} edge {:.4f} acc {:.4f} clustering: loss: {:.4f} acc {:.4f} props: loss {:.5f} mae {:.5f} level {}" .format(epoch, loss_meter.value()[0], n_loss_meter.value()[0], n_acc, e_loss_meter.value()[0], e_acc, c_loss_meter.value()[0], c_acc_meter.value(), p_loss_meter.value()[0], p_mae_meter.value()[0], level)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(n_acc) info['c_loss'].append(c_loss_meter.value()[0]) info['p_loss'].append(p_loss_meter.value()[0]) info['p_mae'].append(p_mae_meter.value()[0]) self.iters += 1 return info # add ground truth label for labeled data, others by the prediction of model_h def generate_p_labels(self, model_h, train_dataset, label_ids, un_labeled_ids, prop_name, device): time0 = time.time() un_dataset = MoleDataset( mols=[train_dataset.mols[i] for i in un_labeled_ids], prop_name=prop_name) dataloader = DataLoader(dataset=un_dataset, batch_size=self.args.batchsize * 5, collate_fn=batcher, shuffle=False, num_workers=self.args.workers) model_h.to(device) # model.set_mean_std(dataset.mean,dataset.std) p_labels = torch.zeros(len(train_dataset)).to(device) scores = [] with torch.no_grad(): for idx, (mols, _) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) score = model_h(g).squeeze() scores.append(score) scores = torch.cat(scores, dim=0) p_labels[label_ids] = train_dataset.prop[label_ids].to(device) p_labels[un_labeled_ids] = scores # p_labels = (p_labels.contiguous()-model_h.mean_per_atom) / model_h.std_per_atom # p_labels = (1+torch.erf(p_labels/2**0.5))/2 #transform it to (0,1), when bins are big, value might overflow # bin_gap = 1/self.wal_settings['prop_bins'] # p_labels = (p_labels/(bin_gap+1e-7)).long() print('pesudo label generation {}'.format(time.time() - time0)) return p_labels # replace the inference when using w-schnet def get_preds_w(args, model, dataset, device): time0 = time.time() level = dataset.get_level() if level == 'n': batcher_ = batcher_n else: batcher_ = batcher_g dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize * 5, collate_fn=batcher_, shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx, datas in enumerate(dataloader): mols = datas[0] g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings, dim=0) print('inference {}'.format(time.time() - time0)) return embeddings def check_point_test(settings, train_dataset, test_dataset, teacher_model, max_epochs, device): dim, cutoff, output_dim, width, n_conv, norm, atom_ref, pre_train = settings[ 'dim'], settings['cutoff'], settings['output_dim'], settings[ 'width'], settings['n_conv'], settings['norm'], settings[ 'atom_ref'], settings['pre_train'] lr, epochs, batch_size, n_patience = settings['lr'], settings[ 'epochs'], settings['batch_size'], settings['n_patience'] model = SchNetModel(dim=dim, cutoff=cutoff, output_dim=output_dim, width=width, n_conv=n_conv, norm=norm, atom_ref=atom_ref, pre_train=pre_train) # model.load_state_dict(copy.deepcopy(teacher_model.state_dict()),strict=False) optimizer = Adam(model.parameters(), lr=lr) train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, collate_fn=batcher, shuffle=True, num_workers=0) test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, collate_fn=batcher, shuffle=True, num_workers=0) print('Start checkpoint testing label num {}'.format(len(train_dataset))) print('dataset mean {} std {}'.format(train_dataset.mean.item(), train_dataset.std.item())) model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) init_lr = lr # optimizer = optimizer_(model.parameters(), lr=args.lr) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() test_mae_meter = meter.AverageValueMeter() train_mae = [] test_mae = [] best_test_mae = 1e8 patience = 0 epoch = 0 for i in range(max_epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() # use SchEmbedding model loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) print("Epoch {:2d}, training: loss: {:.7f}, mae: {:.7f}".format( epoch, mse_meter.value()[0], mae_meter.value()[0])) train_mae.append(mae_meter.value()[0]) epoch += 1 with torch.no_grad(): test_mae_meter.reset() for idx, (mols, label) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() # use SchEmbedding model mae = MAE_fn(res, label) test_mae_meter.add(mae.detach().item()) test_mae.append(test_mae_meter.value()[0]) if (epoch + 1) % 100 == 0: init_lr = init_lr * 0.75 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) if test_mae[-1] > best_test_mae: patience += 1 else: best_test_mae = test_mae[-1] patience = 0 print('checkpoint test mae {} patience {}'.format( test_mae_meter.value()[0], patience)) return model, train_mae, test_mae def save_cpt_xlsx(cpk_path, cpk_datas, train_mae, test_mae): df1s = [] df2s = [] t_mae_min = [] for i in range(len(train_mae)): df1s.append(pd.DataFrame({'data' + str(cpk_datas[i]): train_mae[i]})) df2s.append(pd.DataFrame({'data' + str(cpk_datas[i]): test_mae[i]})) t_mae_min.append(np.min(test_mae[i])) df1 = pd.concat(df1s, ignore_index=False, axis=1) df2 = pd.concat(df2s, ignore_index=False, axis=1) df3 = pd.DataFrame({'test_mae': t_mae_min}) # train_mae = {'data'+str(cpk_datas[i]):train_mae[i] for i in range(len(train_mae))} # test_mae = {'data'+str(cpk_datas[i]):test_mae[i] for i in range(len(test_mae))} # df1 = pd.DataFrame(train_mae) # df2 = pd.DataFrame(test_mae) writer = pd.ExcelWriter(cpk_path, engine='xlsxwriter') df1.to_excel(writer, sheet_name='train_mae') df2.to_excel(writer, sheet_name='test_mae') df3.to_excel(writer, sheet_name='t_min_mae') writer.save() # def _k_center_query(self, input): # time0 = time.time() # # new_batch_ids = [] # # pool = mp.Pool(process_num) # for id in range(self.batch_data_num): # un_embeddings = input[self.data_ids] # core_embeddings = input[self.core_ids] # minimal_cover_dist = torch.zeros(len(self.data_ids)).to(un_embeddings.device) # chunk_ids = chunks(range(un_embeddings.size(0)), int(math.sqrt(un_embeddings.size(0)))) # un_ebd_a = torch.sum(un_embeddings ** 2, dim=1) # c_ebd_b = torch.sum(core_embeddings ** 2, dim=1) # for i in range(len(chunk_ids)): # # minimal_cover_dist[i] = torch.min(torch.norm(un_embeddings[i]-core_embeddings,p=2,dim=1,keepdim=False)) # minimal_cover_dist[chunk_ids[i]] = \ # torch.min(c_ebd_b - 2 * un_embeddings[chunk_ids[i]] @ core_embeddings.t(), dim=1)[0] # # core_point_id = torch.argmax(minimal_cover_dist + un_ebd_a).cpu().numpy() # id in data_ids # new_batch_ids.append(self.data_ids[core_point_id]) # self.data_ids = np.delete(self.data_ids, core_point_id) # # print(id) # self.core_ids = np.sort(np.concatenate([self.core_ids, new_batch_ids])) # print('query new data {}'.format(time.time() - time0)) # return new_batch_ids # def _run_ot(self,model,dataset,optimizer,device,writer=None,p_labels=None,level='g'): # settings = self.wal_settings # train_loader = DataLoader(dataset=dataset, batch_size=self.args.batchsize, collate_fn=batcher_g, # shuffle=self.args.shuffle, num_workers=self.args.workers) # model.to(device) # if p_labels is not None: # p_labels = p_labels.to(device) # loss_fn = nn.CrossEntropyLoss() # MSE_fn = nn.MSELoss() # MAE_fn = nn.L1Loss() # n_loss_meter = meter.AverageValueMeter() # c_loss_meter = meter.AverageValueMeter() # p_loss_meter = meter.AverageValueMeter() # n_acc_meter = meter.ConfusionMeter(100) # clustering num might be too big, do not use confusion matrix # p_mae_meter = meter.AverageValueMeter() # c_acc_meter = AccMeter(settings['cls_num']) # init_lr = self.args.lr # info = {'n_loss': [], # 'n_acc': [], # 'c_loss': [], # 'c_acc': [], # 'p_loss': [], # 'p_mae': [] # } # cls_tags = 0 # K = settings['cls_num'] # N = len(dataset) # q = np.ones(K)/K # cls distribution # p = np.ones(N)/N # instance distribution # # C = np.ones([N, K]) * np.log(K) / N # prob_tensor (cost function) # P = np.ones([N, K]) / (K * N) # the tag is a prob distribution # # for epoch in range(self.args.ft_epochs): # n_loss_meter.reset() # c_loss_meter.reset() # p_loss_meter.reset() # n_acc_meter.reset() # c_acc_meter.reset() # p_mae_meter.reset() # model.train() # # # prepare pesudo labels via optimal transport # if epoch % settings['cls_epochs'] == 1: # time0 = time.time() # P = ot.sinkhorn(p, q, C, 0.04) # print('optimal transport finished {}'.format(time.time() -time0)) # for idx, (mols, n_label, ids) in enumerate(train_loader): # g = dgl.batch([mol.ful_g for mol in mols]) # g.to(device) # n_label = n_label.to(device) # # # Mask node features # mask = torch.randint(0, g.number_of_nodes(), [int(self.args.mask_n_ratio * g.number_of_nodes())]) # g.ndata['nodes'][mask] = 0 # # # make pesudo labels vis k means # cls_labels = N * torch.tensor(P[list(ids)],requires_grad=False).to(device).float() # # atom_preds, cls_preds, prop_preds = model(g) # cls_logits = torch.log(F.softmax(cls_preds, dim=1)) # # n_pred_cls = torch.argmax(atom_preds, dim=1) # p_pred_cls = torch.argmax(prop_preds, dim=1) # # n_loss = loss_fn(atom_preds[mask], n_label[mask]) # c_loss = torch.sum(- cls_labels * cls_logits, dim=1).mean() # # p_loss = torch.Tensor([0.]).to(device) # if level == 'w': # p_loss = loss_fn(prop_preds, p_labels[list(ids)]) # # loss = c_loss + n_loss + p_loss # # optimizer.zero_grad() # loss.backward() # optimizer.step() # # C[idx * self.args.batchsize:idx * self.args.batchsize + len(mols)] = - cls_logits.detach().cpu().numpy() # # n_loss_meter.add(n_loss.detach().item()) # c_loss_meter.add(c_loss.detach().item()) # n_acc_meter.add(n_pred_cls, n_label) # # c_acc_meter.add(c_pred_cls, cls_labels) # p_loss_meter.add(p_loss.detach().item()) # p_acc_meter.add(p_pred_cls, p_labels[list(ids)]) if p_labels is not None else p_acc_meter.add( # p_pred_cls, torch.zeros_like(p_pred_cls).long()) # # if idx % 50 == 0 and self.args.use_tb: # acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() # writer.add_scalar('n_train_loss', n_loss_meter.value()[0], # int((idx + 1 + epoch * len(train_loader)) / 50)) # writer.add_scalar('n_train_acc', acc, int((idx + 1 + epoch * len(train_loader)) / 50)) # print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # # # n_loss_test, n_acc_test= test(args,test_loader,model,device) # # n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() # p_acc = 100 * sum( # p_acc_meter.value()[i, i] for i in range(settings['prop_bins'])) / p_acc_meter.value().sum() # print( # "Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} props: loss {} acc {} level {}".format( # epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0], p_loss_meter.value()[0], p_acc, level)) # if (epoch + 1) % 100 == 0: # init_lr = init_lr / 1 # for param_group in optimizer.param_groups: # param_group['lr'] = init_lr # print('current learning rate: {}'.format(init_lr)) # # info['n_loss'].append(n_loss_meter.value()[0]) # info['n_acc'].append(n_acc) # info['c_loss'].append(c_loss_meter.value()[0]) # # info['c_acc'].append(100 * c_acc_meter.value()) # info['p_loss'].append(p_loss_meter.value()[0]) # info['p_acc'].append(p_acc) # self.iters += 1 # return info
48,770
40.018503
177
py
AS_Molecule
AS_Molecule-master/single_model_al/run_al.py
import torch import torch.nn as nn from torch.utils.data import DataLoader import time import random import numpy as np import sys from tensorboardX import SummaryWriter sys.path.append('..') from bayes_al.mc_sch import MC_SchNetModel from bayes_al.mm_sch import MM_SchNetModel from base_model.schmodel import SchNetModel from geo_al.embedding_model import SchEmbedding from single_model_al.sampler import AL_sampler, Trainer, Inferencer, check_point_test, save_cpt_xlsx from utils.funcs import MoleDataset from config import * def active_learning(input): args = input['args'] config = input['config'] train_dataset = input['train_dataset'] test_dataset = input['test_dataset'] model = input['model'] writer = input['writer'] device = input['device'] al_method = input['al_method'] ft_method = input['ft_method'] ft_epochs = input['ft_epochs'] cpt_data_nums = input['checkpoint_data_num'] cpt_settings = input['cpt_settings'] result_path = input['result_path'] cpt_path = input['cpt_path'] # val_dataset = input['val_dataset'] # test_freq = input['test_freq'] print('start {} active learning'.format(al_method)) ac_info = [] ac_results = [] cpk_train_mae = [] cpk_test_mae = [] label_rates = [] train_info = {'total_epochs': [], 'train_loss': [], 'train_mae': []} t_iterations = int((len(train_dataset) - args.init_data_num) / args.batch_data_num) + 1 #discard tail data total_data_num = (t_iterations - 1) * args.batch_data_num + args.init_data_num train_ids = random.sample( range(len(train_dataset)), args.init_data_num) #record total data not discard al_sampler = AL_sampler(args, len(train_dataset), args.batch_data_num, train_ids, al_method) al_inferencer = Inferencer(args, al_method) al_trainer = Trainer(args, t_iterations, method=ft_method, ft_epochs=ft_epochs) # initialization training train_mols = [train_dataset.mols[i] for i in train_ids] train_subset = MoleDataset(mols=train_mols) input['train_dataset'] = train_subset input['info'] = train_info train_info = al_trainer.finetune(input) # due to the initial iteration, the showed iteration will be 1 smaller than the actual iteration for iters in range(1, t_iterations): preds = al_inferencer.run(model, train_dataset, device) new_batch_ids = al_sampler.query(preds) train_subset_ids = al_sampler.get_label_ids() # train_mols.extend([train_dataset.mols[i] for i in new_batch_ids]) train_subset = MoleDataset( mols=[train_dataset.mols[i] for i in train_subset_ids]) expect_data_num = args.init_data_num + iters * args.batch_data_num label_rate = expect_data_num / total_data_num #finetuning # renew train_dataset input['train_dataset'] = train_subset input['info'] = train_info train_info = al_trainer.finetune(input) # record results if iters % args.test_freq == 0: testing_mse, testing_mae = al_trainer.test(test_dataset, model, device) print('labels ratio {} number {} test mae {}'.format( label_rate, len(train_subset), testing_mae)) label_rates.append(label_rate) ac_info.append( (train_info['train_loss'][-1], train_info['train_mae'][-1], testing_mse, testing_mae)) if args.use_tb: writer.add_scalar('test_mae', testing_mae, label_rate) if args.save_model: torch.save( { 'info_train': train_info, 'testing_mae': testing_mae, 'model': model.state_dict(), 'data_ids': al_sampler.data_ids }, config.save_model_path(args.dataset + al_method + '_' + ft_method)) '''result file description: label_rate train_loss train_mae test_mae ''' ac_results = dict(zip(label_rates, ac_info)) with open(result_path, 'w') as fp: for key in ac_results.keys(): fp.write( str(key) + '\t' + ''.join([str(i) + '\t' for i in ac_results[key]]) + '\n') print('save success') # Do checkpoint_test # tune hyperparameters of checkpoint model outside ! if args.test_checkpoint and (expect_data_num in cpt_data_nums): labeled_ids = al_sampler.get_label_ids() train_ckpset = MoleDataset( mols=[train_dataset.mols[i] for i in labeled_ids]) _, cpk_mae_train, cpk_mae_test = check_point_test( cpt_settings, train_ckpset, test_dataset, device) cpk_train_mae.append(cpk_mae_train) cpk_test_mae.append(cpk_mae_test) save_cpt_xlsx(cpt_path, cpt_data_nums, cpk_train_mae, cpk_test_mae) print('checkpoint test record save success') # exit when the maximum checkpoint data number is reached if expect_data_num >= np.max(cpt_data_nums): return ac_results return ac_results if __name__ == "__main__": config = Global_Config() args = make_args() # # al_method = 'random' # ft_method = 'by_valid' # ft_epochs = 2 al_method = args.al_method ft_method = args.ft_method ft_epochs = args.ft_epochs checkpoint_data_num = [10000, 20000, 30000, 40000, 60000] cpt_settings = { 'dim': 96, 'n_conv': 4, 'cutoff': 30.0, 'width': 0.1, 'norm': True, 'output_dim': 1, 'atom_ref': None, 'pre_train': None, 'lr': 1e-3, 'epochs': 150, 'batch_size': 64, 'n_patience': 40 } print(args) logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') result_path = config.PATH + '/datasets/s_al/' + args.dataset + '_' + al_method + '_' + ft_method + time.strftime( '_%m%d_%H_%M.txt') checkpoint_test_path = config.PATH + '/datasets/s_al/' + args.dataset + '_' + al_method + time.strftime( '_%m%d_%H_%M_cpt.xlsx') train_set, valid_set, test_set = MoleDataset( prop_name=args.prop_name), MoleDataset( prop_name=args.prop_name), MoleDataset(prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), valid_set.load_mol( config.valid_pkl[args.dataset]), test_set.load_mol( config.test_pkl[args.dataset]) device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None print(al_method) if al_method == 'random': model = SchNetModel(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) elif al_method == 'k_center': model = SchEmbedding(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) elif al_method == 'bayes': model = MC_SchNetModel(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) elif al_method == 'msg_mask': model = MM_SchNetModel(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) else: raise ValueError optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) print(model) print(optimizer) input = { 'args': args, 'config': config, 'train_dataset': train_set, 'test_dataset': test_set, 'val_dataset': valid_set, 'model': model, 'optimizer': optimizer, 'writer': writer, 'device': device, 'test_freq': args.test_freq, 'al_method': al_method, 'ft_method': ft_method, 'ft_epochs': ft_epochs, 'checkpoint_data_num': checkpoint_data_num, 'cpt_settings': cpt_settings, 'result_path': result_path, 'cpt_path': checkpoint_test_path } results = active_learning(input) print('test success')
9,062
35.10757
117
py
AS_Molecule
AS_Molecule-master/utils/funcs.py
import networkx as nx from rdkit import Chem import numpy as np import torch import dgl from torch.utils.data import Dataset import pickle from torch.nn import DataParallel import os import torch.utils.data as data import random import time from sklearn.cluster import KMeans # import torch.multiprocessing as mp # torch.multiprocessing.set_sharing_strategy('file_system') def get_mol(data): return Molecule(*data) # PROPID = {'optical_lumo':0,'gap':1,'homo':2,'lumo':3,'spectral_overlap':4,'delta_homo':5,'delta_lumo':6,'delta_optical_lumo':7,'homo_extrapolated':8,'lumo_extrapolated':9,'gap_extrapolated':10,'optical_lumo_extrapolated':11} def get_atom_ref(prop_name=None): atom_ref_ids = [1, 6, 7, 8, 9] # H,C,N,O,F atom_refs = { 'zpve': torch.Tensor([0, 0, 0, 0, 0]), 'U0': torch.Tensor( [-0.500273, -37.846772, -54.583861, -75.064579, -99.718730]), 'U': torch.Tensor( [-0.498857, -37.845355, -54.582445, -75.063163, -99.717314]), 'H': torch.Tensor( [-0.497912, -37.844411, -54.581501, -75.062219, -99.716370]), 'G': torch.Tensor( [-0.510927, -37.861317, -54.598897, -75.079532, -99.733544]), 'Cv': torch.Tensor([2.981, 2.981, 2.981, 2.981, 2.981]) } atom_ref = torch.zeros([100]) if prop_name in ['zpve', 'U0', 'U', 'H', 'G', 'Cv']: atom_ref[atom_ref_ids] = atom_refs[prop_name] atom_ref = atom_ref.unsqueeze(1) else: atom_ref = None return atom_ref class Molecule(): EDGE_TYPE = [ Chem.BondType.SINGLE, Chem.BondType.DOUBLE, Chem.BondType.TRIPLE, Chem.BondType.AROMATIC ] NODE_TYPE = { 'H': 1, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'Si': 14, 'P': 15, 'S': 16, 'Cl': 17 } PROPID = { 'optical_lumo': 0, 'gap': 1, 'homo': 2, 'lumo': 3, 'spectral_overlap': 4 } def __init__(self, coords, atoms, edges, smi, props, distance=None, loc=False, glob=True): self.coordinates = torch.tensor(coords) self.atoms = atoms # types corresponds to coordiantes self.node_num = len(atoms) self.edges = edges self.smi = smi # self.optical_lumo,self.gap,self.homo,self.lumo,self.spectral_overlap,self.delta_homo,self.delta_lumo,self.delta_optical_lumo,self.homo_extrapolated,self.lumo_extrapolated,self.gap_extrapolated,self.optical_lumo_extrapolated = props self.props = props #dict # self.nx_g, self.nidx, self.loc_g, self.ful_g = nx.Graph(), 0, dgl.DGLGraph(), dgl.DGLGraph() #init self._build_nidx() if loc: self._build_loc() if glob: self._build_ful(distance) # pass def _build_nx_g(self): # first build mol self.mol = Chem.RWMol() for i in range(len(self.atoms)): self.mol.AddAtom(Chem.rdchem.Atom(self.atoms[i])) for i in range(len(self.edges)): self.mol.AddBond(int(self.edges[i][0]), int(self.edges[i][1]), Molecule.EDGE_TYPE[self.edges[i][2]]) self.nx_g = mol2nx(self.mol) return self # build a dgl graph only contains edges existing considering edge relation,now no self edge def _build_loc(self): self.loc_g = dgl.DGLGraph() self.loc_g.add_nodes(self.node_num) self.loc_g.add_edges( self.edges[:, 0], self.edges[:, 1], data={'edge_type': torch.tensor(self.edges[:, 2]).long()}) self.loc_g = dgl.to_bidirected(self.loc_g) self.loc_g.ndata['pos'] = self.coordinates self.loc_g.ndata['nodes'] = self.nidx # build a dgl graph for long interaction(full graph) def _build_ful(self, distance_matrix=None): self.ful_g = dgl.DGLGraph() self.ful_g.add_nodes(self.node_num) self.ful_g.add_edges( [i for i in range(self.node_num) for j in range(self.node_num)], [j for i in range(self.node_num) for j in range(self.node_num)]) # self.ful_g.add_edges(self.ful_g.nodes(), self.ful_g.nodes()) #add self edge self.ful_g.ndata['pos'] = self.coordinates self.ful_g.ndata['nodes'] = self.nidx if distance_matrix is None: distance_matrix = torch.zeros(self.node_num * self.node_num) for i in range(self.node_num): distance_matrix[i * self.node_num:(i + 1) * self.node_num] = torch.norm( self.coordinates[i] - self.coordinates, p=2, dim=1) else: distance_matrix = torch.Tensor(distance_matrix) self.ful_g.edata['distance'] = distance_matrix return def _build_nidx(self): self.nidx = torch.zeros(self.node_num).long() for i in range(self.node_num): self.nidx[i] = Molecule.NODE_TYPE[self.atoms[i]] return class Molecule_MD(object): NODE_TYPE = { 'H': 1, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'Si': 14, 'P': 15, 'S': 16, 'Cl': 17 } def __init__(self, coords, atoms, forces, props, distance): self.coordinates = torch.tensor(coords) self.atoms = atoms # types corresponds to coordiantes self.forces = torch.tensor(forces) self.node_num = len(atoms) self.props = props self._build_nidx() self._build_ful() def _build_ful(self): self.ful_g = dgl.DGLGraph() self.ful_g.add_nodes(self.node_num) self.ful_g.add_edges( [i for i in range(self.node_num) for j in range(self.node_num)], [j for i in range(self.node_num) for j in range(self.node_num)]) # self.ful_g.add_edges(self.ful_g.nodes(), self.ful_g.nodes()) #add self edge self.ful_g.ndata['pos'] = self.coordinates self.ful_g.ndata['pos'] = self.forces self.ful_g.ndata['nodes'] = self.nidx def _build_nidx(self): self.nidx = torch.zeros(self.node_num).long() for i in range(self.node_num): self.nidx[i] = Molecule.NODE_TYPE[self.atoms[i]] return def chunks(l, n): l_chunk = [] chunk_size = int(len(l) / n) for i in range(0, n - 1): l_chunk.append(l[i * chunk_size:(i + 1) * chunk_size]) l_chunk.append(l[(n - 1) * chunk_size:]) return l_chunk class MoleDataset(Dataset): def __init__(self, path=None, mols=None, datas=None, prop_name='homo', loc=False, glob=True): self.path = path self.loc_g = loc self.glob_g = glob self.prop_name = prop_name self.datas = datas self.mols = mols if self.path: # data element ( pos, atoms, edges, smi, props, dists) self.datas = pickle.load(open(path, 'rb')) # self.mols = [[] for i in range(self.__len__())] # self.prop = torch.Tensor(np.stack([data[4] for data in self.datas],axis=0)[:,Molecule.PROPID[prop_name]]) self.__get_props() def __len__(self): if self.datas: return len(self.datas) else: return len(self.mols) def __getitem__(self, item): return self.mols[item], self.prop[item] def __get_props(self): if self.mols: self.prop = torch.Tensor( [mol.props[self.prop_name] for mol in self.mols]) self.mean = torch.mean(self.prop) self.std = torch.std(self.prop) elif self.datas: self.prop_keys = self.datas[0][4].keys() self.props = {} for key in self.prop_keys: self.props[key] = torch.Tensor( [data[4][key] for data in self.datas]) # mean for only properties to predict self.prop = self.props[self.prop_name] self.mean = torch.mean(self.props[self.prop_name]) self.std = torch.std(self.props[self.prop_name]) else: assert 'Not initialized dataset' # Now no parallel, load all to dataset def build(self): # mp = torch.multiprocessing.get_context('fork') # cnt = 0 # pool = mp.Pool(processes=5) # for _ in pool.imap(get_mol, self.datas): # self.mols[cnt] = _ # cnt+=1 # print(cnt) self.mols = [[] for i in range(self.__len__())] for i in range(self.__len__()): pos, atoms, edges, smi, prop, dists = self.datas[i] self.mols[i] = Molecule(pos, atoms, edges, smi, prop, distance=dists, loc=self.loc_g, glob=self.glob_g) print(i) return def get_props(self): return self.prop def load_mol(self, paths): self.mols = [] if type(paths) is list: for path in paths: self.mols.extend(pickle.load(open(path, 'rb'))) print('loading...') else: self.mols = pickle.load(open(paths, 'rb')) self.__get_props() def save_mol(self, paths): if type(paths) is list: path_num = len(paths) mols_chunks = chunks(self.mols, path_num) for i in range(path_num): pickle.dump(mols_chunks[i], open(paths[i], 'wb')) else: pickle.dump(self.mols, open(paths, 'wb')) return class SelfMolDataSet(Dataset): def __init__(self, mols=None, level='n', prop_name='homo'): super(Dataset, self).__init__() self.level = level self.mols = mols self.data_num = len(mols) self.n_ids = [mol.ful_g.ndata['nodes'] for mol in self.mols] self.prop = torch.Tensor([mol.props[prop_name] for mol in self.mols]) self.mean = torch.mean(self.prop) self.std = torch.std(self.prop) if level not in ['n', 'g', 'w']: raise ValueError def get_level(self): return self.level def __len__(self): return self.data_num def __getitem__(self, item): if (self.level == 'n'): return self.mols[item], self.n_ids[item] elif (self.level == 'g') or (self.level == 'w'): return self.mols[item], self.n_ids[item], item else: raise ValueError # deal with large molecules, load mols from seperate .pkl class FMolDataSet(Dataset): def __init__(self, dir, prop_name='homo', data_ids=None): self.dir = dir self.prop_name = prop_name self.data_ids = np.sort( data_ids) if data_ids is not None else np.arange( len(os.listdir(dir)) - 1) self.data_num = len(self.data_ids) self.__get_props() def __len__(self): return self.data_num def __getitem__(self, item): return pickle.load( open( self.dir + '/mol_{0:06d}'.format(self.data_ids[item]) + '.pkl', 'rb')), self.prop[item] # data id must be increasing list def __get_props(self): props = pickle.load(open(self.dir + '/props.pkl', 'rb')) props = [props[i] for i in self.data_ids] self.prop = torch.Tensor([prop[self.prop_name] for prop in props]) self.mean = torch.mean(self.prop) self.std = torch.std(self.prop) def get_dataset_from_files(paths, prop_name): if type(paths) is list: props = [] mols = [] for path in paths: mols_, props_ = pickle.load(open(path, 'rb')) mols.extend(mols_), props.append(props_) props = np.concatenate(props, axis=0) return MoleDataset(mols, torch.Tensor(props), prop_name) else: mols, props = pickle.load(open(paths, 'rb')) return MoleDataset(mols, torch.Tensor(props), prop_name) def load_dataset(path, prop_name, loc_g=False, glob_g=True): datas = pickle.load(open(path, 'rb')) print('load success, preprocessing...') mols = [] props = [] i = 0 for data in datas: pos, atoms, edges, smi, prop, dists = data mols.append( Molecule(pos, atoms, edges, smi, prop, distance=dists, loc=False, glob=True)) props.append(prop) print(i) i += 1 props = np.stack(props, axis=0) return MoleDataset(mols, torch.Tensor(props), prop_name) # a list of tuple to tuple of list def batcher(input): mols, props = zip(*input) props = torch.stack(props, dim=0) return mols, props def batcher_n(input): mols, nodes = zip(*input) nodes = torch.cat(nodes, dim=0) return mols, nodes def batcher_g(input): mols, nodes, ids = zip(*input) nodes = torch.cat(nodes, dim=0) return mols, nodes, ids # dataparallel support set_mean and std for model class RefDataParallel(DataParallel): def set_mean_std(self, mean, std): return getattr(self.module, 'set_mean_std')(mean, std) # c_ij = \sum_k (a_ik - b_jk)^2,torch Tensor def pairwise_L2(A, B): A_norm2 = torch.sum(A**2, dim=1).unsqueeze(1).expand([A.shape[0], B.shape[0]]) B_norm2 = torch.sum(B**2, dim=1).unsqueeze(0).expand([A.shape[0], B.shape[0]]) C = A_norm2 + B_norm2 - 2 * A @ B.t() return C # torch tensor data_num*embed_dim, calculate by L2 distance # show stats: calculate mean MSE (mean on L2 and clusters) def k_medoid(embeddings, cluster_num, iters, center_ids=None, show_stats=False): # init if center_ids is None: center_ids = random.sample(range(embeddings.shape[0]), cluster_num) cluster_centers = embeddings[center_ids] for iteration in range(iters): distances = pairwise_L2(embeddings, cluster_centers) data_tags = torch.argmin(distances, dim=1) n_count = torch.ones_like(embeddings).float() # see: https://stackoverflow.com/questions/58007127/pytorch-differentiable-conditional-index-based-sum n_centers = torch.zeros([data_tags.max() + 1, embeddings.shape[1]]) avg_centers = torch.zeros([data_tags.max() + 1, embeddings.shape[1]]) n_centers.index_add_(0, data_tags, n_count) avg_centers.index_add_(0, data_tags, embeddings) avg_centers = avg_centers / n_centers cls_ids = [[] for _ in range(cluster_num) ] # record the data ids of each cluster [ cls_ids[int(data_tags[i])].append(i) for i in range(embeddings.shape[0]) ] for i in range(cluster_num): if len(cls_ids[i]): center_ids[i] = cls_ids[i][int( torch.argmin( torch.sum((embeddings[cls_ids[i]] - avg_centers[i])**2, dim=1)))] # update cluster centers cluster_centers = embeddings[center_ids] if show_stats: E = 0 for i in range(cluster_num): E += torch.sum( torch.mean((embeddings[cls_ids[i]] - avg_centers[i])**2, dim=1)) E = E / cluster_num print('Iteration {} Mean MSE {}'.format(iteration + 1, E)) return center_ids def k_center(embeddings, cluster_num): time0 = time.time() center_ids = [] center_ids.append(random.choice(range(embeddings.shape[0]))) cluster_center = embeddings[center_ids[-1]].unsqueeze(0) # distances = 1e9 * torch.ones(embeddings.shape[0]) min_dist = 1e9 * torch.ones(embeddings.shape[0]) for k in range(cluster_num - 1): # anchor_ids = random.sample(range(embeddings.shape[0]),embeddings.shape[0]//10) distances = torch.sum((embeddings - cluster_center)**2, dim=1) min_dist = torch.min(torch.stack([min_dist, distances], dim=0), dim=0)[0] center_ids.append(int(torch.argmax(min_dist))) cluster_center = embeddings[center_ids[-1]] print('k_center finished {}'.format(time.time() - time0)) return center_ids # see: https://stackoverflow.com/questions/58007127/pytorch-differentiable-conditional-index-based-sum #clear up clusters def get_centers(embeddings, data_tags, cluster_num): val_cls_num = data_tags.max() + 1 cluster_centers = torch.zeros([cluster_num, embeddings.shape[1]]) n_count = torch.ones_like(embeddings).float() n_centers = torch.zeros([data_tags.max() + 1, embeddings.shape[1]]).to(embeddings.device) avg_centers = torch.zeros([data_tags.max() + 1, embeddings.shape[1]]).to(embeddings.device) n_centers.index_add_(0, data_tags, n_count) avg_centers.index_add_(0, data_tags, embeddings) avg_centers = avg_centers / n_centers cluster_centers[:val_cls_num] = avg_centers cls_ids = [[] for _ in range(cluster_num) ] # record the data ids of each cluster [cls_ids[int(data_tags[i])].append(i) for i in range(data_tags.shape[0])] # reassign empty clusters ept_cls_num = 0 for i in range(cluster_num): if len(cls_ids[i]) == 0: cls_ids[i] = random.choice(range(embeddings.shape[0])) cluster_centers[i] = embeddings[cls_ids[i]] ept_cls_num += 1 if ept_cls_num > 0: print('{} empty cluster detected'.format(ept_cls_num)) return cluster_centers, cls_ids # return the id of each data def k_means(embeddings, cluster_num, iters, inits='random', show_stats=True): if inits is 'random': center_ids = random.sample(range(embeddings.shape[0]), cluster_num) cluster_centers = embeddings[center_ids] data_tags = 0 elif inits is 'k_center': center_ids = k_center(embeddings, cluster_num) cluster_centers = embeddings[center_ids] data_tags = 0 print('seed initialization finished') else: data_tags = inits cluster_centers, cls_ids = get_centers(embeddings, data_tags, cluster_num) for iteration in range(iters): distances = pairwise_L2(embeddings, cluster_centers) data_tags = torch.argmin(distances, dim=1) cluster_centers, cls_ids = get_centers(embeddings, data_tags, cluster_num) if show_stats: E = 0 for i in range(cluster_num): try: E += torch.sum( torch.mean((embeddings[cls_ids[i]].view( -1, embeddings.size(1)) - cluster_centers[i])**2, dim=1)) except Exception: pass E = E / cluster_num print('Iteration {} Mean MSE {}'.format(iteration + 1, E)) return data_tags def k_medoids_pp(embeddings, cluster_num, iters, show_stats=True): # seed initialization time0 = time.time() center_ids = k_center(embeddings, cluster_num) if show_stats: print(time.time() - time0) print('seed initialization finished') cluster_centers = embeddings[center_ids] for iteration in range(iters): distances = pairwise_L2(embeddings, cluster_centers) data_tags = torch.argmin(distances, dim=1) n_count = torch.ones_like(embeddings).float() # see: https://stackoverflow.com/questions/58007127/pytorch-differentiable-conditional-index-based-sum n_centers = torch.zeros([data_tags.max() + 1, embeddings.shape[1]]) avg_centers = torch.zeros([data_tags.max() + 1, embeddings.shape[1]]) n_centers.index_add_(0, data_tags, n_count) avg_centers.index_add_(0, data_tags, embeddings) avg_centers = avg_centers / n_centers cls_ids = [[] for _ in range(cluster_num) ] # record the data ids of each cluster [ cls_ids[int(data_tags[i])].append(i) for i in range(embeddings.shape[0]) ] for i in range(cluster_num): if len(cls_ids[i]): center_ids[i] = cls_ids[i][int( torch.argmin( torch.sum((embeddings[cls_ids[i]] - avg_centers[i])**2, dim=1)))] # update cluster centers cluster_centers = embeddings[center_ids] if show_stats: E = 0 for i in range(cluster_num): E += torch.sum( torch.mean((embeddings[cls_ids[i]] - avg_centers[i])**2, dim=1)) E = E / cluster_num print('Iteration {} Mean MSE {}'.format(iteration + 1, E)) return center_ids def mol2nx(mol): G = nx.Graph() for atom in mol.GetAtoms(): G.add_node(atom.GetIdx(), atomic_num=atom.GetAtomicNum(), formal_charge=atom.GetFormalCharge(), chiral_tag=atom.GetChiralTag(), hybridization=atom.GetHybridization(), num_explicit_hs=atom.GetNumExplicitHs(), is_aromatic=atom.GetIsAromatic()) for bond in mol.GetBonds(): G.add_edge(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx(), bond_type=bond.GetBondType()) return G class Cifar(data.Dataset): def __init__(self, data, label): '''获取并划分数据''' self.data = data self.label = label self.num = self.data.shape[0] def __getitem__(self, index): data = torch.Tensor(self.data[index]) label = torch.Tensor(self.label[index]) return data, label def __len__(self): return self.num def nx2mol(G): mol = Chem.RWMol() atomic_nums = nx.get_node_attributes(G, 'atomic_num') chiral_tags = nx.get_node_attributes(G, 'chiral_tag') formal_charges = nx.get_node_attributes(G, 'formal_charge') node_is_aromatics = nx.get_node_attributes(G, 'is_aromatic') node_hybridizations = nx.get_node_attributes(G, 'hybridization') num_explicit_hss = nx.get_node_attributes(G, 'num_explicit_hs') node_to_idx = {} for node in G.nodes(): a = Chem.Atom(atomic_nums[node]) a.SetChiralTag(chiral_tags[node]) a.SetFormalCharge(formal_charges[node]) a.SetIsAromatic(node_is_aromatics[node]) a.SetHybridization(node_hybridizations[node]) a.SetNumExplicitHs(num_explicit_hss[node]) idx = mol.AddAtom(a) node_to_idx[node] = idx bond_types = nx.get_edge_attributes(G, 'bond_type') for edge in G.edges(): first, second = edge ifirst = node_to_idx[first] isecond = node_to_idx[second] bond_type = bond_types[first, second] mol.AddBond(ifirst, isecond, bond_type) # Chem.SanitizeMol(mol) return mol class AccMeter(): def __init__(self, n_classes): self.n_classes = n_classes self.correct_num = 0.0 self.total_num = 0 self.iters = 0 def add(self, preds, targets): self.correct_num += torch.sum(preds.eq(targets)) self.total_num += preds.shape[0] self.iters += 1 def reset(self): self.correct_num = 0.0 self.total_num = 0.0 self.iters = 0 def value(self): return float(self.correct_num) / (self.total_num + 1e-10) # avg_centers = get_avg_centers(data_tags, embeddings) # val_cls_num = data_tags.max() + 1 # cls_ids = [[] for _ in range(cluster_num)] # record the data ids of each cluster # [cls_ids[int(data_tags[i])].append(i) for i in range(embeddings.shape[0])] # cluster_centers = avg_centers # # # avoid empty clusters # ept_cls_num = 0 # for i in range(cluster_num): # if len(cls_ids[i]) == 0: # cls_ids[i] = random.choice(range(embeddings.shape[0])) # try: # cluster_centers[i] = embeddings[cls_ids[i]] # except Exception: # print("errrrrrrrrror") # ept_cls_num += 1 # # if ept_cls_num > 0: # print('{} empty cluster detected'.format(ept_cls_num)) # class MoleDataset(Dataset): # def __init__(self, mols, props,prop_name): # self.mols = mols # self.prop = props[:,Molecule.PROPID[prop_name]] # self.mean = torch.mean(self.prop) # self.std = torch.std(self.prop) # # # def __len__(self): # return len(self.mols) # # # def __getitem__(self, item): # return self.mols[item], self.prop[item]
25,279
32.932886
241
py
AS_Molecule
AS_Molecule-master/utils/prepare_data.py
import pickle import torch ''' Please download and prepare dataset files under the following instructions 1.download '''
130
20.833333
82
py
AS_Molecule
AS_Molecule-master/utils/data_utils.py
# -*- coding:utf-8 -*- """Example dataloader of Tencent Alchemy Dataset https://alchemy.tencent.com/ """ import os import zipfile import os.path as osp from rdkit import Chem from rdkit.Chem import ChemicalFeatures from rdkit import RDConfig import dgl from dgl.data.utils import download import torch from collections import defaultdict from torch.utils.data import Dataset from torch.utils.data import DataLoader import pathlib import pandas as pd import numpy as np _urls = {'Alchemy': 'https://alchemy.tencent.com/data/'} class AlchemyBatcher: def __init__(self, graph=None, label=None): self.graph = graph self.label = label def batcher(): def batcher_dev(batch): graphs, labels = zip(*batch) batch_graphs = dgl.batch(graphs) labels = torch.stack(labels, 0) return AlchemyBatcher(graph=batch_graphs, label=labels) return batcher_dev class TencentAlchemyDataset(Dataset): fdef_name = osp.join(RDConfig.RDDataDir, 'BaseFeatures.fdef') chem_feature_factory = ChemicalFeatures.BuildFeatureFactory(fdef_name) def alchemy_nodes(self, mol): """Featurization for all atoms in a molecule. The atom indices will be preserved. Args: mol : rdkit.Chem.rdchem.Mol RDKit molecule object Returns atom_feats_dict : dict Dictionary for atom features """ atom_feats_dict = defaultdict(list) is_donor = defaultdict(int) is_acceptor = defaultdict(int) fdef_name = osp.join(RDConfig.RDDataDir, 'BaseFeatures.fdef') mol_featurizer = ChemicalFeatures.BuildFeatureFactory(fdef_name) mol_feats = mol_featurizer.GetFeaturesForMol(mol) mol_conformers = mol.GetConformers() assert len(mol_conformers) == 1 geom = mol_conformers[0].GetPositions() for i in range(len(mol_feats)): if mol_feats[i].GetFamily() == 'Donor': node_list = mol_feats[i].GetAtomIds() for u in node_list: is_donor[u] = 1 elif mol_feats[i].GetFamily() == 'Acceptor': node_list = mol_feats[i].GetAtomIds() for u in node_list: is_acceptor[u] = 1 num_atoms = mol.GetNumAtoms() for u in range(num_atoms): atom = mol.GetAtomWithIdx(u) symbol = atom.GetSymbol() atom_type = atom.GetAtomicNum() aromatic = atom.GetIsAromatic() hybridization = atom.GetHybridization() num_h = atom.GetTotalNumHs() atom_feats_dict['pos'].append(torch.FloatTensor(geom[u])) atom_feats_dict['node_type'].append(atom_type) h_u = [] h_u += [ int(symbol == x) for x in ['H', 'C', 'N', 'O', 'F', 'S', 'Cl'] ] h_u.append(atom_type) h_u.append(is_acceptor[u]) h_u.append(is_donor[u]) h_u.append(int(aromatic)) h_u += [ int(hybridization == x) for x in (Chem.rdchem.HybridizationType.SP, Chem.rdchem.HybridizationType.SP2, Chem.rdchem.HybridizationType.SP3) ] h_u.append(num_h) atom_feats_dict['n_feat'].append(torch.FloatTensor(h_u)) atom_feats_dict['n_feat'] = torch.stack(atom_feats_dict['n_feat'], dim=0) atom_feats_dict['pos'] = torch.stack(atom_feats_dict['pos'], dim=0) atom_feats_dict['node_type'] = torch.LongTensor( atom_feats_dict['node_type']) return atom_feats_dict def alchemy_edges(self, mol, self_loop=True): """Featurization for all bonds in a molecule. The bond indices will be preserved. Args: mol : rdkit.Chem.rdchem.Mol RDKit molecule object Returns bond_feats_dict : dict Dictionary for bond features """ bond_feats_dict = defaultdict(list) mol_conformers = mol.GetConformers() assert len(mol_conformers) == 1 geom = mol_conformers[0].GetPositions() num_atoms = mol.GetNumAtoms() for u in range(num_atoms): for v in range(num_atoms): if u == v and not self_loop: continue e_uv = mol.GetBondBetweenAtoms(u, v) if e_uv is None: bond_type = None else: bond_type = e_uv.GetBondType() bond_feats_dict['e_feat'].append([ float(bond_type == x) for x in (Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, Chem.rdchem.BondType.TRIPLE, Chem.rdchem.BondType.AROMATIC, None) ]) bond_feats_dict['distance'].append( np.linalg.norm(geom[u] - geom[v])) bond_feats_dict['e_feat'] = torch.FloatTensor( bond_feats_dict['e_feat']) bond_feats_dict['distance'] = torch.FloatTensor( bond_feats_dict['distance']).reshape(-1, 1) return bond_feats_dict def sdf_to_dgl(self, sdf_file, self_loop=False): """ Read sdf file and convert to dgl_graph Args: sdf_file: path of sdf file self_loop: Whetaher to add self loop Returns: g: DGLGraph l: related labels """ sdf = open(str(sdf_file)).read() mol = Chem.MolFromMolBlock(sdf, removeHs=False) g = dgl.DGLGraph() # add nodes num_atoms = mol.GetNumAtoms() atom_feats = self.alchemy_nodes(mol) g.add_nodes(num=num_atoms, data=atom_feats) # add edges # The model we were interested assumes a complete graph. # If this is not the case, do the code below instead # # for bond in mol.GetBonds(): # u = bond.GetBeginAtomIdx() # v = bond.GetEndAtomIdx() if self_loop: g.add_edges( [i for i in range(num_atoms) for j in range(num_atoms)], [j for i in range(num_atoms) for j in range(num_atoms)]) else: g.add_edges( [i for i in range(num_atoms) for j in range(num_atoms - 1)], [ j for i in range(num_atoms) for j in range(num_atoms) if i != j ]) bond_feats = self.alchemy_edges(mol, self_loop) g.edata.update(bond_feats) # for val/test set, labels are molecule ID l = torch.FloatTensor(self.target.loc[int(sdf_file.stem)].tolist()) \ if self.mode == 'dev' else torch.LongTensor([int(sdf_file.stem)]) return (g, l) def __init__(self, mode='dev', transform=None): assert mode in ['dev', 'valid', 'test'], "mode should be dev/valid/test" self.mode = mode self.transform = transform self.file_dir = pathlib.Path('./Alchemy_data', mode) self.zip_file_path = pathlib.Path('./Alchemy_data', '%s.zip' % mode) download(_urls['Alchemy'] + "%s.zip" % mode, path=str(self.zip_file_path)) if not os.path.exists(str(self.file_dir)): archive = zipfile.ZipFile(self.zip_file_path) archive.extractall('./Alchemy_data') archive.close() self._load() def _load(self): if self.mode == 'dev': target_file = pathlib.Path(self.file_dir, "dev_target.csv") self.target = pd.read_csv(target_file, index_col=0, usecols=[ 'gdb_idx', ] + ['property_%d' % x for x in range(12)]) self.target = self.target[['property_%d' % x for x in range(12)]] sdf_dir = pathlib.Path(self.file_dir, "sdf") self.graphs, self.labels = [], [] for sdf_file in sdf_dir.glob("**/*.sdf"): result = self.sdf_to_dgl(sdf_file) if result is None: continue self.graphs.append(result[0]) self.labels.append(result[1]) self.normalize() print(len(self.graphs), "loaded!") def normalize(self, mean=None, std=None): labels = np.array([i.numpy() for i in self.labels]) if mean is None: mean = np.mean(labels, axis=0) if std is None: std = np.std(labels, axis=0) self.mean = mean self.std = std def __len__(self): return len(self.graphs) def __getitem__(self, idx): g, l = self.graphs[idx], self.labels[idx] if self.transform: g = self.transform(g) return g, l if __name__ == '__main__': alchemy_dataset = TencentAlchemyDataset() device = torch.device('cpu') # To speed up the training with multi-process data loader, # the num_workers could be set to > 1 to alchemy_loader = DataLoader(dataset=alchemy_dataset, batch_size=20, collate_fn=batcher(), shuffle=False, num_workers=0) for step, batch in enumerate(alchemy_loader): print("bs =", batch.graph.batch_size) print('feature size =', batch.graph.ndata['n_feat'].size()) print('pos size =', batch.graph.ndata['pos'].size()) print('edge feature size =', batch.graph.edata['e_feat'].size()) print('edge distance size =', batch.graph.edata['distance'].size()) print('label size=', batch.label.size()) print(dgl.sum_nodes(batch.graph, 'n_feat').size()) break
9,990
35.068592
78
py
AS_Molecule
AS_Molecule-master/utils/pre/time_pre.py
import dgl import networkx as nx import numpy as np import time import pickle # import torch.multiprocessing as _mp from torch.multiprocessing import Pool, Manager, Process, Queue import sys import rdkit.Chem as Chem import torch from copy import deepcopy # from utils.funcs import Molecule torch.multiprocessing.set_sharing_strategy('file_system') class Molecule(): EDGE_TYPE = [ Chem.BondType.SINGLE, Chem.BondType.DOUBLE, Chem.BondType.TRIPLE, Chem.BondType.AROMATIC ] NODE_TYPE = { 'H': 1, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'Si': 14, 'P': 15, 'S': 16, 'Cl': 17 } PROPID = { 'optical_lumo': 0, 'gap': 1, 'homo': 2, 'lumo': 3, 'spectral_overlap': 4 } def __init__(self, coords, atoms, edges, smi, props, distance=None, loc=False, glob=True): self.coordinates = torch.Tensor(coords) self.atoms = atoms # types corresponds to coordiantes self.node_num = len(atoms) self.edges = edges self.smi = smi # self.optical_lumo,self.gap,self.homo,self.lumo,self.spectral_overlap,self.delta_homo,self.delta_lumo,self.delta_optical_lumo,self.homo_extrapolated,self.lumo_extrapolated,self.gap_extrapolated,self.optical_lumo_extrapolated = props self.optical_lumo, self.gap, self.homo, self.lumo, self.spectral_overlap = props self.nx_g, self.nidx, self.loc_g, self.ful_g = nx.Graph( ), 0, dgl.DGLGraph(), dgl.DGLGraph() #init self._build_nidx() if loc: self._build_loc() if glob: self._build_ful(distance) def _build_nx_g(self): # first build mol self.mol = Chem.RWMol() for i in range(len(self.atoms)): self.mol.AddAtom(Chem.rdchem.Atom(self.atoms[i])) for i in range(len(self.edges)): self.mol.AddBond(int(self.edges[i][0]), int(self.edges[i][1]), Molecule.EDGE_TYPE[self.edges[i][2]]) # self.nx_g = mol2nx(self.mol) return self # build a dgl graph only contains edges existing considering edge relation,now no self edge def _build_loc(self): self.loc_g = dgl.DGLGraph() self.loc_g.add_nodes(self.node_num) self.loc_g.add_edges( self.edges[:, 0], self.edges[:, 1], data={'edge_type': torch.tensor(self.edges[:, 2]).long()}) self.loc_g = dgl.to_bidirected(self.loc_g) self.loc_g.ndata['pos'] = self.coordinates self.loc_g.ndata['nodes'] = self.nidx # build a dgl graph for long interaction(full graph) def _build_ful(self, distance_matrix=None): self.ful_g = dgl.DGLGraph() self.ful_g.add_nodes(self.node_num) self.ful_g.add_edges( [i for i in range(self.node_num) for j in range(self.node_num)], [j for i in range(self.node_num) for j in range(self.node_num)]) # self.ful_g.add_edges(self.ful_g.nodes(), self.ful_g.nodes()) #add self edge self.ful_g.ndata['pos'] = self.coordinates self.ful_g.ndata['nodes'] = self.nidx if distance_matrix is None: distance_matrix = torch.zeros(self.node_num * self.node_num) for i in range(self.node_num): distance_matrix[i * self.node_num:(i + 1) * self.node_num] = torch.norm( self.coordinates[i] - self.coordinates, p=2, dim=1) else: distance_matrix = torch.Tensor(distance_matrix) self.ful_g.edata['distance'] = distance_matrix return def _build_nidx(self): self.nidx = torch.zeros(self.node_num).long() for i in range(self.node_num): self.nidx[i] = Molecule.NODE_TYPE[self.atoms[i]] return def get_mol(data): pos, atoms, edges, smi, prop, dists = data return Molecule(pos, atoms, edges, smi, prop, distance=dists, loc=False, glob=False) # return pos, atoms, edges, smi, prop, dists def get_mols(l, datas): l.extend(deepcopy([get_mol(data) for data in datas])) # l.put([get_mol(data) for data in datas]) return def bd_mol(mol): mol._build_ful() # if __name__ == '__main__': if __name__ == '__main__': num_atoms = 100 gs = [] t0 = time.time() ''' for i in range(10000): g = dgl.DGLGraph() g.from_networkx(nx.complete_graph(num_atoms)) # g.add_nodes(num_atoms) # g.add_edges( # [i for i in range(num_atoms) for j in range(num_atoms)], # [j for i in range(num_atoms) for j in range(num_atoms)]) print(i) gs.append(g) ''' path = '/media/sdc/seg3d/anaconda3/pkgs/libsnn/datasets/OPV/data_elem_train.pkl' datas = pickle.load(open(path, 'rb'))[1:] print('load success, preprocessing...') # mols = [[] for _ in range(len(datas))] mols = [] props = [] i = 0 for data in datas: pos, atoms, edges, smi, prop, dists = data mols.append( Molecule(pos, atoms, edges, smi, prop, distance=dists, loc=False, glob=False)) props.append(prop) print(i) i += 1 # mp = _mp.get_context('forkserver') # set_start_method('spawn') pool = Pool(processes=4) manager = Manager() # mols = manager.list([[] for _ in range(len(datas))]) # mols = manager.list([]) # pool.map(get_mol,datas,chunksize=100) i = 0 for _ in pool.imap(bd_mol, mols, chunksize=100): print(i) # mols[i] = _ i += 1 # props = np.concatenate(props,axis=0) #process based # processes = [] # # indexes = [range(i*3000,(i+1)*3000) for i in range(4)] # for i in range(4): # p = Process(target=get_mols, args=(mols, [datas[j] for j in indexes[i]])) # p.start() # processes.append(p) # # for i in range(4): # processes[i].join() t1 = time.time() print(t1 - t0) print(0)
6,546
29.03211
241
py
AS_Molecule
AS_Molecule-master/utils/pre/opv_savedata.py
from utils.funcs import Molecule import numpy as np from multiprocessing import Manager, Process import torch import dgl import sys sys.path.append('..') from utils.funcs import MoleDataset2 from config import Global_Config as Config config = Config() def get_mol(data): pos, atoms, edges, smi, prop, dists = data return Molecule(pos, atoms, edges, smi, prop, distance=dists, loc=False, glob=True) class M(): L = 1 def __init__(self, num): self.num = num self.ar = np.array([5]) self.th = torch.Tensor([num, num]) self.g = dgl.DGLGraph() self.build() def build(self): self.g.add_nodes(self.num) def get_M(num): return M(num) if __name__ == '__main__': # num = range(10000) # mp = _mp.get_context('spawn') # cnt = 0 # pool = mp.Pool(10) # for _ in pool.imap(get_M, num): # sys.stdout.write('id{}\n'.format(cnt)) # cnt+=1 # manager = Manager() # path = config.PATH+'/datasets/OPV/data_elem_train.pkl' path = config.PATH + '/datasets/OPV/data_elem_test.pkl' # save_path = [config.PATH+'/datasets/OPV/opv_mol_train1.pkl', # config.PATH+'/datasets/OPV/opv_mol_train2.pkl', # config.PATH+'/datasets/OPV/opv_mol_train3.pkl', # config.PATH+'/datasets/OPV/opv_mol_train4.pkl', # config.PATH+'/datasets/OPV/opv_mol_train5.pkl', # # ] save_path = config.PATH + '/datasets/OPV/opv_mol_test.pkl' dataset = MoleDataset2(path, 'homo', False, True) dataset.build() dataset.save_mol(save_path) print('ok')
1,776
24.385714
66
py
AS_Molecule
AS_Molecule-master/utils/pre/op_savedata.py
import sys import os sys.path.append(os.path.abspath(os.path.join(os.getcwd(), "../.."))) from utils.funcs import Molecule import numpy as np from multiprocessing import Manager, Process import torch import dgl from utils.funcs import MoleDataset from config import Global_Config as Config config = Config() def get_mol(data): pos, atoms, edges, smi, prop, dists = data return Molecule(pos, atoms, edges, smi, prop, distance=dists, loc=False, glob=True) class M(): L = 1 def __init__(self, num): self.num = num self.ar = np.array([5]) self.th = torch.Tensor([num, num]) self.g = dgl.DGLGraph() self.build() def build(self): self.g.add_nodes(self.num) def get_M(num): return M(num) if __name__ == '__main__': # num = range(10000) # mp = _mp.get_context('spawn') # cnt = 0 # pool = mp.Pool(10) # for _ in pool.imap(get_M, num): # sys.stdout.write('id{}\n'.format(cnt)) # cnt+=1 # manager = Manager() # path = config.PATH+'/datasets/OPV/data_elem_train.pkl' path = config.PATH + '/datasets/OPV/data_elem_test.pkl' # save_path = [config.PATH+'/datasets/OPV/opv_mol_train1.pkl', # config.PATH+'/datasets/OPV/opv_mol_train2.pkl', # config.PATH+'/datasets/OPV/opv_mol_train3.pkl', # config.PATH+'/datasets/OPV/opv_mol_train4.pkl', # config.PATH+'/datasets/OPV/opv_mol_train5.pkl', # # ] save_path = config.PATH + '/datasets/OPV/opv_mol_test.pkl' dataset = MoleDataset(path=path, prop_name='homo', loc=False, glob=True) dataset.build() dataset.save_mol(save_path) print('ok')
1,855
25.140845
76
py
AS_Molecule
AS_Molecule-master/utils/pre/parallelload.py
from utils.funcs import Molecule import numpy as np from multiprocessing import Manager, Process import torch import dgl import sys from utils.funcs import MoleDataset2 from config import Global_Config as Config config = Config() def get_mol(data): pos, atoms, edges, smi, prop, dists = data return Molecule(pos, atoms, edges, smi, prop, distance=dists, loc=False, glob=True) class M(): L = 1 def __init__(self, num): self.num = num self.ar = np.array([5]) self.th = torch.Tensor([num, num]) self.g = dgl.DGLGraph() self.build() def build(self): self.g.add_nodes(self.num) def get_M(num): return M(num) if __name__ == '__main__': # num = range(10000) # mp = _mp.get_context('spawn') # cnt = 0 # pool = mp.Pool(10) # for _ in pool.imap(get_M, num): # sys.stdout.write('id{}\n'.format(cnt)) # cnt+=1 # manager = Manager() # path = config.PATH+'/datasets/OPV/data_elem_train.pkl' path = config.PATH + '/datasets/OPV/data_elem_test.pkl' # save_path = [config.PATH+'/datasets/OPV/opv_mol_train1.pkl', # config.PATH+'/datasets/OPV/opv_mol_train2.pkl', # config.PATH+'/datasets/OPV/opv_mol_train3.pkl', # config.PATH+'/datasets/OPV/opv_mol_train4.pkl', # config.PATH+'/datasets/OPV/opv_mol_train5.pkl', # # ] save_path = config.PATH + '/datasets/OPV/opv_mol_test.pkl' dataset = MoleDataset2(path, 'homo', False, True) dataset.build() dataset.save_mol(save_path) print('ok')
1,753
24.794118
66
py
AS_Molecule
AS_Molecule-master/utils/data_clustering/smilarity_sch.py
#!/usr/bin/env python #-*- coding:utf-8 _*- import pickle from utils import * import rdkit from rdkit import Chem from rdkit import DataStructs import numpy as np from rdkit.Chem import rdMolDescriptors import pandas as pd from sklearn.decomposition import PCA from sklearn.preprocessing import MinMaxScaler from torch.utils.data import DataLoader import matplotlib.pyplot as plt import time import dgl import torch from utils.funcs import batcher, MoleDataset, k_medoid, k_medoids_pp from config import Global_Config, make_args import random from pre_training.sch_embeddings import SchEmbedding config = Global_Config() args = make_args() '''观察由随机的(或者预训练的)schnet输出的graph embedding的pca''' n_bit = 512 def smi2vec(smi): mol = Chem.MolFromSmiles(smi) bit_vec = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 4, nBits=n_bit) vec = [bit_vec[i] for i in range(n_bit)] return vec def get_preds(args, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize * 5, collate_fn=batcher, shuffle=False, num_workers=args.workers) model.to(device) model.set_mean_std(dataset.mean, dataset.std) embeddings = [] with torch.no_grad(): for idx, (mols, _) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings, dim=0) print('inference {}'.format(time.time() - time0)) return embeddings qm9_data_path = config.train_pkl['qm9'] mols = pickle.load(open(qm9_data_path, 'rb')) # smis = [mol.smi for mol in mols] model = SchEmbedding(dim=48, n_conv=4, cutoff=5.0, width=0.5, norm=True, output_dim=1) # model = WSchnet_N(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) dataset = MoleDataset(mols=mols, prop_name='homo') embeddings = get_preds(args, model, dataset, torch.device(args.device)) embeddings = embeddings.cpu() center_ids = k_medoids_pp(embeddings, 5000, 15, show_stats=True) # center_ids = random.sample(range(embeddings.shape[0]),5000) embeddings = embeddings.numpy() # fingerprints = [smi2vec(smi) for smi in smis] n_components = 2 time0 = time.time() pca = PCA(n_components=n_components) pca.fit(embeddings) qm9_pca = pca.transform(embeddings) print('time {}'.format(time.time() - time0)) plt.scatter(qm9_pca[:, 0], qm9_pca[:, 1], marker='.', color='b') plt.scatter(qm9_pca[center_ids, 0], qm9_pca[center_ids, 1], marker='.', color='g') plt.savefig('qm9_pca_sch.png') # qm9_pca_t = torch.Tensor(qm9_pca) # save_path = config.DATASET_PATH['qm9']+'/qm9_fingerprint_'+str(n_components)+'.pkl' save_path = config.DATASET_PATH['qm9'] + '/sch_ebd.pkl' pickle.dump(qm9_pca, open(save_path, 'wb'))
3,186
27.972727
86
py
AS_Molecule
AS_Molecule-master/utils/data_clustering/smilarity.py
import pickle from utils import * import rdkit from rdkit import Chem from rdkit import DataStructs import numpy as np from rdkit.Chem import rdMolDescriptors from config import Global_Config import pandas as pd from sklearn.decomposition import PCA from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt import time import torch config = Global_Config() # zinc_data = pickle.load(open('zinc_clean_smi.pkl','rb')) # chemge_data = pickle.load(open('chemge_mol_100000.pkl','rb')) # cgam_data = pickle.load(open('max_logp_total_pool.pkl','rb')) # # def get_top100(dataset, name): # length = len(dataset) # logp_set = [] # # for i in range(length): # logp = calc_score(Chem.MolFromSmiles(dataset[i])) # logp_set.append(logp) # print(i) # # tuple = [(dataset[i],logp_set[i]) for i in range(length)] # sorted_tuple = sorted(tuple, key=lambda x:x[1], reverse=True) # # print(sorted_tuple[:100]) # pickle.dump(sorted_tuple[:100], open(name,'wb')) # # get_top100(cgam_data, 'cgam_top100.pkl') # zinc_top100_name = 'zinc_top100.pkl' # chemge_top100_name = 'chemge_top100.pkl' # cgam_top100_name = 'cgam_top100.pkl' # # data_len = 100 # # zinc_data = pickle.load(open(zinc_top100_name,'rb')) # zinc_smi = [zinc_data[i][0] for i in range(data_len)] # # chemge_data = pickle.load(open(chemge_top100_name,'rb')) # chemge_smi = [chemge_data[i][0] for i in range(data_len)] # # cgam_data = pickle.load(open(cgam_top100_name,'rb')) # cgam_smi = [cgam_data[i][0] for i in range(data_len)] # # print(zinc_smi) # print(chemge_smi) # print(cgam_smi) # # def smilarity_between_two_mols(smi1, smi2): # mol1, mol2 = Chem.MolFromSmiles(smi1), Chem.MolFromSmiles(smi2) # # vec1 = Chem.rdMolDescriptors.GetMorganFingerprintAsBitVect(mol1, 4, nBits=2048) # vec2 = Chem.rdMolDescriptors.GetMorganFingerprintAsBitVect(mol2, 4, nBits=2048) # # tani = DataStructs.TanimotoSimilarity(vec1, vec2) # return tani # res1 = [] # for i in range(100): # g_smi = chemge_smi[i] # pool = [smilarity_between_two_mols(g_smi, zinc_smi[j]) for j in range(100)] # max_smilarity = max(pool) # #print(max_smilarity) # res1.append(max_smilarity) # print(np.mean(res1)) # # res2 = [] # for i in range(100): # g_smi = cgam_smi[i] # pool = [smilarity_between_two_mols(g_smi, zinc_smi[j]) for j in range(100)] # max_smilarity = max(pool) # #print(max_smilarity) # res2.append(max_smilarity) # print(np.mean(res2)) n_bit = 512 def smi2vec(smi): mol = Chem.MolFromSmiles(smi) bit_vec = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 4, nBits=n_bit) vec = [bit_vec[i] for i in range(n_bit)] return vec qm9_data_path_train = config.train_pkl['qm9'] qm9_data_path_test = config.test_pkl['qm9'] mols_train = pickle.load(open(qm9_data_path_train, 'rb')) smis_train = [mol.smi for mol in mols_train] mols_test = pickle.load(open(qm9_data_path_test, 'rb')) smis_test = [mol.smi for mol in mols_test] time0 = time.time() fingerprints_train = [smi2vec(smi) for smi in smis_train] fingerprints_test = [smi2vec(smi) for smi in smis_test] n_components = 20 print('time {}'.format(time.time() - time0)) time0 = time.time() pca = PCA(n_components=n_components) pca.fit(fingerprints_train) qm9_pca = pca.transform(fingerprints_train) qm9_pca_te = pca.transform(fingerprints_test) print('time {}'.format(time.time() - time0)) plt.scatter(qm9_pca[:, 0], qm9_pca[:, 1], marker='.') plt.scatter(qm9_pca_te[:, 0], qm9_pca_te[:, 1], marker='.') plt.savefig('qm9_pca.png') # qm9_pca_t = torch.Tensor(qm9_pca) # save_path = config.DATASET_PATH['qm9']+'/qm9_fingerprint_'+str(n_components)+'.pkl' # pickle.dump(qm9_pca_t,open(save_path,'wb')) # zinc_data = pickle.load(open('zinc_clean_smi.pkl','rb')) # # zinc_top100_name = 'zinc_top100.pkl' # chemge_top100_name = 'chemge_top100.pkl' # cgam_top100_name = 'cgam_top100.pkl' # # zinc_top100_smi = [pickle.load(open(zinc_top100_name,'rb'))[i][0] for i in range(100)] # chemvae_top100_smi = [pickle.load(open(chemge_top100_name,'rb'))[i][0] for i in range(100)] # cgam_top100_smi = [pickle.load(open(cgam_top100_name,'rb'))[i][0] for i in range(100)] # # zinc_data_len = len(zinc_data) # selected_index = np.random.choice(zinc_data_len, 20000, replace=False) # # train_data = [smi2vec(zinc_data[i]) for i in selected_index] # # zinc_top_data = [smi2vec(zinc_top100_smi[i]) for i in range(100)] # chemvae_top_data = [smi2vec(chemvae_top100_smi[i]) for i in range(100)] # cgam_top_data = [smi2vec(cgam_top100_smi[i]) for i in range(100)] # # # pca = PCA(n_components=2) # pca.fit(train_data) # # zinc_pca = pca.transform(zinc_top_data) # chemvae_pca = pca.transform(chemvae_top_data) # cgam_pca = pca.transform(cgam_top_data) # # df_zinc = pd.DataFrame(np.transpose((zinc_pca[:,0],zinc_pca[:,1]))) # df_zinc.columns = ['x','y'] # # plt.scatter(x=df_zinc['x'], y=df_zinc['y'], c = 'y', # cmap= 'viridis', marker='.', # s=100,alpha=0.5, edgecolors='none',label='ZINC') # # df_chemvae = pd.DataFrame(np.transpose((chemvae_pca[:,0],chemvae_pca[:,1]))) # df_chemvae.columns = ['x','y'] # # plt.scatter(x=df_chemvae['x'], y=df_chemvae['y'], c = 'b', # cmap= 'viridis', marker='.', # s=100,alpha=0.5, edgecolors='none',label='ChemVAE') # # df_cgam = pd.DataFrame(np.transpose((cgam_pca[:,0],cgam_pca[:,1]))) # df_cgam.columns = ['x','y'] # # plt.scatter(x=df_cgam['x'], y=df_cgam['y'], c = 'r', # cmap= 'viridis', marker='.', # s=100,alpha=0.5, edgecolors='none',label='CGAM') # # plt.legend(loc='upper right') # plt.savefig('comparison_top100.png')
5,780
30.939227
93
py
AS_Molecule
AS_Molecule-master/pre_training/train_part_msg.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import random import pickle sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from bayes_al.mc_sch import MC_SchNetModel from bayes_al.mm_sch import MM_SchNetModel from pre_training.wsch import WSchnet_R from config import * def train(args,train_dataset,test_dataset, model,optimizer, writer,device): print("start") train_loader = DataLoader(dataset=train_dataset,batch_size=args.batchsize,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) test_loader = DataLoader(dataset=test_dataset,batch_size=args.batchsize*2,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) print(model) print(train_dataset.mean.item(), train_dataset.std.item()) # if model.name in ["MGCN", "SchNet"]: if args.multi_gpu: model.module.set_mean_std(train_dataset.mean, train_dataset.std) else: model.set_mean_std(train_dataset.mean,train_dataset.std) model.to(device) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() init_lr = args.lr info = {'train_loss':[], 'train_mae':[], 'test_loss':[], 'test_mae':[]} for epoch in range(args.epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model.inference(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) if idx%50 == 0 and args.use_tb: writer.add_scalar('training_loss',mse_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) writer.add_scalar('training_mae',mae_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) print('training loss {} mae {}'.format(mse_meter.value()[0], mae_meter.value()[0])) loss_test, mae_test = test(args,test_loader,model,device) print("Epoch {:2d}, training: loss: {:.7f}, mae: {:.7f} test: loss{:.7f}, mae:{:.7f}".format(epoch, mse_meter.value()[0], mae_meter.value()[0],loss_test,mae_test)) if (epoch+1) % 100 == 0: init_lr = init_lr / 1.5 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) info['test_loss'].append(loss_test) info['test_mae'].append(mae_test) if args.use_tb: writer.add_scalar('testing_loss',loss_test,epoch) writer.add_scalar('testing_mae',mae_test,epoch) return info def test(args, test_loader,model,device): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model.inference(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 1200 args.batchsize = 64 args.lr = 1e-3 args.use_tb = True args.dataset = 'qm9' args.device = 0 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' print(args) train_data_num = 110000 logs_path = config.PATH+'/datasets/logs'+ time.strftime('/%m%d_%H_%M') train_set, test_set = MoleDataset(prop_name=args.prop_name), MoleDataset(prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol(config.test_pkl[args.dataset]) # train_part train_set = MoleDataset(mols=random.sample(train_set.mols,train_data_num)) device = torch.device('cuda:'+str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path,comment='baseline_sch') else: writer = None # model = SchNetModel(dim=48,n_conv=4,cutoff=5.0,width=0.5,norm=True, output_dim=1) # model = MC_SchNetModel(dim=32,n_conv=4,cutoff=5.0,width=0.5,norm=True, output_dim=1) # model = SchNetModel(dim=128,n_conv=4,cutoff=30.0,width=0.1,norm=True, output_dim=1) model = MM_SchNetModel(dim=128,n_conv=4,cutoff=30.0,width=0.1,norm=True, output_dim=1,mask_rate=0.2) # model = WSchnet_R(dim=128,n_conv=4,cutoff=30.0,cls_dim=1000,width=0.1,norm=True, output_dim=1) # run a mini SchNet model # optimizer = torch.optim.SGD(model.parameters(), lr=args.lr,momentum=0.5,nesterov=0.6) optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) print(time.strftime('%m%d_%H_%M model {} optimizer {}'.format(str(model),str(optimizer)))) if args.multi_gpu: model = DataParallel(model,device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args,train_set,test_set,model,optimizer, writer, device) if args.save_model: torch.save({'model_state_dict':model.state_dict(), 'optimizier_state_dict':optimizer.state_dict(), 'info':info, },config.save_model_path(args.dataset))
6,253
34.737143
171
py
AS_Molecule
AS_Molecule-master/pre_training/graph_ae.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle import torch.nn.functional as F import ot sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * import numpy as np from pre_training.wsch import WSchnet_N, WSchnet_G, WSchnet, WSchnet_R '''provide pre-trained model for transfer A AE like model first mask some nodes to reconstruct the features of the atoms then sample some edges to reconstruct the distance (divide to bins) to simulate a AE the edges number are n^2, however the degree of freedom is 3*n, we sample alpha* sqrt(n) ''' def train(args, settings, train_datset, test_dataset, model, optimizer, writer, device): print("start") train_loader = DataLoader(dataset=train_datset, batch_size=args.batchsize, collate_fn=batcher_g, shuffle=args.shuffle, num_workers=args.workers) # test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) # prepare labels p_labels = train_datset.prop # p_labels = (train_datset.prop - train_datset.mean) / train_datset.std # p_labels = (1 + torch.erf(p_labels / 2 ** 0.5)) / 2 # transform it to (0,1), constant must be bigger than 1e-7 # bin_gap = 1 / settings['prop_bins'] # p_labels = (p_labels / (bin_gap+1e-7)).long() p_labels = p_labels.to(device) print(model) model.set_mean_std(train_datset.mean, train_datset.std) model.to(device) loss_fn = nn.CrossEntropyLoss() loss_r = nn.MSELoss() loss_mae = nn.L1Loss() # MAE_fn = nn.L1Loss() loss_meter = meter.AverageValueMeter() n_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() p_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter( 100) # clustering num might be too big, do not use confusion matrix c_acc_meter = AccMeter(settings['cls_num']) p_mae_meter = meter.AverageValueMeter() e_acc_meter = meter.ConfusionMeter(150) e_loss_meter = meter.AverageValueMeter() init_lr = args.lr info = { 'n_loss': [], 'n_acc': [], 'c_loss': [], 'c_acc': [], 'p_loss': [], 'p_mae': [] } # TODO: For edge labeling (transform a edge to discrete label, use W|h1 - h2|) edge_bins = torch.linspace(0, 30, 150).to(device) # 0.2 per bin node_classifier, edge_classifier = nn.Linear(64, 100), nn.Linear(64, 150) node_classifier.to(device), edge_classifier.to(device) Q = 0 K = settings['cls_num'] N = len(train_datset) # uniform distribution # cls_distr = torch.ones(K) / K # inst_distr = torch.ones(N) / N # C = np.ones([N, K]) * np.log(K) / N # prob_tensor (cost function) # Q = np.ones([N, K]) / (K * N) # the tag is a prob distribution # cls_tags = torch.Tensor(np.argmax(Q,axis=1)).to(device) # # TODO: For Test # Now I replace it by a normal distribution 4 is decided by 100000*Gauss(4)~10 cls_distr = np.exp(-(np.linspace(-4, 4, K)**2) / 2) / (np.sqrt(2 * np.pi)) cls_distr = cls_distr / cls_distr.sum() inst_distr = torch.ones(N) / N C = np.ones([N, K]) * np.log(K) / N # cost matrix Q = np.copy(np.tile(cls_distr, (N, 1))) / N # joint distribution for epoch in range(args.epochs): loss_meter.reset() n_loss_meter.reset() c_loss_meter.reset() p_loss_meter.reset() n_acc_meter.reset() c_acc_meter.reset() p_mae_meter.reset() e_acc_meter.reset() e_loss_meter.reset() model.train() # prepare pesudo labels via k means if epoch % settings['cls_epochs'] == 1: # feats_all = get_preds(args,model,train_datset,device) # if epoch == 0: # Q = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=settings['init_method'],show_stats=True) # else: # Q = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=Q,show_stats=True) # perform optimal transport time0 = time.time() Q = ot.sinkhorn( inst_distr, cls_distr, C, 0.04) # shape dataset_num*cls_num ...takes 40s~250s on cpu print('optimal transport solved: {}'.format(time.time() - time0)) for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) # Mask node features mask = torch.randint( 0, g.number_of_nodes(), [int(args.mask_n_ratio * g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 # sampling edges Now it is confused whether to mask these edges or simply reconstruct them edges_ids = torch.randint(0, g.number_of_edges(), [ int(settings['edge_sampling_rate'] * np.sqrt(g.number_of_edges())) ]) edge_dist = torch.clone( g.edata['distance'][edges_ids]).requires_grad_(False) edge_labels = torch.argmin( torch.abs(edge_dist.unsqueeze(1) - edge_bins), dim=1).long() # make pesudo labels vis k means # cls_labels = Q[list(ids)].to(device) # make pesudo labels vis optimal transport cls_labels = torch.tensor(np.argmax(Q[list(ids)], axis=1), requires_grad=False).to(device).long() atom_preds, cls_preds, prop_preds = model(g) # get edge logits src_ids, dst_ids, _ = g._graph.edges('eid') src_ids, dst_ids = [src_ids[i] for i in edges_ids ], [dst_ids[i] for i in edges_ids] node_logits = node_classifier(atom_preds[mask]) edge_logits = edge_classifier( torch.abs(atom_preds[src_ids] - atom_preds[dst_ids])) n_pred_cls = torch.argmax(node_logits, dim=1) e_pred_cls = torch.argmax(edge_logits, dim=1) # c_pred_cls = torch.argmax(cls_preds, dim=1) cls_logits = torch.log(F.softmax(cls_preds, dim=1)) n_loss = loss_fn(node_logits, n_label[mask]) e_loss = loss_fn(edge_logits, edge_labels) # compute c loss Now it is CrossEntropyLoss by hard pesudo labeling # c_loss = torch.sum( - cls_labels*cls_logits,dim=1).mean() c_loss = loss_fn(cls_preds, cls_labels) p_loss = loss_r(prop_preds.squeeze(), p_labels[list(ids)]) # squeeze is really important p_mae = loss_mae(prop_preds.squeeze(), p_labels[list(ids)]) loss = 0.3 * n_loss + e_loss + c_loss optimizer.zero_grad() loss.backward() optimizer.step() C[idx * args.batchsize:idx * args.batchsize + len(mols)] = -cls_logits.detach().cpu().numpy() loss_meter.add(loss.detach().item()) n_loss_meter.add(n_loss.detach().item()) # total loss c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, n_label[mask]) # c_acc_meter.add(c_pred_cls, cls_labels) p_loss_meter.add(p_loss.detach().item()) p_mae_meter.add(p_mae.detach().item()) e_acc_meter.add(e_pred_cls, edge_labels) e_loss_meter.add(e_loss.detach().item()) if idx % 50 == 0 and args.use_tb: acc = 100 * sum( n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() writer.add_scalar( 'n_train_loss', n_loss_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) writer.add_scalar( 'n_train_acc', acc, int((idx + 1 + epoch * len(train_loader)) / 50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() e_acc = 100 * sum(e_acc_meter.value()[i, i] for i in range(150)) / e_acc_meter.value().sum() test_loss, test_mae = test(args, test_dataset, model, device) # p_acc = 100 * sum(p_acc_meter.value()[i, i] for i in range(settings['prop_bins'])) / p_acc_meter.value().sum() # print("Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} acc: {:.7f} props: loss {} mae {}".format(epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0], 100 * c_acc_meter.value(), p_loss_meter.value()[0],p_mae_meter.value()[0])) print( "Epoch {:2d}, training: loss: {:.7f}, node loss {} acc: {:.7f} edge loss {} acc {} self-clustering: loss: {:.7f} props loss {} mae {}" .format(epoch, loss_meter.value()[0], n_loss_meter.value()[0], n_acc, e_loss_meter.value()[0], e_acc, c_loss_meter.value()[0], p_loss_meter.value()[0], p_mae_meter.value()[0])) print("Test loss {} mae {}".format(test_loss, test_mae)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(n_acc) info['c_loss'].append(c_loss_meter.value()[0]) info['c_acc'].append(100 * c_acc_meter.value()) info['p_loss'].append(p_loss_meter.value()[0]) info['p_mae'].append(p_mae_meter.value()[0]) return info def test(args, test_dataset, model, device): test_loader = DataLoader(dataset=test_dataset, batch_size=args.batchsize, collate_fn=batcher_g, shuffle=args.shuffle, num_workers=args.workers) labels = test_dataset.prop loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, n_label, ids) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = labels[list(ids)].to(device) _, _, res = model(g) res = res.squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def get_preds(args, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize * 5, collate_fn=batcher_g, shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx, (mols, _, _) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings, dim=0) print('inference {}'.format(time.time() - time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 30 args.batchsize = 64 args.use_tb = False args.dataset = 'qm9' args.device = 0 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.5 print(args) settings = { 'cls_num': 2000, 'cls_epochs': 5, # clustering every 5epochs 'iters': 10, 'init_method': 'random', 'prop_bins': 25, 'edge_sampling_rate': 0.2, } train_data_num = 110000 logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') model_save_path = config.PATH + '/datasets/models' + time.strftime( '/wsch_g_ae_ot_%m%d_%H_%M.pkl') print('model save path {}'.format(model_save_path)) train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'], 'rb')), pickle.load( open(config.test_pkl['qm9'], 'rb')) train_dataset, test_dataset = SelfMolDataSet( mols=train_mols, level='g'), SelfMolDataSet(mols=test_mols, level='g') # train_part train_dataset = SelfMolDataSet(mols=random.sample(train_dataset.mols, train_data_num), level='g') device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None model = WSchnet_R(dim=128, n_conv=4, cutoff=30.0, cls_dim=settings['cls_num'], width=0.1, norm=True, output_dim=1, props_bins=settings['prop_bins']) optimizer = torch.optim.Adam(model.parameters(), lr=2e-4) if args.multi_gpu: model = DataParallel( model, device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args, settings, train_dataset, test_dataset, model, optimizer, writer, device) pickle.dump(model, open(model_save_path, 'wb')) if args.save_model: torch.save( { 'model_state_dict': model.state_dict(), 'optimizier_state_dict': optimizer.state_dict(), 'info': info, }, config.save_model_path(args.dataset))
14,972
37.992188
279
py
AS_Molecule
AS_Molecule-master/pre_training/ot_pretrain.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle import ot import torch.nn.functional as F sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * import numpy as np from pre_training.wsch import WSchnet_N, WSchnet_G '''Jointly self-training with node level masking and clustering center labeling''' def train(args, settings, train_datset, model, optimizer, writer, device): print("start") train_loader = DataLoader(dataset=train_datset, batch_size=args.batchsize, collate_fn=batcher_g, shuffle=args.shuffle, num_workers=args.workers) # test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) print(model) model.to(device) loss_fn = nn.CrossEntropyLoss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter( 100) # clustering num might be too big, do not use confusion matrix c_acc_meter = AccMeter(settings['cls_num']) init_lr = args.lr info = {'n_loss': [], 'n_acc': [], 'c_loss': [], 'c_acc': []} cls_tags = 0 K = settings['cls_num'] N = len(train_datset) cls_distr = torch.ones(K) / K inst_distr = torch.ones(N) / N cls_log_prob = np.ones([N, K ]) * np.log(K) / N # prob_tensor (cost function) cls_tags = np.ones([N, K]) / (K * N) # the tag is a prob distribution for epoch in range(args.epochs): n_loss_meter.reset() c_loss_meter.reset() n_acc_meter.reset() c_acc_meter.reset() model.train() # prepare pesudo labels via k means if epoch % settings['cls_epochs'] == 1: # feats_all = get_preds(args, model, train_datset, device) # if epoch == 0: # cls_tags = k_means(feats_all.cpu(), settings['cls_num'], settings['iters'], # inits=settings['init_method'], show_stats=True) # else: # cls_tags = k_means(feats_all.cpu(), settings['cls_num'], settings['iters'], inits='random', #use random tags # show_stats=True) # perform optimal transport time0 = time.time() cls_tags = ot.sinkhorn( inst_distr, cls_distr, cls_log_prob, 0.04) # shape dataset_num*cls_num ...takes 40s~250s on cpu print('optimal transport solved: {}'.format(time.time() - time0)) # model.re_init_head() for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) # Mask node features mask = torch.randint( 0, g.number_of_nodes(), [int(args.mask_n_ratio * g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 # make pesudo labels vis optimal transport cls_labels = N * torch.tensor( cls_tags[list(ids)], requires_grad=False).to(device).float() atom_preds, cls_preds = model(g) cls_logits = torch.log(F.softmax(cls_preds, dim=1)) n_pred_cls = torch.argmax(atom_preds, dim=1) n_loss = loss_fn(atom_preds[mask], n_label[mask]) # compute c loss c_loss = torch.sum(-cls_labels * cls_logits, dim=1).mean() loss = c_loss + n_loss optimizer.zero_grad() loss.backward() optimizer.step() cls_log_prob[idx * args.batchsize:idx * args.batchsize + len(mols)] = -cls_logits.detach().cpu().numpy() # n_loss_meter.add(n_loss.detach().item()) c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, n_label) # c_acc_meter.add(c_pred_cls, cls_labels) if idx % 50 == 0 and args.use_tb: acc = 100 * sum( n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() writer.add_scalar( 'n_train_loss', n_loss_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) writer.add_scalar( 'n_train_acc', acc, int((idx + 1 + epoch * len(train_loader)) / 50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() print( "Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f}" .format(epoch, n_loss_meter.value()[0], acc, c_loss_meter.value()[0])) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(acc) info['c_loss'].append(c_loss_meter.value()[0]) info['c_acc'].append(100 * c_acc_meter.value()) return info def get_preds(args, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize * 5, collate_fn=batcher_g, shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx, (mols, _, _) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings, dim=0) print('inference {}'.format(time.time() - time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 21 args.batchsize = 64 args.use_tb = False args.dataset = 'qm9' args.device = 1 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.2 print(args) settings = { 'cls_num': 5000, 'cls_epochs': 5, # clustering every 5epochs 'iters': 10, 'init_method': 'random' } logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') model_save_path = config.PATH + '/datasets/models' + time.strftime( '/wsch_g_%m%d_%H_%M.pkl') train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'], 'rb')), pickle.load( open(config.test_pkl['qm9'], 'rb')) train_dataset, test_dataset = SelfMolDataSet( mols=train_mols, level='g'), SelfMolDataSet(mols=test_mols, level='g') device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None model = WSchnet_G(dim=96, n_conv=4, cutoff=30.0, cls_dim=settings['cls_num'], width=0.1, norm=True, output_dim=1) optimizer = torch.optim.Adam(model.parameters(), lr=3e-4) if args.multi_gpu: model = DataParallel( model, device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args, settings, train_dataset, model, optimizer, writer, device) pickle.dump(model, open(model_save_path, 'wb')) if args.save_model: torch.save( { 'model_state_dict': model.state_dict(), 'optimizier_state_dict': optimizer.state_dict(), 'info': info, }, config.save_model_path(args.dataset))
8,961
35.430894
144
py
AS_Molecule
AS_Molecule-master/pre_training/train_part.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import random import pickle sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel,SchNet from bayes_al.mc_sch import MC_SchNetModel from bayes_al.mm_sch import MM_SchNetModel from config import * def train(args,train_dataset,test_dataset, model,optimizer, writer,device): print("start") train_loader = DataLoader(dataset=train_dataset,batch_size=args.batchsize,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) test_loader = DataLoader(dataset=test_dataset,batch_size=args.batchsize*2,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) print(model) print(train_dataset.mean.item(), train_dataset.std.item()) # if model.name in ["MGCN", "SchNet"]: if args.multi_gpu: model.module.set_mean_std(train_dataset.mean, train_dataset.std) else: model.set_mean_std(train_dataset.mean,train_dataset.std) model.to(device) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() init_lr = args.lr info = {'train_loss':[], 'train_mae':[], 'test_loss':[], 'test_mae':[]} for epoch in range(args.epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) if idx%50 == 0 and args.use_tb: writer.add_scalar('training_loss',mse_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) writer.add_scalar('training_mae',mae_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) print('training loss {} mae {}'.format(mse_meter.value()[0], mae_meter.value()[0])) loss_test, mae_test = test(args,test_loader,model,device) print("Epoch {:2d}, training: loss: {:.7f}, mae: {:.7f} test: loss{:.7f}, mae:{:.7f}".format(epoch, mse_meter.value()[0], mae_meter.value()[0],loss_test,mae_test)) if (epoch+1) % 100 == 0: init_lr = init_lr *1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) info['test_loss'].append(loss_test) info['test_mae'].append(mae_test) if args.use_tb: writer.add_scalar('testing_loss',loss_test,epoch) writer.add_scalar('testing_mae',mae_test,epoch) return info def test(args, test_loader,model,device): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 2 args.batchsize = 32 args.lr = 1e-3 args.use_tb = False args.dataset = 'qm9' args.device = 0 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.train_data_num = 5000 print(args) result_path = config.PATH + '/datasets/rd/' + args.dataset +str(args.train_data_num) + time.strftime('_%m%d_%H_%M.txt') logs_path = config.PATH+'/datasets/logs'+ time.strftime('/%m%d_%H_%M') train_set, test_set = MoleDataset(prop_name=args.prop_name), MoleDataset(prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol(config.test_pkl[args.dataset]) # train_part train_set = MoleDataset(mols=random.sample(train_set.mols,args.train_data_num),prop_name=args.prop_name) device = torch.device('cuda:'+str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path,comment='baseline_sch') else: writer = None atom_ref = get_atom_ref(args.prop_name) model = SchNetModel(dim=128,n_conv=4,cutoff=30.0,width=0.1,norm=False, output_dim=1,atom_ref=atom_ref) # model = SchNet(dim=128,n_conv=3,cutoff=30,width=0.1,norm=True, output_dim=1) # model = MC_SchNetModel(dim=96,n_conv=4,cutoff=30.0,width=0.1,norm=True, output_dim=1) # model = SchNetModel(dim=96,n_conv=4,cutoff=30.0,width=0.1,norm=True, output_dim=1) # model = MM_SchNetModel(dim=128,n_conv=4,cutoff=30.0,width=0.1,norm=True, output_dim=1,mask_rate=0.3) # run a mini SchNet model # optimizer = torch.optim.SGD(model.parameters(), lr=args.lr,momentum=0.5,nesterov=0.6) optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) print(time.strftime('%m%d_%H_%M model {} optimizer {}'.format(str(model),str(optimizer)))) if args.multi_gpu: model = DataParallel(model,device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args,train_set,test_set,model,optimizer, writer, device) with open(result_path, 'w') as fp: for key in info.keys(): fp.write(str(key) + '\t') fp.write('\n') for i in range(len(info['test_mae'])): for key in info.keys(): fp.write(str(info[key][i])+'\t') fp.write('\n') if args.save_model: torch.save({'model_state_dict':model.state_dict(), 'optimizier_state_dict':optimizer.state_dict(), 'info':info },config.save_model_path(args.dataset))
6,692
35.57377
171
py
AS_Molecule
AS_Molecule-master/pre_training/w_ptr.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * import numpy as np from pre_training.wsch import WSchnet_N, WSchnet_G, WSchnet '''Jointly self-training with node level masking and clustering center labeling''' def train(args,settings,train_datset, model,optimizer, writer,device): print("start") train_loader = DataLoader(dataset=train_datset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) # test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) # prepare labels p_labels = (train_datset.prop - train_datset.mean) / train_datset.std p_labels = (1 + torch.erf(p_labels / 2 ** 0.5)) / 2 # transform it to (0,1), constant must be bigger than 1e-7 bin_gap = 1 / settings['prop_bins'] p_labels = (p_labels / (bin_gap+1e-7)).long() p_labels = p_labels.to(device) print(model) model.to(device) loss_fn = nn.CrossEntropyLoss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() p_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter(100) # clustering num might be too big, do not use confusion matrix c_acc_meter = AccMeter(settings['cls_num']) p_acc_meter = meter.ConfusionMeter(settings['prop_bins']) init_lr = args.lr info = {'n_loss':[], 'n_acc':[], 'c_loss':[], 'c_acc':[], 'p_loss': [], 'p_acc': [] } cls_tags = 0 for epoch in range(args.epochs): n_loss_meter.reset() c_loss_meter.reset() p_loss_meter.reset() n_acc_meter.reset() c_acc_meter.reset() p_acc_meter.reset() model.train() # prepare pesudo labels via k means if epoch % settings['cls_epochs'] == 0: feats_all = get_preds(args,model,train_datset,device) if epoch == 0: cls_tags = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=settings['init_method'],show_stats=True) else: cls_tags = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=cls_tags,show_stats=True) for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) # Mask node features mask = torch.randint(0,g.number_of_nodes(),[int(args.mask_n_ratio*g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 # make pesudo labels vis k means cls_labels = cls_tags[list(ids)].to(device) atom_preds, cls_preds, prop_preds = model(g) n_pred_cls = torch.argmax(atom_preds, dim=1) c_pred_cls = torch.argmax(cls_preds, dim=1) p_pred_cls = torch.argmax(prop_preds, dim=1) n_loss = loss_fn(atom_preds[mask], n_label[mask]) c_loss = loss_fn(cls_preds,cls_labels) p_loss = loss_fn(prop_preds, p_labels[list(ids)]) loss = c_loss + n_loss + p_loss optimizer.zero_grad() loss.backward() optimizer.step() n_loss_meter.add(n_loss.detach().item()) c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, n_label) c_acc_meter.add(c_pred_cls, cls_labels) p_loss_meter.add(p_loss.detach().item()) p_acc_meter.add(p_pred_cls, p_labels[list(ids)]) if idx%50 == 0 and args.use_tb: acc = 100*sum(n_acc_meter.value()[i,i] for i in range(10))/n_acc_meter.value().sum() writer.add_scalar('n_train_loss',n_loss_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) writer.add_scalar('n_train_acc',acc,int((idx+1+epoch*len(train_loader))/50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() p_acc = 100 * sum(p_acc_meter.value()[i, i] for i in range(settings['prop_bins'])) / p_acc_meter.value().sum() print( "Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} acc: {:.7f} props: loss {} acc {}".format( epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0], 100 * c_acc_meter.value(), p_loss_meter.value()[0],p_acc)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(n_acc) info['c_loss'].append(c_loss_meter.value()[0]) info['c_acc'].append(100 * c_acc_meter.value()) info['p_loss'].append(p_loss_meter.value()[0]) info['p_acc'].append(p_acc) return info def get_preds(args,model,dataset,device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize*5, collate_fn=batcher_g,shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx,(mols,_,_) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings,dim=0) print('inference {}'.format(time.time()-time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 200 args.batchsize = 64 args.use_tb = False args.dataset = 'qm9' args.device = 0 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.2 print(args) settings = { 'cls_num':5000, 'cls_epochs':1, # clustering every 5epochs 'iters': 10, 'init_method':'k_center', 'prop_bins':25 } print(time.strftime('%m%d_%H_%M')) logs_path = config.PATH+'/datasets/logs'+ time.strftime('/%m%d_%H_%M') model_save_path = config.PATH+'/datasets/models'+ time.strftime('/wsch_g_%m%d_%H_%M.pkl') train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'],'rb')), pickle.load(open(config.test_pkl['qm9'],'rb')) train_dataset, test_dataset = SelfMolDataSet(mols=train_mols,level='g'), SelfMolDataSet(mols=test_mols,level='g') device = torch.device('cuda:'+str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path,comment='baseline_sch') else: writer = None model = WSchnet(dim=256,n_conv=4,cutoff=30.0,cls_dim=settings['cls_num'],width=0.1,norm=True, output_dim=1,props_bins=settings['prop_bins']) optimizer = torch.optim.Adam(model.parameters(), lr=2e-4) if args.multi_gpu: model = DataParallel(model,device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args,settings,train_dataset,model,optimizer, writer, device) pickle.dump(model,open(model_save_path,'wb')) if args.save_model: torch.save({'model_state_dict':model.state_dict(), 'optimizier_state_dict':optimizer.state_dict(), 'info':info, },config.save_model_path(args.dataset))
8,188
35.887387
144
py
AS_Molecule
AS_Molecule-master/pre_training/sch_embeddings.py
import torch as th import torch.nn as nn import numpy as np import dgl import dgl.function as fn from torch.nn import Softplus #cannot first write device in model class AtomEmbedding(nn.Module): """ Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. """ def __init__(self, dim=128, type_num=100, pre_train=None): """ Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings """ super(AtomEmbedding,self).__init__() self._dim = dim self._type_num = type_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(type_num, dim, padding_idx=0) def forward(self, g, p_name="node"): """Input type is dgl graph""" atom_list = g.ndata["nodes"] g.ndata[p_name] = self.embedding(atom_list) return g.ndata[p_name] class EdgeEmbedding(nn.Module): """ Convert the edge to embedding. The edge links same pair of atoms share the same initial embedding. """ def __init__(self, dim=128, edge_num=3000, pre_train=None): """ Randomly init the edge embeddings. Args: dim: the dim of embeddings edge_num: the maximum type of edges pre_train: the pre_trained embeddings """ super(EdgeEmbedding,self).__init__() self._dim = dim self._edge_num = edge_num if pre_train is not None: self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) else: self.embedding = nn.Embedding(edge_num, dim, padding_idx=0) def generate_edge_type(self, edges): """ Generate the edge type based on the src&dst atom type of the edge. Note that C-O and O-C are the same edge type. To map a pair of nodes to one number, we use an unordered pairing function here See more detail in this disscussion: https://math.stackexchange.com/questions/23503/create-unique-number-from-2-numbers Note that, the edge_num should larger than the square of maximum atomic number in the dataset. """ atom_type_x = edges.src["node_type"] atom_type_y = edges.dst["node_type"] return { "type": atom_type_x * atom_type_y + (th.abs(atom_type_x - atom_type_y) - 1)**2 / 4 } def forward(self, g, p_name="edge_f"): g.apply_edges(self.generate_edge_type) g.edata[p_name] = self.embedding(g.edata["type"]) return g.edata[p_name] class ShiftSoftplus(Softplus): """ Shiftsoft plus activation function: 1/beta * (log(1 + exp**(beta * x)) - log(shift)) """ def __init__(self, beta=1, shift=2, threshold=20): super().__init__(beta, threshold) self.shift = shift self.softplus = Softplus(beta, threshold) def forward(self, input): return self.softplus(input) - np.log(float(self.shift)) class RBFLayer(nn.Module): """ Radial basis functions Layer. e(d) = exp(- gamma * ||d - mu_k||^2) default settings: gamma = 10 0 <= mu_k <= 30 for k=1~300 """ def __init__(self, low=0, high=30, gap=0.1, dim=1): super(RBFLayer,self).__init__() self._low = low self._high = high self._gap = gap self._dim = dim self._n_centers = int(np.ceil((high - low) / gap)) centers = np.linspace(low, high, self._n_centers) self.centers = nn.Parameter(th.Tensor(centers), requires_grad=False) self._fan_out = self._dim * self._n_centers self._gap = centers[1] - centers[0] def dis2rbf(self, edges): dist = edges.data["distance"] radial = dist - self.centers coef = float(-1 / self._gap) rbf = th.exp(coef * (radial**2)) return {"rbf": rbf} def forward(self, g): """Convert distance scalar to rbf vector""" g.apply_edges(self.dis2rbf) return g.edata["rbf"] class CFConv(nn.Module): """ The continuous-filter convolution layer in SchNet. One CFConv contains one rbf layer and three linear layer (two of them have activation funct). """ def __init__(self, rbf_dim, dim=64, act="sp"): """ Args: rbf_dim: the dimsion of the RBF layer dim: the dimension of linear layers act: activation function (default shifted softplus) """ super(CFConv,self).__init__() self._rbf_dim = rbf_dim self._dim = dim self.linear_layer1 = nn.Linear(self._rbf_dim, self._dim) self.linear_layer2 = nn.Linear(self._dim, self._dim) if act == "sp": self.activation = nn.Softplus(beta=0.5, threshold=14) else: self.activation = act def update_edge(self, edges): rbf = edges.data["rbf"] h = self.linear_layer1(rbf) h = self.activation(h) h = self.linear_layer2(h) return {"h": h} def forward(self, g): g.apply_edges(self.update_edge) g.update_all(message_func=fn.u_mul_e('new_node', 'h', 'neighbor_info'), reduce_func=fn.sum('neighbor_info', 'new_node')) return g.ndata["new_node"] class Interaction(nn.Module): """ The interaction layer in the SchNet model. """ def __init__(self, rbf_dim, dim): super(Interaction,self).__init__() self._node_dim = dim self.activation = nn.Softplus(beta=0.5, threshold=14) self.node_layer1 = nn.Linear(dim, dim, bias=False) self.cfconv = CFConv(rbf_dim, dim, act=self.activation) self.node_layer2 = nn.Linear(dim, dim) self.node_layer3 = nn.Linear(dim, dim) def forward(self, g): g.ndata["new_node"] = self.node_layer1(g.ndata["node"]) cf_node = self.cfconv(g) cf_node_1 = self.node_layer2(cf_node) cf_node_1a = self.activation(cf_node_1) new_node = self.node_layer3(cf_node_1a) g.ndata["node"] = g.ndata["node"] + new_node return g.ndata["node"] class SchEmbedding(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(SchEmbedding,self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64, output_dim) self.ebd_dense_layer = nn.Linear(64,32) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g ): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1,1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] if self.norm: g.ndata["res"] = g.ndata[ "res"] * self.std_per_atom + self.mean_per_atom preds = self.atom_dense_layer2(dgl.mean_nodes(g,"res")) return preds def embed_g(self, g): with th.no_grad(): g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.activation(self.atom_dense_layer1(g.ndata["node"])) atom = self.ebd_dense_layer(atom) g.ndata['atom'] = atom embeddings = dgl.mean_nodes(g, "atom") return embeddings
9,876
30.758842
90
py
AS_Molecule
AS_Molecule-master/pre_training/w_ptr_r.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle import torch.nn.functional as F import ot sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * from pre_training.sch_embeddings import SchEmbedding import numpy as np from pre_training.wsch import WSchnet_N, WSchnet_G, WSchnet, WSchnet_R '''Jointly self-training with node level masking and clustering center labeling with label regression ''' def train(args,settings,train_datset, test_dataset, model,optimizer, writer,device): print("start") train_loader = DataLoader(dataset=train_datset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) # test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) # prepare labels p_labels = train_datset.prop # p_labels = (train_datset.prop - train_datset.mean) / train_datset.std # p_labels = (1 + torch.erf(p_labels / 2 ** 0.5)) / 2 # transform it to (0,1), constant must be bigger than 1e-7 # bin_gap = 1 / settings['prop_bins'] # p_labels = (p_labels / (bin_gap+1e-7)).long() p_labels = p_labels.to(device) print(model) model.set_mean_std(train_datset.mean,train_datset.std) model.to(device) loss_fn = nn.CrossEntropyLoss() loss_r = nn.MSELoss() loss_mae = nn.L1Loss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() p_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter(100) # clustering num might be too big, do not use confusion matrix c_acc_meter = AccMeter(settings['cls_num']) p_mae_meter = meter.AverageValueMeter() init_lr = args.lr info = {'n_loss':[], 'n_acc':[], 'c_loss':[], 'c_acc':[], 'p_loss': [], 'p_mae': [] } cls_tags = 0 K = settings['cls_num'] N = len(train_datset) cls_distr = torch.ones(K) / K inst_distr = torch.ones(N) / N cls_log_prob = np.ones([N, K]) * np.log(K) / N # prob_tensor (cost function) cls_tags = np.ones([N, K]) / (K * N) # the tag is a prob distribution for epoch in range(args.epochs): n_loss_meter.reset() c_loss_meter.reset() p_loss_meter.reset() n_acc_meter.reset() c_acc_meter.reset() p_mae_meter.reset() model.train() # prepare pesudo labels via k means if epoch % settings['cls_epochs'] == 1: # feats_all = get_preds(args,model,train_datset,device) # if epoch == 0: # cls_tags = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=settings['init_method'],show_stats=True) # else: # cls_tags = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=cls_tags,show_stats=True) # perform optimal transport time0 = time.time() # cls_tags = ot.sinkhorn(inst_distr, cls_distr, cls_log_prob,0.04) # shape dataset_num*cls_num ...takes 40s~250s on cpu print('optimal transport solved: {}'.format(time.time() - time0)) for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) # Mask node features mask = torch.randint(0,g.number_of_nodes(),[int(args.mask_n_ratio*g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 # make pesudo labels vis k means # cls_labels = cls_tags[list(ids)].to(device) # make pesudo labels vis optimal transport cls_labels = N * torch.tensor(cls_tags[list(ids)], requires_grad=False).to(device).float() atom_preds, cls_preds, prop_preds = model(g) n_pred_cls = torch.argmax(atom_preds, dim=1) # c_pred_cls = torch.argmax(cls_preds, dim=1) cls_logits = torch.log(F.softmax(cls_preds,dim=1)) n_loss = loss_fn(atom_preds[mask], n_label[mask]) # compute c loss c_loss = torch.sum( - cls_labels*cls_logits,dim=1).mean() p_loss = loss_r(prop_preds.squeeze(), p_labels[list(ids)]) # squeeze is really important p_mae = loss_mae(prop_preds.squeeze(),p_labels[list(ids)]) loss = 1e4*p_loss + n_loss optimizer.zero_grad() loss.backward() optimizer.step() cls_log_prob[idx*args.batchsize:idx*args.batchsize+len(mols)] = - cls_logits.detach().cpu().numpy() n_loss_meter.add(loss.detach().item()) # total loss c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, n_label) # c_acc_meter.add(c_pred_cls, cls_labels) p_loss_meter.add(p_loss.detach().item()) p_mae_meter.add(p_mae.detach().item()) if idx%50 == 0 and args.use_tb: acc = 100*sum(n_acc_meter.value()[i,i] for i in range(10))/n_acc_meter.value().sum() writer.add_scalar('n_train_loss',n_loss_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) writer.add_scalar('n_train_acc',acc,int((idx+1+epoch*len(train_loader))/50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() test_loss, test_mae = test(args,test_dataset,model,device) # p_acc = 100 * sum(p_acc_meter.value()[i, i] for i in range(settings['prop_bins'])) / p_acc_meter.value().sum() # print("Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} acc: {:.7f} props: loss {} mae {}".format(epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0], 100 * c_acc_meter.value(), p_loss_meter.value()[0],p_mae_meter.value()[0])) print("Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} props loss {} mae {}".format(epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0],p_loss_meter.value()[0], p_mae_meter.value()[0])) print("Test loss {} mae {}".format(test_loss, test_mae)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 2 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(n_acc) info['c_loss'].append(c_loss_meter.value()[0]) info['c_acc'].append(100 * c_acc_meter.value()) info['p_loss'].append(p_loss_meter.value()[0]) info['p_mae'].append(p_mae_meter.value()[0]) return info def test(args, test_dataset,model,device): test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) labels = test_dataset.prop loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, n_label, ids) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = labels[list(ids)].to(device) _,_,res = model(g) res = res.squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def get_preds(args,model,dataset,device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize*5, collate_fn=batcher_g,shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx,(mols,_,_) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings,dim=0) print('inference {}'.format(time.time()-time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 1000 args.batchsize = 64 args.use_tb = False args.dataset = 'qm9' args.device = 1 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.4 print(args) settings = { 'cls_num':2000, 'cls_epochs':10, # clustering every 5epochs 'iters': 10, 'init_method':'random', 'prop_bins':25 } train_data_num = 20000 embed_method = 'sch_embedding' load_path = '/home/jeffzhu/AL/datasets/models/wsch_g_1205_15_58.pkl' print(time.strftime('%m%d_%H_%M')) logs_path = config.PATH+'/datasets/logs'+ time.strftime('/%m%d_%H_%M') model_save_path = config.PATH+'/datasets/models'+ time.strftime('/wsch_g_%m%d_%H_%M.pkl') train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'],'rb')), pickle.load(open(config.test_pkl['qm9'],'rb')) train_dataset, test_dataset = SelfMolDataSet(mols=train_mols,level='g'), SelfMolDataSet(mols=test_mols,level='g') # # if embed_method is 'sch_embedding': # embedding_model = SchEmbedding(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) #64 dim # mols_embeddings = get_preds(args,embedding_model,train_dataset,torch.device(args.device)) # # # elif embed_method is 'wsch_n': # # embedding_model = WSchnet_N(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) # # embedding_model.load_state_dict(torch.load(pre_model_path)) # # mols_embeddings = get_preds(args,embedding_model,train_set,torch.device(args.device)) # else: # raise ValueError # mols_embeddings = mols_embeddings.cpu() # data_ids = k_medoid(mols_embeddings, train_data_num, 10, show_stats=True) # train_set = MoleDataset(mols=[train_dataset.mols[i] for i in data_ids]) # train_part train_dataset = SelfMolDataSet(mols=random.sample(train_dataset.mols, train_data_num),level='g') device = torch.device('cuda:'+str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path,comment='baseline_sch') else: writer = None model = WSchnet_R(dim=128,n_conv=4,cutoff=30.0,cls_dim=settings['cls_num'],width=0.1,norm=True, output_dim=1,props_bins=settings['prop_bins']) # model = pickle.load(open(load_path,'rb')) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) if args.multi_gpu: model = DataParallel(model,device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args,settings,train_dataset,test_dataset,model,optimizer, writer, device) pickle.dump(model,open(model_save_path,'wb')) if args.save_model: torch.save({'model_state_dict':model.state_dict(), 'optimizier_state_dict':optimizer.state_dict(), 'info':info, },config.save_model_path(args.dataset))
11,913
37.934641
279
py
AS_Molecule
AS_Molecule-master/pre_training/wsch.py
#!/usr/bin/env python #-*- coding:utf-8 _*- '''Schnet in a weakly supervised manner 1. node level pre_training with node attributes Masking 2. graph level pre_training with contrasive loss or clustering loss 3. weakly supervised learning on specific properties ''' import torch as th import torch.nn as nn import numpy as np import dgl import dgl.function as fn from torch.nn import Softplus import torch.nn.init as inits import sys sys.path.append('..') from base_model.schmodel import AtomEmbedding, RBFLayer, Interaction, ShiftSoftplus from bayes_al.mm_sch import MM_Interaction class WSchnet_N(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(WSchnet_N,self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.type_num = 100 self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_classifier = nn.Linear(64, 100) # 100 denote the number of atom types self.ebd_dense_layer = nn.Linear(64,32) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g ): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1,1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] # # if self.norm: # g.ndata["res"] = g.ndata[ # "res"] * self.std_per_atom + self.mean_per_atom atoms_preds = self.atom_classifier(g.ndata["res"]) return atoms_preds # get whole graph embeddings by meaning the nodes def embed_g(self, g): with th.no_grad(): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") # atom = self.activation(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] # # if self.norm: # g.ndata["res"] = g.ndata[ # "res"] * self.std_per_atom + self.mean_per_atom # g.ndata["res"] = self.atom_classifier(g.ndata["res"]) embeddings_g = dgl.mean_nodes(g, 'res') return embeddings_g '''G denote whole graph pre_training''' class WSchnet_G(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, cls_dim = 2000, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(WSchnet_G,self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.type_num = 100 self.cls_dim = cls_dim self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 256) self.atom_dense_layer2 = nn.Linear(256,256) self.cls_classifier = nn.Linear(256,cls_dim) self.atom_classifier = nn.Sequential( nn.ReLU(), nn.Linear(256, 100) ) # 100 denote the number of atom types # self.ebd_dense_layer = nn.Linear(64,32) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g ): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1,1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] # # if self.norm: # g.ndata["res"] = g.ndata[ # "res"] * self.std_per_atom + self.mean_per_atom atoms_preds = self.atom_classifier(g.ndata["res"]) embeddings_g = dgl.mean_nodes(g, 'res') cls_preds = self.cls_classifier(embeddings_g) return atoms_preds, cls_preds # get whole graph embeddings by meaning the nodes def embed_g(self, g): with th.no_grad(): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) # g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] embeddings_g = dgl.mean_nodes(g, 'res') return embeddings_g def re_init_head(self): inits.xavier_normal_(self.cls_classifier.weight) return '''G denote whole graph pre_training''' class WSchnet(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, props_bins = 30, cls_dim = 2000, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(WSchnet,self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.type_num = 100 self.cls_dim = cls_dim self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 256) self.atom_dense_layer2 = nn.Linear(256,256) # self.cls_classifier = nn.Sequential( # nn.ReLU(), # nn.Linear(64,128), # nn.ReLU(), # nn.Linear(128,512), # nn.ReLU(), # nn.Linear(512,cls_dim) # ) self.cls_classifier = nn.Linear(256,cls_dim) self.atom_classifier = nn.Linear(256, 100) # 100 denote the number of atom types self.prop_classifier = nn.Linear(256,props_bins) # self.ebd_dense_layer = nn.Linear(64,32) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g ): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1,1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] # # if self.norm: # g.ndata["res"] = g.ndata[ # "res"] * self.std_per_atom + self.mean_per_atom atoms_preds = self.atom_classifier(g.ndata["res"]) embeddings_g = dgl.mean_nodes(g, 'res') # normalize # embeddings_g = embeddings_g / th.norm(embeddings_g,p=2, dim=1, keepdim=True).expand(-1,embeddings_g.size(1)) cls_preds = self.cls_classifier(embeddings_g) prop_preds = self.prop_classifier(embeddings_g) return atoms_preds, cls_preds, prop_preds # get whole graph embeddings by meaning the nodes def embed_g(self, g): with th.no_grad(): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) # g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] embeddings_g = dgl.mean_nodes(g, 'res') # normalize # embeddings_g = embeddings_g / th.norm(embeddings_g, p=2, dim=1, keepdim=True).expand(-1,embeddings_g.size(1)) return embeddings_g def inference(self,g): return self.embed_g(g) def re_init_head(self): inits.xavier_normal_(self.cls_classifier.weight) print('clustering head re-initialized') return '''G denote whole graph pre_training''' class WSchnet_R(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, props_bins = 30, cls_dim = 2000, width=1, n_conv=3, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(WSchnet_R,self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.type_num = 100 self.cls_dim = cls_dim self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64,64) # self.cls_classifier = nn.Sequential( # nn.ReLU(), # nn.Linear(64,128), # nn.ReLU(), # nn.Linear(128,512), # nn.ReLU(), # nn.Linear(512,cls_dim) # ) self.cls_classifier = nn.Linear(64,cls_dim) self.atom_classifier = nn.Linear(64, 100) # 100 denote the number of atom types self.prop_regressor = nn.Sequential( nn.Linear(64,1), # nn.ReLU(), # nn.Linear(32,1) ) # self.ebd_dense_layer = nn.Linear(64,32) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g ): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1,1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] # # if self.norm: # g.ndata["res"] = g.ndata[ # "res"] * self.std_per_atom + self.mean_per_atom atoms_preds = self.atom_classifier(g.ndata["res"]) embeddings_g = dgl.mean_nodes(g, 'res') # normalize # embeddings_g = embeddings_g / th.norm(embeddings_g,p=2, dim=1, keepdim=True).expand(-1,embeddings_g.size(1)) cls_preds = self.cls_classifier(embeddings_g) #TODO: delete it when test finished prop_preds = self.prop_regressor(embeddings_g) # g.ndata['res'] = self.prop_regressor(g.ndata['res']) # prop_preds = dgl.mean_nodes(g,'res') return g.ndata['res'], cls_preds, prop_preds # get whole graph embeddings by meaning the nodes def embed_g(self, g): with th.no_grad(): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) # g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] embeddings_g = dgl.mean_nodes(g, 'res') # normalize # embeddings_g = embeddings_g / th.norm(embeddings_g, p=2, dim=1, keepdim=True).expand(-1,embeddings_g.size(1)) return embeddings_g def inference(self,g): return self.embed_g(g) def re_init_head(self): inits.xavier_normal_(self.cls_classifier.weight) print('clustering head re-initialized') return '''G denote whole graph pre_training''' class MM_WSchnet_R(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, props_bins = 30, cls_dim = 2000, width=1, n_conv=3, mask_rate = 0.2, norm=False, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(MM_WSchnet_R,self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.type_num = 100 self.cls_dim = cls_dim self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [MM_Interaction(self.rbf_layer._fan_out, dim, mask_rate=mask_rate) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64,64) # self.cls_classifier = nn.Sequential( # nn.ReLU(), # nn.Linear(64,128), # nn.ReLU(), # nn.Linear(128,512), # nn.ReLU(), # nn.Linear(512,cls_dim) # ) self.cls_classifier = nn.Linear(64,cls_dim) self.atom_classifier = nn.Linear(64, 100) # 100 denote the number of atom types self.prop_regressor = nn.Sequential( nn.Linear(64,1), # nn.ReLU(), # nn.Linear(32,1) ) self.final_bn = nn.BatchNorm1d(64) # self.ebd_dense_layer = nn.Linear(64,32) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g ): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1,1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx].message_masking_inference(g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") # atom = self.final_bn(atom) atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] # # if self.norm: # g.ndata["res"] = g.ndata[ # "res"] * self.std_per_atom + self.mean_per_atom atoms_preds = self.atom_classifier(g.ndata["res"]) embeddings_g = dgl.mean_nodes(g, 'res') # normalize # embeddings_g = embeddings_g / th.norm(embeddings_g,p=2, dim=1, keepdim=True).expand(-1,embeddings_g.size(1)) cls_preds = self.cls_classifier(embeddings_g) #TODO: delete it when test finished prop_preds = self.prop_regressor(embeddings_g) # g.ndata['res'] = self.prop_regressor(g.ndata['res']) # prop_preds = dgl.mean_nodes(g,'res') return atoms_preds, cls_preds, prop_preds # get whole graph embeddings by meaning the nodes def embed_g(self, g): with th.no_grad(): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) # g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] embeddings_g = dgl.mean_nodes(g, 'res') # normalize # embeddings_g = embeddings_g / th.norm(embeddings_g, p=2, dim=1, keepdim=True).expand(-1,embeddings_g.size(1)) return embeddings_g def inference(self,g): return self.embed_g(g) def re_init_head(self): inits.xavier_normal_(self.cls_classifier.weight) print('clustering head re-initialized') return '''main model: contains 3 components 1. node / edge reconstructio module 2. ot unsupervised module 3. property prediction module ''' class Semi_Schnet(nn.Module): """ SchNet Model from: Schütt, Kristof, et al. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions. (NIPS'2017) """ def __init__(self, dim=64, cutoff=5.0, output_dim=1, props_bins = 30, cls_dim = 2000, width=1, n_conv=3, norm=False, edge_bins = 150, mask_n_ratio = 0.2, mask_msg_ratio = 0.2, atom_ref=None, pre_train=None, ): """ Args: dim: dimension of features output_dim: dimension of prediction cutoff: radius cutoff width: width in the RBF function n_conv: number of interaction layers atom_ref: used as the initial value of atom embeddings, or set to None with random initialization norm: normalization """ super(Semi_Schnet,self).__init__() self.name = "SchNet" self._dim = dim self.cutoff = cutoff self.width = width self.n_conv = n_conv self.atom_ref = atom_ref self.norm = norm self.type_num = 100 self.cls_dim = cls_dim self.edge_bins = edge_bins self.mask_n_ratio = mask_n_ratio self.mask_msg_ratio = mask_msg_ratio self.activation = ShiftSoftplus() if atom_ref is not None: self.e0 = AtomEmbedding(1, pre_train=atom_ref) if pre_train is None: self.embedding_layer = AtomEmbedding(dim) else: self.embedding_layer = AtomEmbedding(pre_train=pre_train) self.rbf_layer = RBFLayer(0, cutoff, width) self.conv_layers = nn.ModuleList( [Interaction(self.rbf_layer._fan_out, dim) for i in range(n_conv)]) self.atom_dense_layer1 = nn.Linear(dim, 64) self.atom_dense_layer2 = nn.Linear(64,64) # self.cls_classifier = nn.Sequential( # nn.ReLU(), # nn.Linear(64,128), # nn.ReLU(), # nn.Linear(128,512), # nn.ReLU(), # nn.Linear(512,cls_dim) # ) self.cls_classifier = nn.Linear(64,cls_dim) self.atom_classifier = nn.Linear(64, 100) # 100 denote the number of atom types self.edge_classifier = nn.Linear(64, edge_bins) self.prop_regressor = nn.Sequential( nn.Linear(64,1) ) # self.ebd_dense_layer = nn.Linear(64,32) def set_mean_std(self, mean, std): self.mean_per_atom = mean.clone().detach() self.std_per_atom = std.clone().detach() def forward(self, g ): # return node_embeddings, graph_embeddings, props g.edata['distance'] = g.edata['distance'].reshape(-1,1) # node and edge to be masked, for nodes, mask src_ids mask = th.randint(0,g.number_of_edges(),[int(self.mask_n_ratio*g.number_of_nodes())]) src_ids, dst_ids, _ = g._graph.edges('eid') src_ids, dst_ids = [src_ids[i] for i in mask], [dst_ids[i] for i in mask] g.ndata['nodes'][src_ids] = 0 self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom g.ndata["prop"] = self.prop_regressor(g.ndata["res"]).squeeze() if self.atom_ref is not None: g.ndata["prop"] = g.ndata["prop"] + g.ndata["e0"].squeeze() # if self.norm: g.ndata["prop"] = g.ndata["prop"] * self.std_per_atom.to(atom.device) + self.mean_per_atom.to(atom.device) embeddings_g = dgl.mean_nodes(g, 'res') # get edge predicts atoms_preds = self.atom_classifier(g.ndata["res"][src_ids]) edge_preds = self.edge_classifier(th.abs(g.ndata["res"][src_ids] - g.ndata["res"][dst_ids])) cls_preds = self.cls_classifier(embeddings_g) # prop_preds = dgl.mean_nodes(g,'prop') prop_preds = dgl.sum_nodes(g,'prop') return atom, atoms_preds, edge_preds, (src_ids, dst_ids, mask),cls_preds, embeddings_g, prop_preds # get whole graph embeddings by meaning the nodes def embed_g(self, g): with th.no_grad(): # g_list list of molecules g.edata['distance'] = g.edata['distance'].reshape(-1, 1) self.embedding_layer(g) if self.atom_ref is not None: self.e0(g, "e0") self.rbf_layer(g) for idx in range(self.n_conv): self.conv_layers[idx](g) atom = self.atom_dense_layer1(g.ndata["node"]) # g.ndata['atom'] = atom # res = dgl.mean_nodes(g, "atom") atom = self.activation(atom) atom = self.atom_dense_layer2(atom) g.ndata["res"] = atom if self.atom_ref is not None: g.ndata["res"] = g.ndata["res"] + g.ndata["e0"] embeddings_g = dgl.mean_nodes(g, 'res') # normalize # embeddings_g = embeddings_g / th.norm(embeddings_g, p=2, dim=1, keepdim=True).expand(-1,embeddings_g.size(1)) return embeddings_g def inference(self,g): return self.embed_g(g) def re_init_head(self): inits.xavier_normal_(self.cls_classifier.weight) print('clustering head re-initialized') return
30,468
30.50879
123
py
AS_Molecule
AS_Molecule-master/pre_training/ot_unsupervised.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle import torch.nn.functional as F import ot sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * import numpy as np from pre_training.wsch import WSchnet_N, WSchnet_G, WSchnet, WSchnet_R '''provide pre-trained model for transfer ''' def train(args, settings, train_datset, test_dataset, model, optimizer, writer, device): print("start") train_loader = DataLoader(dataset=train_datset, batch_size=args.batchsize, collate_fn=batcher_g, shuffle=args.shuffle, num_workers=args.workers) # test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) # prepare labels p_labels = train_datset.prop # p_labels = (train_datset.prop - train_datset.mean) / train_datset.std # p_labels = (1 + torch.erf(p_labels / 2 ** 0.5)) / 2 # transform it to (0,1), constant must be bigger than 1e-7 # bin_gap = 1 / settings['prop_bins'] # p_labels = (p_labels / (bin_gap+1e-7)).long() p_labels = p_labels.to(device) print(model) model.set_mean_std(train_datset.mean, train_datset.std) model.to(device) loss_fn = nn.CrossEntropyLoss() loss_r = nn.MSELoss() loss_mae = nn.L1Loss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() p_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter( 100) # clustering num might be too big, do not use confusion matrix c_acc_meter = AccMeter(settings['cls_num']) p_mae_meter = meter.AverageValueMeter() init_lr = args.lr info = { 'n_loss': [], 'n_acc': [], 'c_loss': [], 'c_acc': [], 'p_loss': [], 'p_mae': [] } Q = 0 K = settings['cls_num'] N = len(train_datset) # uniform distribution cls_distr = torch.ones(K) / K inst_distr = torch.ones(N) / N C = np.ones([N, K]) * np.log(K) / N # prob_tensor (cost function) Q = np.ones([N, K]) / (K * N) # the tag is a prob distribution cls_tags = torch.Tensor(np.argmax(Q, axis=1)).to(device) # # TODO: For Test # # Now I replace it by a normal distribution 4 is decided by 100000*Gauss(4)~10 # cls_distr = np.exp(-(np.linspace(-4,4,K)**2)/2)/(np.sqrt(2*np.pi)) # cls_distr = cls_distr / cls_distr.sum() # inst_distr = torch.ones(N) / N # # C = np.ones([N, K])* np.log(K) / N # cost matrix # Q = np.copy(np.tile(cls_distr,(N, 1))) / N # joint distribution for epoch in range(args.epochs): n_loss_meter.reset() c_loss_meter.reset() p_loss_meter.reset() n_acc_meter.reset() c_acc_meter.reset() p_mae_meter.reset() model.train() # prepare pesudo labels via k means if epoch % settings['cls_epochs'] == 1: # feats_all = get_preds(args,model,train_datset,device) # if epoch == 0: # Q = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=settings['init_method'],show_stats=True) # else: # Q = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=Q,show_stats=True) # perform optimal transport time0 = time.time() Q = ot.sinkhorn( inst_distr, cls_distr, C, 0.04) # shape dataset_num*cls_num ...takes 40s~250s on cpu print('optimal transport solved: {}'.format(time.time() - time0)) for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) # Mask node features mask = torch.randint( 0, g.number_of_nodes(), [int(args.mask_n_ratio * g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 # make pesudo labels vis k means # cls_labels = Q[list(ids)].to(device) # make pesudo labels vis optimal transport cls_labels = torch.tensor(np.argmax(Q[list(ids)], axis=1), requires_grad=False).to(device).long() atom_preds, cls_preds, prop_preds = model(g) n_pred_cls = torch.argmax(atom_preds, dim=1) # c_pred_cls = torch.argmax(cls_preds, dim=1) cls_logits = torch.log(F.softmax(cls_preds, dim=1)) n_loss = loss_fn(atom_preds[mask], n_label[mask]) # compute c loss Now it is CrossEntropyLoss by hard pesudo labeling # c_loss = torch.sum( - cls_labels*cls_logits,dim=1).mean() c_loss = loss_fn(cls_preds, cls_labels) p_loss = loss_r(prop_preds.squeeze(), p_labels[list(ids)]) # squeeze is really important p_mae = loss_mae(prop_preds.squeeze(), p_labels[list(ids)]) loss = 0 + c_loss optimizer.zero_grad() loss.backward() optimizer.step() C[idx * args.batchsize:idx * args.batchsize + len(mols)] = -cls_logits.detach().cpu().numpy() n_loss_meter.add(loss.detach().item()) # total loss c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, n_label) # c_acc_meter.add(c_pred_cls, cls_labels) p_loss_meter.add(p_loss.detach().item()) p_mae_meter.add(p_mae.detach().item()) if idx % 50 == 0 and args.use_tb: acc = 100 * sum( n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() writer.add_scalar( 'n_train_loss', n_loss_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) writer.add_scalar( 'n_train_acc', acc, int((idx + 1 + epoch * len(train_loader)) / 50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() test_loss, test_mae = test(args, test_dataset, model, device) # p_acc = 100 * sum(p_acc_meter.value()[i, i] for i in range(settings['prop_bins'])) / p_acc_meter.value().sum() # print("Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} acc: {:.7f} props: loss {} mae {}".format(epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0], 100 * c_acc_meter.value(), p_loss_meter.value()[0],p_mae_meter.value()[0])) print( "Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} props loss {} mae {}" .format(epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0], p_loss_meter.value()[0], p_mae_meter.value()[0])) print("Test loss {} mae {}".format(test_loss, test_mae)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(n_acc) info['c_loss'].append(c_loss_meter.value()[0]) info['c_acc'].append(100 * c_acc_meter.value()) info['p_loss'].append(p_loss_meter.value()[0]) info['p_mae'].append(p_mae_meter.value()[0]) return info def test(args, test_dataset, model, device): test_loader = DataLoader(dataset=test_dataset, batch_size=args.batchsize, collate_fn=batcher_g, shuffle=args.shuffle, num_workers=args.workers) labels = test_dataset.prop loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, n_label, ids) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = labels[list(ids)].to(device) _, _, res = model(g) res = res.squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def get_preds(args, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize * 5, collate_fn=batcher_g, shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx, (mols, _, _) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings, dim=0) print('inference {}'.format(time.time() - time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 40 args.batchsize = 64 args.use_tb = False args.dataset = 'qm9' args.device = 1 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.4 print(args) settings = { 'cls_num': 2000, 'cls_epochs': 4, # clustering every 5epochs 'iters': 10, 'init_method': 'random', 'prop_bins': 25 } train_data_num = 110000 logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') model_save_path = config.PATH + '/datasets/models' + time.strftime( '/wsch_g_otonly_%m%d_%H_%M.pkl') print('model save path {}'.format(model_save_path)) train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'], 'rb')), pickle.load( open(config.test_pkl['qm9'], 'rb')) train_dataset, test_dataset = SelfMolDataSet( mols=train_mols, level='g'), SelfMolDataSet(mols=test_mols, level='g') # train_part train_dataset = SelfMolDataSet(mols=random.sample(train_dataset.mols, train_data_num), level='g') device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None model = WSchnet_R(dim=128, n_conv=4, cutoff=30.0, cls_dim=settings['cls_num'], width=0.1, norm=True, output_dim=1, props_bins=settings['prop_bins']) optimizer = torch.optim.Adam(model.parameters(), lr=2e-4) if args.multi_gpu: model = DataParallel( model, device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args, settings, train_dataset, test_dataset, model, optimizer, writer, device) pickle.dump(model, open(model_save_path, 'wb')) if args.save_model: torch.save( { 'model_state_dict': model.state_dict(), 'optimizier_state_dict': optimizer.state_dict(), 'info': info, }, config.save_model_path(args.dataset))
12,711
36.498525
279
py
AS_Molecule
AS_Molecule-master/pre_training/train_part_cls.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import random import pickle sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from bayes_al.mc_sch import MC_SchNetModel from config import * '''Train on part of the data, the data is chosen by a naive clustering algorithm via the PCA transformation of the molecule fingerprint ''' def train(args,train_dataset,test_dataset, model,optimizer, writer,device): print("start") train_loader = DataLoader(dataset=train_dataset,batch_size=args.batchsize,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) test_loader = DataLoader(dataset=test_dataset,batch_size=args.batchsize*2,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) print(model) print(train_dataset.mean.item(), train_dataset.std.item()) # if model.name in ["MGCN", "SchNet"]: if args.multi_gpu: model.module.set_mean_std(train_dataset.mean, train_dataset.std) else: model.set_mean_std(train_dataset.mean,train_dataset.std) model.to(device) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() init_lr = args.lr info = {'train_loss':[], 'train_mae':[], 'test_loss':[], 'test_mae':[]} for epoch in range(args.epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) if idx%50 == 0 and args.use_tb: writer.add_scalar('training_loss',mse_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) writer.add_scalar('training_mae',mae_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) print('training loss {} mae {}'.format(mse_meter.value()[0], mae_meter.value()[0])) loss_test, mae_test = test(args,test_loader,model,device) print("Epoch {:2d}, training: loss: {:.7f}, mae: {:.7f} test: loss{:.7f}, mae:{:.7f}".format(epoch, mse_meter.value()[0], mae_meter.value()[0],loss_test,mae_test)) if (epoch+1) % 100 == 0: init_lr = init_lr / 2 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) info['test_loss'].append(loss_test) info['test_mae'].append(mae_test) if args.use_tb: writer.add_scalar('testing_loss',loss_test,epoch) writer.add_scalar('testing_mae',mae_test,epoch) return info def test(args, test_loader,model,device): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 800 args.batchsize = 48 args.lr = 5e-4 args.use_tb = True args.dataset = 'qm9' args.device = 1 args.save_model = False args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' print(args) train_data_num = 10000 train_fingerprint_path = config.DATASET_PATH['qm9']+'/qm9_fingerprint_20.pkl' clustering_iters = 10 logs_path = config.PATH+'/datasets/logs'+ time.strftime('/%m%d_%H_%M') train_set, test_set = MoleDataset(prop_name=args.prop_name), MoleDataset(prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol(config.test_pkl[args.dataset]) # load dataset mols_fingerprint = pickle.load(open(train_fingerprint_path,'rb')) # mols_fingerprint = mols_fingerprint.to(args.device) data_ids = k_medoid(mols_fingerprint,train_data_num,clustering_iters,show_stats=True) mols_fingerprint.cpu() train_set = MoleDataset(mols=[train_set.mols[i] for i in data_ids]) device = torch.device('cuda:'+str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path,comment='baseline_sch') else: writer = None model = SchNetModel(dim=48,n_conv=4,cutoff=5.0,width=0.5,norm=True, output_dim=1) # model = MC_SchNetModel(dim=48,n_conv=4,cutoff=5.0,width=0.5,norm=True, output_dim=1) # optimizer = torch.optim.SGD(model.parameters(), lr=args.lr,momentum=0.5,nesterov=0.6) optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) print(time.strftime('%m%d_%H_%M model {} optimizer {}'.format(str(model),str(optimizer)))) if args.multi_gpu: model = DataParallel(model,device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args,train_set,test_set,model,optimizer, writer, device) if args.save_model: torch.save({'model_state_dict':model.state_dict(), 'optimizier_state_dict':optimizer.state_dict(), 'info':info, },config.save_model_path(args.dataset))
6,312
34.466292
171
py
AS_Molecule
AS_Molecule-master/pre_training/non_ptrain_cls.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import random import pickle sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from pre_training.sch_embeddings import SchEmbedding from pre_training.wsch import WSchnet_N from bayes_al.mc_sch import MC_SchNetModel from config import * '''Train on part of the data, the data is chosen by a naive clustering algorithm via the PCA transformation of the molecule fingerprint ''' def train(args, train_dataset, test_dataset, model, optimizer, writer, device): print("start") train_loader = DataLoader(dataset=train_dataset, batch_size=args.batchsize, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) test_loader = DataLoader(dataset=test_dataset, batch_size=args.batchsize * 2, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) print(model) print(train_dataset.mean.item(), train_dataset.std.item()) # if model.name in ["MGCN", "SchNet"]: if args.multi_gpu: model.module.set_mean_std(train_dataset.mean, train_dataset.std) else: model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() init_lr = args.lr info = {'train_loss': [], 'train_mae': [], 'test_loss': [], 'test_mae': []} for epoch in range(args.epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) if idx % 50 == 0 and args.use_tb: writer.add_scalar( 'training_loss', mse_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) writer.add_scalar( 'training_mae', mae_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) print('training loss {} mae {}'.format(mse_meter.value()[0], mae_meter.value()[0])) loss_test, mae_test = test(args, test_loader, model, device) print( "Epoch {:2d}, training: loss: {:.7f}, mae: {:.7f} test: loss{:.7f}, mae:{:.7f}" .format(epoch, mse_meter.value()[0], mae_meter.value()[0], loss_test, mae_test)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) info['test_loss'].append(loss_test) info['test_mae'].append(mae_test) if args.use_tb: writer.add_scalar('testing_loss', loss_test, epoch) writer.add_scalar('testing_mae', mae_test, epoch) return info def test(args, test_loader, model, device): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) res = model(g).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def get_preds(args, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize * 5, collate_fn=batcher, shuffle=False, num_workers=args.workers) model.to(device) model.set_mean_std(dataset.mean, dataset.std) embeddings = [] with torch.no_grad(): for idx, (mols, _) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings, dim=0) print('inference {}'.format(time.time() - time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 600 args.batchsize = 64 args.lr = 3e-4 args.use_tb = True args.dataset = 'qm9' args.device = 0 args.save_model = False args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' print(args) train_data_num = 10000 train_fingerprint_path = config.DATASET_PATH[ 'qm9'] + '/qm9_fingerprint_20.pkl' pre_model_path = config.PATH + '/datasets/models/' + 'wsch_n_1124_18_M.pkl' # pre_model_path = None clustering_iters = 15 embed_method = 'sch_embedding' logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') model = SchNetModel(dim=128, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) # model = MC_SchNetModel(dim=48,n_conv=4,cutoff=5.0,width=0.5,norm=True, output_dim=1) # optimizer = torch.optim.SGD(model.parameters(), lr=args.lr,momentum=0.5,nesterov=0.6) optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) print(time.strftime('%m%d_%H_%M model {} optimizer {}'.format( str(model), str(optimizer)))) if args.multi_gpu: model = DataParallel( model, device_ids=[i for i in range(torch.cuda.device_count())]) train_set, test_set = MoleDataset(prop_name=args.prop_name), MoleDataset( prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol( config.test_pkl[args.dataset]) if embed_method is 'fingerprint': mols_embeddings = pickle.load(open(train_fingerprint_path, 'rb')) elif embed_method is 'sch_embedding': embedding_model = SchEmbedding(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) #64 dim mols_embeddings = get_preds(args, embedding_model, train_set, torch.device(args.device)) elif embed_method is 'wsch_n': embedding_model = WSchnet_N(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) embedding_model.load_state_dict(torch.load(pre_model_path)) mols_embeddings = get_preds(args, embedding_model, train_set, torch.device(args.device)) else: raise ValueError # mols_fingerprint = mols_fingerprint.to(args.device) # data_ids = k_center(mols_embeddings, train_data_num) mols_embeddings = mols_embeddings.cpu() data_ids = k_medoid(mols_embeddings, train_data_num, clustering_iters, show_stats=True) train_set = MoleDataset(mols=[train_set.mols[i] for i in data_ids]) device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None info = train(args, train_set, test_set, model, optimizer, writer, device) if args.save_model: torch.save( { 'model_state_dict': model.state_dict(), 'optimizier_state_dict': optimizer.state_dict(), 'info': info, }, config.save_model_path(args.dataset))
9,243
35.25098
91
py
AS_Molecule
AS_Molecule-master/pre_training/train_part_transfer.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle import torch.nn.functional as F import ot sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * import numpy as np from pre_training.sch_embeddings import SchEmbedding from pre_training.wsch import WSchnet_N, WSchnet_G, WSchnet, WSchnet_R, MM_WSchnet_R ''' Train from a transfer model ''' def train(args,settings,train_datset, test_dataset, model,optimizer, writer,device): print("start training with {} data".format(len(train_datset))) train_loader = DataLoader(dataset=train_datset,batch_size=args.batchsize,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) # prepare labels p_labels = train_datset.prop # p_labels = (train_datset.prop - train_datset.mean) / train_datset.std # p_labels = (1 + torch.erf(p_labels / 2 ** 0.5)) / 2 # transform it to (0,1), constant must be bigger than 1e-7 # bin_gap = 1 / settings['prop_bins'] # p_labels = (p_labels / (bin_gap+1e-7)).long() p_labels = p_labels.to(device) print(model) model.set_mean_std(train_datset.mean,train_datset.std) model.to(device) loss_fn = nn.CrossEntropyLoss() loss_r = nn.MSELoss() loss_mae = nn.L1Loss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() p_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter(100) # clustering num might be too big, do not use confusion matrix p_mae_meter = meter.AverageValueMeter() init_lr = args.lr regressor = nn.Linear(64, 1,bias=True) regressor.to(device) for epoch in range(args.epochs): n_loss_meter.reset() p_loss_meter.reset() n_acc_meter.reset() p_mae_meter.reset() model.train() for idx, (mols, labels) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) labels = labels.to(device) # Mask node features mask = torch.randint(0,g.number_of_nodes(),[int(args.mask_n_ratio*g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 _,_, prop_preds = model(g) # n_pred_cls = torch.argmax(atom_preds, dim=1) # c_pred_cls = torch.argmax(cls_preds, dim=1) # cls_logits = torch.log(F.softmax(cls_preds,dim=1)) # n_loss = loss_fn(atom_preds[mask], n_label[mask]) # compute c loss # c_loss = torch.sum( - cls_labels*cls_logits,dim=1).mean() p_loss = loss_r(prop_preds.squeeze(),labels) # squeeze is really important p_mae = loss_mae(prop_preds.squeeze(),labels) loss = p_loss optimizer.zero_grad() loss.backward() optimizer.step() # cls_log_prob[idx*args.batchsize:idx*args.batchsize+len(mols)] = - cls_logits.detach().cpu().numpy() # n_loss_meter.add(loss.detach().item()) # total loss # c_loss_meter.add(c_loss.detach().item()) # n_acc_meter.add(n_pred_cls, n_label) # c_acc_meter.add(c_pred_cls, cls_labels) p_loss_meter.add(p_loss.detach().item()) p_mae_meter.add(p_mae.detach().item()) if idx%50 == 0 and args.use_tb: acc = 100*sum(n_acc_meter.value()[i,i] for i in range(10))/n_acc_meter.value().sum() writer.add_scalar('n_train_loss',n_loss_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) writer.add_scalar('n_train_acc',acc,int((idx+1+epoch*len(train_loader))/50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() test_loss, test_mae = test(args,test_dataset,model,device) # p_acc = 100 * sum(p_acc_meter.value()[i, i] for i in range(settings['prop_bins'])) / p_acc_meter.value().sum() # print("Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} acc: {:.7f} props: loss {} mae {}".format(epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0], 100 * c_acc_meter.value(), p_loss_meter.value()[0],p_mae_meter.value()[0])) print("Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} props loss {} mae {}".format(epoch, n_loss_meter.value()[0], n_acc, p_loss_meter.value()[0], p_mae_meter.value()[0])) print("Test loss {} mae {}".format(test_loss, test_mae)) if (epoch + 1) % 100 == 0: init_lr = init_lr *0.9 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) # # info['n_loss'].append(n_loss_meter.value()[0]) # info['n_acc'].append(n_acc) # # info['c_loss'].append(c_loss_meter.value()[0]) # # info['c_acc'].append(100 * c_acc_meter.value()) # info['p_loss'].append(p_loss_meter.value()[0]) # info['p_mae'].append(p_mae_meter.value()[0]) return def test(args, test_dataset,model,device): test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher,shuffle=args.shuffle,num_workers=args.workers) # labels = test_dataset.prop loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, labels) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) labels = labels.to(device) _,_,res = model(g) res = res.squeeze() loss = loss_fn(res, labels) mae = MAE_fn(res, labels) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def get_preds(args,model,dataset,device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize*5, collate_fn=batcher,shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx,(mols,_) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings,dim=0) print('inference {}'.format(time.time()-time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 2000 args.batchsize = 32 args.use_tb = False args.dataset = 'qm9' args.device = 0 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.2 args.lr = 1e-3 print(args) embed_method = 'sch_embedding' settings = { 'cls_num':5000, 'cls_epochs':3, # clustering every 5epochs 'iters': 10, 'init_method':'random', 'prop_bins':25 } train_data_num = 5000 # load_path = '/home/jeffzhu/AL/datasets/models/wsch_g_gauss_1205_19_43.pkl' load_path = '/home/jeffzhu/AL/datasets/models/wsch_g_ae_ot_1208_09_56.pkl' logs_path = config.PATH+'/datasets/logs'+ time.strftime('/%m%d_%H_%M') model_save_path = config.PATH+'/datasets/models'+ time.strftime('/wsch_g_%m%d_%H_%M.pkl') print('model save path {} load path {}'.format(model_save_path, load_path)) train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'],'rb')), pickle.load(open(config.test_pkl['qm9'],'rb')) train_dataset, test_dataset = MoleDataset(mols=train_mols), MoleDataset(mols=test_mols) # train_part if embed_method is 'sch_embedding': embedding_model = SchEmbedding(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) #64 dim mols_embeddings = get_preds(args,embedding_model,train_dataset,torch.device(args.device)) elif embed_method is 'wsch_g': # embedding_model = WSchnet_N(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) # embedding_model.load_state_dict(torch.load(pre_model_path)) embedding_model = pickle.load(open(load_path, 'rb')) mols_embeddings = get_preds(args,embedding_model,train_dataset,torch.device(args.device)) else: raise ValueError # mols_embeddings = mols_embeddings.cpu() # data_ids = k_medoid(mols_embeddings, train_data_num, 10, show_stats=True) # data_ids = k_center(mols_embeddings,train_data_num) # print('data selection finished') # train_subset = MoleDataset(mols=[train_dataset.mols[i] for i in data_ids]) # # train_subset = MoleDataset(mols=random.sample(train_dataset.mols, train_data_num)) device = torch.device('cuda:'+str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path,comment='baseline_sch') else: writer = None # model = WSchnet_R(dim=128,n_conv=4,cutoff=30.0,cls_dim=settings['cls_num'],width=0.1,norm=True, output_dim=1,props_bins=settings['prop_bins']) # model = MM_WSchnet_R(dim=128,n_conv=4,cutoff=30.0,cls_dim=settings['cls_num'],width=0.1,norm=True, output_dim=1,mask_rate=0.2,props_bins=settings['prop_bins']) model = pickle.load(open(load_path,'rb')) # fix part of the model, first try the embedding layer for param in model.embedding_layer.parameters(): param.requires_grad = False # for param in model.conv_layers[:1].parameters(): # param.requires_grad = False optimizer = torch.optim.Adam(filter(lambda p:p.requires_grad,model.parameters()), lr=args.lr) # optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) if args.multi_gpu: model = DataParallel(model,device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args,settings,train_subset,test_dataset,model,optimizer, writer, device) pickle.dump(model,open(model_save_path,'wb')) if args.save_model: torch.save({'model_state_dict':model.state_dict(), 'optimizier_state_dict':optimizer.state_dict(), 'info':info, },config.save_model_path(args.dataset))
10,862
36.588235
279
py
AS_Molecule
AS_Molecule-master/pre_training/node_ptr.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * import numpy as np from pre_training.wsch import WSchnet_N def train(args, train_datset, test_dataset, model, optimizer, writer, device): print("start") train_loader = DataLoader(dataset=train_datset, batch_size=args.batchsize, collate_fn=batcher_n, shuffle=args.shuffle, num_workers=args.workers) test_loader = DataLoader(dataset=test_dataset, batch_size=args.batchsize, collate_fn=batcher_n, shuffle=args.shuffle, num_workers=args.workers) print(model) model.to(device) loss_fn = nn.CrossEntropyLoss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter(100) init_lr = args.lr info = {'n_loss': [], 'n_acc': []} for epoch in range(args.epochs): n_loss_meter.reset() n_acc_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) # Mask node features mask = torch.randint( 0, g.number_of_nodes(), [int(args.mask_n_ratio * g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 res = model(g).squeeze() n_pred_cls = torch.argmax(res, dim=1) n_loss = loss_fn(res[mask], label[mask]) optimizer.zero_grad() n_loss.backward() optimizer.step() n_loss_meter.add(n_loss.detach().item()) n_acc_meter.add(n_pred_cls, label) if idx % 50 == 0 and args.use_tb: acc = 100 * sum( n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() writer.add_scalar( 'n_train_loss', n_loss_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) writer.add_scalar( 'n_train_acc', acc, int((idx + 1 + epoch * len(train_loader)) / 50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) n_loss_test, n_acc_test = test(args, test_loader, model, device) acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() print( "Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} test: loss: {:.7f} acc: {:.7f}" .format(epoch, n_loss_meter.value()[0], acc, n_loss_test, n_acc_test)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(acc) return info def test(args, test_loader, model, device): model.eval() model.to(device) loss_fn = nn.CrossEntropyLoss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter(100) with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = label.to(device) # Mask node features mask = torch.randint( 0, g.number_of_nodes(), [int(args.mask_n_ratio * g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 res = model(g).squeeze() n_pred_cls = torch.argmax(res, dim=1) n_loss = loss_fn(res[mask], label[mask]) n_loss_meter.add(n_loss.detach().item()) n_acc_meter.add(n_pred_cls, label) n_loss_test = n_loss_meter.value()[0] n_acc_test = 100 * sum(n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() return n_loss_test, n_acc_test if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 20 args.batchsize = 64 args.use_tb = False args.dataset = 'qm9' args.device = 1 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.2 print(args) logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') model_save_path = config.PATH + '/datasets/models' + time.strftime( '/wsch_n_%m%d_%H_M.pkl') train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'], 'rb')), pickle.load( open(config.test_pkl['qm9'], 'rb')) train_dataset, test_dataset = SelfMolDataSet( mols=train_mols, level='n'), SelfMolDataSet(mols=test_mols, level='n') device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None model = WSchnet_N(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) optimizer = torch.optim.Adam(model.parameters(), lr=3e-4) if args.multi_gpu: model = DataParallel( model, device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args, train_dataset, test_dataset, model, optimizer, writer, device) pickle.dump(model, open(model_save_path, 'wb')) if args.save_model: torch.save( { 'model_state_dict': model.state_dict(), 'optimizier_state_dict': optimizer.state_dict(), 'info': info, }, config.save_model_path(args.dataset))
6,778
33.065327
94
py
AS_Molecule
AS_Molecule-master/pre_training/semi_supervised_learn.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle import torch.nn.functional as F import ot sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * import numpy as np from pre_training.sch_embeddings import SchEmbedding from pre_training.wsch import WSchnet_N, WSchnet_G, WSchnet, WSchnet_R, Semi_Schnet '''provide pre-trained model for transfer A AE like model first mask some nodes to reconstruct the features of the atoms then sample some edges to reconstruct the distance (divide to bins) to simulate a AE the edges number are n^2, however the degree of freedom is 3*n, we sample alpha* sqrt(n) ''' def train(args,settings,train_datset, test_dataset, model, data_ids,optimizer, writer,device): print("start") train_loader = DataLoader(dataset=train_datset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) # prepare labels p_labels = train_datset.prop p_labels = p_labels.to(device) print(model) model.set_mean_std(train_datset.mean,train_datset.std) model.to(device) loss_fn = nn.CrossEntropyLoss() loss_r = nn.MSELoss() loss_mae = nn.L1Loss() loss_meter = meter.AverageValueMeter() n_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() p_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter(100) # clustering num might be too big, do not use confusion matrix c_acc_meter = AccMeter(settings['cls_num']) p_mae_meter = meter.AverageValueMeter() e_acc_meter = meter.ConfusionMeter(150) e_loss_meter = meter.AverageValueMeter() init_lr = args.lr info = {'n_loss':[], 'n_acc':[], 'c_loss':[], 'c_acc':[], 'p_loss': [], 'p_mae': [] } # TODO: For edge labeling (transform a edge to discrete label, use W|h1 - h2|) edge_bins = torch.linspace(0,30,150).to(device) # 0.2 per bin # node_classifier, edge_classifier = nn.Linear(64,100), nn.Linear(64,150) # node_classifier.to(device), edge_classifier.to(device) # # optimal transport setup Q = 0 K = settings['cls_num'] N = len(train_datset) # uniform distribution q = torch.ones(K) / K p = torch.ones(N) / N C = np.ones([N, K]) * np.log(K) / N # prob_tensor (cost function) Q = np.ones([N, K]) / (K * N) # the tag is a prob distribution cls_tags = torch.Tensor(np.argmax(Q,axis=1)).to(device) # # TODO: For Test # # Now I replace it by a normal distribution 4 is decided by 100000*Gauss(4)~10 # q = np.exp(-(np.linspace(-4,4,K)**2)/2)/(np.sqrt(2*np.pi)) # q = q / q.sum() # p = torch.ones(N) / N # # C = np.ones([N, K])* np.log(K) / N # cost matrix # Q = np.copy(np.tile(q,(N, 1))) / N # joint distribution for epoch in range(args.epochs): loss_meter.reset() n_loss_meter.reset() c_loss_meter.reset() p_loss_meter.reset() n_acc_meter.reset() c_acc_meter.reset() p_mae_meter.reset() e_acc_meter.reset() e_loss_meter.reset() model.train() # prepare pesudo labels via k means if epoch % settings['cls_epochs'] == 1 and settings['ot_loss']: time0 = time.time() Q = ot.sinkhorn(p, q, C, 0.04) # shape dataset_num*cls_num ...takes 40s~250s on cpu print('optimal transport solved: {}'.format(time.time() - time0)) if epoch % settings['pesudo_epochs'] == 0: p_labels = get_pesudo_labels(args,model,train_datset,data_ids,device) for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) atom, atom_preds, edge_preds, (src, dst, edge_ids), cls_preds, embeddings_g, prop_preds = model(g) # sampling edges Now it is confused whether to mask these edges or simply reconstruct them edge_dist = torch.clone(g.edata['distance'][edge_ids]).requires_grad_(False) edge_labels = torch.argmin(torch.abs(edge_dist-edge_bins),dim=1).long() node_labels = n_label[src] # make pesudo labels vis optimal transport cls_labels = torch.tensor(np.argmax(Q[list(ids)],axis=1), requires_grad=False).to(device).long() n_pred_cls = torch.argmax(atom_preds, dim=1) e_pred_cls = torch.argmax(edge_preds,dim=1) c_pred_cls = torch.argmax(cls_preds, dim=1) cls_logits = torch.log(F.softmax(cls_preds,dim=1)) n_loss = loss_fn(atom_preds, node_labels) e_loss = loss_fn(edge_preds,edge_labels) c_loss = loss_fn(cls_preds, cls_labels) p_loss = loss_r(prop_preds.squeeze(), p_labels[list(ids)]) # squeeze is really important p_mae = loss_mae(prop_preds.squeeze(),p_labels[list(ids)]) loss = n_loss + e_loss + 1e4 * p_loss optimizer.zero_grad() loss.backward() optimizer.step() C[idx*args.batchsize:idx*args.batchsize+len(mols)] = - cls_logits.detach().cpu().numpy() loss_meter.add(loss.detach().item()) n_loss_meter.add(n_loss.detach().item()) # total loss c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, node_labels) c_acc_meter.add(c_pred_cls, cls_labels) p_loss_meter.add(p_loss.detach().item()) p_mae_meter.add(p_mae.detach().item()) e_acc_meter.add(e_pred_cls,edge_labels) e_loss_meter.add(e_loss.detach().item()) if idx%50 == 0 and args.use_tb: acc = 100*sum(n_acc_meter.value()[i,i] for i in range(10))/n_acc_meter.value().sum() writer.add_scalar('n_train_loss',n_loss_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) writer.add_scalar('n_train_acc',acc,int((idx+1+epoch*len(train_loader))/50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() e_acc = 100 * sum(e_acc_meter.value()[i, i] for i in range(150)) / e_acc_meter.value().sum() # c_acc = 100 * sum(c_acc_meter.value()[i, i] for i in range(150)) / c_acc_meter.value().sum() test_loss, test_mae = test(args,test_dataset,model,device) print("Epoch {:2d}, training: loss: {:.7f}, node loss {} acc: {:.7f} edge loss {} acc {} self-clustering: loss: {:.7f} props loss {} mae {}".format(epoch, loss_meter.value()[0],n_loss_meter.value()[0], n_acc,e_loss_meter.value()[0] ,e_acc,c_loss_meter.value()[0],p_loss_meter.value()[0], p_mae_meter.value()[0])) print("Test loss {} mae {}".format(test_loss, test_mae)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(n_acc) info['c_loss'].append(c_loss_meter.value()[0]) info['c_acc'].append(100 * c_acc_meter.value()) info['p_loss'].append(p_loss_meter.value()[0]) info['p_mae'].append(p_mae_meter.value()[0]) return info def test(args, test_dataset,model,device): test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) labels = test_dataset.prop loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() with torch.no_grad(): for idx, (mols, n_label, ids) in enumerate(test_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) label = labels[list(ids)].to(device) output = model(g) res = output[-1].squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def get_pesudo_labels(args,model,dataset,data_ids,device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize*5, collate_fn=batcher_g,shuffle=False, num_workers=args.workers) model.to(device) model.set_mean_std(dataset.prop[data_ids].mean(),dataset.prop[data_ids].std()) p_labels = [] with torch.no_grad(): for idx,(mols,_,_) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) output = model(g) p_labels.append(output[-1].squeeze()) p_labels = torch.cat(p_labels,dim=0) p_labels[data_ids] = dataset.prop[data_ids].to(device) print('get pesudo labels {}'.format(time.time()-time0)) return p_labels def get_preds(args,model,dataset,device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize*5, collate_fn=batcher,shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx,(mols,_) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings,dim=0) print('inference {}'.format(time.time()-time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 40 args.batchsize = 64 args.use_tb = False args.dataset = 'qm9' args.device = 1 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.2 print(args) settings = { 'cls_num':2000, 'cls_epochs':4, # clustering every 5epochs 'iters': 10, 'init_method':'random', 'prop_bins':25, 'edge_sampling_rate':0.2, 'ot_loss':False, 'pesudo_epochs':2, } train_data_num = 10000 embed_method = 'other' # load_path = '/home/jeffzhu/AL/datasets/models/wsch_g_gauss_1205_19_43.pkl' load_path = '/home/jeffzhu/AL/datasets/models/wsch_g_ae_ot_1207_11_52.pkl' logs_path = config.PATH+'/datasets/logs'+ time.strftime('/%m%d_%H_%M') model_save_path = config.PATH+'/datasets/models'+ time.strftime('/wsch_g_ae_ot_%m%d_%H_%M.pkl') print('model save path {}'.format(model_save_path)) train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'],'rb')), pickle.load(open(config.test_pkl['qm9'],'rb')) train_dataset, test_dataset = SelfMolDataSet(mols=train_mols,level='g'), SelfMolDataSet(mols=test_mols,level='g') # train_part # train_dataset = SelfMolDataSet(mols=random.sample(train_dataset.mols, train_data_num),level='g') # train_part if embed_method is 'sch_embedding': embedding_model = SchEmbedding(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) # 64 dim mols_embeddings = get_preds(args, embedding_model, train_dataset, torch.device(args.device)) elif embed_method is 'wsch_g': # embedding_model = WSchnet_N(dim=96, n_conv=4, cutoff=30.0, width=0.1, norm=True, output_dim=1) # embedding_model.load_state_dict(torch.load(pre_model_path)) embedding_model = pickle.load(open(load_path, 'rb')) mols_embeddings = get_preds(args, embedding_model, train_dataset, torch.device(args.device)) else: pass # mols_embeddings = mols_embeddings.cpu() # data_ids = k_medoid(mols_embeddings, train_data_num, 10, show_stats=True) # data_ids = k_center(mols_embeddings,train_data_num) # print('data selection finished') data_ids = random.sample(range(len(train_dataset)),train_data_num) device = torch.device('cuda:'+str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path,comment='baseline_sch') else: writer = None # model = WSchnet_R(dim=128,n_conv=4,cutoff=30.0,cls_dim=settings['cls_num'],width=0.1,norm=True, output_dim=1,props_bins=settings['prop_bins']) model = Semi_Schnet(dim=128,n_conv=4,cutoff=30.0,cls_dim=settings['cls_num'],width=0.1,norm=True, output_dim=1,edge_bins=150,mask_n_ratio=args.mask_n_ratio,mask_msg_ratio=0,props_bins=settings['prop_bins']) optimizer = torch.optim.Adam(model.parameters(), lr=2e-4) if args.multi_gpu: model = DataParallel(model,device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args,settings,train_dataset,test_dataset,model,data_ids,optimizer, writer, device) pickle.dump(model,open(model_save_path,'wb')) if args.save_model: torch.save({'model_state_dict':model.state_dict(), 'optimizier_state_dict':optimizer.state_dict(), 'info':info, },config.save_model_path(args.dataset))
13,797
36.906593
323
py
AS_Molecule
AS_Molecule-master/pre_training/w_ptr_part.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * import numpy as np from pre_training.wsch import WSchnet_N, WSchnet_G, WSchnet '''Jointly self-training with node level masking and clustering center labeling''' def train(args,settings,train_datset, model,optimizer, writer,device): print("start") train_loader = DataLoader(dataset=train_datset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) # test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) # prepare labels p_labels = (train_datset.prop - train_datset.mean) / train_datset.std p_labels = (1 + torch.erf(p_labels / 2 ** 0.5)) / 2 # transform it to (0,1), constant must be bigger than 1e-7 bin_gap = 1 / settings['prop_bins'] p_labels = (p_labels / (bin_gap+1e-7)).long() p_labels = p_labels.to(device) print(model) model.to(device) loss_fn = nn.CrossEntropyLoss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() p_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter(100) # clustering num might be too big, do not use confusion matrix c_acc_meter = AccMeter(settings['cls_num']) p_acc_meter = meter.ConfusionMeter(settings['prop_bins']) init_lr = args.lr info = {'n_loss':[], 'n_acc':[], 'c_loss':[], 'c_acc':[], 'p_loss': [], 'p_acc': [] } cls_tags = 0 for epoch in range(args.epochs): n_loss_meter.reset() c_loss_meter.reset() p_loss_meter.reset() n_acc_meter.reset() c_acc_meter.reset() p_acc_meter.reset() model.train() # prepare pesudo labels via k means if epoch % settings['cls_epochs'] == 0: feats_all = get_preds(args,model,train_datset,device) if epoch == 0: cls_tags = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=settings['init_method'],show_stats=True) else: cls_tags = k_means(feats_all.cpu(),settings['cls_num'],settings['iters'],inits=cls_tags,show_stats=True) for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) # Mask node features mask = torch.randint(0,g.number_of_nodes(),[int(args.mask_n_ratio*g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 # make pesudo labels vis k means cls_labels = cls_tags[list(ids)].to(device) atom_preds, cls_preds, prop_preds = model(g) n_pred_cls = torch.argmax(atom_preds, dim=1) c_pred_cls = torch.argmax(cls_preds, dim=1) p_pred_cls = torch.argmax(prop_preds, dim=1) n_loss = loss_fn(atom_preds[mask], n_label[mask]) c_loss = loss_fn(cls_preds,cls_labels) p_loss = loss_fn(prop_preds, p_labels[list(ids)]) loss = c_loss + n_loss + p_loss optimizer.zero_grad() loss.backward() optimizer.step() n_loss_meter.add(n_loss.detach().item()) c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, n_label) c_acc_meter.add(c_pred_cls, cls_labels) p_loss_meter.add(p_loss.detach().item()) p_acc_meter.add(p_pred_cls, p_labels[list(ids)]) if idx%50 == 0 and args.use_tb: acc = 100*sum(n_acc_meter.value()[i,i] for i in range(10))/n_acc_meter.value().sum() writer.add_scalar('n_train_loss',n_loss_meter.value()[0],int((idx+1+epoch*len(train_loader))/50)) writer.add_scalar('n_train_acc',acc,int((idx+1+epoch*len(train_loader))/50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) n_acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(100)) / n_acc_meter.value().sum() p_acc = 100 * sum(p_acc_meter.value()[i, i] for i in range(settings['prop_bins'])) / p_acc_meter.value().sum() print( "Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} acc: {:.7f} props: loss {} acc {}".format( epoch, n_loss_meter.value()[0], n_acc, c_loss_meter.value()[0], 100 * c_acc_meter.value(), p_loss_meter.value()[0],p_acc)) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(n_acc) info['c_loss'].append(c_loss_meter.value()[0]) info['c_acc'].append(100 * c_acc_meter.value()) info['p_loss'].append(p_loss_meter.value()[0]) info['p_acc'].append(p_acc) return info def get_preds(args,model,dataset,device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize*5, collate_fn=batcher_g,shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx,(mols,_,_) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings,dim=0) print('inference {}'.format(time.time()-time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 200 args.batchsize = 64 args.use_tb = False args.dataset = 'qm9' args.device = 0 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.2 print(args) settings = { 'cls_num':5000, 'cls_epochs':1, # clustering every 5epochs 'iters': 10, 'init_method':'k_center', 'prop_bins':25 } print(time.strftime('%m%d_%H_%M')) logs_path = config.PATH+'/datasets/logs'+ time.strftime('/%m%d_%H_%M') model_save_path = config.PATH+'/datasets/models'+ time.strftime('/wsch_g_%m%d_%H_%M.pkl') train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'],'rb')), pickle.load(open(config.test_pkl['qm9'],'rb')) train_dataset, test_dataset = SelfMolDataSet(mols=train_mols,level='g'), SelfMolDataSet(mols=test_mols,level='g') device = torch.device('cuda:'+str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path,comment='baseline_sch') else: writer = None model = WSchnet(dim=256,n_conv=4,cutoff=30.0,cls_dim=settings['cls_num'],width=0.1,norm=True, output_dim=1,props_bins=settings['prop_bins']) optimizer = torch.optim.Adam(model.parameters(), lr=2e-4) if args.multi_gpu: model = DataParallel(model,device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args,settings,train_dataset,model,optimizer, writer, device) pickle.dump(model,open(model_save_path,'wb')) if args.save_model: torch.save({'model_state_dict':model.state_dict(), 'optimizier_state_dict':optimizer.state_dict(), 'info':info, },config.save_model_path(args.dataset))
8,188
35.887387
144
py
AS_Molecule
AS_Molecule-master/pre_training/cls_ptr.py
#!usr/bin/env python3 # -*- coding:utf-8 -*- import argparse import torch import sys import torch.nn as nn from torch.utils.data import DataLoader from torchnet import meter from tensorboardX import SummaryWriter import time import pickle sys.path.append('..') from utils.funcs import * from base_model.schmodel import SchNetModel from config import * import numpy as np from pre_training.wsch import WSchnet_N, WSchnet_G '''Jointly self-training with node level masking and clustering center labeling''' def train(args, settings, train_datset, model, optimizer, writer, device): print("start") train_loader = DataLoader(dataset=train_datset, batch_size=args.batchsize, collate_fn=batcher_g, shuffle=args.shuffle, num_workers=args.workers) # test_loader= DataLoader(dataset=test_dataset,batch_size=args.batchsize,collate_fn=batcher_g,shuffle=args.shuffle,num_workers=args.workers) print(model) model.to(device) loss_fn = nn.CrossEntropyLoss() # MAE_fn = nn.L1Loss() n_loss_meter = meter.AverageValueMeter() c_loss_meter = meter.AverageValueMeter() n_acc_meter = meter.ConfusionMeter( 100) # clustering num might be too big, do not use confusion matrix c_acc_meter = AccMeter(settings['cls_num']) init_lr = args.lr info = {'n_loss': [], 'n_acc': [], 'c_loss': [], 'c_acc': []} cls_tags = 0 for epoch in range(args.epochs): n_loss_meter.reset() c_loss_meter.reset() n_acc_meter.reset() c_acc_meter.reset() model.train() # prepare pesudo labels via k means if epoch % settings['cls_epochs'] == 0: feats_all = get_preds(args, model, train_datset, device) if epoch == 0: cls_tags = k_means(feats_all.cpu(), settings['cls_num'], settings['iters'], inits=settings['init_method'], show_stats=True) else: cls_tags = k_means( feats_all.cpu(), settings['cls_num'], settings['iters'], inits='random', #use random tags show_stats=True) model.re_init_head() for idx, (mols, n_label, ids) in enumerate(train_loader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) n_label = n_label.to(device) # Mask node features mask = torch.randint( 0, g.number_of_nodes(), [int(args.mask_n_ratio * g.number_of_nodes())]) g.ndata['nodes'][mask] = 0 # make pesudo labels vis k means cls_labels = cls_tags[list(ids)].to(device) atom_preds, cls_preds = model(g) n_pred_cls = torch.argmax(atom_preds, dim=1) c_pred_cls = torch.argmax(cls_preds, dim=1) n_loss = loss_fn(atom_preds[mask], n_label[mask]) # n_loss = torch.Tensor([0]).to(device) c_loss = loss_fn(cls_preds, cls_labels) loss = c_loss + n_loss optimizer.zero_grad() loss.backward() optimizer.step() # n_loss_meter.add(n_loss.detach().item()) c_loss_meter.add(c_loss.detach().item()) n_acc_meter.add(n_pred_cls, n_label) c_acc_meter.add(c_pred_cls, cls_labels) if idx % 50 == 0 and args.use_tb: acc = 100 * sum( n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() writer.add_scalar( 'n_train_loss', n_loss_meter.value()[0], int((idx + 1 + epoch * len(train_loader)) / 50)) writer.add_scalar( 'n_train_acc', acc, int((idx + 1 + epoch * len(train_loader)) / 50)) print('training loss {} acc {}'.format(n_loss_meter.value()[0], acc)) # n_loss_test, n_acc_test= test(args,test_loader,model,device) acc = 100 * sum(n_acc_meter.value()[i, i] for i in range(10)) / n_acc_meter.value().sum() print( "Epoch {:2d}, training: loss: {:.7f}, acc: {:.7f} self-clustering: loss: {:.7f} acc: {:.7f}" .format(epoch, n_loss_meter.value()[0], acc, c_loss_meter.value()[0], 100 * c_acc_meter.value())) if (epoch + 1) % 100 == 0: init_lr = init_lr / 1 for param_group in optimizer.param_groups: param_group['lr'] = init_lr print('current learning rate: {}'.format(init_lr)) info['n_loss'].append(n_loss_meter.value()[0]) info['n_acc'].append(acc) info['c_loss'].append(c_loss_meter.value()[0]) info['c_acc'].append(100 * c_acc_meter.value()) return info def get_preds(args, model, dataset, device): time0 = time.time() dataloader = DataLoader(dataset=dataset, batch_size=args.batchsize * 5, collate_fn=batcher_g, shuffle=False, num_workers=args.workers) model.to(device) # model.set_mean_std(dataset.mean,dataset.std) embeddings = [] with torch.no_grad(): for idx, (mols, _, _) in enumerate(dataloader): g = dgl.batch([mol.ful_g for mol in mols]) g.to(device) embedding = model.embed_g(g) embeddings.append(embedding) embeddings = torch.cat(embeddings, dim=0) print('inference {}'.format(time.time() - time0)) return embeddings if __name__ == "__main__": config = Global_Config() args = make_args() if args.use_default is False: args.epochs = 21 args.batchsize = 64 args.use_tb = False args.dataset = 'qm9' args.device = 0 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.mask_n_ratio = 0.2 print(args) settings = { 'cls_num': 5000, 'cls_epochs': 3, # clustering every 5epochs 'iters': 10, 'init_method': 'random' } logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') model_save_path = config.PATH + '/datasets/models' + time.strftime( '/wsch_g_%m%d_%H_%M.pkl') train_mols, test_mols = pickle.load(open(config.train_pkl['qm9'], 'rb')), pickle.load( open(config.test_pkl['qm9'], 'rb')) train_dataset, test_dataset = SelfMolDataSet( mols=train_mols, level='g'), SelfMolDataSet(mols=test_mols, level='g') device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None model = WSchnet_G(dim=96, n_conv=4, cutoff=30.0, cls_dim=settings['cls_num'], width=0.1, norm=True, output_dim=1) optimizer = torch.optim.Adam(model.parameters(), lr=3e-4) if args.multi_gpu: model = DataParallel( model, device_ids=[i for i in range(torch.cuda.device_count())]) info = train(args, settings, train_dataset, model, optimizer, writer, device) pickle.dump(model, open(model_save_path, 'wb')) if args.save_model: torch.save( { 'model_state_dict': model.state_dict(), 'optimizier_state_dict': optimizer.state_dict(), 'info': info, }, config.save_model_path(args.dataset))
8,259
34.757576
144
py
AS_Molecule
AS_Molecule-master/rd_learn/rd_al.py
from utils.funcs import * import numpy as np import random import torch.nn as nn from torchnet import meter from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from config import * from base_model.sch import SchNetModel from copy import deepcopy def random_data_sampler(MaDataset, label_rate): rd_index = random.sample(range(len(MaDataset)), int(label_rate * len(MaDataset))) subdataset = None if MaDataset.mols: new_mols = [MaDataset.mols[i] for i in rd_index] subdataset = MoleDataset(mols=new_mols) elif MaDataset.datas: new_datas = [MaDataset.datas[i] for i in rd_index] subdataset = MoleDataset(datas=new_datas) subdataset.build() else: assert 'Not initialized dataset' return subdataset def test(args, test_set, model, device): loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() model.eval() model.to(device) test_loader = DataLoader(dataset=test_set, batch_size=args.batchsize, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) model.set_mean_std(test_set.mean, test_set.std) with torch.no_grad(): for idx, (mols, label) in enumerate(test_loader): label = label.to(device) res = model(mols).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) return mse_meter.value()[0], mae_meter.value()[0] def train(args, train_dataset, model, optimizer_, writer, device=torch.device('cpu')): train_loader = DataLoader(dataset=train_dataset, batch_size=args.batchsize, collate_fn=batcher, shuffle=args.shuffle, num_workers=args.workers) print('start training with label numbers {}'.format(len(train_dataset))) print('mean {} std {}'.format(train_dataset.mean.item(), train_dataset.std.item())) # if model.name in ["MGCN", "SchNet"]: model.set_mean_std(train_dataset.mean, train_dataset.std) model.to(device) optimizer = optimizer_(model.parameters(), lr=args.lr) loss_fn = nn.MSELoss() MAE_fn = nn.L1Loss() mse_meter = meter.AverageValueMeter() mae_meter = meter.AverageValueMeter() info = {'train_loss': [], 'train_mae': []} for epoch in range(args.epochs): mse_meter.reset() mae_meter.reset() model.train() for idx, (mols, label) in enumerate(train_loader): label = label.to(device) res = model(mols).squeeze() loss = loss_fn(res, label) mae = MAE_fn(res, label) optimizer.zero_grad() loss.backward() optimizer.step() mae_meter.add(mae.detach().item()) mse_meter.add(loss.detach().item()) print("Epoch {:2d}, training: loss: {:.7f}, mae: {:.7f}".format( epoch, mse_meter.value()[0], mae_meter.value()[0])) info['train_loss'].append(mse_meter.value()[0]) info['train_mae'].append(mae_meter.value()[0]) # if args.use_tb: # writer.add_scalar('testing_loss',loss_test,epoch) # writer.add_scalar('testing_mae',mae_test,epoch) return info def rd_active_learning(args, config, train_set, test_set, model, optimizer_, label_rates, writer, device): # label_rates = np.arange(0,100,step=5)/100 ac_info = [] #[tuple(train mse, train mae, test mse, test mae)] #zero model_learner = deepcopy(model) test_mse, test_mae = test(args, test_set, model_learner, device) ac_info.append((0.0, 0.0, test_mse, test_mae)) print('test with no training {}'.format(test_mae)) for i in range(1, len(label_rates)): model_learner = deepcopy(model) train_subset = random_data_sampler(train_set, label_rates[i]) train_info = train(args, train_subset, model_learner, optimizer_, writer, device) test_mse, test_mae = test(args, test_set, model_learner, device) ac_info.append((train_info['train_loss'][-1], train_info['train_mae'][-1], test_mse, test_mae)) print('labels number {} test mae {}'.format(len(train_subset), test_mae)) if args.use_tb: writer.add_scalar('test_mae', test_mae, i) if args.save_model: torch.save( { 'info_train': train_info, 'test_mae': test_mae, 'model': model_learner.state_dict() }, config.save_model_path(args.dataset + 'rd_ac')) ac_result = dict(zip(label_rates, ac_info)) return ac_result if __name__ == '__main__': config = Global_Config() args = make_args() if args.use_default is False: args.batchsize = 64 args.epochs = 300 args.use_tb = True args.dataset = 'qm9' args.device = 1 args.save_model = True args.workers = 0 args.shuffle = True args.multi_gpu = False args.prop_name = 'homo' args.lr = 1e-3 print(args) logs_path = config.PATH + '/datasets/logs' + time.strftime('/%m%d_%H_%M') result_path = config.PATH + '/datasets/rd/' + args.dataset + time.strftime( '_%m%d_%H_%M.txt') train_set, test_set = MoleDataset(prop_name=args.prop_name), MoleDataset( prop_name=args.prop_name) train_set.load_mol(config.train_pkl[args.dataset]), test_set.load_mol( config.test_pkl[args.dataset]) device = torch.device( 'cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu') # th.set_default_tensor_type(device) if args.use_tb: writer = SummaryWriter(log_dir=logs_path, comment='baseline_sch') else: writer = None model = SchNetModel(dim=32, n_conv=4, cutoff=5.0, width=0.5, norm=True, output_dim=1, device=device) print(model) optimizer = torch.optim.Adam label_rates = np.arange(75, 105, 5) / 100 #the first will not be trained results = rd_active_learning(args, config, train_set, test_set, model, optimizer, label_rates, writer, device) with open(result_path, 'w') as fp: for key in results.keys(): fp.write( str(key) + '\t' + ''.join([str(i) + '\t' for i in results[key]]) + '\n') print('test success')
7,055
33.930693
79
py
NEDMP
NEDMP-main/structure_generalization.py
import argparse import numpy as np import pickle as pkl from collections import defaultdict import torch from torch.utils import data from src.utils.dataset import graph_dataset from src.utils.utils import aligning, L1_error from src.model.model import NodeGNN, NEDMP def eval(model, loader): # Eval model.eval() test_predict = [] test_label = [] dmp_predict = [] for i, inputs in enumerate(loader): """ inputs = *, simu_marginal, dmp_marginal, adj """ data4model, label, dmp = inputs[:-2], inputs[-2], inputs[-1] dmp = aligning(label, dmp).cpu().numpy() # 1. forward pred, _ = model(data4model) # 2. loss: label and pred both have size [T, N, K] pred = aligning(label, pred) pred = np.exp(pred.detach().cpu().numpy()) # 3. record training L1 error test_predict.append(pred) test_label.append(label.detach().cpu().numpy()) dmp_predict.append(dmp) model_l1 = L1_error(test_predict, test_label) dmp_l1 = L1_error(dmp_predict, test_label) return model_l1, dmp_l1 if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--model", type=str, default="gnn") parser.add_argument("--num_status", type=int, default=3) parser.add_argument("--diff", type=str, default="SIR") parser.add_argument("--data", type=str, default="syn") parser.add_argument("--cuda", type=int, default=-1) args = parser.parse_args() if args.cuda == -1: device = torch.device("cpu") else: device = torch.device("cuda:{}".format(args.cuda)) if args.model == "gnn": model = NodeGNN(node_feat_dim = 32, edge_feat_dim = 32, message_dim = 32, number_layers = 30, num_status = 3, device = device) elif args.model == "nedmp": model = NEDMP(hid_dim = 32, number_layers = 30, device = device) if args.data == "syn": data_names = ["tree", "grid", "barbell", "regular_graph", "er03", "er05", "er08", "complete"] model_paths = ["./data/synthetic/{}/train_data/{}_200.pkl_{}_{}.pt".format(name, args.diff, args.model, args.diff) for name in data_names] data_paths = ["./data/synthetic/{}/train_data/{}_200.pkl".format(name, args.diff) for name in data_names] elif args.data == "real": data_names = ["dolphins", "fb-food", "fb-social", "norwegain", "openflights", "top-500"] model_paths = ["./data/realnets/{}/train_data/{}_150.pkl_{}_{}.pt".format(name, args.diff, args.model, args.diff) for name in data_names] data_paths = ["./data/realnets/{}/train_data/{}_150.pkl".format(name, args.diff) for name in data_names] preds = defaultdict(list) dmps = defaultdict(list) for mp, model_name in zip(model_paths, data_names): model.load_state_dict(torch.load(mp)) tmp_pred = [] tmp_dmps = [] for dp in data_paths: # dataset loaded_data = graph_dataset(root=dp, device=device, nedmp = args.model == "nedmp") test_pred_l1, dmp_l1 = eval(model, loaded_data) tmp_pred.append(test_pred_l1) tmp_dmps.append(dmp_l1) preds[model_name] = tmp_pred dmps[model_name] = tmp_dmps print(tmp_pred) print(tmp_dmps) print("*"*72) if args.data == "syn": with open("./data/synthetic/structure_generalization_{}.pkl".format(args.model), "wb") as f: pkl.dump([preds, dmps], f) elif args.data == "real": with open("./data/realnets/structure_generalization_{}.pkl".format(args.model), "wb") as f: pkl.dump([preds, dmps], f)
3,845
38.244898
146
py
NEDMP
NEDMP-main/train.py
import time import argparse import numpy as np from tqdm import tqdm import pickle as pkl from functools import partial import torch from torch import optim from torch.utils.data import DataLoader from src.utils.dataset import graph_dataset from src.utils.utils import aligning, L1_error from src.model.model import NodeGNN, NEDMP torch.manual_seed(42) def train(model, optimizer, loader): # Train model.train() train_loss = 0 train_predict = [] train_label = [] for i, inputs in tqdm(enumerate(loader)): optimizer.zero_grad() """ inputs = *, simu_marginal, dmp_marginal, adj """ data4model, label = inputs[:-2], inputs[-2] pred, _ = model(data4model) pred = aligning(label, pred) loss = model.loss_function(pred, label) loss.backward() optimizer.step() train_loss += loss.item() pred = np.exp(pred.detach().cpu().numpy()) train_predict.append(pred) train_label.append(label.detach().cpu().numpy()) train_loss /= len(loader) train_pred_l1, _ = L1_error(train_predict, train_label) return train_loss, train_pred_l1 def eval(model, loader, testing=False, saving=False): # Eval model.eval() device = model.device if not testing: val_predict = [] val_label = [] for i, inputs in enumerate(loader): """ inputs = *, simu_marginal, dmp_marginal, adj """ data4model, label = inputs[:-2], inputs[-2] # 1. forward pred, _ = model(data4model) # 2. loss: label and pred both have size [T, N, K] #print("Train Shape: ", label.shape[0], pred.shape[0]) pred = aligning(label, pred) # 3. record training L1 error pred = np.exp(pred.detach().cpu().numpy()) val_predict.append(pred) val_label.append(label.detach().cpu().numpy()) val_pred_l1, _ = L1_error(val_predict, val_label) return val_pred_l1 else: test_predict = [] test_label = [] dmp_predict = [] for i, inputs in enumerate(loader): """ inputs = *, simu_marginal, dmp_marginal, adj """ data4model, label, dmp = inputs[:-2], inputs[-2], inputs[-1] dmp = aligning(label, dmp).cpu().numpy() # 1. forward pred, _ = model(data4model) # 2. loss: label and pred both have size [T, N, K] pred = aligning(label, pred) pred = np.exp(pred.detach().cpu().numpy()) # 3. record training L1 error test_predict.append(pred) test_label.append(label.detach().cpu().numpy()) dmp_predict.append(dmp) model_l1 = L1_error(test_predict, test_label) dmp_l1 = L1_error(dmp_predict, test_label) if saving: return test_predict, test_label, dmp_predict, model_l1, dmp_l1 else: return model_l1, dmp_l1 if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--node_feat_dim", type=int, default=32) parser.add_argument("--edge_feat_dim", type=int, default=32) parser.add_argument("--message_dim", type=int, default=32) parser.add_argument("--cuda_id", type=int, default=0, help="-1 for cpu") parser.add_argument("--number_layers", type=int, default=30) parser.add_argument("--lr", type=float, default=1e-2) parser.add_argument("--batch_size", type=int, default=1) parser.add_argument("--factor", type=float, default=0.5, help="LR reduce factor") parser.add_argument("--patience", type=int, default=5, help="patience of LR reduce schema") parser.add_argument("--data_path", type=str, default=None) parser.add_argument("--train_ratio", type=float, default=0.6) parser.add_argument("--val_ratio", type=float, default=0.2) parser.add_argument("--model", type=str, default="gnn") parser.add_argument("--num_status", type=int, default=3) parser.add_argument("--early_stop", type=int, default=10) parser.add_argument("--testing", action="store_true") parser.add_argument("--diff", type=str, default="SIR") parser.add_argument("--tmp", type=str, default="") args = parser.parse_args() # print args print("=== Setting Args ===") for arg, value in vars(args).items(): print("{:>20} : {:<20}".format(arg, value)) if args.cuda_id >=0 : device = torch.device("cuda:{}".format(args.cuda_id)) else: device = torch.device("cpu") if args.model == "gnn": model = NodeGNN(node_feat_dim=args.node_feat_dim, edge_feat_dim=args.edge_feat_dim, message_dim=args.message_dim, number_layers=args.number_layers, num_status=args.num_status, device=device) elif args.model == "nedmp": model = NEDMP(hid_dim=args.message_dim, number_layers=args.number_layers, device=device) # optimizer optimizer = optim.Adamax(model.parameters(), lr=args.lr) scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, "min", factor=args.factor, patience=args.patience, verbose=True) # dataset loaded_data = graph_dataset(root=args.data_path, device=device, nedmp = args.model == "nedmp") train_size = int(args.train_ratio*len(loaded_data)) val_size = int(args.val_ratio*len(loaded_data)) test_size = len(loaded_data) - train_size - val_size train_data, val_data, test_data = torch.utils.data.random_split(loaded_data, [train_size, val_size, test_size], generator=torch.Generator().manual_seed(42)) print("DataSize: Train={} Val={} Test={}".format(len(train_data), len(val_data), len(test_data))) model_save_path = args.data_path+"_{}_{}{}.pt".format(args.model, args.diff, args.tmp) test_save_path = args.data_path+"_{}_{}{}_testResults.pkl".format(args.model, args.diff, args.tmp) # Training if not args.testing: train_time = time.time() best_eval_l1 = 1E+10 early_stop = 0 # Traing and Eval for epoch in range(100): # Train train_loss, train_pred_l1 = train(model, optimizer, train_data) # Eval eval_pred_l1 = eval(model, val_data) print(" Epoch={:<3}, Loss={:<.3f} || Train L1 : model={:.3f} || Eval L1 : model={:.3f} || Time = {:.1f}s".format(epoch, train_loss, train_pred_l1, eval_pred_l1, time.time()-train_time)) if eval_pred_l1<best_eval_l1: early_stop = 0 best_eval_l1 = eval_pred_l1 torch.save(model.state_dict(), model_save_path) # Test test_pred_l1, dmp_l1 = eval(model, test_data, testing=True) print("-"*72) print("Test: L1 = {:.3f} Base = {:.3f}".format(test_pred_l1[0], dmp_l1[0])) print("-"*72) else: early_stop += 1 if early_stop > args.early_stop: break scheduler.step(eval_pred_l1) # Test model.load_state_dict(torch.load(model_save_path)) test_pred_l1, dmp_l1 = eval(model, test_data, testing=True) print("Final Test: L1 = {:.3f} Base = {:.3f}".format(test_pred_l1[0], dmp_l1[0])) else: # Test device = "cpu" if args.cuda_id==-1 else "cuda:{}".format(args.cuda_id) model.load_state_dict(torch.load(model_save_path, map_location=device)) test_predict, test_label, dmp_predict, test_pred_l1, dmp_l1 = eval(model, test_data, testing=True, saving=True) print("Final Test: L1 = {:.3f} $\\pm$ {:.3f} Base = {:.3f} \\pm {:.3f} ".format(test_pred_l1[0], test_pred_l1[1], dmp_l1[0], dmp_l1[1])) with open(test_save_path, "wb") as f: pkl.dump({"test_predict": test_predict, "test_label": test_label, "dmp_predict": dmp_predict}, f)
8,214
39.668317
197
py
NEDMP
NEDMP-main/src/utils/utils.py
# -*- encoding: utf-8 -*- ''' @File : utils.py @Time : 2021/04/01 17:04:49 @Author : Fei gao @Contact : feig@mail.bnu.edu.cn BNU, Beijing, China ''' import scipy.sparse as sp import numpy as np import torch import networkx as nx def line_graph(edge_index, N, E): """generate the line graph from edge_index Args: edge_index ([type]): [E, 2] N ([type]): number of nodes E ([type]): number of directed edges Returns: [type]: [description] """ snode2edge = np.zeros((N, E)) tnode2edge = np.zeros((N, E)) edge2tnode = np.zeros((E, N)) NB_matrix = np.zeros((E, E)) assert edge_index.shape[0] == E assert np.max(edge_index) == N-1, "{} N-1={}".format(np.max(edge_index), N-1) puppet_graph = nx.DiGraph() puppet_graph.add_edges_from(edge_index) nx.set_edge_attributes(puppet_graph, {tuple(edge):cnt for cnt, edge in enumerate(edge_index)}, "cnt") for cnt, edge in enumerate(edge_index): snode, tnode = edge snode2edge[snode][cnt] = 1 tnode2edge[tnode][cnt] = 1 edge2tnode[cnt][tnode] = 1 for tnode2 in puppet_graph.successors(tnode): if snode != tnode2: cnt2 = puppet_graph[tnode][tnode2]["cnt"] NB_matrix[cnt][cnt2] = 1 return sp.coo_matrix(snode2edge.T), \ sp.coo_matrix(tnode2edge.T), \ sp.coo_matrix(edge2tnode.T), \ sp.coo_matrix(NB_matrix.T) def aligning(target, x): """align two tensor by time dimension Args: target (target tensor): of size [T1, N, K] x ([type]): of size [T, N, K] Returns: aligned x: of size [T1, N, K] """ step = target.shape[0] xstep = x.shape[0] if xstep>=step: x = x[:step] else: tail = x[-1].squeeze() padd = torch.stack([tail]*(step-xstep), dim=0) x = torch.cat([x, padd], dim=0) return x def L1_error(pred_list, label_list): """ pred_list: a list of [T, N, K] array label_list: same as pred_list """ pred = np.vstack([x.reshape(-1, 1) for x in pred_list]) label = np.vstack([x.reshape(-1, 1) for x in label_list]) l1_error = np.mean(np.abs(pred-label)) l1_error_std = np.std(np.abs(pred-label)) return l1_error, l1_error_std
2,315
27.592593
105
py
NEDMP
NEDMP-main/src/utils/dataset.py
# -*- encoding: utf-8 -*- ''' @File : dataset.py @Time : 2021/03/30 20:38:14 @Author : Fei gao @Contact : feig@mail.bnu.edu.cn BNU, Beijing, China ''' from numpy.lib.arraysetops import isin from scipy import sparse from scipy.sparse import block_diag import networkx as nx import scipy.sparse as sp import numpy as np import torch from torch.utils.data import Dataset import pickle as pkl class graph_dataset(Dataset): def __init__(self, root, device, nedmp=False): super(graph_dataset, self).__init__() self.data = self.load(root) self.device = device self.nedmp = nedmp self.data["adj"] = [self.adj(g) for g in self.data["graph"]] self.data["simu_marginal"] = [x[1:] for x in self.data["simu_marginal"]] # remove t=0 self.data["simu_marginal"] = [self.cut_redundancy(x) for x in self.data["simu_marginal"]] if isinstance(self.data["dmp_marginal"][0], np.ndarray): self.data["dmp_marginal"] = [self.cut_redundancy(x) for x in self.data["dmp_marginal"]] else: self.data["dmp_marginal"] = [self.cut_redundancy(x.numpy()) for x in self.data["dmp_marginal"]] self.data2cuda() def load(self, root): with open(root, "rb") as f: data = pkl.load(f) return data def __len__(self): return len(self.data["snode2edge"]) def __getitem__(self, index): if not self.nedmp: snode2edge = self.data["snode2edge"][index] tnode2edge = self.data["tnode2edge"][index] edge2tnode = self.data["edge2tnode"][index] nb_matrix = self.data["nb_matrix"][index] edge_prob = self.data["edge_prob"][index] node_prob = self.data["node_prob"][index] node_seed = self.data["node_seed"][index] simu_marginal = self.data["simu_marginal"][index] dmp_marginal = self.data["dmp_marginal"][index] return (snode2edge, tnode2edge, edge2tnode, nb_matrix, edge_prob, node_prob, node_seed, simu_marginal, dmp_marginal) else: edge2tnode = self.data["edge2tnode"][index] nb_matrix = self.data["nb_matrix"][index] cave_index = self.data["cave_index"][index] adj = self.data["adj"][index] weights = self.data["edge_prob"][index].squeeze() nodes_gamma = self.data["node_prob"][index].squeeze() node_seed = self.data["node_seed"][index] simu_marginal = self.data["simu_marginal"][index] dmp_marginal = self.data["dmp_marginal"][index] adj_index = adj.coalesce().indices() seed_list = torch.nonzero(node_seed.squeeze()).squeeze() return (edge2tnode, nb_matrix, adj_index, cave_index, weights, nodes_gamma, seed_list, simu_marginal, dmp_marginal) def adj(self, graph): """Return the sparse adj of graph""" N = graph.number_of_nodes() row, col = np.array(graph.edges()).T data = np.ones_like(row) adj = sparse.coo_matrix((data, (row, col)), shape=(N, N)) return adj def data2cuda(self): for k, v in self.data.items(): if not isinstance(v, list): continue if isinstance(v[0], sp.coo_matrix): self.data[k] = [self.sci2torch(x).to(self.device) for x in self.data[k]] elif isinstance(v[0], np.ndarray): if v[0].dtype == np.long: self.data[k] = [torch.LongTensor(x).to(self.device) for x in self.data[k]] else: self.data[k] = [torch.Tensor(x).to(self.device) for x in self.data[k]] else: continue def sci2torch(self, sparse_mat): values = sparse_mat.data indices = np.vstack((sparse_mat.row, sparse_mat.col)) i = torch.LongTensor(indices) v = torch.FloatTensor(values) shape = sparse_mat.shape return torch.sparse.FloatTensor(i, v, torch.Size(shape)) def cut_redundancy(self, marginals): # cut redundancy from marginal for i in range(1, len(marginals)): delta = marginals[i-1, :,-1] - marginals[i,:,-1] delta = np.max(np.abs(delta)) if delta<5E-3: break marginals = marginals[:i] return marginals
4,747
34.699248
107
py
NEDMP
NEDMP-main/src/model/model.py
from numpy import NaN import torch import torch.nn as nn import torch.nn.functional as F from torch_scatter import scatter class baseModule(nn.Module): def __init__(self): super(baseModule, self).__init__() def loss_function(self, p, q, reduce="mean"): logits = p labels = q loss = -torch.sum(logits*labels, dim=2) loss = torch.mean(loss).squeeze() return loss def reset_parameter(self): for m in self.modules(): if isinstance(m, (nn.Linear)): nn.init.xavier_normal_(m.weight) ################## Edge GNN ######################## class EdgeGNN_layer(nn.Module): def __init__(self, node_feat_dim, edge_feat_dim, message_dim): super(EdgeGNN_layer, self).__init__() self.message_edge_lin = nn.Sequential(nn.Linear(edge_feat_dim+message_dim, message_dim, bias=True), nn.ReLU()) self.message_pass_lin = nn.Sequential(nn.Linear(message_dim, message_dim), nn.ReLU()) self.message_node_lin = nn.Sequential(nn.Linear(node_feat_dim+message_dim, message_dim), nn.ReLU()) self.gates = nn.GRUCell(message_dim, message_dim, bias=True) def forward(self, inputs): _, _, edge_feat, message_old, nb_adj = inputs message = self.message_edge_lin(torch.cat((message_old, edge_feat), dim=1)) message = torch.sparse.mm(nb_adj, message) message = self.message_pass_lin(message) # gates message = self.gates(message, message_old) return message class EdgeGNN(baseModule): def __init__(self, num_status, node_feat_dim, edge_feat_dim, message_dim, number_layers, device): super(EdgeGNN, self).__init__() self.node_feat_dim = node_feat_dim self.edge_feat_dim = edge_feat_dim self.message_dim = message_dim self.number_layers = number_layers self.num_status = num_status self.device = device self.node_emb = nn.Sequential(nn.Linear(2, node_feat_dim, bias=True), nn.ReLU()) self.edge_emb = nn.Sequential(nn.Linear(1, edge_feat_dim, bias=True), nn.ReLU()) self.init_lin = nn.Sequential(nn.Linear(node_feat_dim+edge_feat_dim, message_dim, bias=True), nn.ReLU()) self.aggr_lin = nn.Sequential(nn.Linear(message_dim, message_dim, bias=True), nn.ReLU()) self.node_lin = nn.Sequential(nn.Linear(message_dim+node_feat_dim, self.num_status, bias=True), nn.ReLU()) self.message_passing = EdgeGNN_layer(self.node_feat_dim, self.edge_feat_dim, self.message_dim) self.reset_parameter() self.to(self.device) def forward(self, inputs): snode2edge, tnode2edge, edge2tnode, nb_matrix, edge_feat, node_prob, node_seed = inputs # embedding node and edge feature node_feat_ori = self.node_emb(torch.cat((node_prob, node_seed), dim=1)) snode_feat = torch.sparse.mm(snode2edge, node_feat_ori) tnode_feat = torch.sparse.mm(tnode2edge, node_feat_ori) edge_feat = self.edge_emb(edge_feat) # [E, F] # initial values for message message = torch.cat((snode_feat, edge_feat), dim=1) message = self.init_lin(message) # message passing message_delta = [] marginal_log = [] # readout marginal_log.append(self.nodes_out(edge2tnode, message, node_feat_ori)) # start from t=1 for _ in range(self.number_layers): message = self.message_passing([snode_feat, tnode_feat, edge_feat, message, nb_matrix]) marginal_log.append(self.nodes_out(edge2tnode, message, node_feat_ori)) delta = self.marginal_delta(marginal_log) message_delta.append(delta) if delta < 5E-5: break marginal = torch.stack(marginal_log, dim=0) return marginal, message_delta def nodes_out(self, edge2tnode, message, node_feat_seed_ori): node_agg = torch.sparse.mm(edge2tnode, message) node_agg = self.aggr_lin(node_agg) node_agg = torch.cat((node_agg, node_feat_seed_ori), dim=1) marginal = F.log_softmax(self.node_lin(node_agg), dim=1) return marginal def marginal_delta(self, marginal_log): marginal_new = torch.exp(marginal_log[-2][:, -1]) marginal_old = torch.exp(marginal_log[-1][:, -1]) return torch.max(torch.abs(marginal_new-marginal_old)).item() ################## NEDMP ######################## class NEDMP_layer(nn.Module): def __init__(self, hid_dim): super(NEDMP_layer, self).__init__() self.theta_emb= nn.Sequential(nn.Linear(3, hid_dim), nn.ReLU()) self.message_emb1 = nn.Sequential(nn.Linear(1, hid_dim), nn.ReLU()) self.message_emb2 = nn.Sequential(nn.Linear(1, hid_dim), nn.ReLU()) self.agg_layer1 = nn.Sequential(nn.Linear(hid_dim, hid_dim), nn.ReLU()) self.agg_layer2 = nn.Sequential(nn.Linear(hid_dim, hid_dim), nn.ReLU()) self.cat_hidden_layer = nn.Sequential(nn.Linear(hid_dim*2, hid_dim), nn.ReLU()) self.gates = nn.GRUCell(hid_dim, hid_dim, bias=True) self.scale_delta1 = nn.Sequential(nn.Linear(2*hid_dim, 2), nn.Sigmoid()) self.scale_delta2 = nn.Sequential(nn.Linear(2*hid_dim, 2), nn.Sigmoid()) def init(self, theta): self.hidden = self.theta_emb(theta) def forward(self, theta, edge_message, node_message, nb_matrix, edge2tnode): theta_emb = self.theta_emb(theta) node_message = self.message_emb1(node_message.reshape(-1, 1)) edge_message = self.message_emb2(edge_message.reshape(-1, 1)) hidden = self.cat_hidden_layer(torch.cat((self.hidden, theta_emb), dim=1)) node_agg = self.agg_layer1(torch.mm(edge2tnode, hidden)) cat_emb = torch.cat((node_agg, node_message), dim=1) node_res = self.scale_delta1(cat_emb) node_scale, node_delta = node_res[:, 0], node_res[:, 1] hidden_agg = self.agg_layer2(torch.mm(nb_matrix, hidden)) self.hidden = self.gates(hidden_agg, self.hidden) # cat_emb = torch.cat((self.hidden, edge_message), dim=1) cat_emb = torch.cat((hidden_agg, edge_message), dim=1) edge_res = self.scale_delta2(cat_emb) edge_scale, edge_delta = edge_res[:, 0], edge_res[:, 1] return node_scale, node_delta, edge_scale, edge_delta class NEDMP(baseModule): def __init__(self, hid_dim, number_layers, device): super(NEDMP, self).__init__() self.number_layers = number_layers self.device = device self.mpnn = NEDMP_layer(hid_dim).to(device) def forward(self, inputs): edge2tnode, nb_matrix, adj_index, cave_index, weights, nodes_gamma, seed_list = inputs self.marginals = [] self.regulars = [] message_delta = [] self.edge2tnode = edge2tnode self.nb_matrix = nb_matrix self.cave_index = cave_index self.edge_index = adj_index self.src_nodes = adj_index[0] self.tar_nodes = adj_index[1] self.weights = weights self.nodes_gamma = nodes_gamma self.gamma = nodes_gamma[self.src_nodes] self.N = max([torch.max(self.src_nodes), torch.max(self.tar_nodes)]).item()+1 self.E = len(self.src_nodes) # init self.seeds = torch.zeros(self.N).to(self.device) self.seeds[seed_list] = 1 self.Ps_0 = 1 - self.seeds self.Pi_0 = self.seeds self.Pr_0 = torch.zeros_like(self.seeds).to(self.device) self.Ps_i_0 = self.Ps_0[self.src_nodes] self.Pi_i_0 = self.Pi_0[self.src_nodes] self.Pr_i_0 = self.Pr_0[self.src_nodes] self.Phi_ij_0 = 1 - self.Ps_i_0 self.Theta_ij_0 = torch.ones(self.E).to(self.device) # first iteration, t = 1 self.Theta_ij_t = self.Theta_ij_0 - self.weights * self.Phi_ij_0 + 1E-20 # get rid of NaN self.Ps_ij_t_1 = self.Ps_i_0 # t-1 self.Ps_ij_t = self.Ps_i_0 * self.mulmul(self.Theta_ij_t) # t self.Phi_ij_t = (1-self.weights)*(1-self.gamma)*self.Phi_ij_0 - (self.Ps_ij_t-self.Ps_ij_t_1) # marginals (t=1) self.Ps_t = self.Ps_0 * scatter(self.Theta_ij_t, self.tar_nodes, reduce="mul", dim_size=self.N) self.Pr_t = self.Pr_0 + self.nodes_gamma*self.Pi_0 self.Pi_t = 1 - self.Ps_t - self.Pr_t self.marginals.append(torch.stack([self.Ps_t, self.Pi_t, self.Pr_t], dim=1)) message = torch.stack((self.Theta_ij_t, self.Phi_ij_t, self.Ps_ij_t), dim=1) self.mpnn.init(message) # Iteration for l in range(self.number_layers): self.iteration() delta = self.marginal_delta(self.marginals) message_delta.append(delta) if delta < 5E-5: break marginals = torch.stack(self.marginals, dim=0) # [T, N, 3] self.regular_loss() # TODO: 合理吗? marginals[marginals<=0] = 1E-20 marginals[marginals>1] = 1 marginals = torch.log(marginals) return marginals, message_delta def iteration(self): self.Theta_ij_t = self.Theta_ij_t - self.weights * self.Phi_ij_t edge_message = self.mulmul(self.Theta_ij_t) node_messgae = scatter(self.Theta_ij_t, self.tar_nodes, reduce="mul", dim_size=self.N) message = torch.stack((self.Theta_ij_t, self.Phi_ij_t, self.Ps_ij_t), dim=1) node_scale, node_delta, edge_scale, edge_delta = self.mpnn(message, edge_message, node_messgae, self.nb_matrix, self.edge2tnode) edge_message = edge_message * edge_scale + edge_delta node_messgae = node_messgae * node_scale + node_delta # Read out node-wise prediction node_messgae[node_messgae>1] = 1 Ps_t = self.Ps_0 * node_messgae ### self.regulars.append((Ps_t-self.Ps_t)[Ps_t>self.Ps_t]) self.Ps_t = torch.where(Ps_t>self.Ps_t, self.Ps_t, Ps_t) ### Pr_t = self.Pr_t + self.nodes_gamma*self.Pi_t self.regulars.append((self.Pr_t-Pr_t)[Pr_t<self.Pr_t]) self.Pr_t = torch.where(Pr_t<self.Pr_t, self.Pr_t, Pr_t) self.Pi_t = 1 - self.Ps_t - self.Pr_t self.marginals.append(torch.stack([self.Ps_t, self.Pi_t, self.Pr_t], dim=1)) # Iteration edge_message[edge_message>1] = 1 new_Ps_ij_t = self.Ps_i_0 * edge_message Ps_ij_t_1 = self.Ps_ij_t self.Ps_ij_t = new_Ps_ij_t self.Phi_ij_t = (1-self.weights)*(1-self.gamma)*self.Phi_ij_t - (self.Ps_ij_t-Ps_ij_t_1) def mulmul(self, Theta_t): Theta = scatter(Theta_t, index=self.tar_nodes, reduce="mul", dim_size=self.N) # [N] Theta = Theta[self.src_nodes] #[E] Theta_cav = scatter(Theta_t, index=self.cave_index, reduce="mul", dim_size=self.E+1)[:self.E] mul = Theta / Theta_cav return mul def marginal_delta(self, marginal_log): if len(marginal_log)<=1: return 1000 else: marginal_new = marginal_log[-1] marginal_old = marginal_log[-2] return torch.max(torch.abs(marginal_new-marginal_old)).item() def regular_loss(self): loss = torch.mean(torch.cat(self.regulars)) self.regularLoss = 0 if torch.isnan(loss) else loss def loss_function(self, p, q): logits = p labels = q loss = -torch.sum(logits*labels, dim=2) loss = torch.mean(loss).squeeze() return loss + 10*self.regularLoss class NEDMPR(baseModule): def __init__(self, hid_dim, number_layers, device): super(NEDMP, self).__init__() self.number_layers = number_layers self.device = device self.mpnn = NEDMP_layer(hid_dim).to(device) def forward(self, inputs): edge2tnode, nb_matrix, adj_index, cave_index, weights, nodes_gamma, seed_list = inputs self.marginals = [] message_delta = [] self.edge2tnode = edge2tnode self.nb_matrix = nb_matrix self.cave_index = cave_index self.edge_index = adj_index self.src_nodes = adj_index[0] self.tar_nodes = adj_index[1] self.weights = weights self.nodes_gamma = nodes_gamma self.gamma = nodes_gamma[self.src_nodes] self.N = max([torch.max(self.src_nodes), torch.max(self.tar_nodes)]).item()+1 self.E = len(self.src_nodes) # init self.seeds = torch.zeros(self.N).to(self.device) self.seeds[seed_list] = 1 self.Ps = 1 - self.seeds self.Pi = self.seeds self.Pij = torch.zeros(self.E) # that i is in the Infectious state as a result of being infected from one of its neighbors other than j for i, src in enumerate(self.src_nodes): if src in seed_list: self.Pij[i] = 1 self.max_steps = 30 for i in range(self.max_steps): self.iteration() def iteration(self): message = NaN message_aggregation = scatter(self.Pij * self.weights * self.Ps[self.tar_ndoes], self.tar_ndoes, reduce="sum") # message update message_aggregation_cave = message_aggregation[self.src_nodes] - message[self.cave_idx] self.message = self.message - self.node_prob_edge * self.message + message_aggregation_cave # Nodes update self.I = self.I - self.node_prob * self.I + message_aggregation self.S = 1 - self.I return self.I, self.S def _set_seeds(self, seed_list): """ setting the initial conditions using seed_list """ # The probabilities being infectious and susceptible self.I = torch.zeros(self.number_of_nodes) self.S = torch.ones(self.number_of_nodes) for seed in seed_list: self.I[seed] = 1 self.S[seed] = 0 self.record() # self.message[i] is the message for edge [src_node[i], tar_node[i]] # If src_node[i] is seed node, then self.message[i] = 1, else 0 self.message = torch.zeros(self.number_of_edges) for i, src in enumerate(self.src_nodes): if src in seed_list: self.message[i] = 1 def record(self): """ recording a [N, 2] tensor for each step """ I = deepcopy(self.I) S = deepcopy(self.S) self.marginal_each_step.append(torch.stack((S, I), dim=1)) def _stop(self): if len(self.marginal_each_step) < 2: return False else: former, later = self.marginal_each_step[-2:] delta = torch.max(torch.abs(former-later)) if delta > 0.0001: return False else: return True def run(self, seed_list): assert isinstance(seed_list, list) seed_list = [int(seed) for seed in seed_list] self._set_seeds(seed_list) for step in range(self.max_steps): self.iteration() self.record() if self._stop(): break # stack marginals for output marginals = torch.stack(self.marginal_each_step, dim=0) # ==> [T, N, 2] return marginals ################## NodeGNN ######################## class NodeGNN_layer(nn.Module): def __init__(self, node_feat_dim, edge_feat_dim, message_dim): super(NodeGNN_layer, self).__init__() self.message_edge_lin = nn.Sequential(nn.Linear(edge_feat_dim+message_dim, message_dim, bias=True), nn.ReLU()) self.message_pass_lin = nn.Sequential(nn.Linear(message_dim, message_dim), nn.ReLU()) self.gates = nn.GRUCell(message_dim, message_dim, bias=True) def forward(self, inputs): edge_feat, snode2edge, edge2tnode, message_old = inputs message = torch.mm(snode2edge, message_old) message = self.message_edge_lin(torch.cat((message, edge_feat), dim=1)) message = self.message_pass_lin(torch.mm(edge2tnode, message)) message = self.gates(message, message_old) return message class NodeGNN(baseModule): def __init__(self, num_status, node_feat_dim, edge_feat_dim, message_dim, number_layers, device): super(NodeGNN, self).__init__() self.node_feat_dim = node_feat_dim self.edge_feat_dim = edge_feat_dim self.message_dim = message_dim self.number_layers = number_layers self.device = device self.num_status = num_status self.node_emb = nn.Sequential(nn.Linear(2, node_feat_dim, bias=True), nn.ReLU()) self.edge_emb = nn.Sequential(nn.Linear(1, edge_feat_dim, bias=True), nn.ReLU()) self.init_lin = nn.Sequential(nn.Linear(node_feat_dim, message_dim, bias=True), nn.ReLU()) self.node_lin = nn.Linear(message_dim, num_status, bias=True) self.message_passing = NodeGNN_layer(self.node_feat_dim, self.edge_feat_dim, self.message_dim) self.reset_parameter() self.to(self.device) def forward(self, inputs): snode2edge, _, edge2tnode, _, edge_feat, node_prob, node_seed = inputs # embedding node and edge feature node_feat = self.node_emb(torch.cat((node_prob, node_seed), dim=1)) edge_feat = self.edge_emb(edge_feat) # initial values for message message = self.init_lin(node_feat) # message passing message_delta = [] marginal_log = [] for _ in range(self.number_layers): message = self.message_passing([edge_feat, snode2edge, edge2tnode, message]) marginal_log.append(self.nodes_out(message)) delta = self.marginal_delta(marginal_log) message_delta.append(delta) if delta < 5E-5: break marginal = torch.stack(marginal_log, dim=0) return marginal, message_delta def nodes_out(self, message): message = self.node_lin(message) marginal = F.log_softmax(message, dim=1) return marginal def marginal_delta(self, marginal_log): if len(marginal_log)<=1: return 1000 else: marginal_new = torch.exp(marginal_log[-1]) marginal_old = torch.exp(marginal_log[-2]) return torch.max(torch.abs(marginal_new-marginal_old)).item()
18,399
37.983051
143
py