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
DiffProxy
DiffProxy-main/stylegan/metrics/metric_utils.py
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """Miscellaneous utilities used internally by the quality metrics.""" import os import time import hashlib import pickle import copy import uuid import numpy as np import torch import dnnlib #---------------------------------------------------------------------------- class MetricOptions: def __init__(self, G=None, G_kwargs={}, dataset_kwargs={}, num_gpus=1, rank=0, device=None, progress=None, cache=True): assert 0 <= rank < num_gpus self.G = G self.G_kwargs = dnnlib.EasyDict(G_kwargs) self.dataset_kwargs = dnnlib.EasyDict(dataset_kwargs) self.num_gpus = num_gpus self.rank = rank self.device = device if device is not None else torch.device('cuda', rank) self.progress = progress.sub() if progress is not None and rank == 0 else ProgressMonitor() self.cache = cache #---------------------------------------------------------------------------- _feature_detector_cache = dict() def get_feature_detector_name(url): return os.path.splitext(url.split('/')[-1])[0] def get_feature_detector(url, device=torch.device('cpu'), num_gpus=1, rank=0, verbose=False): assert 0 <= rank < num_gpus key = (url, device) if key not in _feature_detector_cache: is_leader = (rank == 0) if not is_leader and num_gpus > 1: torch.distributed.barrier() # leader goes first with dnnlib.util.open_url(url, verbose=(verbose and is_leader)) as f: _feature_detector_cache[key] = pickle.load(f).to(device) if is_leader and num_gpus > 1: torch.distributed.barrier() # others follow return _feature_detector_cache[key] #---------------------------------------------------------------------------- def iterate_random_labels(opts, batch_size): if opts.G.c_dim == 0: c = torch.zeros([batch_size, opts.G.c_dim], device=opts.device) while True: yield c else: dataset = dnnlib.util.construct_class_by_name(**opts.dataset_kwargs) while True: c = [dataset.get_label(np.random.randint(len(dataset))) for _i in range(batch_size)] c = torch.from_numpy(np.stack(c)).pin_memory().to(opts.device) yield c #---------------------------------------------------------------------------- class FeatureStats: def __init__(self, capture_all=False, capture_mean_cov=False, max_items=None): self.capture_all = capture_all self.capture_mean_cov = capture_mean_cov self.max_items = max_items self.num_items = 0 self.num_features = None self.all_features = None self.raw_mean = None self.raw_cov = None def set_num_features(self, num_features): if self.num_features is not None: assert num_features == self.num_features else: self.num_features = num_features self.all_features = [] self.raw_mean = np.zeros([num_features], dtype=np.float64) self.raw_cov = np.zeros([num_features, num_features], dtype=np.float64) def is_full(self): return (self.max_items is not None) and (self.num_items >= self.max_items) def append(self, x): x = np.asarray(x, dtype=np.float32) assert x.ndim == 2 if (self.max_items is not None) and (self.num_items + x.shape[0] > self.max_items): if self.num_items >= self.max_items: return x = x[:self.max_items - self.num_items] self.set_num_features(x.shape[1]) self.num_items += x.shape[0] if self.capture_all: self.all_features.append(x) if self.capture_mean_cov: x64 = x.astype(np.float64) self.raw_mean += x64.sum(axis=0) self.raw_cov += x64.T @ x64 def append_torch(self, x, num_gpus=1, rank=0): assert isinstance(x, torch.Tensor) and x.ndim == 2 assert 0 <= rank < num_gpus if num_gpus > 1: ys = [] for src in range(num_gpus): y = x.clone() torch.distributed.broadcast(y, src=src) ys.append(y) x = torch.stack(ys, dim=1).flatten(0, 1) # interleave samples self.append(x.cpu().numpy()) def get_all(self): assert self.capture_all return np.concatenate(self.all_features, axis=0) def get_all_torch(self): return torch.from_numpy(self.get_all()) def get_mean_cov(self): assert self.capture_mean_cov mean = self.raw_mean / self.num_items cov = self.raw_cov / self.num_items cov = cov - np.outer(mean, mean) return mean, cov def save(self, pkl_file): with open(pkl_file, 'wb') as f: pickle.dump(self.__dict__, f) @staticmethod def load(pkl_file): with open(pkl_file, 'rb') as f: s = dnnlib.EasyDict(pickle.load(f)) obj = FeatureStats(capture_all=s.capture_all, max_items=s.max_items) obj.__dict__.update(s) return obj #---------------------------------------------------------------------------- class ProgressMonitor: def __init__(self, tag=None, num_items=None, flush_interval=1000, verbose=False, progress_fn=None, pfn_lo=0, pfn_hi=1000, pfn_total=1000): self.tag = tag self.num_items = num_items self.verbose = verbose self.flush_interval = flush_interval self.progress_fn = progress_fn self.pfn_lo = pfn_lo self.pfn_hi = pfn_hi self.pfn_total = pfn_total self.start_time = time.time() self.batch_time = self.start_time self.batch_items = 0 if self.progress_fn is not None: self.progress_fn(self.pfn_lo, self.pfn_total) def update(self, cur_items): assert (self.num_items is None) or (cur_items <= self.num_items) if (cur_items < self.batch_items + self.flush_interval) and (self.num_items is None or cur_items < self.num_items): return cur_time = time.time() total_time = cur_time - self.start_time time_per_item = (cur_time - self.batch_time) / max(cur_items - self.batch_items, 1) if (self.verbose) and (self.tag is not None): print(f'{self.tag:<19s} items {cur_items:<7d} time {dnnlib.util.format_time(total_time):<12s} ms/item {time_per_item*1e3:.2f}') self.batch_time = cur_time self.batch_items = cur_items if (self.progress_fn is not None) and (self.num_items is not None): self.progress_fn(self.pfn_lo + (self.pfn_hi - self.pfn_lo) * (cur_items / self.num_items), self.pfn_total) def sub(self, tag=None, num_items=None, flush_interval=1000, rel_lo=0, rel_hi=1): return ProgressMonitor( tag = tag, num_items = num_items, flush_interval = flush_interval, verbose = self.verbose, progress_fn = self.progress_fn, pfn_lo = self.pfn_lo + (self.pfn_hi - self.pfn_lo) * rel_lo, pfn_hi = self.pfn_lo + (self.pfn_hi - self.pfn_lo) * rel_hi, pfn_total = self.pfn_total, ) #---------------------------------------------------------------------------- def compute_feature_stats_for_dataset(opts, detector_url, detector_kwargs, rel_lo=0, rel_hi=1, batch_size=64, data_loader_kwargs=None, max_items=None, **stats_kwargs): dataset = dnnlib.util.construct_class_by_name(**opts.dataset_kwargs) if data_loader_kwargs is None: data_loader_kwargs = dict(pin_memory=True, num_workers=3, prefetch_factor=2) # Try to lookup from cache. cache_file = None if opts.cache: # Choose cache file name. args = dict(dataset_kwargs=opts.dataset_kwargs, detector_url=detector_url, detector_kwargs=detector_kwargs, stats_kwargs=stats_kwargs) md5 = hashlib.md5(repr(sorted(args.items())).encode('utf-8')) cache_tag = f'{dataset.name}-{get_feature_detector_name(detector_url)}-{md5.hexdigest()}' cache_file = dnnlib.make_cache_dir_path('gan-metrics', cache_tag + '.pkl') # Check if the file exists (all processes must agree). flag = os.path.isfile(cache_file) if opts.rank == 0 else False if opts.num_gpus > 1: flag = torch.as_tensor(flag, dtype=torch.float32, device=opts.device) torch.distributed.broadcast(tensor=flag, src=0) flag = (float(flag.cpu()) != 0) # Load. if flag: return FeatureStats.load(cache_file) # Initialize. num_items = len(dataset) if max_items is not None: num_items = min(num_items, max_items) stats = FeatureStats(max_items=num_items, **stats_kwargs) progress = opts.progress.sub(tag='dataset features', num_items=num_items, rel_lo=rel_lo, rel_hi=rel_hi) detector = get_feature_detector(url=detector_url, device=opts.device, num_gpus=opts.num_gpus, rank=opts.rank, verbose=progress.verbose) # Main loop. item_subset = [(i * opts.num_gpus + opts.rank) % num_items for i in range((num_items - 1) // opts.num_gpus + 1)] for images, _labels in torch.utils.data.DataLoader(dataset=dataset, sampler=item_subset, batch_size=batch_size, **data_loader_kwargs): if images.shape[1] == 1: images = images.repeat([1, 3, 1, 1]) features = detector(images.to(opts.device), **detector_kwargs) stats.append_torch(features, num_gpus=opts.num_gpus, rank=opts.rank) progress.update(stats.num_items) # Save to cache. if cache_file is not None and opts.rank == 0: os.makedirs(os.path.dirname(cache_file), exist_ok=True) temp_file = cache_file + '.' + uuid.uuid4().hex stats.save(temp_file) os.replace(temp_file, cache_file) # atomic return stats #---------------------------------------------------------------------------- def compute_feature_stats_for_generator(opts, detector_url, detector_kwargs, rel_lo=0, rel_hi=1, batch_size=64, batch_gen=None, **stats_kwargs): if batch_gen is None: batch_gen = min(batch_size, 4) assert batch_size % batch_gen == 0 # Setup generator and labels. G = copy.deepcopy(opts.G).eval().requires_grad_(False).to(opts.device) c_iter = iterate_random_labels(opts=opts, batch_size=batch_gen) # Initialize. stats = FeatureStats(**stats_kwargs) assert stats.max_items is not None progress = opts.progress.sub(tag='generator features', num_items=stats.max_items, rel_lo=rel_lo, rel_hi=rel_hi) detector = get_feature_detector(url=detector_url, device=opts.device, num_gpus=opts.num_gpus, rank=opts.rank, verbose=progress.verbose) # Main loop. while not stats.is_full(): images = [] for _i in range(batch_size // batch_gen): z = torch.randn([batch_gen, G.z_dim], device=opts.device) img = G(z=z, c=next(c_iter), **opts.G_kwargs) img = (img * 127.5 + 128).clamp(0, 255).to(torch.uint8) images.append(img) images = torch.cat(images) if images.shape[1] == 1: images = images.repeat([1, 3, 1, 1]) features = detector(images, **detector_kwargs) stats.append_torch(features, num_gpus=opts.num_gpus, rank=opts.rank) progress.update(stats.num_items) return stats #----------------------------------------------------------------------------
11,936
41.632143
167
py
DiffProxy
DiffProxy-main/stylegan/metrics/equivariance.py
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """Equivariance metrics (EQ-T, EQ-T_frac, and EQ-R) from the paper "Alias-Free Generative Adversarial Networks".""" import copy import numpy as np import torch import torch.fft from torch_utils.ops import upfirdn2d from . import metric_utils #---------------------------------------------------------------------------- # Utilities. def sinc(x): y = (x * np.pi).abs() z = torch.sin(y) / y.clamp(1e-30, float('inf')) return torch.where(y < 1e-30, torch.ones_like(x), z) def lanczos_window(x, a): x = x.abs() / a return torch.where(x < 1, sinc(x), torch.zeros_like(x)) def rotation_matrix(angle): angle = torch.as_tensor(angle).to(torch.float32) mat = torch.eye(3, device=angle.device) mat[0, 0] = angle.cos() mat[0, 1] = angle.sin() mat[1, 0] = -angle.sin() mat[1, 1] = angle.cos() return mat #---------------------------------------------------------------------------- # Apply integer translation to a batch of 2D images. Corresponds to the # operator T_x in Appendix E.1. def apply_integer_translation(x, tx, ty): _N, _C, H, W = x.shape tx = torch.as_tensor(tx * W).to(dtype=torch.float32, device=x.device) ty = torch.as_tensor(ty * H).to(dtype=torch.float32, device=x.device) ix = tx.round().to(torch.int64) iy = ty.round().to(torch.int64) z = torch.zeros_like(x) m = torch.zeros_like(x) if abs(ix) < W and abs(iy) < H: y = x[:, :, max(-iy,0) : H+min(-iy,0), max(-ix,0) : W+min(-ix,0)] z[:, :, max(iy,0) : H+min(iy,0), max(ix,0) : W+min(ix,0)] = y m[:, :, max(iy,0) : H+min(iy,0), max(ix,0) : W+min(ix,0)] = 1 return z, m #---------------------------------------------------------------------------- # Apply integer translation to a batch of 2D images. Corresponds to the # operator T_x in Appendix E.2. def apply_fractional_translation(x, tx, ty, a=3): _N, _C, H, W = x.shape tx = torch.as_tensor(tx * W).to(dtype=torch.float32, device=x.device) ty = torch.as_tensor(ty * H).to(dtype=torch.float32, device=x.device) ix = tx.floor().to(torch.int64) iy = ty.floor().to(torch.int64) fx = tx - ix fy = ty - iy b = a - 1 z = torch.zeros_like(x) zx0 = max(ix - b, 0) zy0 = max(iy - b, 0) zx1 = min(ix + a, 0) + W zy1 = min(iy + a, 0) + H if zx0 < zx1 and zy0 < zy1: taps = torch.arange(a * 2, device=x.device) - b filter_x = (sinc(taps - fx) * sinc((taps - fx) / a)).unsqueeze(0) filter_y = (sinc(taps - fy) * sinc((taps - fy) / a)).unsqueeze(1) y = x y = upfirdn2d.filter2d(y, filter_x / filter_x.sum(), padding=[b,a,0,0]) y = upfirdn2d.filter2d(y, filter_y / filter_y.sum(), padding=[0,0,b,a]) y = y[:, :, max(b-iy,0) : H+b+a+min(-iy-a,0), max(b-ix,0) : W+b+a+min(-ix-a,0)] z[:, :, zy0:zy1, zx0:zx1] = y m = torch.zeros_like(x) mx0 = max(ix + a, 0) my0 = max(iy + a, 0) mx1 = min(ix - b, 0) + W my1 = min(iy - b, 0) + H if mx0 < mx1 and my0 < my1: m[:, :, my0:my1, mx0:mx1] = 1 return z, m #---------------------------------------------------------------------------- # Construct an oriented low-pass filter that applies the appropriate # bandlimit with respect to the input and output of the given affine 2D # image transformation. def construct_affine_bandlimit_filter(mat, a=3, amax=16, aflt=64, up=4, cutoff_in=1, cutoff_out=1): assert a <= amax < aflt mat = torch.as_tensor(mat).to(torch.float32) # Construct 2D filter taps in input & output coordinate spaces. taps = ((torch.arange(aflt * up * 2 - 1, device=mat.device) + 1) / up - aflt).roll(1 - aflt * up) yi, xi = torch.meshgrid(taps, taps) xo, yo = (torch.stack([xi, yi], dim=2) @ mat[:2, :2].t()).unbind(2) # Convolution of two oriented 2D sinc filters. fi = sinc(xi * cutoff_in) * sinc(yi * cutoff_in) fo = sinc(xo * cutoff_out) * sinc(yo * cutoff_out) f = torch.fft.ifftn(torch.fft.fftn(fi) * torch.fft.fftn(fo)).real # Convolution of two oriented 2D Lanczos windows. wi = lanczos_window(xi, a) * lanczos_window(yi, a) wo = lanczos_window(xo, a) * lanczos_window(yo, a) w = torch.fft.ifftn(torch.fft.fftn(wi) * torch.fft.fftn(wo)).real # Construct windowed FIR filter. f = f * w # Finalize. c = (aflt - amax) * up f = f.roll([aflt * up - 1] * 2, dims=[0,1])[c:-c, c:-c] f = torch.nn.functional.pad(f, [0, 1, 0, 1]).reshape(amax * 2, up, amax * 2, up) f = f / f.sum([0,2], keepdim=True) / (up ** 2) f = f.reshape(amax * 2 * up, amax * 2 * up)[:-1, :-1] return f #---------------------------------------------------------------------------- # Apply the given affine transformation to a batch of 2D images. def apply_affine_transformation(x, mat, up=4, **filter_kwargs): _N, _C, H, W = x.shape mat = torch.as_tensor(mat).to(dtype=torch.float32, device=x.device) # Construct filter. f = construct_affine_bandlimit_filter(mat, up=up, **filter_kwargs) assert f.ndim == 2 and f.shape[0] == f.shape[1] and f.shape[0] % 2 == 1 p = f.shape[0] // 2 # Construct sampling grid. theta = mat.inverse() theta[:2, 2] *= 2 theta[0, 2] += 1 / up / W theta[1, 2] += 1 / up / H theta[0, :] *= W / (W + p / up * 2) theta[1, :] *= H / (H + p / up * 2) theta = theta[:2, :3].unsqueeze(0).repeat([x.shape[0], 1, 1]) g = torch.nn.functional.affine_grid(theta, x.shape, align_corners=False) # Resample image. y = upfirdn2d.upsample2d(x=x, f=f, up=up, padding=p) z = torch.nn.functional.grid_sample(y, g, mode='bilinear', padding_mode='zeros', align_corners=False) # Form mask. m = torch.zeros_like(y) c = p * 2 + 1 m[:, :, c:-c, c:-c] = 1 m = torch.nn.functional.grid_sample(m, g, mode='nearest', padding_mode='zeros', align_corners=False) return z, m #---------------------------------------------------------------------------- # Apply fractional rotation to a batch of 2D images. Corresponds to the # operator R_\alpha in Appendix E.3. def apply_fractional_rotation(x, angle, a=3, **filter_kwargs): angle = torch.as_tensor(angle).to(dtype=torch.float32, device=x.device) mat = rotation_matrix(angle) return apply_affine_transformation(x, mat, a=a, amax=a*2, **filter_kwargs) #---------------------------------------------------------------------------- # Modify the frequency content of a batch of 2D images as if they had undergo # fractional rotation -- but without actually rotating them. Corresponds to # the operator R^*_\alpha in Appendix E.3. def apply_fractional_pseudo_rotation(x, angle, a=3, **filter_kwargs): angle = torch.as_tensor(angle).to(dtype=torch.float32, device=x.device) mat = rotation_matrix(-angle) f = construct_affine_bandlimit_filter(mat, a=a, amax=a*2, up=1, **filter_kwargs) y = upfirdn2d.filter2d(x=x, f=f) m = torch.zeros_like(y) c = f.shape[0] // 2 m[:, :, c:-c, c:-c] = 1 return y, m #---------------------------------------------------------------------------- # Compute the selected equivariance metrics for the given generator. def compute_equivariance_metrics(opts, num_samples, batch_size, translate_max=0.125, rotate_max=1, compute_eqt_int=False, compute_eqt_frac=False, compute_eqr=False): assert compute_eqt_int or compute_eqt_frac or compute_eqr # Setup generator and labels. G = copy.deepcopy(opts.G).eval().requires_grad_(False).to(opts.device) I = torch.eye(3, device=opts.device) M = getattr(getattr(getattr(G, 'synthesis', None), 'input', None), 'transform', None) if M is None: raise ValueError('Cannot compute equivariance metrics; the given generator does not support user-specified image transformations') c_iter = metric_utils.iterate_random_labels(opts=opts, batch_size=batch_size) # Sampling loop. sums = None progress = opts.progress.sub(tag='eq sampling', num_items=num_samples) for batch_start in range(0, num_samples, batch_size * opts.num_gpus): progress.update(batch_start) s = [] # Randomize noise buffers, if any. for name, buf in G.named_buffers(): if name.endswith('.noise_const'): buf.copy_(torch.randn_like(buf)) # Run mapping network. z = torch.randn([batch_size, G.z_dim], device=opts.device) c = next(c_iter) ws = G.mapping(z=z, c=c) # Generate reference image. M[:] = I orig = G.synthesis(ws=ws, noise_mode='const', **opts.G_kwargs) # Integer translation (EQ-T). if compute_eqt_int: t = (torch.rand(2, device=opts.device) * 2 - 1) * translate_max t = (t * G.img_resolution).round() / G.img_resolution M[:] = I M[:2, 2] = -t img = G.synthesis(ws=ws, noise_mode='const', **opts.G_kwargs) ref, mask = apply_integer_translation(orig, t[0], t[1]) s += [(ref - img).square() * mask, mask] # Fractional translation (EQ-T_frac). if compute_eqt_frac: t = (torch.rand(2, device=opts.device) * 2 - 1) * translate_max M[:] = I M[:2, 2] = -t img = G.synthesis(ws=ws, noise_mode='const', **opts.G_kwargs) ref, mask = apply_fractional_translation(orig, t[0], t[1]) s += [(ref - img).square() * mask, mask] # Rotation (EQ-R). if compute_eqr: angle = (torch.rand([], device=opts.device) * 2 - 1) * (rotate_max * np.pi) M[:] = rotation_matrix(-angle) img = G.synthesis(ws=ws, noise_mode='const', **opts.G_kwargs) ref, ref_mask = apply_fractional_rotation(orig, angle) pseudo, pseudo_mask = apply_fractional_pseudo_rotation(img, angle) mask = ref_mask * pseudo_mask s += [(ref - pseudo).square() * mask, mask] # Accumulate results. s = torch.stack([x.to(torch.float64).sum() for x in s]) sums = sums + s if sums is not None else s progress.update(num_samples) # Compute PSNRs. if opts.num_gpus > 1: torch.distributed.all_reduce(sums) sums = sums.cpu() mses = sums[0::2] / sums[1::2] psnrs = np.log10(2) * 20 - mses.log10() * 10 psnrs = tuple(psnrs.numpy()) return psnrs[0] if len(psnrs) == 1 else psnrs #----------------------------------------------------------------------------
10,868
39.55597
165
py
DiffProxy
DiffProxy-main/stylegan/metrics/perceptual_path_length.py
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """Perceptual Path Length (PPL) from the paper "A Style-Based Generator Architecture for Generative Adversarial Networks". Matches the original implementation by Karras et al. at https://github.com/NVlabs/stylegan/blob/master/metrics/perceptual_path_length.py""" import copy import numpy as np import torch from . import metric_utils #---------------------------------------------------------------------------- # Spherical interpolation of a batch of vectors. def slerp(a, b, t): a = a / a.norm(dim=-1, keepdim=True) b = b / b.norm(dim=-1, keepdim=True) d = (a * b).sum(dim=-1, keepdim=True) p = t * torch.acos(d) c = b - d * a c = c / c.norm(dim=-1, keepdim=True) d = a * torch.cos(p) + c * torch.sin(p) d = d / d.norm(dim=-1, keepdim=True) return d #---------------------------------------------------------------------------- class PPLSampler(torch.nn.Module): def __init__(self, G, G_kwargs, epsilon, space, sampling, crop, vgg16): assert space in ['z', 'w'] assert sampling in ['full', 'end'] super().__init__() self.G = copy.deepcopy(G) self.G_kwargs = G_kwargs self.epsilon = epsilon self.space = space self.sampling = sampling self.crop = crop self.vgg16 = copy.deepcopy(vgg16) def forward(self, c): # Generate random latents and interpolation t-values. t = torch.rand([c.shape[0]], device=c.device) * (1 if self.sampling == 'full' else 0) z0, z1 = torch.randn([c.shape[0] * 2, self.G.z_dim], device=c.device).chunk(2) # Interpolate in W or Z. if self.space == 'w': w0, w1 = self.G.mapping(z=torch.cat([z0,z1]), c=torch.cat([c,c])).chunk(2) wt0 = w0.lerp(w1, t.unsqueeze(1).unsqueeze(2)) wt1 = w0.lerp(w1, t.unsqueeze(1).unsqueeze(2) + self.epsilon) else: # space == 'z' zt0 = slerp(z0, z1, t.unsqueeze(1)) zt1 = slerp(z0, z1, t.unsqueeze(1) + self.epsilon) wt0, wt1 = self.G.mapping(z=torch.cat([zt0,zt1]), c=torch.cat([c,c])).chunk(2) # Randomize noise buffers. for name, buf in self.G.named_buffers(): if name.endswith('.noise_const'): buf.copy_(torch.randn_like(buf)) # Generate images. img = self.G.synthesis(ws=torch.cat([wt0,wt1]), noise_mode='const', force_fp32=True, **self.G_kwargs) # Center crop. if self.crop: assert img.shape[2] == img.shape[3] c = img.shape[2] // 8 img = img[:, :, c*3 : c*7, c*2 : c*6] # Downsample to 256x256. factor = self.G.img_resolution // 256 if factor > 1: img = img.reshape([-1, img.shape[1], img.shape[2] // factor, factor, img.shape[3] // factor, factor]).mean([3, 5]) # Scale dynamic range from [-1,1] to [0,255]. img = (img + 1) * (255 / 2) if self.G.img_channels == 1: img = img.repeat([1, 3, 1, 1]) # Evaluate differential LPIPS. lpips_t0, lpips_t1 = self.vgg16(img, resize_images=False, return_lpips=True).chunk(2) dist = (lpips_t0 - lpips_t1).square().sum(1) / self.epsilon ** 2 return dist #---------------------------------------------------------------------------- def compute_ppl(opts, num_samples, epsilon, space, sampling, crop, batch_size): vgg16_url = 'https://api.ngc.nvidia.com/v2/models/nvidia/research/stylegan3/versions/1/files/metrics/vgg16.pkl' vgg16 = metric_utils.get_feature_detector(vgg16_url, num_gpus=opts.num_gpus, rank=opts.rank, verbose=opts.progress.verbose) # Setup sampler and labels. sampler = PPLSampler(G=opts.G, G_kwargs=opts.G_kwargs, epsilon=epsilon, space=space, sampling=sampling, crop=crop, vgg16=vgg16) sampler.eval().requires_grad_(False).to(opts.device) c_iter = metric_utils.iterate_random_labels(opts=opts, batch_size=batch_size) # Sampling loop. dist = [] progress = opts.progress.sub(tag='ppl sampling', num_items=num_samples) for batch_start in range(0, num_samples, batch_size * opts.num_gpus): progress.update(batch_start) x = sampler(next(c_iter)) for src in range(opts.num_gpus): y = x.clone() if opts.num_gpus > 1: torch.distributed.broadcast(y, src=src) dist.append(y) progress.update(num_samples) # Compute PPL. if opts.rank != 0: return float('nan') dist = torch.cat(dist)[:num_samples].cpu().numpy() lo = np.percentile(dist, 1, interpolation='lower') hi = np.percentile(dist, 99, interpolation='higher') ppl = np.extract(np.logical_and(dist >= lo, dist <= hi), dist).mean() return float(ppl) #----------------------------------------------------------------------------
5,256
40.722222
131
py
DiffProxy
DiffProxy-main/stylegan/metrics/metric_main.py
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """Main API for computing and reporting quality metrics.""" import os import time import json import torch import dnnlib from . import metric_utils from . import frechet_inception_distance from . import kernel_inception_distance from . import precision_recall from . import perceptual_path_length from . import inception_score from . import equivariance #---------------------------------------------------------------------------- _metric_dict = dict() # name => fn def register_metric(fn): assert callable(fn) _metric_dict[fn.__name__] = fn return fn def is_valid_metric(metric): return metric in _metric_dict def list_valid_metrics(): return list(_metric_dict.keys()) #---------------------------------------------------------------------------- def calc_metric(metric, **kwargs): # See metric_utils.MetricOptions for the full list of arguments. assert is_valid_metric(metric) opts = metric_utils.MetricOptions(**kwargs) # Calculate. start_time = time.time() results = _metric_dict[metric](opts) total_time = time.time() - start_time # Broadcast results. for key, value in list(results.items()): if opts.num_gpus > 1: value = torch.as_tensor(value, dtype=torch.float64, device=opts.device) torch.distributed.broadcast(tensor=value, src=0) value = float(value.cpu()) results[key] = value # Decorate with metadata. return dnnlib.EasyDict( results = dnnlib.EasyDict(results), metric = metric, total_time = total_time, total_time_str = dnnlib.util.format_time(total_time), num_gpus = opts.num_gpus, ) #---------------------------------------------------------------------------- def report_metric(result_dict, run_dir=None, snapshot_pkl=None): metric = result_dict['metric'] assert is_valid_metric(metric) if run_dir is not None and snapshot_pkl is not None: snapshot_pkl = os.path.relpath(snapshot_pkl, run_dir) jsonl_line = json.dumps(dict(result_dict, snapshot_pkl=snapshot_pkl, timestamp=time.time())) print(jsonl_line) if run_dir is not None and os.path.isdir(run_dir): with open(os.path.join(run_dir, f'metric-{metric}.jsonl'), 'at') as f: f.write(jsonl_line + '\n') #---------------------------------------------------------------------------- # Recommended metrics. @register_metric def fid50k_full(opts): opts.dataset_kwargs.update(max_size=None, xflip=False) fid = frechet_inception_distance.compute_fid(opts, max_real=None, num_gen=50000) return dict(fid50k_full=fid) @register_metric def kid50k_full(opts): opts.dataset_kwargs.update(max_size=None, xflip=False) kid = kernel_inception_distance.compute_kid(opts, max_real=1000000, num_gen=50000, num_subsets=100, max_subset_size=1000) return dict(kid50k_full=kid) @register_metric def pr50k3_full(opts): opts.dataset_kwargs.update(max_size=None, xflip=False) precision, recall = precision_recall.compute_pr(opts, max_real=200000, num_gen=50000, nhood_size=3, row_batch_size=10000, col_batch_size=10000) return dict(pr50k3_full_precision=precision, pr50k3_full_recall=recall) @register_metric def ppl2_wend(opts): ppl = perceptual_path_length.compute_ppl(opts, num_samples=50000, epsilon=1e-4, space='w', sampling='end', crop=False, batch_size=2) return dict(ppl2_wend=ppl) @register_metric def eqt50k_int(opts): opts.G_kwargs.update(force_fp32=True) psnr = equivariance.compute_equivariance_metrics(opts, num_samples=50000, batch_size=4, compute_eqt_int=True) return dict(eqt50k_int=psnr) @register_metric def eqt50k_frac(opts): opts.G_kwargs.update(force_fp32=True) psnr = equivariance.compute_equivariance_metrics(opts, num_samples=50000, batch_size=4, compute_eqt_frac=True) return dict(eqt50k_frac=psnr) @register_metric def eqr50k(opts): opts.G_kwargs.update(force_fp32=True) psnr = equivariance.compute_equivariance_metrics(opts, num_samples=50000, batch_size=4, compute_eqr=True) return dict(eqr50k=psnr) #---------------------------------------------------------------------------- # Legacy metrics. @register_metric def fid50k(opts): opts.dataset_kwargs.update(max_size=None) fid = frechet_inception_distance.compute_fid(opts, max_real=50000, num_gen=50000) return dict(fid50k=fid) @register_metric def kid50k(opts): opts.dataset_kwargs.update(max_size=None) kid = kernel_inception_distance.compute_kid(opts, max_real=50000, num_gen=50000, num_subsets=100, max_subset_size=1000) return dict(kid50k=kid) @register_metric def pr50k3(opts): opts.dataset_kwargs.update(max_size=None) precision, recall = precision_recall.compute_pr(opts, max_real=50000, num_gen=50000, nhood_size=3, row_batch_size=10000, col_batch_size=10000) return dict(pr50k3_precision=precision, pr50k3_recall=recall) @register_metric def is50k(opts): opts.dataset_kwargs.update(max_size=None, xflip=False) mean, std = inception_score.compute_is(opts, num_gen=50000, num_splits=10) return dict(is50k_mean=mean, is50k_std=std) #----------------------------------------------------------------------------
5,675
35.857143
147
py
DiffProxy
DiffProxy-main/stylegan/metrics/precision_recall.py
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """Precision/Recall (PR) from the paper "Improved Precision and Recall Metric for Assessing Generative Models". Matches the original implementation by Kynkaanniemi et al. at https://github.com/kynkaat/improved-precision-and-recall-metric/blob/master/precision_recall.py""" import torch from . import metric_utils #---------------------------------------------------------------------------- def compute_distances(row_features, col_features, num_gpus, rank, col_batch_size): assert 0 <= rank < num_gpus num_cols = col_features.shape[0] num_batches = ((num_cols - 1) // col_batch_size // num_gpus + 1) * num_gpus col_batches = torch.nn.functional.pad(col_features, [0, 0, 0, -num_cols % num_batches]).chunk(num_batches) dist_batches = [] for col_batch in col_batches[rank :: num_gpus]: dist_batch = torch.cdist(row_features.unsqueeze(0), col_batch.unsqueeze(0))[0] for src in range(num_gpus): dist_broadcast = dist_batch.clone() if num_gpus > 1: torch.distributed.broadcast(dist_broadcast, src=src) dist_batches.append(dist_broadcast.cpu() if rank == 0 else None) return torch.cat(dist_batches, dim=1)[:, :num_cols] if rank == 0 else None #---------------------------------------------------------------------------- def compute_pr(opts, max_real, num_gen, nhood_size, row_batch_size, col_batch_size): detector_url = 'https://api.ngc.nvidia.com/v2/models/nvidia/research/stylegan3/versions/1/files/metrics/vgg16.pkl' detector_kwargs = dict(return_features=True) real_features = metric_utils.compute_feature_stats_for_dataset( opts=opts, detector_url=detector_url, detector_kwargs=detector_kwargs, rel_lo=0, rel_hi=0, capture_all=True, max_items=max_real).get_all_torch().to(torch.float16).to(opts.device) gen_features = metric_utils.compute_feature_stats_for_generator( opts=opts, detector_url=detector_url, detector_kwargs=detector_kwargs, rel_lo=0, rel_hi=1, capture_all=True, max_items=num_gen).get_all_torch().to(torch.float16).to(opts.device) results = dict() for name, manifold, probes in [('precision', real_features, gen_features), ('recall', gen_features, real_features)]: kth = [] for manifold_batch in manifold.split(row_batch_size): dist = compute_distances(row_features=manifold_batch, col_features=manifold, num_gpus=opts.num_gpus, rank=opts.rank, col_batch_size=col_batch_size) kth.append(dist.to(torch.float32).kthvalue(nhood_size + 1).values.to(torch.float16) if opts.rank == 0 else None) kth = torch.cat(kth) if opts.rank == 0 else None pred = [] for probes_batch in probes.split(row_batch_size): dist = compute_distances(row_features=probes_batch, col_features=manifold, num_gpus=opts.num_gpus, rank=opts.rank, col_batch_size=col_batch_size) pred.append((dist <= kth).any(dim=1) if opts.rank == 0 else None) results[name] = float(torch.cat(pred).to(torch.float32).mean() if opts.rank == 0 else 'nan') return results['precision'], results['recall'] #----------------------------------------------------------------------------
3,644
56.857143
159
py
DebuggableDeepNetworks
DebuggableDeepNetworks-main/main.py
import os, math, time import torch as ch import torch.nn as nn from robustness.datasets import DATASETS # be sure to pip install glm_saga, or clone the repo from # https://github.com/madrylab/glm_saga from glm_saga.elasticnet import glm_saga import helpers.data_helpers as data_helpers import helpers.feature_helpers as feature_helpers from argparse import ArgumentParser ch.manual_seed(0) ch.set_grad_enabled(False) if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--dataset', type=str, help='dataset name') parser.add_argument('--dataset-type', type=str, help='One of ["language", "vision"]') parser.add_argument('--dataset-path', type=str, help='path to dataset') parser.add_argument('--model-path', type=str, help='path to model checkpoint') parser.add_argument('--arch', type=str, help='model architecture type') parser.add_argument('--out-path', help='location for saving results') parser.add_argument('--cache', action='store_true', help='cache deep features') parser.add_argument('--balance', action='store_true', help='balance classes for evaluation') parser.add_argument('--device', default='cuda') parser.add_argument('--random-seed', default=0) parser.add_argument('--num-workers', type=int, default=2) parser.add_argument('--batch-size', type=int, default=256) parser.add_argument('--val-frac', type=float, default=0.1) parser.add_argument('--lr-decay-factor', type=float, default=1) parser.add_argument('--lr', type=float, default=0.1) parser.add_argument('--alpha', type=float, default=0.99) parser.add_argument('--max-epochs', type=int, default=2000) parser.add_argument('--verbose', type=int, default=200) parser.add_argument('--tol', type=float, default=1e-4) parser.add_argument('--lookbehind', type=int, default=3) parser.add_argument('--lam-factor', type=float, default=0.001) parser.add_argument('--group', action='store_true') args = parser.parse_args() start_time = time.time() out_dir = args.out_path out_dir_ckpt = f'{out_dir}/checkpoint' out_dir_feats = f'{out_dir}/features' for path in [out_dir, out_dir_ckpt, out_dir_feats]: if not os.path.exists(path): os.makedirs(path) print("Initializing dataset and loader...") dataset, train_loader, test_loader = data_helpers.load_dataset(args.dataset, os.path.expandvars(args.dataset_path), args.dataset_type, args.batch_size, args.num_workers, shuffle=False, model_path=args.model_path) num_classes = dataset.num_classes Ntotal = len(train_loader.dataset) print("Loading model...") model, pooled_output = feature_helpers.load_model(args.model_path, args.arch, dataset, args.dataset, args.dataset_type, device=args.device) print("Computing/loading deep features...") feature_loaders = {} for mode, loader in zip(['train', 'test'], [train_loader, test_loader]): print(f"For {mode} set...") sink_path = f"{out_dir_feats}/features_{mode}" if args.cache else None metadata_path = f"{out_dir_feats}/metadata_{mode}.pth" if args.cache else None feature_ds, feature_loader = feature_helpers.compute_features(loader, model, dataset_type=args.dataset_type, pooled_output=pooled_output, batch_size=args.batch_size, num_workers=args.num_workers, shuffle=(mode == 'test'), device=args.device, filename=sink_path, balance=args.balance if mode == 'test' else False) if mode == 'train': metadata = feature_helpers.calculate_metadata(feature_loader, num_classes=num_classes, filename=metadata_path) split_datasets, split_loaders = feature_helpers.split_dataset(feature_ds, Ntotal, val_frac=args.val_frac, batch_size=args.batch_size, num_workers=args.num_workers, random_seed=args.random_seed, shuffle=True, balance=args.balance) feature_loaders.update({mm : data_helpers.add_index_to_dataloader(split_loaders[mi]) for mi, mm in enumerate(['train', 'val'])}) else: feature_loaders[mode] = feature_loader num_features = metadata["X"]["num_features"][0] assert metadata["y"]["num_classes"].numpy() == num_classes print("Initializing linear model...") linear = nn.Linear(num_features, num_classes).to(args.device) for p in [linear.weight, linear.bias]: p.data.zero_() print("Preparing normalization preprocess and indexed dataloader") preprocess = data_helpers.NormalizedRepresentation(feature_loaders['train'], metadata=metadata, device=linear.weight.device) print("Calculating the regularization path") params = glm_saga(linear, feature_loaders['train'], args.lr, args.max_epochs, args.alpha, val_loader=feature_loaders['val'], test_loader=feature_loaders['test'], n_classes=num_classes, checkpoint=out_dir_ckpt, verbose=args.verbose, tol=args.tol, lookbehind=args.lookbehind, lr_decay_factor=args.lr_decay_factor, group=args.group, epsilon=args.lam_factor, metadata=metadata, preprocess=preprocess) print(f"Total time: {time.time() - start_time}")
7,330
48.533784
120
py
DebuggableDeepNetworks
DebuggableDeepNetworks-main/helpers/data_helpers.py
import os, sys sys.path.append('..') import numpy as np import torch as ch from torch.utils.data import TensorDataset from robustness.datasets import DATASETS as VISION_DATASETS from robustness.tools.label_maps import CLASS_DICT from language.datasets import DATASETS as LANGUAGE_DATASETS from language.models import LANGUAGE_MODEL_DICT from transformers import AutoTokenizer def get_label_mapping(dataset_name): if dataset_name == 'imagenet': return CLASS_DICT['ImageNet'] elif dataset_name == 'places-10': return CD_PLACES elif dataset_name == 'sst': return {0: 'negative', 1: 'positive'} elif 'jigsaw' in dataset_name: category = dataset_name.split('jigsaw-')[1] if 'alt' not in dataset_name \ else dataset_name.split('jigsaw-alt-')[1] return {0: f'not {category}', 1: f'{category}'} else: raise ValueError("Dataset not currently supported...") def load_dataset(dataset_name, dataset_path, dataset_type, batch_size, num_workers, maxlen_train=256, maxlen_val=256, shuffle=False, model_path=None, return_sentences=False): if dataset_type == 'vision': if dataset_name == 'places-10': dataset_name = 'places365' if dataset_name not in VISION_DATASETS: raise ValueError("Vision dataset not currently supported...") dataset = VISION_DATASETS[dataset_name](os.path.expandvars(dataset_path)) if dataset_name == 'places365': dataset.num_classes = 10 train_loader, test_loader = dataset.make_loaders(num_workers, batch_size, data_aug=False, shuffle_train=shuffle, shuffle_val=shuffle) return dataset, train_loader, test_loader else: if model_path is None: model_path = LANGUAGE_MODEL_DICT[dataset_name] tokenizer = AutoTokenizer.from_pretrained(model_path) kwargs = {} if 'jigsaw' not in dataset_name else \ {'label': dataset_name[11:] if 'alt' in dataset_name \ else dataset_name[7:]} kwargs['return_sentences'] = return_sentences train_set = LANGUAGE_DATASETS(dataset_name)(filename=f'{dataset_path}/train.tsv', maxlen=maxlen_train, tokenizer=tokenizer, **kwargs) test_set = LANGUAGE_DATASETS(dataset_name)(filename=f'{dataset_path}/test.tsv', maxlen=maxlen_val, tokenizer=tokenizer, **kwargs) train_loader = ch.utils.data.DataLoader(dataset=train_set, batch_size=batch_size, num_workers=num_workers) test_loader = ch.utils.data.DataLoader(dataset=test_set, batch_size=batch_size, num_workers=num_workers) #assert len(np.unique(train_set.df['label'].values)) == len(np.unique(test_set.df['label'].values)) train_set.num_classes = 2 # train_loader.dataset.targets = train_loader.dataset.df['label'].values # test_loader.dataset.targets = test_loader.dataset.df['label'].values return train_set, train_loader, test_loader class IndexedTensorDataset(ch.utils.data.TensorDataset): def __getitem__(self, index): val = super(IndexedTensorDataset, self).__getitem__(index) return val + (index,) class IndexedDataset(ch.utils.data.Dataset): def __init__(self, ds, sample_weight=None): super(ch.utils.data.Dataset, self).__init__() self.dataset = ds self.sample_weight=sample_weight def __getitem__(self, index): val = self.dataset[index] if self.sample_weight is None: return val + (index,) else: weight = self.sample_weight[index] return val + (weight,index) def __len__(self): return len(self.dataset) def add_index_to_dataloader(loader, sample_weight=None): return ch.utils.data.DataLoader( IndexedDataset(loader.dataset, sample_weight=sample_weight), batch_size=loader.batch_size, sampler=loader.sampler, num_workers=loader.num_workers, collate_fn=loader.collate_fn, pin_memory=loader.pin_memory, drop_last=loader.drop_last, timeout=loader.timeout, worker_init_fn=loader.worker_init_fn, multiprocessing_context=loader.multiprocessing_context ) class NormalizedRepresentation(ch.nn.Module): def __init__(self, loader, metadata, device='cuda', tol=1e-5): super(NormalizedRepresentation, self).__init__() assert metadata is not None self.device = device self.mu = metadata['X']['mean'] self.sigma = ch.clamp(metadata['X']['std'], tol) def forward(self, X): return (X - self.mu.to(self.device))/self.sigma.to(self.device) CD_PLACES = {0: 'airport_terminal', 1: 'boat_deck', 2: 'bridge', 3: 'butchers_shop', 4: 'church-outdoor', 5: 'hotel_room', 6: 'laundromat', 7: 'river', 8: 'ski_slope', 9: 'volcano'}
5,692
40.554745
107
py
DebuggableDeepNetworks
DebuggableDeepNetworks-main/helpers/feature_helpers.py
import os, math, sys sys.path.append('..') import numpy as np import torch as ch from torch._utils import _accumulate from torch.utils.data import Subset from tqdm import tqdm from robustness.model_utils import make_and_restore_model from robustness.loaders import LambdaLoader from transformers import AutoConfig import language.models as lm def load_model(model_root, arch, dataset, dataset_name, dataset_type, device='cuda'): """Loads existing vision/language models. Args: model_root (str): Path to model arch (str): Model architecture dataset (torch dataset): Dataset on which the model was trained dataset_name (str): Name of dataset dataset_type (str): One of vision or language device (str): Device on which to keep the model Returns: model: Torch model pooled_output (bool): Whether or not to pool outputs (only relevant for some language models) """ if model_root is None and dataset_type == 'language': model_root = lm.LANGUAGE_MODEL_DICT[dataset_name] pooled_output = None if dataset_type == 'vision': model, _ = make_and_restore_model(arch=arch, dataset=dataset, resume_path=model_root, pytorch_pretrained=(model_root is None) ) else: config = AutoConfig.from_pretrained(model_root) if config.model_type == 'bert': if model_root == 'barissayil/bert-sentiment-analysis-sst': model = lm.BertForSentimentClassification.from_pretrained(model_root) pooled_output = False else: model = lm.BertForSequenceClassification.from_pretrained(model_root) pooled_output = True elif config.model_type == 'roberta': model = lm.RobertaForSequenceClassification.from_pretrained(model_root) pooled_output = False else: raise ValueError('This transformer model is not supported yet.') model.eval() model = ch.nn.DataParallel(model.to(device)) return model, pooled_output def get_features_batch(batch, model, dataset_type, pooled_output=None, device='cuda'): if dataset_type == 'vision': ims, targets = batch (_,latents), _ = model(ims.to(device), with_latent=True) else: (input_ids, attention_mask, targets) = batch mask = targets != -1 input_ids, attention_mask, targets = [t[mask] for t in (input_ids, attention_mask, targets)] if hasattr(model, 'module'): model = model.module if hasattr(model, "roberta"): latents = model.roberta(input_ids=input_ids.to(device), attention_mask=attention_mask.to(device))[0] latents = model.classifier.dropout(latents[:,0,:]) latents = model.classifier.dense(latents) latents = ch.tanh(latents) latents = model.classifier.dropout(latents) else: latents = model.bert(input_ids=input_ids.to(device), attention_mask=attention_mask.to(device)) if pooled_output: latents = latents[1] else: latents = latents[0][:,0] return latents, targets def compute_features(loader, model, dataset_type, pooled_output, batch_size, num_workers, shuffle=False, device='cuda', filename=None, chunk_threshold=20000, balance=False): """Compute deep features for a given dataset using a modeln and returnss them as a pytorch dataset and loader. Args: loader : Torch data loader model: Torch model dataset_type (str): One of vision or language pooled_output (bool): Whether or not to pool outputs (only relevant for some language models) batch_size (int): Batch size for output loader num_workers (int): Number of workers to use for output loader shuffle (bool): Whether or not to shuffle output data loaoder device (str): Device on which to keep the model filename (str):Optional file to cache computed feature. Recommended for large datasets like ImageNet. chunk_threshold (int): Size of shard while caching balance (bool): Whether or not to balance output data loader (only relevant for some language models) Returns: feature_dataset: Torch dataset with deep features feature_loader: Torch data loader with deep features """ if filename is None or not os.path.exists(os.path.join(filename, f'0_features.npy')): all_latents, all_targets = [], [] Nsamples, chunk_id = 0, 0 for batch_idx, batch in tqdm(enumerate(loader), total=len(loader)): with ch.no_grad(): latents, targets = get_features_batch(batch, model, dataset_type, pooled_output=pooled_output, device=device) if batch_idx == 0: print("Latents shape", latents.shape) Nsamples += latents.size(0) all_latents.append(latents.cpu()) all_targets.append(targets.cpu()) if filename is not None and Nsamples > chunk_threshold: if not os.path.exists(filename): os.makedirs(filename) np.save(os.path.join(filename, f'{chunk_id}_features.npy'), ch.cat(all_latents).numpy()) np.save(os.path.join(filename, f'{chunk_id}_labels.npy'), ch.cat(all_targets).numpy()) all_latents, all_targets, Nsamples = [], [], 0 chunk_id += 1 if filename is not None and Nsamples > 0: if not os.path.exists(filename): os.makedirs(filename) np.save(os.path.join(filename, f'{chunk_id}_features.npy'), ch.cat(all_latents).numpy()) np.save(os.path.join(filename, f'{chunk_id}_labels.npy'), ch.cat(all_targets).numpy()) feature_dataset = load_features(filename) if filename is not None else \ ch.utils.data.TensorDataset(ch.cat(all_latents), ch.cat(all_targets)) if balance: feature_dataset = balance_dataset(feature_dataset) feature_loader = ch.utils.data.DataLoader(feature_dataset, num_workers=num_workers, batch_size=batch_size, shuffle=shuffle) return feature_dataset, feature_loader def balance_dataset(dataset): """Balances a given dataset to have the same number of samples/class. Args: dataset : Torch dataset Returns: Torch dataset with equal number of samples/class """ print("Balancing dataset...") n = len(dataset) labels = ch.Tensor([dataset[i][1] for i in range(n)]).int() n0 = sum(labels).item() I_pos = labels == 1 idx = ch.arange(n) idx_pos = idx[I_pos] ch.manual_seed(0) I = ch.randperm(n - n0)[:n0] idx_neg = idx[~I_pos][I] idx_bal = ch.cat([idx_pos, idx_neg],dim=0) return Subset(dataset, idx_bal) def load_features_mode(feature_path, mode='test', num_workers=10, batch_size=128): """Loads precomputed deep features corresponding to the train/test set along with normalization statitic. Args: feature_path (str): Path to precomputed deep features mode (str): One of train or tesst num_workers (int): Number of workers to use for output loader batch_size (int): Batch size for output loader Returns: features (np.array): Recovered deep features feature_mean: Mean of deep features feature_std: Standard deviation of deep features """ feature_dataset = load_features(os.path.join(feature_path, f'features_{mode}')) feature_loader = ch.utils.data.DataLoader(feature_dataset, num_workers=num_workers, batch_size=batch_size, shuffle=False) feature_metadata = ch.load(os.path.join(feature_path, f'metadata_train.pth')) feature_mean, feature_std = feature_metadata['X']['mean'], feature_metadata['X']['std'] features = [] for _, (feature, _) in tqdm(enumerate(feature_loader), total=len(feature_loader)): features.append(feature) features = ch.cat(features).numpy() return features, feature_mean, feature_std def load_features(feature_path): """Loads precomputed deep features. Args: feature_path (str): Path to precomputed deep features Returns: Torch dataset with recovered deep features. """ if not os.path.exists(os.path.join(feature_path, f"0_features.npy")): raise ValueError(f"The provided location {feature_path} does not contain any representation files") ds_list, chunk_id = [], 0 while os.path.exists(os.path.join(feature_path, f"{chunk_id}_features.npy")): features = ch.from_numpy(np.load(os.path.join(feature_path, f"{chunk_id}_features.npy"))).float() labels = ch.from_numpy(np.load(os.path.join(feature_path, f"{chunk_id}_labels.npy"))).long() ds_list.append(ch.utils.data.TensorDataset(features, labels)) chunk_id += 1 print(f"==> loaded {chunk_id} files of representations...") return ch.utils.data.ConcatDataset(ds_list) def calculate_metadata(loader, num_classes=None, filename=None): """Calculates mean and standard deviation of the deep features over a given set of images. Args: loader : torch data loader num_classes (int): Number of classes in the dataset filename (str): Optional filepath to cache metadata. Recommended for large datasets like ImageNet. Returns: metadata (dict): Dictionary with desired statistics. """ if filename is not None and os.path.exists(filename): return ch.load(filename) # Calculate number of classes if not given if num_classes is None: num_classes = 1 for batch in loader: y = batch[1] print(y) num_classes = max(num_classes, y.max().item()+1) eye = ch.eye(num_classes) X_bar, y_bar, y_max, n = 0, 0, 0, 0 # calculate means and maximum print("Calculating means") for X,y in tqdm(loader, total=len(loader)): X_bar += X.sum(0) y_bar += eye[y].sum(0) y_max = max(y_max, y.max()) n += y.size(0) X_bar = X_bar.float()/n y_bar = y_bar.float()/n # calculate std X_std, y_std = 0, 0 print("Calculating standard deviations") for X,y in tqdm(loader, total=len(loader)): X_std += ((X - X_bar)**2).sum(0) y_std += ((eye[y] - y_bar)**2).sum(0) X_std = ch.sqrt(X_std.float()/n) y_std = ch.sqrt(y_std.float()/n) # calculate maximum regularization inner_products = 0 print("Calculating maximum lambda") for X,y in tqdm(loader, total=len(loader)): y_map = (eye[y] - y_bar)/y_std inner_products += X.t().mm(y_map)*y_std inner_products_group = inner_products.norm(p=2,dim=1) metadata = { "X": { "mean": X_bar, "std": X_std, "num_features": X.size()[1:], "num_examples": n }, "y": { "mean": y_bar, "std": y_std, "num_classes": y_max+1 }, "max_reg": { "group": inner_products_group.abs().max().item()/n, "nongrouped": inner_products.abs().max().item()/n } } if filename is not None: ch.save(metadata, filename) return metadata def split_dataset(dataset, Ntotal, val_frac, batch_size, num_workers, random_seed=0, shuffle=True, balance=False): """Splits a given dataset into train and validation Args: dataset : Torch dataset Ntotal: Total number of dataset samples val_frac: Fraction to reserve for validation batch_size (int): Batch size for output loader num_workers (int): Number of workers to use for output loader random_seed (int): Random seed shuffle (bool): Whether or not to shuffle output data loaoder balance (bool): Whether or not to balance output data loader (only relevant for some language models) Returns: split_datasets (list): List of datasets (one each for train and val) split_loaders (list): List of loaders (one each for train and val) """ Nval = math.floor(Ntotal*val_frac) train_ds, val_ds = ch.utils.data.random_split(dataset, [Ntotal - Nval, Nval], generator=ch.Generator().manual_seed(random_seed)) if balance: val_ds = balance_dataset(val_ds) split_datasets = [train_ds, val_ds] split_loaders = [] for ds in split_datasets: split_loaders.append(ch.utils.data.DataLoader(ds, num_workers=num_workers, batch_size=batch_size, shuffle=shuffle)) return split_datasets, split_loaders
13,878
38.31728
107
py
DebuggableDeepNetworks
DebuggableDeepNetworks-main/helpers/nlp_helpers.py
import torch as ch import numpy as np from lime.lime_text import LimeTextExplainer from tqdm import tqdm from wordcloud import WordCloud import matplotlib import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') import os from collections import defaultdict def make_lime_fn(model,val_set, pooled_output, mu, std, bs=128): device = 'cuda' def classifier_fn(sentences): try: input_ids, attention_mask = zip(*[val_set.process_sentence(s) for s in sentences]) except: input_ids, attention_mask = zip(*[val_set.dataset.process_sentence(s) for s in sentences]) input_ids, attention_mask = ch.stack(input_ids), ch.stack(attention_mask) all_reps = [] n = input_ids.size(0) # bs = args.batch_size for i in range(0,input_ids.size(0),bs): i0 = min(i+bs,n) # reps, _ = if hasattr(model, "roberta"): output = model.roberta(input_ids=input_ids[i:i0].to(device), attention_mask=attention_mask[i:i0].to(device)) output = output[0] # do RobertA classification head minus last out_proj classifier # https://huggingface.co/transformers/_modules/transformers/models/roberta/modeling_roberta.html output = output[:,0,:] output = model.classifier.dropout(output) output = model.classifier.dense(output) output = ch.tanh(output) cls_reps = model.classifier.dropout(output) else: output = model.bert(input_ids=input_ids[i:i0].to(device), attention_mask=attention_mask[i:i0].to(device)) if pooled_output: cls_reps = output[1] else: cls_reps = output[0][:,0] cls_reps = cls_reps.cpu() cls_reps = (cls_reps - mu)/std all_reps.append(cls_reps.cpu()) return ch.cat(all_reps,dim=0).numpy() return classifier_fn def get_lime_features(model, val_set, val_loader, out_dir, pooled_output, mu, std): os.makedirs(out_dir,exist_ok=True) explainer = LimeTextExplainer() reps_size = 768 clf_fn = make_lime_fn(model,val_set, pooled_output, mu, std) files = [] with ch.no_grad(): print('number of sentences', len(val_loader)) for i,(sentences, labels) in enumerate(tqdm(val_loader, total=len(val_loader), desc="Generating LIME")): assert len(sentences) == 1 sentence, label = sentences[0], labels[0] if label.item() == -1: continue out_file = f"{out_dir}/{i}.pth" try: files.append(ch.load(out_file)) continue except: pass # if os.path.exists(out_file): # continue exp = explainer.explain_instance(sentence, clf_fn, labels=list(range(reps_size))) out = { "sentence": sentence, "explanation": exp } ch.save(out, out_file) files.append(out) return files def top_and_bottom_words(files, num_features=768): top_words = [] bot_words = [] for j in range(num_features): exps = [f['explanation'].as_list(label=j) for f in files] exps_collapsed = [a for e in exps for a in e] accumulator = defaultdict(lambda: []) for word,weight in exps_collapsed: accumulator[word].append(weight) exps_collapsed = [(k,np.array(accumulator[k]).mean()) for k in accumulator] exps_collapsed.sort(key=lambda a: a[1]) weights = [a[1] for a in exps_collapsed] l = np.percentile(weights, q=1) u = np.percentile(weights, q=99) top_words.append([a for a in reversed(exps_collapsed) if a[1] > u]) bot_words.append([a for a in exps_collapsed if a[1] < l]) return top_words,bot_words def get_explanations(feature_idxs, sparse, top_words, bot_words): expl_dict = {} maxfreq = 0 for i,idx in enumerate(feature_idxs): expl_dict[idx] = {} aligned = sparse[1,idx] > 0 for words, j in zip([top_words, bot_words],[0,1]): if not aligned: j = 1-j expl_dict[idx][j] = { a[0]:abs(a[1]) for a in words[idx] ## ARE THESE SIGNS CORRECT } maxfreq = max(maxfreq, max(list(expl_dict[idx][j].values()))) for k in expl_dict: for s in expl_dict[k]: expl_dict[k][s] = {kk: vv / maxfreq for kk, vv in expl_dict[k][s].items()} return expl_dict from matplotlib.colors import ListedColormap def grey_color_func(word, font_size, position, orientation, random_state=None, **kwargs): #cmap = sns.color_palette("RdYlGn_r", as_cmap=True) cmap = ListedColormap(sns.color_palette("RdYlGn_r").as_hex()) fs = (font_size - 14) / (42 - 14) color_orig = cmap(fs) color = (255 * np.array(cmap(fs))).astype(np.uint8) return tuple(color[:3]) def plot_wordcloud(expln_dict, weights, factor=3, transpose=False, labels=("Positive Sentiment", "Negative Sentiment")): if transpose: fig, axs = plt.subplots(2, len(expln_dict), figsize=(factor*3.5*len(expln_dict), factor*4), squeeze=False) else: fig, axs = plt.subplots(len(expln_dict), 2, figsize=(factor*7, factor*1.5*len(expln_dict)), squeeze=False) for i,idx in enumerate(expln_dict.keys()): if i == 0: if transpose: axs[0,0].set_ylabel(labels[0], fontsize=36) axs[1,0].set_ylabel(labels[1], fontsize=36) else: axs[i,0].set_title(labels[0], fontsize=36) axs[i,1].set_title(labels[1], fontsize=36) for j in [0, 1]: wc = WordCloud(background_color="white", max_words=1000, min_font_size=14, max_font_size=42) # generate word cloud d = {k[:20]:v for k,v in expln_dict[idx][j].items()} wc.generate_from_frequencies(d) default_colors = wc.to_array() if transpose: ax = axs[j,i] else: ax = axs[i,j] ax.imshow(wc.recolor(color_func=grey_color_func, random_state=3), interpolation="bilinear") ax.set_xticks([]) ax.set_yticks([]) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['bottom'].set_visible(False) # ax.set_axis_off() if not transpose: axs[i,0].set_ylabel(f"#{idx}\nW={weights[i]:.4f}", fontsize=36) else: axs[0,i].set_title(f"#{idx}", fontsize=36) plt.tight_layout() # plt.subplots_adjust(left=None, bottom=0.1, right=None, top=0.9, wspace=0.25, hspace=0.0) return fig, axs
7,049
37.736264
124
py
DebuggableDeepNetworks
DebuggableDeepNetworks-main/helpers/vis_helpers.py
import sys sys.path.append('./lucent') import torch as ch import torchvision import numpy as np import matplotlib.pyplot as plt import seaborn as sns from functools import partial from lucent.optvis import render, param, transform, objectives from lime import lime_image def plot_sparsity(results): """Function to visualize the sparsity-accuracy trade-off of regularized decision layers Args: results (dictionary): Appropriately formatted dictionary with regularization paths and logs of train/val/test accuracy. """ if type(results['metrics']['acc_train'].values[0]) == list: all_tr = 100 * np.array(results['metrics']['acc_train'].values[0]) all_val = 100 * np.array(results['metrics']['acc_val'].values[0]) all_te = 100 * np.array(results['metrics']['acc_test'].values[0]) else: all_tr = 100 * np.array(results['metrics']['acc_train'].values) all_val = 100 * np.array(results['metrics']['acc_val'].values) all_te = 100 * np.array(results['metrics']['acc_test'].values) fig, axarr = plt.subplots(1, 2, figsize=(14, 5)) axarr[0].plot(all_tr) axarr[0].plot(all_val) axarr[0].plot(all_te) axarr[0].legend(['Train', 'Val', 'Test'], fontsize=16) axarr[0].set_ylabel("Accuracy (%)", fontsize=18) axarr[0].set_xlabel("Regularization index", fontsize=18) num_features = results['weights'][0].shape[1] total_sparsity = np.mean(results['sparsity'], axis=1) / num_features axarr[1].plot(total_sparsity, all_tr, 'o-') axarr[1].plot(total_sparsity, all_te, 'o-') axarr[1].legend(['Train', 'Val', 'Test'], fontsize=16) axarr[1].set_ylabel("Accuracy (%)", fontsize=18) axarr[1].set_xlabel("1 - Sparsity", fontsize=18) axarr[1].set_xscale('log') plt.show() def normalize_weight(w): """Normalizes weights to a unit vector Args: w (tensor): Weight vector for a class. Returns: Normalized weight vector in the form of a numpy array. """ return w.numpy() / np.linalg.norm(w.numpy()) def get_feature_visualization(model, feature_idx, signs): """Performs feature visualization using Lucid. Args: model: deep network whose deep features are to be visualized. feature_idx: indice of features to visualize. signs: +/-1 array indicating whether a feature should be maximized/minimized. Returns: Batch of feature visualizations . """ param_f = lambda: param.image(224, batch=len(feature_idx), fft=True, decorrelate=True) obj = 0 for fi, (f, s) in enumerate(zip(feature_idx, signs)): obj += s * objectives.channel('avgpool', f, batch=fi) op = render.render_vis(model.model, show_inline=False, objective_f=obj, param_f=param_f, thresholds=(512,))[0] return ch.tensor(op).permute(0, 3, 1, 2) def latent_predict(images, model, mean=None, std=None): """LIME helper function that computes the deep feature representation for a given batch of images. Args: image (tensor): batch of images. model: deep network whose deep features are to be visualized. mean (tensor): mean of deep features. std (tensor): std deviation of deep features. Returns: Normalized deep features for batch of images. """ preprocess_transform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), ]) device = 'cuda' if next(model.parameters()).is_cuda else 'cpu' batch = ch.stack(tuple(preprocess_transform(i) for i in images), dim=0).to(device) (_, latents), _ = model(batch.to(ch.float), with_latent=True) scaled_latents = (latents.detach().cpu() - mean.to(ch.float)) / std.to(ch.float) return scaled_latents.numpy() def parse_lime_explanation(expln, f, sign, NLime=3): """LIME helper function that extracts a mask from a lime explanation Args: expln: LIME explanation from LIME library f: indice of features to visualize sign: +/-1 array indicating whether the feature should be maximized/minimized. images (tensor): batch of images. NLime (int): Number of top-superpixels to visualize. Returns: Tensor where the first and second channels contains superpixels that cause the deep feature to activate and deactivate respectively. """ segs = expln.segments vis_mask = np.zeros(segs.shape + (3,)) weights = sorted([v for v in expln.local_exp[f]], key=lambda x: -np.abs(x[1])) weight_values = [w[1] for w in weights] pos_lim, neg_lim = np.max(weight_values), (1e-8 + np.min(weight_values)) if NLime is not None: weights = weights[:NLime] for wi, w in enumerate(weights): if w[1] >= 0: si = (w[1] / pos_lim, 0, 0) if sign == 1 else (0, w[1] / pos_lim, 0) else: si = (0, w[1] / neg_lim, 0) if sign == 1 else (w[1] / neg_lim, 0, 0) vis_mask[segs == w[0]] = si return ch.tensor(vis_mask.transpose(2, 0, 1)) def get_lime_explanation(model, feature_idx, signs, images, rep_mean, rep_std, num_samples=1000, NLime=3, background_color=0.6): """Computes LIME explanations for a given set of deep features. The LIME objective in this case is to identify the superpixels within the specified images that maximally/minimally activate the corresponding deep feature. Args: model: deep network whose deep features are to be visualized. feature_idx: indice of features to visualize signs: +/-1 array indicating whether a feature should be maximized/minimized. images (tensor): batch of images. rep_mean (tensor): mean of deep features. rep_std (tensor): std deviation of deep features. NLime (int): Number of top-superpixels to visualize background_color (float): Color to assign non-relevant super pixels Returns: Tensor comprising LIME explanations for the given set of deep features. """ explainer = lime_image.LimeImageExplainer() lime_objective = partial(latent_predict, model=model, mean=rep_mean, std=rep_std) explanations = [] for im, feature, sign in zip(images, feature_idx, signs): explanation = explainer.explain_instance(im.numpy().transpose(1, 2, 0), lime_objective, labels=np.array([feature]), top_labels=None, hide_color=0, num_samples=num_samples) explanation = parse_lime_explanation(explanation, feature, sign, NLime=NLime) if sign == 1: explanation = explanation[:1].unsqueeze(0).repeat(1, 3, 1, 1) else: explanation = explanation[1:2].unsqueeze(0).repeat(1, 3, 1, 1) interpolated = im * explanation + background_color * ch.ones_like(im) * (1 - explanation) explanations.append(interpolated) return ch.cat(explanations)
7,415
41.62069
97
py
DebuggableDeepNetworks
DebuggableDeepNetworks-main/helpers/decisionlayer_helpers.py
import os import numpy as np import torch as ch import pandas as pd def load_glm(result_dir): Nlambda = max([int(f.split('params')[1].split('.pth')[0]) for f in os.listdir(result_dir) if 'params' in f]) + 1 print(f"Loading regularization path of length {Nlambda}") params_dict = {i: ch.load(os.path.join(result_dir, f"params{i}.pth"), map_location=ch.device('cpu')) for i in range(Nlambda)} regularization_strengths = [params_dict[i]['lam'].item() for i in range(Nlambda)] weights = [params_dict[i]['weight'] for i in range(Nlambda)] biases = [params_dict[i]['bias'] for i in range(Nlambda)] metrics = {'acc_tr': [], 'acc_val': [], 'acc_test': []} for k in metrics.keys(): for i in range(Nlambda): metrics[k].append(params_dict[i]['metrics'][k]) metrics[k] = 100 * np.stack(metrics[k]) metrics = pd.DataFrame(metrics) metrics = metrics.rename(columns={'acc_tr': 'acc_train'}) weights_stacked = ch.stack(weights) sparsity = ch.sum(weights_stacked != 0, dim=2).numpy() return {'metrics': metrics, 'regularization_strengths': regularization_strengths, 'weights': weights, 'biases': biases, 'sparsity': sparsity, 'weight_dense': weights[-1], 'bias_dense': biases[-1]} def select_sparse_model(result_dict, selection_criterion='absolute', factor=6): assert selection_criterion in ['sparsity', 'absolute', 'relative', 'percentile'] metrics, sparsity = result_dict['metrics'], result_dict['sparsity'] acc_val, acc_test = metrics['acc_val'], metrics['acc_test'] if factor == 0: sel_idx = -1 elif selection_criterion == 'sparsity': sel_idx = np.argmin(np.abs(np.mean(sparsity, axis=1) - factor)) elif selection_criterion == 'relative': sel_idx = np.argmin(np.abs(acc_val - factor * np.max(acc_val))) elif selection_criterion == 'absolute': delta = acc_val - (np.max(acc_val) - factor) lidx = np.where(delta <= 0)[0] sel_idx = lidx[np.argmin(-delta[lidx])] elif selection_criterion == 'percentile': diff = np.max(acc_val) - np.min(acc_val) sel_idx = np.argmax(acc_val > np.max(acc_val) - factor * diff) print(f"Test accuracy | Best: {max(acc_test): .2f},", f"Sparse: {acc_test[sel_idx]:.2f}", f"Sparsity: {np.mean(sparsity[sel_idx]):.2f}") result_dict.update({'weight_sparse': result_dict['weights'][sel_idx], 'bias_sparse': result_dict['biases'][sel_idx]}) return result_dict
2,735
38.085714
85
py
DebuggableDeepNetworks
DebuggableDeepNetworks-main/language/datasets.py
import pandas as pd import torch from torch.utils.data import Dataset from transformers import AutoTokenizer, AutoConfig from .jigsaw_loaders import JigsawDataOriginal def DATASETS(dataset_name): if dataset_name == 'sst': return SSTDataset elif dataset_name.startswith('jigsaw'): return JigsawDataset else: raise ValueError("Language dataset is not currently supported...") class SSTDataset(Dataset): """ Stanford Sentiment Treebank V1.0 Recursive Deep Models for Semantic Compositionality Over a Sentiment Treebank Richard Socher, Alex Perelygin, Jean Wu, Jason Chuang, Christopher Manning, Andrew Ng and Christopher Potts Conference on Empirical Methods in Natural Language Processing (EMNLP 2013) """ def __init__(self, filename, maxlen, tokenizer, return_sentences=False): #Store the contents of the file in a pandas dataframe self.df = pd.read_csv(filename, delimiter = '\t') #Initialize the tokenizer for the desired transformer model self.tokenizer = tokenizer #Maximum length of the tokens list to keep all the sequences of fixed size self.maxlen = maxlen #whether to tokenize or return raw setences self.return_sentences = return_sentences def __len__(self): return len(self.df) def __getitem__(self, index): #Select the sentence and label at the specified index in the data frame sentence = self.df.loc[index, 'sentence'] label = self.df.loc[index, 'label'] #Preprocess the text to be suitable for the transformer if self.return_sentences: return sentence, label else: input_ids, attention_mask = self.process_sentence(sentence) return input_ids, attention_mask, label def process_sentence(self, sentence): tokens = self.tokenizer.tokenize(sentence) tokens = ['[CLS]'] + tokens + ['[SEP]'] if len(tokens) < self.maxlen: tokens = tokens + ['[PAD]' for _ in range(self.maxlen - len(tokens))] else: tokens = tokens[:self.maxlen-1] + ['[SEP]'] #Obtain the indices of the tokens in the BERT Vocabulary input_ids = self.tokenizer.convert_tokens_to_ids(tokens) input_ids = torch.tensor(input_ids) #Obtain the attention mask i.e a tensor containing 1s for no padded tokens and 0s for padded ones attention_mask = (input_ids != 0).long() return input_ids, attention_mask class JigsawDataset(Dataset): def __init__(self, filename, maxlen, tokenizer, return_sentences=False, label="toxic"): classes=[label] if 'train' in filename: self.dataset = JigsawDataOriginal( train_csv_file=filename, test_csv_file=None, train=True, create_val_set=False, add_test_labels=False, classes=classes ) elif 'test' in filename: self.dataset = JigsawDataOriginal( train_csv_file=None, test_csv_file=filename, train=False, create_val_set=False, add_test_labels=True, classes=classes ) else: raise ValueError("Unknown filename {filename}") # #Store the contents of the file in a pandas dataframe # self.df = pd.read_csv(filename, header=None, names=['label', 'sentence']) #Initialize the tokenizer for the desired transformer model self.tokenizer = tokenizer #Maximum length of the tokens list to keep all the sequences of fixed size self.maxlen = maxlen #whether to tokenize or return raw setences self.return_sentences = return_sentences def __len__(self): return len(self.dataset) def __getitem__(self, index): #Select the sentence and label at the specified index in the data frame sentence, meta = self.dataset[index] label = meta["multi_target"].squeeze() #Preprocess the text to be suitable for the transformer if self.return_sentences: return sentence, label else: input_ids, attention_mask = self.process_sentence(sentence) return input_ids, attention_mask, label def process_sentence(self, sentence): # print(sentence) d = self.tokenizer(sentence, padding='max_length', truncation=True) input_ids = torch.tensor(d["input_ids"]) attention_mask = torch.tensor(d["attention_mask"]) return input_ids, attention_mask
4,062
35.603604
108
py
DebuggableDeepNetworks
DebuggableDeepNetworks-main/language/jigsaw_loaders.py
from torch.utils.data.dataset import Dataset import torch import pandas as pd import numpy as np import language.datasets from tqdm import tqdm class JigsawData(Dataset): """Dataloader for the Jigsaw Toxic Comment Classification Challenges. If test_csv_file is None and create_val_set is True the train file specified gets split into a train and validation set according to train_fraction.""" def __init__( self, train_csv_file, test_csv_file, train=True, val_fraction=0.9, add_test_labels=False, create_val_set=True, ): if train_csv_file is not None: if isinstance(train_csv_file, list): train_set_pd = self.load_data(train_csv_file) else: train_set_pd = pd.read_csv(train_csv_file) self.train_set_pd = train_set_pd if "toxicity" not in train_set_pd.columns: train_set_pd.rename(columns={"target": "toxicity"}, inplace=True) self.train_set = datasets.Dataset.from_pandas(train_set_pd) if create_val_set: data = self.train_set.train_test_split(val_fraction) self.train_set = data["train"] self.val_set = data["test"] if test_csv_file is not None: val_set = pd.read_csv(test_csv_file) if add_test_labels: data_labels = pd.read_csv(test_csv_file[:-4] + "_labels.csv") for category in data_labels.columns[1:]: val_set[category] = data_labels[category] val_set = datasets.Dataset.from_pandas(val_set) self.val_set = val_set if train: self.data = self.train_set else: self.data = self.val_set self.train = train def __len__(self): return len(self.data) def load_data(self, train_csv_file): files = [] cols = ["id", "comment_text", "toxic"] for file in tqdm(train_csv_file): file_df = pd.read_csv(file) file_df = file_df[cols] file_df = file_df.astype({"id": "string"}, {"toxic": "float64"}) files.append(file_df) train = pd.concat(files) return train class JigsawDataOriginal(JigsawData): """Dataloader for the original Jigsaw Toxic Comment Classification Challenge. Source: https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge """ def __init__( self, train_csv_file="jigsaw_data/train.csv", test_csv_file="jigsaw_data/test.csv", train=True, val_fraction=0.1, create_val_set=True, add_test_labels=True, classes=["toxic"], ): super().__init__( train_csv_file=train_csv_file, test_csv_file=test_csv_file, train=train, val_fraction=val_fraction, add_test_labels=add_test_labels, create_val_set=create_val_set, ) self.classes = classes def __getitem__(self, index): meta = {} entry = self.data[index] text_id = entry["id"] text = entry["comment_text"] target_dict = { label: value for label, value in entry.items() if label in self.classes } meta["multi_target"] = torch.tensor( list(target_dict.values()), dtype=torch.int32 ) meta["text_id"] = text_id return text, meta class JigsawDataBias(JigsawData): """Dataloader for the Jigsaw Unintended Bias in Toxicity Classification. Source: https://www.kaggle.com/c/jigsaw-unintended-bias-in-toxicity-classification/ """ def __init__( self, train_csv_file="jigsaw_data/train.csv", test_csv_file="jigsaw_data/test.csv", train=True, val_fraction=0.1, create_val_set=True, compute_bias_weights=True, loss_weight=0.75, classes=["toxic"], identity_classes=["female"], ): self.classes = classes self.identity_classes = identity_classes super().__init__( train_csv_file=train_csv_file, test_csv_file=test_csv_file, train=train, val_fraction=val_fraction, create_val_set=create_val_set, ) if train: if compute_bias_weights: self.weights = self.compute_weigths(self.train_set_pd) else: self.weights = None self.train = train self.loss_weight = loss_weight def __getitem__(self, index): meta = {} entry = self.data[index] text_id = entry["id"] text = entry["comment_text"] target_dict = {label: 1 if entry[label] >= 0.5 else 0 for label in self.classes} identity_target = { label: -1 if entry[label] is None else entry[label] for label in self.identity_classes } identity_target.update( {label: 1 for label in identity_target if identity_target[label] >= 0.5} ) identity_target.update( {label: 0 for label in identity_target if 0 <= identity_target[label] < 0.5} ) target_dict.update(identity_target) meta["multi_target"] = torch.tensor( list(target_dict.values()), dtype=torch.float32 ) meta["text_id"] = text_id if self.train: meta["weights"] = self.weights[index] toxic_weight = ( self.weights[index] * self.loss_weight * 1.0 / len(self.classes) ) identity_weight = (1 - self.loss_weight) * 1.0 / len(self.identity_classes) meta["weights1"] = torch.tensor( [ *[toxic_weight] * len(self.classes), *[identity_weight] * len(self.identity_classes), ] ) return text, meta def compute_weigths(self, train_df): """Inspired from 2nd solution. Source: https://www.kaggle.com/c/jigsaw-unintended-bias-in-toxicity-classification/discussion/100661""" subgroup_bool = (train_df[self.identity_classes].fillna(0) >= 0.5).sum( axis=1 ) > 0 positive_bool = train_df["toxicity"] >= 0.5 weights = np.ones(len(train_df)) * 0.25 # Backgroud Positive and Subgroup Negative weights[ ((~subgroup_bool) & (positive_bool)) | ((subgroup_bool) & (~positive_bool)) ] += 0.25 weights[(subgroup_bool)] += 0.25 return weights class JigsawDataMultilingual(JigsawData): """Dataloader for the Jigsaw Multilingual Toxic Comment Classification. Source: https://www.kaggle.com/c/jigsaw-multilingual-toxic-comment-classification/ """ def __init__( self, train_csv_file="jigsaw_data/multilingual_challenge/jigsaw-toxic-comment-train.csv", test_csv_file="jigsaw_data/multilingual_challenge/validation.csv", train=True, val_fraction=0.1, create_val_set=False, classes=["toxic"], ): self.classes = classes super().__init__( train_csv_file=train_csv_file, test_csv_file=test_csv_file, train=train, val_fraction=val_fraction, create_val_set=create_val_set, ) def __getitem__(self, index): meta = {} entry = self.data[index] text_id = entry["id"] if "translated" in entry: text = entry["translated"] elif "comment_text_en" in entry: text = entry["comment_text_en"] else: text = entry["comment_text"] target_dict = {label: 1 if entry[label] >= 0.5 else 0 for label in self.classes} meta["target"] = torch.tensor(list(target_dict.values()), dtype=torch.int32) meta["text_id"] = text_id return text, meta
7,960
30.717131
111
py
DebuggableDeepNetworks
DebuggableDeepNetworks-main/language/models.py
import torch import torch.nn as nn from transformers import BertModel, BertPreTrainedModel, BertForSequenceClassification, RobertaForSequenceClassification LANGUAGE_MODEL_DICT = { 'sst': 'barissayil/bert-sentiment-analysis-sst', 'jigsaw-toxic': 'unitary/toxic-bert', 'jigsaw-severe_toxic': 'unitary/toxic-bert', 'jigsaw-obscene': 'unitary/toxic-bert', 'jigsaw-threat': 'unitary/toxic-bert', 'jigsaw-insult': 'unitary/toxic-bert', 'jigsaw-identity_hate': 'unitary/toxic-bert', 'jigsaw-alt-toxic': 'unitary/unbiased-toxic-roberta', 'jigsaw-alt-severe_toxic': 'unitary/unbiased-toxic-roberta', 'jigsaw-alt-obscene': 'unitary/unbiased-toxic-roberta', 'jigsaw-alt-threat': 'unitary/unbiased-toxic-roberta', 'jigsaw-alt-insult': 'unitary/unbiased-toxic-roberta', 'jigsaw-alt-identity_hate': 'unitary/unbiased-toxic-roberta' } class BertForSentimentClassification(BertPreTrainedModel): def __init__(self, config): super().__init__(config) self.bert = BertModel(config) # self.dropout = nn.Dropout(config.hidden_dropout_prob) #The classification layer that takes the [CLS] representation and outputs the logit self.cls_layer = nn.Linear(config.hidden_size, 1) def forward(self, input_ids, attention_mask): ''' Inputs: -input_ids : Tensor of shape [B, T] containing token ids of sequences -attention_mask : Tensor of shape [B, T] containing attention masks to be used to avoid contibution of PAD tokens (where B is the batch size and T is the input length) ''' #Feed the input to Bert model to obtain contextualized representations reps, _ = self.bert(input_ids=input_ids, attention_mask=attention_mask) #Obtain the representations of [CLS] heads cls_reps = reps[:, 0] # cls_reps = self.dropout(cls_reps) logits = self.cls_layer(cls_reps) return logits
1,850
43.071429
120
py
fed_iot_guard
fed_iot_guard-main/src/main.py
from argparse import ArgumentParser import torch.utils.data from data import read_all_data, all_devices from federated_util import * from grid_search import run_grid_search from supervised_data import get_client_supervised_initial_splitting from test_hparams import test_hyperparameters from unsupervised_data import get_client_unsupervised_initial_splitting def main(experiment: str, setup: str, federated: str, test: bool, collaborative: bool): Ctp.set_automatic_skip(True) Ctp.print('\n\t\t\t\t\t' + (federated.upper() + ' ' if federated is not None else '') + setup.upper() + ' ' + experiment.upper() + (' TESTING' if test else ' GRID SEARCH') + '\n', bold=True) common_params = {'n_features': 115, 'normalization': 'min-max', # "min-max", "0-mean 1var" 'test_bs': 4096, 'p_test': 0.2, 'p_unused': 0.01, # Proportion of data left unused between *train_val set* and *test set* 'val_part': None, # This is the proportion of *train_val set* that goes into the validation set, not the proportion of all data 'n_splits': 5, # number of splits in the cross validation 'n_random_reruns': 5, 'cuda': False, # It looks like cuda is slower than CPU for me so I enforce using the CPU 'benign_prop': 0.0787, # Desired proportion of benign data in the train/validation sets (or None to keep the natural proportions) 'samples_per_device': 100_000} # Total number of datapoints (train & val + unused + test) for each device. # p_test, p_unused and p_train_val are the proportions of *all data* that go into respectively the *test set*, the *unused set* # and the *train_val set*. # val_part and threshold_part are the proportions of the the *train_val set* used for respectively the validation and the threshold # note that we either use one or the other: when grid searching we do not compute the threshold, so we have the *train_val set* # split between val_part proportion of validation data and (1. - val_part) proportion of train data # when testing hyper-params, we have *train & validation set* split between threshold_part proportion of threshold data and # (1. - threshold_part) proportion of train data. # benign_prop is yet another thing, determining the proportion of benign data when applicable (everywhere except in the *train_val set* # of the unsupervised method) p_train_val = 1. - common_params['p_test'] - common_params['p_unused'] if common_params['val_part'] is None: val_part = 1. / common_params['n_splits'] else: val_part = common_params['val_part'] common_params.update({'p_train_val': p_train_val, 'val_part': val_part}) if common_params['cuda']: Ctp.print('Using CUDA') else: Ctp.print('Using CPU') autoencoder_params = {'activation_fn': torch.nn.ELU, 'threshold_part': 0.5, 'quantile': 0.95, 'epochs': 120, 'train_bs': 64, 'optimizer': torch.optim.SGD, 'lr_scheduler': torch.optim.lr_scheduler.StepLR, 'lr_scheduler_params': {'step_size': 20, 'gamma': 0.5}} classifier_params = {'activation_fn': torch.nn.ELU, 'epochs': 4, 'train_bs': 64, 'optimizer': torch.optim.SGD, 'lr_scheduler': torch.optim.lr_scheduler.StepLR, 'lr_scheduler_params': {'step_size': 1, 'gamma': 0.5}} # Note that other architecture-specific parameters, such as the dimensions of the hidden layers, can be specified in either in the # varying_params for the grid searches, or in the configurations_params for the tests. n_devices = len(all_devices) # TODO: Be careful to switch that back to 64 for other aggregation functions fedsgd_params = {'train_bs': 8} # We can divide the batch size by the number of clients to make fedSGD closer to the centralized method fedavg_params = {'federation_rounds': 30, 'gamma_round': 0.75} federation_params = {'aggregation_function': federated_averaging, 'resampling': None} # s-resampling if federated is not None: if federated == 'fedsgd': federation_params.update(fedsgd_params) elif federated == 'fedavg': federation_params.update(fedavg_params) else: raise ValueError() Ctp.print("Federation params: {}".format(federation_params), color='blue') # data_poisoning: 'all_labels_flipping', 'benign_labels_flipping', 'attack_labels_flipping' # model_poisoning: 'cancel_attack', 'mimic_attack' # model update factor is the factor by which the difference between the original (global) model and the trained model is multiplied # (only applies to the malicious clients; for honest clients this factor is always 1) poisoning_params = {'n_malicious': 0, 'data_poisoning': None, 'p_poison': None, 'model_update_factor': 1.0, 'model_poisoning': None} if poisoning_params['n_malicious'] != 0: Ctp.print("Poisoning params: {}".format(poisoning_params), color='red') # 9 configurations in which we have 8 clients (each one owns the data from 1 device) and the data from the last device is left unseen. decentralized_configurations = [{'clients_devices': [[i] for i in range(n_devices) if i != test_device], 'test_devices': [test_device]} for test_device in range(n_devices)] local_configurations = [{'clients_devices': [[known_device]], 'test_devices': [i for i in range(n_devices) if i != known_device]} for known_device in range(n_devices)] # 9 configurations in which we have 1 client (owning the data from 8 devices) and he data from the last device is left unseen. centralized_configurations = [{'clients_devices': [[i for i in range(n_devices) if i != test_device]], 'test_devices': [test_device]} for test_device in range(n_devices)] if setup == 'centralized': configurations = centralized_configurations elif setup == 'decentralized': if collaborative: configurations = decentralized_configurations else: configurations = local_configurations else: raise ValueError Ctp.print(configurations) # Loading the data all_data = read_all_data() if experiment == 'autoencoder': constant_params = {**common_params, **autoencoder_params, **poisoning_params} splitting_function = get_client_unsupervised_initial_splitting if test: # TESTING if federated is not None: constant_params.update(federation_params) # set the hyper-parameters specific to each configuration (overrides the parameters defined in constant_params) configurations_params = [{'hidden_layers': [29], 'optimizer_params': {'lr': 1.0, 'weight_decay': 0.0}}, {'hidden_layers': [29], 'optimizer_params': {'lr': 1.0, 'weight_decay': 0.0}}, {'hidden_layers': [29], 'optimizer_params': {'lr': 1.0, 'weight_decay': 1e-05}}, {'hidden_layers': [29], 'optimizer_params': {'lr': 1.0, 'weight_decay': 0.0}}, {'hidden_layers': [29], 'optimizer_params': {'lr': 1.0, 'weight_decay': 0.0}}, {'hidden_layers': [29], 'optimizer_params': {'lr': 1.0, 'weight_decay': 0.0}}, {'hidden_layers': [29], 'optimizer_params': {'lr': 1.0, 'weight_decay': 0.0}}, {'hidden_layers': [29], 'optimizer_params': {'lr': 1.0, 'weight_decay': 0.0}}, {'hidden_layers': [29], 'optimizer_params': {'lr': 1.0, 'weight_decay': 0.0}}] test_hyperparameters(all_data, setup, experiment, federated, splitting_function, constant_params, configurations_params, configurations) else: # GRID-SEARCH varying_params = {'hidden_layers': [[86, 58, 38, 29, 38, 58, 86], [58, 29, 58], [29]], 'optimizer_params': [{'lr': 1.0, 'weight_decay': 0.}, {'lr': 1.0, 'weight_decay': 1e-5}, {'lr': 1.0, 'weight_decay': 1e-4}]} run_grid_search(all_data, setup, experiment, splitting_function, constant_params, varying_params, configurations, collaborative) elif experiment == 'classifier': constant_params = {**common_params, **classifier_params, **poisoning_params} splitting_function = get_client_supervised_initial_splitting if test: # TESTING if federated is not None: constant_params.update(federation_params) # set the hyper-parameters specific to each configuration (overrides the parameters defined in constant_params) configurations_params = [{'optimizer_params': {'lr': 0.5, 'weight_decay': 0.0}, 'hidden_layers': [115, 58, 29]}, {'optimizer_params': {'lr': 0.5, 'weight_decay': 1e-05}, 'hidden_layers': [115]}, {'optimizer_params': {'lr': 0.5, 'weight_decay': 0.0001}, 'hidden_layers': [115, 58, 29]}, {'optimizer_params': {'lr': 0.5, 'weight_decay': 0.0}, 'hidden_layers': [115, 58]}, {'optimizer_params': {'lr': 0.5, 'weight_decay': 0.0}, 'hidden_layers': [115, 58]}, {'optimizer_params': {'lr': 0.5, 'weight_decay': 1e-05}, 'hidden_layers': [115, 58, 29]}, {'optimizer_params': {'lr': 0.5, 'weight_decay': 0.0}, 'hidden_layers': [115, 58, 29]}, {'optimizer_params': {'lr': 0.5, 'weight_decay': 0.0}, 'hidden_layers': [115, 58]}, {'optimizer_params': {'lr': 0.5, 'weight_decay': 0.0001}, 'hidden_layers': [115, 58]}] test_hyperparameters(all_data, setup, experiment, federated, splitting_function, constant_params, configurations_params, configurations) else: # GRID-SEARCH varying_params = {'optimizer_params': [{'lr': 0.5, 'weight_decay': 0.}, {'lr': 0.5, 'weight_decay': 1e-5}, {'lr': 0.5, 'weight_decay': 1e-4}], 'hidden_layers': [[115, 58, 29], [115, 58], [115], []]} run_grid_search(all_data, setup, experiment, splitting_function, constant_params, varying_params, configurations, collaborative) else: raise ValueError if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('setup', help='centralized or decentralized') parser.add_argument('experiment', help='Experiment to run (classifier or autoencoder)') test_parser = parser.add_mutually_exclusive_group(required=False) test_parser.add_argument('--test', dest='test', action='store_true') test_parser.add_argument('--gs', dest='test', action='store_false') parser.set_defaults(test=False) collaborative_parser = parser.add_mutually_exclusive_group(required=False) collaborative_parser.add_argument('--collaborative', dest='collaborative', action='store_true', help='Makes the clients collaborate during the grid search by sharing their validation results. The results will be per configuration.') collaborative_parser.add_argument('--no-collaborative', dest='collaborative', action='store_false', help='Makes the clients not collaborate during the grid search by sharing their validation results. The results will be per client.') parser.set_defaults(collaborative=True) federated_parser = parser.add_mutually_exclusive_group(required=False) federated_parser.add_argument('--fedavg', dest='federated', action='store_const', const='fedavg', help='Federation of the models (default: None)') federated_parser.add_argument('--fedsgd', dest='federated', action='store_const', const='fedsgd', help='Federation of the models (default: None)') parser.set_defaults(federated=None) verbose_parser = parser.add_mutually_exclusive_group(required=False) verbose_parser.add_argument('--verbose', dest='verbose', action='store_true') verbose_parser.add_argument('--no-verbose', dest='verbose', action='store_false') parser.set_defaults(verbose=True) parser.add_argument('--verbose-depth', dest='max_depth', type=int, help='Maximum number of nested sections after which the printing will stop') parser.set_defaults(max_depth=None) args = parser.parse_args() if not args.verbose: # Deactivate all printing in the console Ctp.deactivate() if args.max_depth is not None: Ctp.set_max_depth(args.max_depth) # Set the max depth at which we print in the console main(args.experiment, args.setup, args.federated, args.test, args.collaborative)
13,742
58.493506
174
py
fed_iot_guard
fed_iot_guard-main/src/unsupervised_ml.py
from types import SimpleNamespace from typing import List, Dict, Tuple, Union, Optional import torch import torch.nn as nn from context_printer import Color from context_printer import ContextPrinter as Ctp # noinspection PyProtectedMember from torch.utils.data import DataLoader from architectures import Threshold from federated_util import model_poisoning, model_aggregation from metrics import BinaryClassificationResult from print_util import print_autoencoder_loss_stats, print_rates, print_autoencoder_loss_header def optimize(model: nn.Module, data: torch.Tensor, optimizer: torch.optim.Optimizer, criterion: torch.nn.Module) -> torch.Tensor: output = model(data) # Since the normalization is made by the model itself, the output is computed on the normalized x # so we need to compute the loss with respect to the normalized x loss = criterion(output, model.normalize(data)) optimizer.zero_grad() loss.mean().backward() optimizer.step() return loss def train_autoencoder(model: nn.Module, params: SimpleNamespace, train_loader, lr_factor: float = 1.0) -> None: criterion = nn.MSELoss(reduction='none') optimizer = params.optimizer(model.parameters(), **params.optimizer_params) for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * lr_factor scheduler = params.lr_scheduler(optimizer, **params.lr_scheduler_params) model.train() num_elements = len(train_loader.dataset) num_batches = len(train_loader) batch_size = train_loader.batch_size print_autoencoder_loss_header(first_column='Epoch', print_lr=True) for epoch in range(params.epochs): losses = torch.zeros(num_elements) for i, (data,) in enumerate(train_loader): start = i * batch_size end = start + batch_size if i == num_batches - 1: end = num_elements loss = optimize(model, data, optimizer, criterion) losses[start:end] = loss.mean(dim=1) print_autoencoder_loss_stats('[{}/{}]'.format(epoch + 1, params.epochs), losses, lr=optimizer.param_groups[0]['lr']) scheduler.step() def train_autoencoders_fedsgd(global_model: nn.Module, models: List[nn.Module], dls: List[DataLoader], params: SimpleNamespace, lr_factor: float = 1.0, mimicked_client_id: Optional[int] = None)\ -> Tuple[torch.nn.Module, List[torch.nn.Module]]: criterion = nn.MSELoss(reduction='none') lr = params.optimizer_params['lr'] * lr_factor for model in models: model.train() for data_tuple in zip(*dls): for model, (data,) in zip(models, data_tuple): optimizer = params.optimizer(model.parameters(), lr=lr, weight_decay=params.optimizer_params['weight_decay']) optimize(model, data, optimizer, criterion) # Model poisoning attacks models = model_poisoning(global_model, models, params, mimicked_client_id=mimicked_client_id, verbose=False) # Aggregation global_model, models = model_aggregation(global_model, models, params, verbose=False) return global_model, models def compute_reconstruction_losses(model: nn.Module, dataloader) -> torch.Tensor: with torch.no_grad(): criterion = nn.MSELoss(reduction='none') model.eval() num_elements = len(dataloader.dataset) num_batches = len(dataloader) batch_size = dataloader.batch_size losses = torch.zeros(num_elements) for i, (x,) in enumerate(dataloader): output = model(x) loss = criterion(output, model.normalize(x)) start = i * batch_size end = start + batch_size if i == num_batches - 1: end = num_elements losses[start:end] = loss.mean(dim=1) return losses def test_autoencoder(model: nn.Module, threshold: nn.Module, dataloaders: Dict[str, DataLoader]) -> BinaryClassificationResult: print_autoencoder_loss_header(print_positives=True) result = BinaryClassificationResult() for key, dataloader in dataloaders.items(): losses = compute_reconstruction_losses(model, dataloader) predictions = torch.gt(losses, threshold.threshold).int() current_results = count_scores(predictions, is_attack=(key != 'benign')) title = ' '.join(key.split('_')).title() # Transforms for example the key "mirai_ack" into the title "Mirai Ack" print_autoencoder_loss_stats(title, losses, positives=current_results.tp + current_results.fp, n_samples=current_results.n_samples()) result += current_results return result # this function will train each model on its associated dataloader, and will print the title for it def multitrain_autoencoders(trains: List[Tuple[str, DataLoader, nn.Module]], params: SimpleNamespace, lr_factor: float = 1.0, main_title: str = 'Multitrain autoencoders', color: Union[str, Color] = Color.NONE) -> None: Ctp.enter_section(main_title, color) for i, (title, dataloader, model) in enumerate(trains): Ctp.enter_section('[{}/{}] '.format(i + 1, len(trains)) + title + ' ({} samples)'.format(len(dataloader.dataset[:][0])), color=Color.NONE, header=' ') train_autoencoder(model, params, dataloader, lr_factor) Ctp.exit_section() Ctp.exit_section() # Compute a single threshold value. If no quantile is indicated, it's the average reconstruction loss + its standard deviation, otherwise # it's the quantile of the loss. def compute_threshold_value(losses: torch.Tensor, quantile: Optional[float] = None) -> torch.Tensor: if quantile is None: threshold_value = losses.mean() + losses.std() else: threshold_value = losses.quantile(quantile) return threshold_value # opts should be a list of tuples (title, dataloader_benign_opt, model) # this function will test each model on its associated dataloader, and will find the correct threshold for them def compute_thresholds(opts: List[Tuple[str, DataLoader, nn.Module]], quantile: Optional[float] = None, main_title: str = 'Computing the thresholds', color: Union[str, Color] = Color.NONE) -> List[Threshold]: Ctp.enter_section(main_title, color) thresholds = [] for i, (title, dataloader, model) in enumerate(opts): Ctp.enter_section('[{}/{}] '.format(i + 1, len(opts)) + title + ' ({} samples)'.format(len(dataloader.dataset[:][0])), color=Color.NONE, header=' ') print_autoencoder_loss_header() losses = compute_reconstruction_losses(model, dataloader) print_autoencoder_loss_stats('Benign (opt)', losses) threshold_value = compute_threshold_value(losses, quantile) threshold = Threshold(threshold_value) thresholds.append(threshold) Ctp.print('The threshold is {:.4f}'.format(threshold.threshold.item())) Ctp.exit_section() Ctp.exit_section() return thresholds def count_scores(predictions: torch.Tensor, is_attack: bool) -> BinaryClassificationResult: positive_predictions = predictions.sum().item() negative_predictions = len(predictions) - positive_predictions results = BinaryClassificationResult() if is_attack: results.add_tp(positive_predictions) results.add_fn(negative_predictions) else: results.add_fp(positive_predictions) results.add_tn(negative_predictions) return results # this function will test each model on its associated dataloader, and will print the title for it def multitest_autoencoders(tests: List[Tuple[str, Dict[str, DataLoader], nn.Module, nn.Module]], main_title: str = 'Multitest autoencoders', color: Union[str, Color] = Color.NONE) -> BinaryClassificationResult: Ctp.enter_section(main_title, color) result = BinaryClassificationResult() for i, (title, dataloaders, model, threshold) in enumerate(tests): n_samples = sum([len(dataloader.dataset[:][0]) for dataloader in dataloaders.values()]) Ctp.enter_section('[{}/{}] '.format(i + 1, len(tests)) + title + ' ({} samples)'.format(n_samples), color=Color.NONE, header=' ') current_result = test_autoencoder(model, threshold, dataloaders) result += current_result Ctp.exit_section() print_rates(current_result) Ctp.exit_section() Ctp.print('Average result') print_rates(result) return result
8,557
42.663265
142
py
fed_iot_guard
fed_iot_guard-main/src/supervised_experiments.py
from types import SimpleNamespace from typing import Tuple, List import torch from context_printer import Color from context_printer import ContextPrinter as Ctp # noinspection PyProtectedMember from torch.utils.data import DataLoader from architectures import BinaryClassifier, NormalizingModel from data import ClientData, FederationData, device_names, get_benign_attack_samples_per_device from federated_util import init_federated_models, model_aggregation, select_mimicked_client, model_poisoning from metrics import BinaryClassificationResult from ml import set_model_sub_div, set_models_sub_divs from print_util import print_federation_round, print_rates, print_federation_epoch from supervised_data import get_train_dl, get_test_dl, prepare_dataloaders from supervised_ml import multitrain_classifiers, multitest_classifiers, train_classifier, test_classifier, train_classifiers_fedsgd def local_classifier_train_val(train_data: ClientData, val_data: ClientData, params: SimpleNamespace) -> BinaryClassificationResult: p_train = params.p_train_val * (1. - params.val_part) p_val = params.p_train_val * params.val_part # Creating the dataloaders benign_samples_per_device, attack_samples_per_device = get_benign_attack_samples_per_device(p_split=p_train, benign_prop=params.benign_prop, samples_per_device=params.samples_per_device) train_dl = get_train_dl(train_data, params.train_bs, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=params.cuda) benign_samples_per_device, attack_samples_per_device = get_benign_attack_samples_per_device(p_split=p_val, benign_prop=params.benign_prop, samples_per_device=params.samples_per_device) val_dl = get_test_dl(val_data, params.test_bs, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=params.cuda) # Initialize the model and compute the normalization values with the client's local training data model = NormalizingModel(BinaryClassifier(activation_function=params.activation_fn, hidden_layers=params.hidden_layers), sub=torch.zeros(params.n_features), div=torch.ones(params.n_features)) if params.cuda: model = model.cuda() set_model_sub_div(params.normalization, model, train_dl) # Local training Ctp.enter_section('Training for {} epochs with {} samples'.format(params.epochs, len(train_dl.dataset[:][0])), color=Color.GREEN) train_classifier(model, params, train_dl) Ctp.exit_section() # Local validation Ctp.print('Validating with {} samples'.format(len(val_dl.dataset[:][0]))) result = test_classifier(model, val_dl) print_rates(result) return result def local_classifiers_train_test(train_data: FederationData, local_test_data: FederationData, new_test_data: ClientData, params: SimpleNamespace) \ -> Tuple[BinaryClassificationResult, BinaryClassificationResult]: train_dls, local_test_dls, new_test_dl = prepare_dataloaders(train_data, local_test_data, new_test_data, params, federated=False) # Initialize the models and compute the normalization values with each client's local training data n_clients = len(params.clients_devices) models = [NormalizingModel(BinaryClassifier(activation_function=params.activation_fn, hidden_layers=params.hidden_layers), sub=torch.zeros(params.n_features), div=torch.ones(params.n_features)) for _ in range(n_clients)] if params.cuda: models = [model.cuda() for model in models] set_models_sub_divs(params.normalization, models, train_dls, color=Color.RED) # Training multitrain_classifiers(trains=list(zip(['Training client {} on: '.format(i) + device_names(client_devices) for i, client_devices in enumerate(params.clients_devices)], train_dls, models)), params=params, main_title='Training the clients', color=Color.GREEN) # Local testing local_result = multitest_classifiers(tests=list(zip(['Testing client {} on: '.format(i) + device_names(client_devices) for i, client_devices in enumerate(params.clients_devices)], local_test_dls, models)), main_title='Testing the clients on their own devices', color=Color.BLUE) # New devices testing new_devices_result = multitest_classifiers( tests=list(zip(['Testing client {} on: '.format(i) + device_names(params.test_devices) for i in range(n_clients)], [new_test_dl for _ in range(n_clients)], models)), main_title='Testing the clients on the new devices: ' + device_names(params.test_devices), color=Color.DARK_CYAN) return local_result, new_devices_result def federated_testing(global_model: torch.nn.Module, local_test_dls: List[DataLoader], new_test_dl: DataLoader, params: SimpleNamespace, local_results: List[BinaryClassificationResult], new_devices_results: List[BinaryClassificationResult]) -> None: # Global model testing on each client's data tests = [] for client_id, client_devices in enumerate(params.clients_devices): if client_id not in params.malicious_clients: tests.append(('Testing global model on: ' + device_names(client_devices), local_test_dls[client_id], global_model)) result = multitest_classifiers(tests=tests, main_title='Testing the global model on data from all clients', color=Color.BLUE) local_results.append(result) # Global model testing on new devices result = multitest_classifiers( tests=list(zip(['Testing global model on: ' + device_names(params.test_devices)], [new_test_dl], [global_model])), main_title='Testing the global model on the new devices: ' + device_names(params.test_devices), color=Color.DARK_CYAN) new_devices_results.append(result) def fedavg_classifiers_train_test(train_data: FederationData, local_test_data: FederationData, new_test_data: ClientData, params: SimpleNamespace) \ -> Tuple[List[BinaryClassificationResult], List[BinaryClassificationResult]]: # Preparation of the dataloaders train_dls, local_test_dls, new_test_dl = prepare_dataloaders(train_data, local_test_data, new_test_data, params, federated=True) # Initialization of the models global_model, models = init_federated_models(train_dls, params, architecture=BinaryClassifier) # Initialization of the results local_results, new_devices_results = [], [] # Selection of a client to mimic in case we use the mimic attack mimicked_client_id = select_mimicked_client(params) for federation_round in range(params.federation_rounds): print_federation_round(federation_round, params.federation_rounds) # Local training of each client multitrain_classifiers(trains=list(zip(['Training client {} on: '.format(i) + device_names(client_devices) for i, client_devices in enumerate(params.clients_devices)], train_dls, models)), params=params, lr_factor=(params.gamma_round ** federation_round), main_title='Training the clients', color=Color.GREEN) # Model poisoning attacks models = model_poisoning(global_model, models, params, mimicked_client_id=mimicked_client_id, verbose=True) # Aggregation global_model, models = model_aggregation(global_model, models, params, verbose=True) # Testing federated_testing(global_model, local_test_dls, new_test_dl, params, local_results, new_devices_results) Ctp.exit_section() return local_results, new_devices_results def fedsgd_classifiers_train_test(train_data: FederationData, local_test_data: FederationData, new_test_data: ClientData, params: SimpleNamespace) \ -> Tuple[List[BinaryClassificationResult], List[BinaryClassificationResult]]: # Preparation of the dataloaders train_dls, local_test_dls, new_test_dl = prepare_dataloaders(train_data, local_test_data, new_test_data, params, federated=True) # Initialization of the models global_model, models = init_federated_models(train_dls, params, architecture=BinaryClassifier) # Initialization of the results local_results, new_devices_results = [], [] # Selection of a client to mimic in case we use the mimic attack mimicked_client_id = select_mimicked_client(params) for epoch in range(params.epochs): print_federation_epoch(epoch, params.epochs) lr_factor = params.lr_scheduler_params['gamma'] ** (epoch // params.lr_scheduler_params['step_size']) global_model, models = train_classifiers_fedsgd(global_model, models, train_dls, params, epoch, lr_factor=lr_factor, mimicked_client_id=mimicked_client_id) federated_testing(global_model, local_test_dls, new_test_dl, params, local_results, new_devices_results) Ctp.exit_section() return local_results, new_devices_results
9,851
53.733333
142
py
fed_iot_guard
fed_iot_guard-main/src/supervised_data.py
from types import SimpleNamespace from typing import List, Tuple, Optional, Set import numpy as np import torch import torch.utils import torch.utils.data # noinspection PyProtectedMember from torch.utils.data import DataLoader, Dataset, TensorDataset from data import multiclass_labels, ClientData, FederationData, split_client_data, resample_array, get_benign_attack_samples_per_device def get_target_tensor(key: str, arr: np.ndarray, multiclass: bool = False, poisoning: Optional[str] = None, p_poison: Optional[float] = None) -> torch.Tensor: if multiclass: if poisoning is not None: raise NotImplementedError('Poisoning not implemented for multiclass data') return torch.full((arr.shape[0], 1), multiclass_labels[key]) else: target = torch.full((arr.shape[0], 1), (0. if key == 'benign' else 1.)) if poisoning is not None: if poisoning == 'all_labels_flipping' \ or (poisoning == 'benign_labels_flipping' and key == 'benign') \ or (poisoning == 'attack_labels_flipping' and key != 'benign'): if p_poison is None: raise ValueError('p_poison should be indicated for label flipping attack') n_poisoned = int(p_poison * len(target)) poisoned_indices = np.random.choice(len(target), n_poisoned, replace=False) # We turn 0 into 1 and 1 into 0 by subtracting 1 and raising to the power of 2 target[poisoned_indices] = torch.pow(target[poisoned_indices] - 1., 2) return target # Creates a dataset with the given client's data. If n_benign and n_attack are specified, up or down sampling will be used to have the right # amount of that class of data. The data can also be poisoned if needed. def get_dataset(data: ClientData, benign_samples_per_device: Optional[int] = None, attack_samples_per_device: Optional[int] = None, cuda: bool = False, multiclass: bool = False, poisoning: Optional[str] = None, p_poison: Optional[float] = None) -> Dataset: data_list, target_list = [], [] resample = benign_samples_per_device is not None and attack_samples_per_device is not None for device_data in data: number_of_attacks = len(device_data.keys()) - 1 n_samples_attack = attack_samples_per_device // 10 if number_of_attacks == 5: n_samples_attack *= 2 for key, arr in device_data.items(): # This will iterate over the benign splits, gafgyt splits and mirai splits (if applicable) if resample: if key == 'benign': arr = resample_array(arr, benign_samples_per_device) else: # We evenly divide the attack samples among the existing attacks on that device arr = resample_array(arr, n_samples_attack) data_tensor = torch.tensor(arr).float() target_tensor = get_target_tensor(key, arr, multiclass=multiclass, poisoning=poisoning, p_poison=p_poison) if cuda: data_tensor = data_tensor.cuda() target_tensor = target_tensor.cuda() data_list.append(data_tensor) target_list.append(target_tensor) dataset = TensorDataset(torch.cat(data_list, dim=0), torch.cat(target_list, dim=0)) return dataset def get_train_dl(client_train_data: ClientData, train_bs: int, benign_samples_per_device: Optional[int] = None, attack_samples_per_device: Optional[int] = None, cuda: bool = False, multiclass: bool = False, poisoning: Optional[str] = None, p_poison: Optional[float] = None) -> DataLoader: dataset_train = get_dataset(client_train_data, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=cuda, multiclass=multiclass, poisoning=poisoning, p_poison=p_poison) train_dl = DataLoader(dataset_train, batch_size=train_bs, shuffle=True) return train_dl def get_test_dl(client_test_data: ClientData, test_bs: int, benign_samples_per_device: Optional[int] = None, attack_samples_per_device: Optional[int] = None, cuda: bool = False, multiclass: bool = False) -> DataLoader: dataset_test = get_dataset(client_test_data, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=cuda, multiclass=multiclass) test_dl = DataLoader(dataset_test, batch_size=test_bs) return test_dl def get_train_dls(train_data: FederationData, train_bs: int, malicious_clients: Set[int], benign_samples_per_device: Optional[int] = None, attack_samples_per_device: Optional[int] = None, cuda: bool = False, multiclass: bool = False, poisoning: Optional[str] = None, p_poison: Optional[float] = None) -> List[DataLoader]: train_dls = [get_train_dl(client_train_data, train_bs, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=cuda, multiclass=multiclass, poisoning=(poisoning if client_id in malicious_clients else None), p_poison=(p_poison if client_id in malicious_clients else None)) for client_id, client_train_data in enumerate(train_data)] return train_dls def get_test_dls(test_data: FederationData, test_bs: int, benign_samples_per_device: Optional[int] = None, attack_samples_per_device: Optional[int] = None, cuda: bool = False, multiclass: bool = False) -> List[DataLoader]: test_dls = [get_test_dl(client_test_data, test_bs, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=cuda, multiclass=multiclass) for client_test_data in test_data] return test_dls def get_client_supervised_initial_splitting(client_data: ClientData, p_test: float, p_unused: float) -> Tuple[ClientData, ClientData]: client_train_val, client_test = split_client_data(client_data, p_second_split=p_test, p_unused=p_unused) return client_train_val, client_test def prepare_dataloaders(train_data: FederationData, local_test_data: FederationData, new_test_data: ClientData, params: SimpleNamespace, federated: bool = False) -> Tuple[List[DataLoader], List[DataLoader], DataLoader]: if federated: malicious_clients = params.malicious_clients poisoning = params.data_poisoning p_poison = params.p_poison else: malicious_clients = set() poisoning = None p_poison = None # Creating the dataloaders benign_samples_per_device, attack_samples_per_device = get_benign_attack_samples_per_device(p_split=params.p_train_val, benign_prop=params.benign_prop, samples_per_device=params.samples_per_device) train_dls = get_train_dls(train_data, params.train_bs, malicious_clients=malicious_clients, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=params.cuda, poisoning=poisoning, p_poison=p_poison) benign_samples_per_device, attack_samples_per_device = get_benign_attack_samples_per_device(p_split=params.p_test, benign_prop=params.benign_prop, samples_per_device=params.samples_per_device) local_test_dls = get_test_dls(local_test_data, params.test_bs, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=params.cuda) new_test_dl = get_test_dl(new_test_data, params.test_bs, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=params.cuda) return train_dls, local_test_dls, new_test_dl
8,434
58.401408
150
py
fed_iot_guard
fed_iot_guard-main/src/supervised_ml.py
from types import SimpleNamespace from typing import List, Union, Tuple, Optional import torch import torch.nn as nn from context_printer import Color from context_printer import ContextPrinter as Ctp # noinspection PyProtectedMember from torch.utils.data import DataLoader from federated_util import model_poisoning, model_aggregation from metrics import BinaryClassificationResult from print_util import print_train_classifier, print_train_classifier_header, print_rates def optimize(model: nn.Module, data: torch.Tensor, label: torch.Tensor, optimizer: torch.optim.Optimizer, criterion: torch.nn.Module, result: Optional[BinaryClassificationResult] = None) -> None: output = model(data) loss = criterion(output, label) optimizer.zero_grad() loss.mean().backward() optimizer.step() pred = torch.gt(output, torch.tensor(0.5)).int() if result is not None: result.update(pred, label) def train_classifier(model: nn.Module, params: SimpleNamespace, train_loader: DataLoader, lr_factor: float = 1.0) -> None: criterion = nn.BCELoss() optimizer = params.optimizer(model.parameters(), **params.optimizer_params) for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * lr_factor scheduler = params.lr_scheduler(optimizer, **params.lr_scheduler_params) print_train_classifier_header() model.train() for epoch in range(params.epochs): lr = optimizer.param_groups[0]['lr'] result = BinaryClassificationResult() for i, (data, label) in enumerate(train_loader): optimize(model, data, label, optimizer, criterion, result) if i % 1000 == 0: print_train_classifier(epoch, params.epochs, i, len(train_loader), result, lr, persistent=False) print_train_classifier(epoch, params.epochs, len(train_loader) - 1, len(train_loader), result, lr, persistent=True) scheduler.step() def train_classifiers_fedsgd(global_model: nn.Module, models: List[nn.Module], dls: List[DataLoader], params: SimpleNamespace, epoch: int, lr_factor: float = 1.0, mimicked_client_id: Optional[int] = None) -> Tuple[torch.nn.Module, List[torch.nn.Module]]: criterion = nn.BCELoss() lr = params.optimizer_params['lr'] * lr_factor # Set the models to train mode for model in models: model.train() result = BinaryClassificationResult() print_train_classifier_header() for i, data_label_tuple in enumerate(zip(*dls)): for model, (data, label) in zip(models, data_label_tuple): optimizer = params.optimizer(model.parameters(), lr=lr, weight_decay=params.optimizer_params['weight_decay']) optimize(model, data, label, optimizer, criterion, result) # Model poisoning attacks models = model_poisoning(global_model, models, params, mimicked_client_id=mimicked_client_id, verbose=False) # Aggregation global_model, models = model_aggregation(global_model, models, params, verbose=False) if i % 100 == 0: print_train_classifier(epoch, params.epochs, i, len(dls[0]), result, lr, persistent=False) print_train_classifier(epoch, params.epochs, len(dls[0]) - 1, len(dls[0]), result, lr, persistent=True) return global_model, models def test_classifier(model: nn.Module, test_loader: DataLoader) -> BinaryClassificationResult: with torch.no_grad(): model.eval() result = BinaryClassificationResult() for i, (data, label) in enumerate(test_loader): output = model(data) pred = torch.gt(output, torch.tensor(0.5)).int() result.update(pred, label) return result # this function will train each model on its associated dataloader, and will print the title for it # lr_factor is used to multiply the lr that is contained in params (and that should remain constant) def multitrain_classifiers(trains: List[Tuple[str, DataLoader, nn.Module]], params: SimpleNamespace, lr_factor: float = 1.0, main_title: str = 'Multitrain classifiers', color: Union[str, Color] = Color.NONE) -> None: Ctp.enter_section(main_title, color) for i, (title, dataloader, model) in enumerate(trains): Ctp.enter_section('[{}/{}] '.format(i + 1, len(trains)) + title + ' ({} samples)'.format(len(dataloader.dataset[:][0])), color=Color.NONE, header=' ') train_classifier(model, params, dataloader, lr_factor) Ctp.exit_section() Ctp.exit_section() # this function will test each model on its associated dataloader, and will print the title for it def multitest_classifiers(tests: List[Tuple[str, DataLoader, nn.Module]], main_title: str = 'Multitest classifiers', color: Union[str, Color] = Color.NONE) -> BinaryClassificationResult: Ctp.enter_section(main_title, color) result = BinaryClassificationResult() for i, (title, dataloader, model) in enumerate(tests): Ctp.print('[{}/{}] '.format(i + 1, len(tests)) + title + ' ({} samples)'.format(len(dataloader.dataset[:][0])), bold=True) current_result = test_classifier(model, dataloader) result += current_result print_rates(current_result) Ctp.exit_section() Ctp.print('Average result') print_rates(result) return result
5,411
42.296
144
py
fed_iot_guard
fed_iot_guard-main/src/federated_util.py
from copy import deepcopy from types import SimpleNamespace from typing import List, Set, Tuple, Callable, Optional import numpy as np import torch from context_printer import ContextPrinter as Ctp, Color # noinspection PyProtectedMember from torch.utils.data import DataLoader from architectures import NormalizingModel from ml import set_models_sub_divs def federated_averaging(global_model: torch.nn.Module, models: List[torch.nn.Module]) -> None: with torch.no_grad(): state_dict_mean = global_model.state_dict() for key in state_dict_mean: state_dict_mean[key] = torch.stack([model.state_dict()[key] for model in models], dim=-1).mean(dim=-1) global_model.load_state_dict(state_dict_mean) # For 8 clients this is equivalent to federated trimmed mean 3 def federated_median(global_model: torch.nn.Module, models: List[torch.nn.Module]) -> None: n_excluded_down = (len(models) - 1) // 2 n_included = 2 if (len(models) % 2 == 0) else 1 with torch.no_grad(): state_dict_median = global_model.state_dict() for key in state_dict_median: # It seems that it's much faster to compute the median by manually sorting and narrowing onto the right element # rather than using torch.median. sorted_tensor, _ = torch.sort(torch.stack([model.state_dict()[key] for model in models], dim=-1), dim=-1) trimmed_tensor = torch.narrow(sorted_tensor, -1, n_excluded_down, n_included) state_dict_median[key] = trimmed_tensor.mean(dim=-1) global_model.load_state_dict(state_dict_median) def federated_min_max(global_model: torch.nn.Module, models: List[torch.nn.Module]) -> None: subs = torch.stack([model.sub for model in models]) sub, _ = torch.min(subs, dim=0) divs = torch.stack([model.div for model in models]) max_values = divs + subs max_value, _ = torch.max(max_values, dim=0) div = max_value - sub global_model.set_sub_div(sub, div) # Shortcut for __federated_trimmed_mean(global_model, models, 1) so that it's easier to set the aggregation function as a single param def federated_trimmed_mean_1(global_model: torch.nn.Module, models: List[torch.nn.Module]) -> None: __federated_trimmed_mean(global_model, models, 1) # Shortcut for __federated_trimmed_mean(global_model, models, 2) so that it's easier to set the aggregation function as a single param def federated_trimmed_mean_2(global_model: torch.nn.Module, models: List[torch.nn.Module]) -> None: __federated_trimmed_mean(global_model, models, 2) def __federated_trimmed_mean(global_model: torch.nn.Module, models: List[torch.nn.Module], trim_num_up: int) -> None: n = len(models) n_remaining = n - 2 * trim_num_up with torch.no_grad(): state_dict_result = global_model.state_dict() for key in state_dict_result: sorted_tensor, _ = torch.sort(torch.stack([model.state_dict()[key] for model in models], dim=-1), dim=-1) trimmed_tensor = torch.narrow(sorted_tensor, -1, trim_num_up, n_remaining) state_dict_result[key] = trimmed_tensor.mean(dim=-1) global_model.load_state_dict(state_dict_result) # As defined in https://arxiv.org/pdf/2006.09365.pdf def s_resampling(models: List[torch.nn.Module], s: int) -> Tuple[List[torch.nn.Module], List[List[int]]]: T = len(models) c = [0 for _ in range(T)] output_models = [] output_indexes = [] for t in range(T): j = [-1 for _ in range(s)] for i in range(s): while True: j[i] = np.random.randint(T) if c[j[i]] < s: c[j[i]] += 1 break output_indexes.append(j) with torch.no_grad(): g_t_bar = deepcopy(models[0]) sampled_models = [models[j[i]] for i in range(s)] federated_averaging(g_t_bar, sampled_models) output_models.append(g_t_bar) return output_models, output_indexes def model_update_scaling(global_model: torch.nn.Module, malicious_clients_models: List[torch.nn.Module], factor: float) -> None: with torch.no_grad(): for model in malicious_clients_models: new_state_dict = {} for key, original_param in global_model.state_dict().items(): param_delta = model.state_dict()[key] - original_param param_delta = param_delta * factor new_state_dict.update({key: original_param + param_delta}) model.load_state_dict(new_state_dict) def model_canceling_attack(global_model: torch.nn.Module, malicious_clients_models: List[torch.nn.Module], n_honest: int) -> None: factor = - n_honest / len(malicious_clients_models) with torch.no_grad(): for normalizing_model in malicious_clients_models: new_state_dict = {} for key, original_param in global_model.model.state_dict().items(): new_state_dict.update({key: original_param * factor}) normalizing_model.model.load_state_dict(new_state_dict) # We only change the internal model of the NormalizingModel. That way we do not actually attack the normalization values # because they are not supposed to change throughout the training anyway. def select_mimicked_client(params: SimpleNamespace) -> Optional[int]: honest_client_ids = [client_id for client_id in range(len(params.clients_devices)) if client_id not in params.malicious_clients] if params.model_poisoning == 'mimic_attack': mimicked_client_id = np.random.choice(honest_client_ids) Ctp.print('The mimicked client is {}'.format(mimicked_client_id)) else: mimicked_client_id = None return mimicked_client_id # Attack in which all malicious clients mimic the model of a single good client. The mimicked client should always be the same throughout # the federation rounds. def mimic_attack(models: List[torch.nn.Module], malicious_clients: Set[int], mimicked_client: int) -> None: with torch.no_grad(): for i in malicious_clients: models[i].load_state_dict(models[mimicked_client].state_dict()) def init_federated_models(train_dls: List[DataLoader], params: SimpleNamespace, architecture: Callable): # Initialization of a global model n_clients = len(params.clients_devices) global_model = NormalizingModel(architecture(activation_function=params.activation_fn, hidden_layers=params.hidden_layers), sub=torch.zeros(params.n_features), div=torch.ones(params.n_features)) if params.cuda: global_model = global_model.cuda() models = [deepcopy(global_model) for _ in range(n_clients)] set_models_sub_divs(params.normalization, models, train_dls, color=Color.RED) if params.normalization == 'min-max': federated_min_max(global_model, models) else: federated_averaging(global_model, models) models = [deepcopy(global_model) for _ in range(n_clients)] return global_model, models def model_poisoning(global_model: torch.nn.Module, models: List[torch.nn.Module], params: SimpleNamespace, mimicked_client_id: Optional[int] = None, verbose: bool = False) -> List[torch.nn.Module]: malicious_clients_models = [model for client_id, model in enumerate(models) if client_id in params.malicious_clients] n_honest = len(models) - len(malicious_clients_models) # Model poisoning attacks if params.model_poisoning is not None: if params.model_poisoning == 'cancel_attack': model_canceling_attack(global_model=global_model, malicious_clients_models=malicious_clients_models, n_honest=n_honest) if verbose: Ctp.print('Performing cancel attack') elif params.model_poisoning == 'mimic_attack': mimic_attack(models, params.malicious_clients, mimicked_client_id) if verbose: Ctp.print('Performing mimic attack on client {}'.format(mimicked_client_id)) else: raise ValueError('Wrong value for model_poisoning: ' + str(params.model_poisoning)) # Rescale the model updates of the malicious clients (if any) model_update_scaling(global_model=global_model, malicious_clients_models=malicious_clients_models, factor=params.model_update_factor) return models # Aggregates the model according to params.aggregation_function, potentially using s-resampling, and distributes the global model back to the clients def model_aggregation(global_model: torch.nn.Module, models: List[torch.nn.Module], params: SimpleNamespace, verbose: bool = False)\ -> Tuple[torch.nn.Module, List[torch.nn.Module]]: if params.resampling is not None: models, indexes = s_resampling(models, params.resampling) if verbose: Ctp.print(indexes) params.aggregation_function(global_model, models) # Distribute the global model back to each client models = [deepcopy(global_model) for _ in range(len(params.clients_devices))] return global_model, models
9,118
45.764103
149
py
fed_iot_guard
fed_iot_guard-main/src/unsupervised_data.py
from types import SimpleNamespace from typing import Dict, Tuple, List, Optional import torch import torch.utils import torch.utils.data # noinspection PyProtectedMember from torch.utils.data import DataLoader, Dataset, TensorDataset from data import mirai_attacks, gafgyt_attacks, split_client_data, ClientData, FederationData, resample_array, split_clients_data, \ get_benign_attack_samples_per_device def get_benign_dataset(data: ClientData, benign_samples_per_device: Optional[int] = None, cuda: bool = False) -> Dataset: data_list = [] for device_data in data: for key, arr in device_data.items(): # This will iterate over the benign splits, gafgyt splits and mirai splits (if applicable) if key == 'benign': if benign_samples_per_device is not None: arr = resample_array(arr, benign_samples_per_device) data_tensor = torch.tensor(arr).float() if cuda: data_tensor = data_tensor.cuda() data_list.append(data_tensor) dataset = TensorDataset(torch.cat(data_list, dim=0)) return dataset def get_test_datasets(test_data: ClientData, benign_samples_per_device: Optional[int] = None, attack_samples_per_device: Optional[int] = None, cuda: bool = False) -> Dict[str, Dataset]: data_dict = {**{'benign': []}, **{'mirai_' + attack: [] for attack in mirai_attacks}, **{'gafgyt_' + attack: [] for attack in gafgyt_attacks}} resample = benign_samples_per_device is not None and attack_samples_per_device is not None for device_data in test_data: if resample: number_of_attacks = len(device_data.keys()) - 1 n_samples_attack = attack_samples_per_device // 10 if number_of_attacks == 5: n_samples_attack *= 2 else: n_samples_attack = None # We evenly divide the attack samples among the existing attacks on that device # With the above trick we always end up with exactly the same total number of attack samples, # whether the device has 5 attacks or 10. It does not work if the device has any other number of attacks, # but with N-BaIoT this is never the case for key, arr in device_data.items(): if resample: if key == 'benign': arr = resample_array(arr, benign_samples_per_device) else: arr = resample_array(arr, n_samples_attack) data_tensor = torch.tensor(arr).float() if cuda: data_tensor = data_tensor.cuda() data_dict[key].append(data_tensor) datasets_test = {key: TensorDataset(torch.cat(data_dict[key], dim=0)) for key in data_dict.keys() if len(data_dict[key]) > 0} return datasets_test def get_train_dl(client_train_data: ClientData, train_bs: int, benign_samples_per_device: Optional[int] = None, cuda: bool = False) -> DataLoader: dataset_train = get_benign_dataset(client_train_data, benign_samples_per_device=benign_samples_per_device, cuda=cuda) train_dl = DataLoader(dataset_train, batch_size=train_bs, shuffle=True) return train_dl def get_val_dl(client_val_data: ClientData, test_bs: int, benign_samples_per_device: Optional[int] = None, cuda: bool = False) -> DataLoader: dataset_val = get_benign_dataset(client_val_data, benign_samples_per_device=benign_samples_per_device, cuda=cuda) val_dl = DataLoader(dataset_val, batch_size=test_bs) return val_dl def get_test_dls_dict(client_test_data: ClientData, test_bs: int, benign_samples_per_device: Optional[int] = None, attack_samples_per_device: Optional[int] = None, cuda: bool = False) -> Dict[str, DataLoader]: datasets = get_test_datasets(client_test_data, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=cuda) test_dls = {key: DataLoader(dataset, batch_size=test_bs) for key, dataset in datasets.items()} return test_dls def get_train_dls(train_data: FederationData, train_bs: int, benign_samples_per_device: Optional[int] = None, cuda: bool = False) -> List[DataLoader]: return [get_train_dl(client_train_data, train_bs, benign_samples_per_device=benign_samples_per_device, cuda=cuda) for client_train_data in train_data] def get_val_dls(val_data: FederationData, test_bs: int, benign_samples_per_device: Optional[int] = None, cuda: bool = False) -> List[DataLoader]: return [get_val_dl(client_val_data, test_bs, benign_samples_per_device=benign_samples_per_device, cuda=cuda) for client_val_data in val_data] def get_test_dls_dicts(local_test_data: FederationData, test_bs: int, benign_samples_per_device: Optional[int] = None, attack_samples_per_device: Optional[int] = None, cuda: bool = False) -> List[Dict[str, DataLoader]]: return [get_test_dls_dict(client_test_data, test_bs, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=cuda) for client_test_data in local_test_data] def get_client_unsupervised_initial_splitting(client_data: ClientData, p_test: float, p_unused: float) -> Tuple[ClientData, ClientData]: # Separate the data of the clients between benign and attack client_benign_data = [{'benign': device_data['benign']} for device_data in client_data] client_attack_data = [{key: device_data[key] for key in device_data.keys() if key != 'benign'} for device_data in client_data] client_train_val, client_benign_test = split_client_data(client_benign_data, p_second_split=p_test, p_unused=p_unused) client_test = [{**device_benign_test, **device_attack_data} for device_benign_test, device_attack_data in zip(client_benign_test, client_attack_data)] return client_train_val, client_test def prepare_dataloaders(train_val_data: FederationData, local_test_data: FederationData, new_test_data: ClientData, params: SimpleNamespace)\ -> Tuple[List[DataLoader], List[DataLoader], List[Dict[str, DataLoader]], Dict[str, DataLoader]]: # Split train data between actual train and the set that will be used to search the threshold train_data, threshold_data = split_clients_data(train_val_data, p_second_split=params.threshold_part, p_unused=0.0) p_train = params.p_train_val * (1. - params.threshold_part) p_threshold = params.p_train_val * params.threshold_part # Creating the dataloaders benign_samples_per_device, _ = get_benign_attack_samples_per_device(p_split=p_train, benign_prop=1., samples_per_device=params.samples_per_device) train_dls = get_train_dls(train_data, params.train_bs, benign_samples_per_device=benign_samples_per_device, cuda=params.cuda) benign_samples_per_device, _ = get_benign_attack_samples_per_device(p_split=p_threshold, benign_prop=1., samples_per_device=params.samples_per_device) threshold_dls = get_val_dls(threshold_data, params.test_bs, benign_samples_per_device=benign_samples_per_device, cuda=params.cuda) benign_samples_per_device, attack_samples_per_device = get_benign_attack_samples_per_device(p_split=params.p_test, benign_prop=params.benign_prop, samples_per_device=params.samples_per_device) local_test_dls_dicts = get_test_dls_dicts(local_test_data, params.test_bs, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=params.cuda) new_test_dls_dict = get_test_dls_dict(new_test_data, params.test_bs, benign_samples_per_device=benign_samples_per_device, attack_samples_per_device=attack_samples_per_device, cuda=params.cuda) return train_dls, threshold_dls, local_test_dls_dicts, new_test_dls_dict
8,206
57.205674
150
py
fed_iot_guard
fed_iot_guard-main/src/architectures.py
from typing import List import torch import torch.nn as nn class SimpleAutoencoder(nn.Module): def __init__(self, activation_function: nn.Module, hidden_layers: List[int], verbose: bool = False) -> None: super(SimpleAutoencoder, self).__init__() self.seq = nn.Sequential() n_neurons_in = 115 n_in = n_neurons_in for i, n_out in enumerate(hidden_layers): self.seq.add_module('fc' + str(i), nn.Linear(n_in, n_out, bias=True)) self.seq.add_module('act_fn' + str(i), activation_function()) n_in = n_out self.seq.add_module('final_fc', nn.Linear(n_in, n_neurons_in, bias=True)) if verbose: print(self.seq) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.seq(x) class Threshold(nn.Module): # This class is only a wrapper around the threshold that allows to use directly the federated aggregation on it. def __init__(self, threshold: torch.Tensor): super(Threshold, self).__init__() self.threshold = nn.Parameter(threshold, requires_grad=False) class BinaryClassifier(nn.Module): def __init__(self, activation_function: nn.Module, hidden_layers: List[int], verbose: bool = False) -> None: super(BinaryClassifier, self).__init__() self.seq = nn.Sequential() n_neurons_in = 115 n_in = n_neurons_in for i, n_out in enumerate(hidden_layers): self.seq.add_module('fc' + str(i), nn.Linear(n_in, n_out, bias=True)) self.seq.add_module('act_fn' + str(i), activation_function()) n_in = n_out self.seq.add_module('final_fc', nn.Linear(n_in, 1, bias=True)) self.seq.add_module('sigmoid', nn.Sigmoid()) if verbose: print(self.seq) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.seq(x) class NormalizingModel(nn.Module): def __init__(self, model: torch.nn.Module, sub: torch.Tensor, div: torch.Tensor) -> None: super(NormalizingModel, self).__init__() self.sub = nn.Parameter(sub, requires_grad=False) self.div = nn.Parameter(div, requires_grad=False) self.model = model # Manually change normalization values def set_sub_div(self, sub: torch.Tensor, div: torch.Tensor) -> None: self.sub = nn.Parameter(sub, requires_grad=False) self.div = nn.Parameter(div, requires_grad=False) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.model(self.normalize(x)) def normalize(self, x: torch.Tensor) -> torch.Tensor: return (x - self.sub) / self.div
2,644
34.743243
116
py
fed_iot_guard
fed_iot_guard-main/src/metrics.py
import torch class BinaryClassificationResult: def __init__(self, tp: int = 0, tn: int = 0, fp: int = 0, fn: int = 0): self.tp = tp # Number of true positives self.tn = tn # Number of true negatives self.fp = fp # Number of false positives self.fn = fn # Number of false negatives def __add__(self, other): result = BinaryClassificationResult( tp=self.tp + other.tp, tn=self.tn + other.tn, fp=self.fp + other.fp, fn=self.fn + other.fn, ) return result def add_tp(self, val: int) -> None: self.tp += val def add_tn(self, val: int) -> None: self.tn += val def add_fp(self, val: int) -> None: self.fp += val def add_fn(self, val: int) -> None: self.fn += val # Update the result based on the pred tensor and on the label tensor def update(self, pred: torch.Tensor, label: torch.Tensor) -> None: self.add_tp(torch.logical_and(torch.eq(pred, label), label.bool()).int().sum().item()) self.add_tn(torch.logical_and(torch.eq(pred, label), torch.logical_not(label.bool())).int().sum().item()) self.add_fp(torch.logical_and(torch.logical_not(torch.eq(pred, label)), torch.logical_not(label.bool())).int().sum().item()) self.add_fn(torch.logical_and(torch.logical_not(torch.eq(pred, label)), label.bool()).int().sum().item()) # True positive rate def tpr(self) -> float: return self.tp / (self.tp + self.fn) if self.tp != 0 else 0. # True negative rate def tnr(self) -> float: return self.tn / (self.tn + self.fp) if self.tn != 0 else 0. # False positive rate def fpr(self) -> float: return self.fp / (self.tn + self.fp) if self.fp != 0 else 0. # False negative rate def fnr(self) -> float: return self.fn / (self.tp + self.fn) if self.fn != 0 else 0. # Accuracy def acc(self) -> float: return (self.tp + self.tn) / self.n_samples() if self.n_samples() != 0 else 0. # Balanced accuracy: equal to the accuracy as if the dataset on which we computed the results originally had benign_prop proportion of negatives def balanced_acc(self, benign_prop: float) -> float: return self.tnr() * benign_prop + self.tpr() * (1. - benign_prop) def __negative_minority(self) -> bool: return (self.tn + self.fp) < (self.n_samples() / 2) # Recall (same as true positive rate) # If minority is set to True, computes the recall of the minority class instead of the recall of the positive class def recall(self, minority: bool = False) -> float: if minority and self.__negative_minority(): return self.tnr() else: return self.tpr() # Precision # If minority is set to True, computes the precision of the minority class instead of the precision of the positive class def precision(self, minority: bool = False) -> float: if minority and self.__negative_minority(): return self.tn / (self.tn + self.fn) if self.tn != 0 else 0. else: return self.tp / (self.tp + self.fp) if self.tp != 0 else 0. # Sensitivity (same as true positive rate) def sensitivity(self) -> float: return self.tpr() # Specificity (same as true negative rate) def specificity(self) -> float: return self.tnr() # F1-Score # If minority is set to True, computes the F1-score of the minority class instead of the F1-score of the positive class def f1(self, minority: bool = False) -> float: return (2 * self.precision(minority) * self.recall(minority)) / (self.precision(minority) + self.recall(minority))\ if (self.precision(minority) + self.recall(minority)) != 0 else 0. def n_samples(self) -> int: return self.tp + self.tn + self.fp + self.fn def to_json(self) -> dict: return {'tp': self.tp, 'tn': self.tn, 'fp': self.fp, 'fn': self.fn}
4,003
38.643564
148
py
fed_iot_guard
fed_iot_guard-main/src/ml.py
from typing import Tuple, List import torch from context_printer import Color from context_printer import ContextPrinter as Ctp # noinspection PyProtectedMember from torch.utils.data import DataLoader from architectures import NormalizingModel def get_sub_div(data: torch.Tensor, normalization: str) -> Tuple[torch.tensor, torch.tensor]: if normalization == '0-mean 1-var': sub = data.mean(dim=0) div = data.std(dim=0) elif normalization == 'min-max': sub = data.min(dim=0)[0] div = data.max(dim=0)[0] - sub elif normalization == 'none': sub = torch.zeros(data.shape[1]) div = torch.ones(data.shape[1]) else: raise NotImplementedError return sub, div def set_model_sub_div(normalization: str, model: NormalizingModel, train_dl: DataLoader) -> None: data = train_dl.dataset[:][0] Ctp.print('Computing normalization with {} train samples'.format(len(data))) sub, div = get_sub_div(data, normalization) model.set_sub_div(sub, div) def set_models_sub_divs(normalization: str, models: List[NormalizingModel], clients_dl_train: List[DataLoader], color: Color = Color.NONE) -> None: Ctp.enter_section('Computing the normalization values for each client', color) for i, (model, train_dl) in enumerate(zip(models, clients_dl_train)): set_model_sub_div(normalization, model, train_dl) Ctp.exit_section()
1,415
34.4
147
py
fed_iot_guard
fed_iot_guard-main/src/print_util.py
from typing import Optional import torch from context_printer import Color from context_printer import ContextPrinter as Ctp from metrics import BinaryClassificationResult class Columns: SMALL = 12 MEDIUM = 16 LARGE = 22 def print_federation_round(federation_round: int, n_rounds: int) -> None: Ctp.enter_section('Federation round [{}/{}]'.format(federation_round + 1, n_rounds), Color.DARK_GRAY) def print_federation_epoch(epoch: int, n_epochs: int) -> None: Ctp.enter_section('Epoch [{}/{}]'.format(epoch + 1, n_epochs), Color.DARK_GRAY) def print_rates(result: BinaryClassificationResult) -> None: Ctp.print('TPR: {:.2f}% - TNR: {:.2f}% - Accuracy: {:.2f}% - Precision: {:.2f}% - F1-Score: {:.2f}%' .format(result.tpr() * 100, result.tnr() * 100, result.acc() * 100, result.precision() * 100, result.f1() * 100)) Ctp.print('TP: {} - TN: {} - FP: {} - FN:{}'.format(result.tp, result.tn, result.fp, result.fn)) def print_train_classifier_header() -> None: Ctp.print('Epoch'.ljust(Columns.SMALL) + '| Batch'.ljust(Columns.MEDIUM) + '| TPR'.ljust(Columns.MEDIUM) + '| TNR'.ljust(Columns.MEDIUM) + '| Accuracy'.ljust(Columns.MEDIUM) + '| Precision'.ljust(Columns.MEDIUM) + '| F1-Score'.ljust(Columns.MEDIUM) + '| LR'.ljust(Columns.MEDIUM), bold=True) def print_train_classifier(epoch: int, num_epochs: int, batch: int, num_batches: int, result: BinaryClassificationResult, lr: float, persistent: bool = False) -> None: Ctp.print('[{}/{}]'.format(epoch + 1, num_epochs).ljust(Columns.SMALL) + '| [{}/{}]'.format(batch + 1, num_batches).ljust(Columns.MEDIUM) + '| {:.5f}'.format(result.tpr()).ljust(Columns.MEDIUM) + '| {:.5f}'.format(result.tnr()).ljust(Columns.MEDIUM) + '| {:.5f}'.format(result.acc()).ljust(Columns.MEDIUM) + '| {:.5f}'.format(result.precision()).ljust(Columns.MEDIUM) + '| {:.5f}'.format(result.f1()).ljust(Columns.MEDIUM) + '| {:.5f}'.format(lr).ljust(Columns.MEDIUM), rewrite=True, end='\n' if persistent else '') def print_autoencoder_loss_header(first_column: str = 'Dataset', print_positives: bool = False, print_lr: bool = False) -> None: Ctp.print(first_column.ljust(Columns.MEDIUM) + '| Min loss'.ljust(Columns.MEDIUM) + '| Q-0.01 loss'.ljust(Columns.MEDIUM) + '| Avg loss'.ljust(Columns.MEDIUM) + '| Q-0.99 loss'.ljust(Columns.MEDIUM) + '| Max loss'.ljust(Columns.MEDIUM) + '| Std loss'.ljust(Columns.MEDIUM) + ('| Positive samples'.ljust(Columns.LARGE) + '| Positive %'.ljust(Columns.MEDIUM) if print_positives else '') + ('| LR'.ljust(Columns.MEDIUM) if print_lr else ''), bold=True) def print_autoencoder_loss_stats(title: str, losses: torch.Tensor, positives: Optional[int] = None, n_samples: Optional[int] = None, lr: Optional[float] = None) -> None: print_positives = (positives is not None and n_samples is not None) Ctp.print(title.ljust(Columns.MEDIUM) + '| {:.4f}'.format(losses.min()).ljust(Columns.MEDIUM) + '| {:.4f}'.format(torch.quantile(losses, 0.01).item()).ljust(Columns.MEDIUM) + '| {:.4f}'.format(losses.mean()).ljust(Columns.MEDIUM) + '| {:.4f}'.format(torch.quantile(losses, 0.99).item()).ljust(Columns.MEDIUM) + '| {:.4f}'.format(losses.max()).ljust(Columns.MEDIUM) + '| {:.4f}'.format(losses.std()).ljust(Columns.MEDIUM) + ('| {}/{}'.format(positives, n_samples).ljust(Columns.LARGE) + '| {:.4f}%'.format(100.0 * positives / n_samples).ljust(Columns.MEDIUM) if print_positives else '') + ('| {:.6f}'.format(lr) if lr is not None else ''))
3,996
48.345679
128
py
fed_iot_guard
fed_iot_guard-main/src/unsupervised_experiments.py
from types import SimpleNamespace from typing import Tuple, List, Dict import torch from context_printer import Color from context_printer import ContextPrinter as Ctp # noinspection PyProtectedMember from torch.utils.data import DataLoader from architectures import SimpleAutoencoder, NormalizingModel, Threshold from data import device_names, ClientData, FederationData, get_benign_attack_samples_per_device from federated_util import init_federated_models, model_aggregation, select_mimicked_client, model_poisoning from metrics import BinaryClassificationResult from ml import set_models_sub_divs, set_model_sub_div from print_util import print_federation_round, print_federation_epoch from unsupervised_data import get_train_dl, get_val_dl, prepare_dataloaders from unsupervised_ml import multitrain_autoencoders, multitest_autoencoders, compute_thresholds, train_autoencoder, \ compute_reconstruction_losses, train_autoencoders_fedsgd def local_autoencoder_train_val(train_data: ClientData, val_data: ClientData, params: SimpleNamespace) -> float: p_train = params.p_train_val * (1. - params.val_part) p_val = params.p_train_val * params.val_part # Create the dataloaders benign_samples_per_device, _ = get_benign_attack_samples_per_device(p_split=p_train, benign_prop=1., samples_per_device=params.samples_per_device) train_dl = get_train_dl(train_data, params.train_bs, benign_samples_per_device=benign_samples_per_device, cuda=params.cuda) benign_samples_per_device, _ = get_benign_attack_samples_per_device(p_split=p_val, benign_prop=1., samples_per_device=params.samples_per_device) val_dl = get_val_dl(val_data, params.test_bs, benign_samples_per_device=benign_samples_per_device, cuda=params.cuda) # Initialize the model and compute the normalization values with the client's local training data model = NormalizingModel(SimpleAutoencoder(activation_function=params.activation_fn, hidden_layers=params.hidden_layers), sub=torch.zeros(params.n_features), div=torch.ones(params.n_features)) if params.cuda: model = model.cuda() set_model_sub_div(params.normalization, model, train_dl) # Local training Ctp.enter_section('Training for {} epochs with {} samples'.format(params.epochs, len(train_dl.dataset[:][0])), color=Color.GREEN) train_autoencoder(model, params, train_dl) Ctp.exit_section() # Local validation Ctp.print("Validating with {} samples".format(len(val_dl.dataset[:][0]))) losses = compute_reconstruction_losses(model, val_dl) loss = (sum(losses) / len(losses)).item() Ctp.print("Validation loss: {:.5f}".format(loss)) return loss def local_autoencoders_train_test(train_val_data: FederationData, local_test_data: FederationData, new_test_data: ClientData, params: SimpleNamespace) -> Tuple[BinaryClassificationResult, BinaryClassificationResult, List[float]]: # Prepare the dataloaders train_dls, threshold_dls, local_test_dls_dicts, new_test_dls_dict = prepare_dataloaders(train_val_data, local_test_data, new_test_data, params) # Initialize the models and compute the normalization values with each client's local training data n_clients = len(params.clients_devices) models = [NormalizingModel(SimpleAutoencoder(activation_function=params.activation_fn, hidden_layers=params.hidden_layers), sub=torch.zeros(params.n_features), div=torch.ones(params.n_features)) for _ in range(n_clients)] if params.cuda: models = [model.cuda() for model in models] set_models_sub_divs(params.normalization, models, train_dls, color=Color.RED) # Local training of the autoencoder multitrain_autoencoders(trains=list(zip(['Training client {} on: '.format(i) + device_names(client_devices) for i, client_devices in enumerate(params.clients_devices)], train_dls, models)), params=params, main_title='Training the clients', color=Color.GREEN) # Computation of the thresholds thresholds = compute_thresholds(opts=list(zip(['Computing threshold for client {} on: '.format(i) + device_names(client_devices) for i, client_devices in enumerate(params.clients_devices)], threshold_dls, models)), quantile=params.quantile, main_title='Computing the thresholds', color=Color.DARK_PURPLE) # Local testing of each autoencoder local_result = multitest_autoencoders(tests=list(zip(['Testing client {} on: '.format(i) + device_names(client_devices) for i, client_devices in enumerate(params.clients_devices)], local_test_dls_dicts, models, thresholds)), main_title='Testing the clients on their own devices', color=Color.BLUE) # New devices testing new_devices_result = multitest_autoencoders( tests=list(zip(['Testing client {} on: '.format(i) + device_names(params.test_devices) for i in range(n_clients)], [new_test_dls_dict for _ in range(n_clients)], models, thresholds)), main_title='Testing the clients on the new devices: ' + device_names(params.test_devices), color=Color.DARK_CYAN) return local_result, new_devices_result, [threshold.threshold.item() for threshold in thresholds] def federated_thresholds(models: List[torch.nn.Module], threshold_dls: List[DataLoader], global_threshold: torch.nn.Module, params: SimpleNamespace, global_thresholds: List[float]) -> None: # Computation of the thresholds thresholds = compute_thresholds(opts=list(zip(['Computing threshold for client {} on: '.format(i) + device_names(client_devices) for i, client_devices in enumerate(params.clients_devices)], threshold_dls, models)), quantile=params.quantile, main_title='Computing the thresholds', color=Color.DARK_PURPLE) # Aggregation of the thresholds global_threshold, thresholds = model_aggregation(global_threshold, thresholds, params, verbose=True) Ctp.print('Global threshold: {:.6f}'.format(global_threshold.threshold.item())) global_thresholds.append(global_threshold.threshold.item()) def federated_testing(global_model: torch.nn.Module, global_threshold: torch.nn.Module, local_test_dls_dicts: List[Dict[str, DataLoader]], new_test_dls_dict: Dict[str, DataLoader], params: SimpleNamespace, local_results: List[BinaryClassificationResult], new_devices_results: List[BinaryClassificationResult]) -> None: # Global model testing on each client's data tests = [] for client_id, client_devices in enumerate(params.clients_devices): if client_id not in params.malicious_clients: tests.append(('Testing global model on: ' + device_names(client_devices), local_test_dls_dicts[client_id], global_model, global_threshold)) local_results.append(multitest_autoencoders(tests=tests, main_title='Testing the global model on data from all clients', color=Color.BLUE)) # Global model testing on new devices new_devices_results.append(multitest_autoencoders(tests=list(zip(['Testing global model on: ' + device_names(params.test_devices)], [new_test_dls_dict], [global_model], [global_threshold])), main_title='Testing the global model on the new devices: ' + device_names( params.test_devices), color=Color.DARK_CYAN)) def fedavg_autoencoders_train_test(train_val_data: FederationData, local_test_data: FederationData, new_test_data: ClientData, params: SimpleNamespace)\ -> Tuple[List[BinaryClassificationResult], List[BinaryClassificationResult], List[float]]: # Preparation of the dataloaders train_dls, threshold_dls, local_test_dls_dicts, new_test_dls_dict = prepare_dataloaders(train_val_data, local_test_data, new_test_data, params) # Initialization of the models global_model, models = init_federated_models(train_dls, params, architecture=SimpleAutoencoder) global_threshold = Threshold(torch.tensor(0.)) # Initialization of the results local_results, new_devices_results, global_thresholds = [], [], [] # Selection of a client to mimic in case we use the mimic attack mimicked_client_id = select_mimicked_client(params) for federation_round in range(params.federation_rounds): print_federation_round(federation_round, params.federation_rounds) # Local training of each client multitrain_autoencoders(trains=list(zip(['Training client {} on: '.format(i) + device_names(client_devices) for i, client_devices in enumerate(params.clients_devices)], train_dls, models)), params=params, lr_factor=(params.gamma_round ** federation_round), main_title='Training the clients', color=Color.GREEN) # Model poisoning attacks models = model_poisoning(global_model, models, params, mimicked_client_id=mimicked_client_id, verbose=True) # Aggregation global_model, models = model_aggregation(global_model, models, params, verbose=True) # Compute and aggregate thresholds federated_thresholds(models, threshold_dls, global_threshold, params, global_thresholds) # Testing federated_testing(global_model, global_threshold, local_test_dls_dicts, new_test_dls_dict, params, local_results, new_devices_results) Ctp.exit_section() return local_results, new_devices_results, global_thresholds def fedsgd_autoencoders_train_test(train_val_data: FederationData, local_test_data: FederationData, new_test_data: ClientData, params: SimpleNamespace)\ -> Tuple[List[BinaryClassificationResult], List[BinaryClassificationResult], List[float]]: # Preparation of the dataloaders train_dls, threshold_dls, local_test_dls_dicts, new_test_dls_dict = prepare_dataloaders(train_val_data, local_test_data, new_test_data, params) # Initialization of the models global_model, models = init_federated_models(train_dls, params, architecture=SimpleAutoencoder) global_threshold = Threshold(torch.tensor(0.)) # Initialization of the results local_results, new_devices_results, global_thresholds = [], [], [] # Selection of a client to mimic in case we use the mimic attack mimicked_client_id = select_mimicked_client(params) for epoch in range(params.epochs): print_federation_epoch(epoch, params.epochs) lr_factor = params.lr_scheduler_params['gamma'] ** (epoch // params.lr_scheduler_params['step_size']) global_model, models = train_autoencoders_fedsgd(global_model, models, train_dls, params, lr_factor=lr_factor, mimicked_client_id=mimicked_client_id) if epoch % 10 == 0: # Compute and aggregate thresholds federated_thresholds(models, threshold_dls, global_threshold, params, global_thresholds) # Testing federated_testing(global_model, global_threshold, local_test_dls_dicts, new_test_dls_dict, params, local_results, new_devices_results) Ctp.exit_section() return local_results, new_devices_results, global_thresholds
12,192
57.620192
147
py
PMIC
PMIC-main/ma_utils.py
import numpy as np import scipy.signal import torch # from mpi_tools import mpi_statistics_scalar # Code based on: # https://github.com/openai/baselines/blob/master/baselines/deepq/replay_buffer.py # Expects tuples of (state, next_state, action, reward, done) class ReplayBuffer(object): def __init__(self, max_size=1e6): self.storage = [] self.eposide_rewad =[] self.max_size = max_size self.ptr = 0 self.max_reward = -1000000 self.min_reward = 1000000 def set_max_reward(self,max_reward): if max_reward >= self.max_reward: self.max_reward = max_reward return bool(max_reward >= self.max_reward) def set_min_reward(self, min_reward): if min_reward <= self.min_reward: self.min_reward = min_reward return bool(min_reward <= self.min_reward) def save(self,file_name): numpy_array = np.array(self.storage) print("total len ", len(numpy_array)) np.save(file_name+'_val_buffer.npy', numpy_array) def load(self,file_name): data = np.load(file_name+'_val_buffer.npy') print("data len :",len(data)) self.storage=list(data) def add(self, data,eposide_reward): if len(self.storage) == self.max_size: self.storage[int(self.ptr)] = data self.eposide_rewad[int(self.ptr)] = eposide_reward self.ptr = (self.ptr + 1) % self.max_size else: self.storage.append(data) self.eposide_rewad.append(eposide_reward) self.ptr = (self.ptr + 1) % self.max_size def sample_recently(self,batch_size,recent_num = 4000): if self.ptr == 0: ind = np.random.randint(int(self.max_size-recent_num), int(self.max_size), size=batch_size) else : ind = np.random.randint(max(int(self.ptr-recent_num),0), self.ptr, size=batch_size) o, x, y, o_, u, r, d = [], [], [], [], [],[],[] for i in ind: O, X, Y, O_, U, R, D = self.storage[i] o.append(np.array(O, copy=False)) o_.append(np.array(O_, copy=False)) x.append(np.array(X, copy=False)) y.append(np.array(Y, copy=False)) u.append(np.array(U, copy=False)) r.append(np.array(R, copy=False)) d.append(np.array(D, copy=False)) return np.array(o), np.array(x), np.array(y), np.array(o_), np.array(u), np.array(r).reshape(-1, 1), np.array( d).reshape(-1, 1) def sample_ago(self,batch_size): if self.ptr < 10000: ind = np.random.randint(self.ptr,int(self.max_size - 8000), size=batch_size) else: ind = np.random.randint(0, self.ptr-8000,size=batch_size) o, x, y, o_, u, r, d = [], [], [], [], [],[],[] for i in ind: O, X, Y, O_, U, R, D = self.storage[i] o.append(np.array(O, copy=False)) o_.append(np.array(O_, copy=False)) x.append(np.array(X, copy=False)) y.append(np.array(Y, copy=False)) u.append(np.array(U, copy=False)) r.append(np.array(R, copy=False)) d.append(np.array(D, copy=False)) return np.array(o), np.array(x), np.array(y), np.array(o_), np.array(u), np.array(r).reshape(-1, 1), np.array( d).reshape(-1, 1) def sample(self, batch_size): ind = np.random.randint(0, len(self.storage), size=batch_size) o,x, y,o_, u, r, d ,ep_reward=[], [], [], [], [], [],[],[] for i in ind: O,X, Y,O_, U, R, D = self.storage[i] ep_r = self.eposide_rewad[i] ep_reward.append(np.array(ep_r, copy=False)) o.append(np.array(O, copy=False)) o_.append(np.array(O_, copy=False)) x.append(np.array(X, copy=False)) y.append(np.array(Y, copy=False)) u.append(np.array(U, copy=False)) r.append(np.array(R, copy=False)) d.append(np.array(D, copy=False)) return np.array(o),np.array(x), np.array(y),np.array(o_), np.array(u), np.array(r).reshape(-1, 1), np.array(d).reshape(-1, 1),np.array(ep_reward) class embedding_Buffer(object): def __init__(self, max_size=1e6): self.pos_storage = [] self.pos_storage_reward = [] self.pos_epoch_reward = [] self.neg_storage = [] self.neg_storage_reward = [] self.neg_epoch_reward = [] self.worse_storage = [] self.worse_storage_reward = [] self.storage = [] self.max_max_size = max_size self.max_size = max_size self.total_max = max_size self.pos_ptr = 0 self.neg_ptr = 0 self.ptr = 0 self.worse_ptr = 0 self.max_reward = -100000000 self.min_reward = 1000000000 def rank_storage(self, current_policy_reward): #print("step 0:", self.pos_storage_reward) index = np.argsort(self.pos_storage_reward) #print("test 1:",index) #print("test 2:",self.pos_storage_reward) self.pos_storage_reward = list(np.array(self.pos_storage_reward)[index]) self.pos_storage = list(np.array(self.pos_storage)[index]) #print("test 3:",self.pos_storage) start_index = 0 for i , d in enumerate(self.pos_storage_reward): if d > current_policy_reward: break; else : start_index = i+1 self.pos_storage_reward = self.pos_storage_reward[start_index::] self.pos_storage = self.pos_storage[start_index::] if len(self.pos_storage) == self.max_size : self.pos_ptr = 0 else : self.pos_ptr = self.pos_ptr - start_index return self.pos_storage_reward[0] def greater(self,reward): if reward > self.max_reward: self.max_reward = reward return True else : return False def can_save(self,reward): if reward > self.max_reward *0.8 : return True else : return False def get_baseline(self): return self.max_reward*0.8 def get_MI(self,policy,deafult = 0): pos_mean_mi_list =[] neg_mena_mi_list =[] for index in range(0,len(self.pos_storage),100): temp_list = [] temp_obs =[] temp_state =[] for i in range(100): if index+i < len(self.pos_storage): temp_list.append(self.pos_storage[index+i][0]) temp_obs.append(self.pos_storage[index+i][1]) temp_state.append(self.pos_storage[index+i][2]) mean_mi = policy.get_mi_from_a(np.array(temp_obs),np.array(temp_list),deafult) pos_mean_mi_list.append(mean_mi) for index in range(0, len(self.neg_storage), 100): temp_list = [] temp_state =[] temp_obs =[] for i in range(100): if index + i < len(self.neg_storage): temp_list.append(self.neg_storage[index + i][0]) temp_obs.append(self.neg_storage[index+i][1]) temp_state.append(self.neg_storage[index + i][2]) mean_mi = policy.get_mi_from_a(np.array(temp_obs),np.array(temp_list),deafult) neg_mena_mi_list.append(mean_mi) return np.mean(pos_mean_mi_list),np.mean(neg_mena_mi_list) def clear_pos(self): self.pos_storage_reward =[] self.pos_storage = [] self.pos_ptr = 0 def get_mean_pos_reward(self): return np.mean(self.pos_epoch_reward) def get_mean_neg_reward(self): return np.mean(self.neg_epoch_reward) def add_pos(self, data, rollout_reward): #print("rollout_reward",rollout_reward) if len(self.pos_storage) == self.max_size: self.pos_storage_reward[int(self.pos_ptr)] = rollout_reward self.pos_storage[int(self.pos_ptr)] = data self.pos_ptr = (self.pos_ptr + 1) % self.max_size else: self.pos_storage.append(data) self.pos_storage_reward.append(rollout_reward) self.pos_ptr = (self.pos_ptr + 1) % self.max_size def add(self, data): if len(self.storage) == self.total_max: self.storage[int(self.ptr)] = data self.ptr = (self.ptr + 1) % self.total_max else: self.storage.append(data) self.ptr = (self.ptr + 1) % self.total_max def add_neg(self,data,rollout_reward): if len(self.neg_storage) == self.max_max_size: #print("int(self.neg_ptr) ",int(self.neg_ptr)) self.neg_storage[int(self.neg_ptr)] = data self.neg_storage_reward[int(self.neg_ptr)] = rollout_reward self.neg_ptr = (self.neg_ptr + 1) % self.max_max_size else: self.neg_storage_reward.append(rollout_reward) self.neg_storage.append(data) self.neg_ptr = (self.neg_ptr + 1) % self.max_max_size # def caculate_Q(self,actor,critic,device): # q_list = [] # obs_list =[] # state_list =[] # for d in self.pos_storage: # obs_list.append(d[1]) # state_list.append(d[2]) # # for i in range(0,len(self.pos_storage),100): # pos_obs = np.array(obs_list)[i:i+100] # pos_state = np.array(state_list)[i:i + 100] # # pos_obs = torch.FloatTensor(pos_obs).to(device) # pos_state = torch.FloatTensor(pos_state).to(device) # action_list =[] # # #print("2222 ",pos_obs[:, 0].shape) # #print("3333 ",pos_obs[:, 1].shape) # for i in range(2): # action_list.append(actor[i](pos_obs[:, i])[0]) # current_Q = critic(pos_state, torch.cat(action_list, 1)) # q_list.extend(list(current_Q.cpu().data.numpy())) # self.pos_Q = np.reshape(q_list,[-1]) # #self.pos_adv = (self.pos_storage_reward - self.pos_Q) / np.abs(np.max(self.pos_storage_reward - self.pos_Q)) # # obs_list = [] # state_list = [] # for d in self.neg_storage: # obs_list.append(d[1]) # state_list.append(d[2]) # q_list = [] # for i in range(0, len(self.neg_storage), 100): # neg_obs = np.array(obs_list)[i:i + 100] # neg_state = np.array(state_list)[i:i + 100] # neg_obs = torch.FloatTensor(neg_obs).to(device) # neg_state = torch.FloatTensor(neg_state).to(device) # action_list = [] # for i in range(2): # action_list.append(actor[i](neg_obs[:, i])[0]) # current_Q = critic(neg_state, torch.cat(action_list, 1)) # q_list.extend(list(current_Q.cpu().data.numpy())) # self.neg_Q = np.reshape(q_list,[-1]) # # #self.neg_adv = (self.neg_Q - self.neg_storage_reward)/np.abs(np.max(self.neg_Q - self.neg_storage_reward)) # # self.pos_adv = (self.pos_storage_reward) / np.abs(np.max(self.pos_storage_reward )) # self.neg_adv = (self.neg_storage_reward) / np.abs(np.max(self.neg_storage_reward)) def sample_pos(self, batch_size): ind = np.random.randint(0, len(self.pos_storage) , size=batch_size) embedding_list,obs_list,state_list =[],[], [] for i in ind: embedding,obs,state= self.pos_storage[i] #discount_reward = self.pos_storage_reward[i] # Q_list.append(self.pos_Q[i]) # adv.append(self.pos_adv[i]) state_list.append(np.array(state, copy=False)) embedding_list.append(np.array(embedding, copy=False)) obs_list.append(np.array(obs,copy=False)) #discount_reward_list.append(discount_reward) return np.array(embedding_list),np.array(obs_list),np.array(state_list) def sample_neg(self, batch_size): ind = np.random.randint(0, len(self.neg_storage) , size=batch_size) embedding_list , discount_reward_list ,obs_list,state_list,Q_list,adv=[],[],[],[], [],[] for i in ind: embedding ,obs,state= self.neg_storage[i] discount_reward = self.neg_storage_reward[i] # adv.append(self.neg_adv[i]) # Q_list.append(self.neg_Q[i]) state_list.append(np.array(state, copy=False)) embedding_list.append(np.array(embedding, copy=False)) obs_list.append(np.array(obs,copy=False)) discount_reward_list.append(discount_reward) return np.array(embedding_list),np.array(discount_reward_list),np.array(obs_list),np.array(state_list) def sample_rencently(self,batch_size,recent_num=10000): if self.ptr == 0: ind = np.random.randint(int(self.max_size - recent_num), int(self.max_size), size=batch_size) else: ind = np.random.randint(max(int(self.ptr - recent_num), 0), self.ptr, size=batch_size) #ind = np.random.randint(0, len(self.storage), size=batch_size) embedding_list, obs_list, state_list = [], [], [] for i in ind: embedding, obs, state = self.storage[i] state_list.append(np.array(state, copy=False)) embedding_list.append(np.array(embedding, copy=False)) obs_list.append(np.array(obs, copy=False)) return np.array(embedding_list), np.array(obs_list), np.array(state_list) def sample(self,batch_size): ind = np.random.randint(0, len(self.storage), size=batch_size) #ind = np.random.randint(0, len(self.storage), size=batch_size) embedding_list, obs_list, state_list = [], [], [] for i in ind: embedding, obs, state = self.storage[i] state_list.append(np.array(state, copy=False)) embedding_list.append(np.array(embedding, copy=False)) obs_list.append(np.array(obs, copy=False)) return np.array(embedding_list), np.array(obs_list), np.array(state_list) def refresh_pos_data(self,mean_reward): new_pos_storage = [] new_pos_storage_reward = [] for index,reward in enumerate(self.pos_storage_reward): if reward > mean_reward: new_pos_storage.append(self.pos_storage[index]) new_pos_storage_reward.append(reward) self.pos_storage = new_pos_storage self.pos_storage_reward = new_pos_storage_reward self.pos_ptr = len(new_pos_storage)%self.max_max_size def refresh_neg_data(self,mean_reward): new_neg_storage = [] new_neg_storage_reward = [] for index, reward in enumerate(self.neg_storage_reward): if reward < mean_reward: new_neg_storage.append(self.neg_storage[index]) new_neg_storage_reward.append(reward) self.neg_storage = new_neg_storage self.neg_storage_reward = new_neg_storage_reward self.neg_ptr = len(new_neg_storage)%self.max_max_size class Buffer(object): def __init__(self, max_size=1e3): self.storage = [] self.max_size = max_size self.ptr = 0 def add(self, data): self.storage[int(self.ptr)] = data def clear(self): self.storage.clear() def combined_shape(length, shape=None): if shape is None: return (length,) return (length, shape) if np.isscalar(shape) else (length, *shape) class ReplayBufferPPO(object): """ original from: https://github.com/bluecontra/tsallis_actor_critic_mujoco/blob/master/spinup/algos/ppo/ppo.py A buffer for storing trajectories experienced by a PPO agent interacting with the environment, and using Generalized Advantage Estimation (GAE-Lambda) for calculating the advantages of state-action pairs. """ def __init__(self, obs_dim, act_dim, size, gamma=0.99, lam=0.95): self.obs_dim = obs_dim self.act_dim = act_dim self.size = size self.gamma, self.lam = gamma, lam self.ptr = 0 self.path_start_idx, self.max_size = 0, size self.reset() def reset(self): self.obs_buf = np.zeros([self.size, self.obs_dim], dtype=np.float32) self.act_buf = np.zeros([self.size, self.act_dim], dtype=np.float32) self.adv_buf = np.zeros(self.size, dtype=np.float32) self.rew_buf = np.zeros(self.size, dtype=np.float32) self.ret_buf = np.zeros(self.size, dtype=np.float32) self.val_buf = np.zeros(self.size, dtype=np.float32) self.logp_buf = np.zeros(self.size, dtype=np.float32) def add(self, obs, act, rew, val, logp): """ Append one timestep of agent-environment interaction to the buffer. """ assert self.ptr < self.max_size # buffer has to have room so you can store self.obs_buf[self.ptr] = obs self.act_buf[self.ptr] = act self.rew_buf[self.ptr] = rew self.val_buf[self.ptr] = val self.logp_buf[self.ptr] = logp self.ptr += 1 def finish_path(self, last_val=0): path_slice = slice(self.path_start_idx, self.ptr) rews = np.append(self.rew_buf[path_slice], last_val) vals = np.append(self.val_buf[path_slice], last_val) # the next two lines implement GAE-Lambda advantage calculation deltas = rews[:-1] + self.gamma * vals[1:] - vals[:-1] self.adv_buf[path_slice] = discount(deltas, self.gamma * self.lam) # the next line computes rewards-to-go, to be targets for the value function self.ret_buf[path_slice] = discount(rews, self.gamma)[:-1] self.path_start_idx = self.ptr def get(self): assert self.ptr == self.max_size # buffer has to be full before you can get self.ptr, self.path_start_idx = 0, 0 # the next two lines implement the advantage normalization trick # adv_mean, adv_std = mpi_statistics_scalar(self.adv_buf) adv_mean = np.mean(self.adv_buf) adv_std = np.std(self.adv_buf) self.adv_buf = (self.adv_buf - adv_mean) / adv_std return [self.obs_buf, self.act_buf, self.adv_buf, self.ret_buf, self.logp_buf] class ReplayBuffer_MC(object): def __init__(self, max_size=1e6): self.storage = [] self.max_size = max_size self.ptr = 0 def add(self, data): if len(self.storage) == self.max_size: self.storage[int(self.ptr)] = data self.ptr = (self.ptr + 1) % self.max_size else: self.storage.append(data) def sample(self, batch_size): ind = np.random.randint(0, len(self.storage), size=batch_size) x, u, r = [], [], [] for i in ind: X, U, R = self.storage[i] x.append(np.array(X, copy=False)) u.append(np.array(U, copy=False)) r.append(np.array(R, copy=False)) return np.array(x), np.array(u), np.array(r).reshape(-1, 1) class ReplayBuffer_VDFP(object): def __init__(self, max_size=1e5): self.storage = [] self.max_size = int(max_size) self.ptr = 0 def add(self, data): if len(self.storage) == self.max_size: self.storage[self.ptr] = data self.ptr = (self.ptr + 1) % self.max_size else: self.storage.append(data) def sample(self, batch_size): ind = np.random.randint(0, len(self.storage), size=batch_size) s, a, u, x = [], [], [], [] for i in ind: S, A, U, X = self.storage[i] s.append(np.array(S, copy=False)) a.append(np.array(A, copy=False)) u.append(np.array(U, copy=False)) x.append(np.array(X, copy=False)) return np.array(s), np.array(a), np.array(u).reshape(-1, 1), np.array(x) def sample_traj(self, batch_size, offset=0): ind = np.random.randint(0, len(self.storage) - int(offset), size=batch_size) if len(self.storage) == self.max_size: ind = (self.ptr + self.max_size - ind) % self.max_size else: ind = len(self.storage) - ind - 1 # ind = (self.ptr - ind + len(self.storage)) % len(self.storage) s, a, x = [], [], [] for i in ind: S, A, _, X = self.storage[i] s.append(np.array(S, copy=False)) a.append(np.array(A, copy=False)) x.append(np.array(X, copy=False)) return np.array(s), np.array(a), np.array(x) def sample_traj_return(self, batch_size): ind = np.random.randint(0, len(self.storage), size=batch_size) u, x = [], [] for i in ind: _, _, U, X = self.storage[i] u.append(np.array(U, copy=False)) x.append(np.array(X, copy=False)) return np.array(u).reshape(-1, 1), np.array(x) def store_experience(replay_buffer, trajectory, s_dim, a_dim, sequence_length, min_sequence_length=0, is_padding=False, gamma=0.99, ): s_traj, a_traj, r_traj = trajectory # for the convenience of manipulation arr_s_traj = np.array(s_traj) arr_a_traj = np.array(a_traj) arr_r_traj = np.array(r_traj) zero_pads = np.zeros(shape=[sequence_length, s_dim + a_dim]) # for i in range(len(s_traj) - self.sequence_length): for i in range(len(s_traj) - min_sequence_length): tmp_s = arr_s_traj[i] tmp_a = arr_a_traj[i] tmp_soff = arr_s_traj[i:i + sequence_length] tmp_aoff = arr_a_traj[i:i + sequence_length] tmp_saoff = np.concatenate([tmp_soff, tmp_aoff], axis=1) tmp_saoff_padded = np.concatenate([tmp_saoff, zero_pads], axis=0) tmp_saoff_padded_clip = tmp_saoff_padded[:sequence_length, :] tmp_roff = arr_r_traj[i:i + sequence_length] tmp_u = np.matmul(tmp_roff, np.power(gamma, [j for j in range(len(tmp_roff))])) replay_buffer.add((tmp_s, tmp_a, tmp_u, tmp_saoff_padded_clip)) def discount(x, gamma): """ Calculate discounted forward sum of a sequence at each point """ """ magic from rllab for computing discounted cumulative sums of vectors. input: vector x, [x0, x1, x2] output: [x0 + discount * x1 + discount^2 * x2, x1 + discount * x2, x2] """ # return scipy.signal.lfilter([1], [1, float(-discount)], x[::-1], axis=0)[::-1] return scipy.signal.lfilter([1.0], [1.0, -gamma], x[::-1])[::-1] class Scaler(object): """ Generate scale and offset based on running mean and stddev along axis=0 offset = running mean scale = 1 / (stddev + 0.1) / 3 (i.e. 3x stddev = +/- 1.0) """ def __init__(self, obs_dim): """ Args: obs_dim: dimension of axis=1 """ self.vars = np.zeros(obs_dim) self.means = np.zeros(obs_dim) self.m = 0 self.n = 0 self.first_pass = True def update(self, x): """ Update running mean and variance (this is an exact method) Args: x: NumPy array, shape = (N, obs_dim) see: https://stats.stackexchange.com/questions/43159/how-to-calculate-pooled- variance-of-two-groups-given-known-group-variances-mean """ if self.first_pass: self.means = np.mean(x, axis=0) self.vars = np.var(x, axis=0) self.m = x.shape[0] self.first_pass = False else: n = x.shape[0] new_data_var = np.var(x, axis=0) new_data_mean = np.mean(x, axis=0) new_data_mean_sq = np.square(new_data_mean) new_means = ((self.means * self.m) + (new_data_mean * n)) / (self.m + n) self.vars = (((self.m * (self.vars + np.square(self.means))) + (n * (new_data_var + new_data_mean_sq))) / (self.m + n) - np.square(new_means)) self.vars = np.maximum(0.0, self.vars) # occasionally goes negative, clip self.means = new_means self.m += n def get(self): """ returns 2-tuple: (scale, offset) """ return 1/(np.sqrt(self.vars) + 0.1)/3, self.means
24,339
37.696343
153
py
PMIC
PMIC-main/run_maxminMADDPG.py
''' Demo run file for different algorithms and Mujoco tasks. ''' import numpy as np import torch import gym import argparse import ma_utils import algorithms.mpe_new_maxminMADDPG as MA_MINE_DDPG import math import os from tensorboardX import SummaryWriter from multiprocessing import cpu_count from maddpg.utils.env_wrappers import SubprocVecEnv, DummyVecEnv import time cpu_num = 1 os.environ ['OMP_NUM_THREADS'] = str(cpu_num) os.environ ['OPENBLAS_NUM_THREADS'] = str(cpu_num) os.environ ['MKL_NUM_THREADS'] = str(cpu_num) os.environ ['VECLIB_MAXIMUM_THREADS'] = str(cpu_num) os.environ ['NUMEXPR_NUM_THREADS'] = str(cpu_num) torch.set_num_threads(cpu_num) def make_parallel_env(env_id, n_rollout_threads, seed, discrete_action): def get_env_fn(rank): def init_env(): env = make_env(env_id, discrete_action=discrete_action) env.seed(seed + rank * 1000) np.random.seed(seed + rank * 1000) return env return init_env if n_rollout_threads == 1: return DummyVecEnv([get_env_fn(0)]) else: return SubprocVecEnv([get_env_fn(i) for i in range(n_rollout_threads)]) def natural_exp_inc(init_param, max_param, global_step, current_step, inc_step=1000, inc_rate=0.5, stair_case=False): p = (global_step - current_step) / inc_step if stair_case: p = math.floor(p) increased_param = min((max_param - init_param) * math.exp(-inc_rate * p) + init_param, max_param) return increased_param def make_env(scenario_name, benchmark=False,discrete_action=False): ''' Creates a MultiAgentEnv object as env. This can be used similar to a gym environment by calling env.reset() and env.step(). Use env.render() to view the environment on the screen. Input: scenario_name : name of the scenario from ./scenarios/ to be Returns (without the .py extension) benchmark : whether you want to produce benchmarking data (usually only done during evaluation) Some useful env properties (see environment.py): .observation_space : Returns the observation space for each agent .action_space : Returns the action space for each agent .n : Returns the number of Agents ''' from multiagent.environment import MultiAgentEnv import multiagent.scenarios as scenarios # load scenario from script scenario = scenarios.load(scenario_name + ".py").Scenario() # create world world = scenario.make_world() # create multiagent environment if benchmark: env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation, scenario.benchmark_data) else: env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation ) return env # Runs policy for X episodes and returns average reward def evaluate_policy(policy, eval_episodes=10): avg_reward = 0. num_step = 0 for _ in range(eval_episodes): obs = env.reset() done = False ep_step_num = 0 #print("obs ",obs) while ep_step_num < 50: t = ep_step_num / 1000 obs_t = [] for i in range(n_agents): obs_t_one = list(obs[i]) obs_t.append(obs_t_one) obs_t = np.array(obs_t) num_step +=1 scaled_a_list = [] for i in range(n_agents): #print("obs_t[i]",obs_t[i]) a = policy.select_action(obs_t[i], i) scaled_a = np.multiply(a, 1.0) scaled_a_list.append(scaled_a) action_n = [[0, a[0], 0, a[1], 0] for a in scaled_a_list] next_obs, reward, done, _ = env.step(action_n) next_state = next_obs[0] obs = next_obs ep_step_num += 1 avg_reward += reward[0] avg_reward /= eval_episodes print("---------------------------------------") print("Evaluation over %d episodes: %f" % (eval_episodes, avg_reward)) print("---------------------------------------") return avg_reward,num_step/eval_episodes if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--policy_name", default="DDPG") # Policy name parser.add_argument("--env_name", default="HalfCheetah-v1") # OpenAI gym environment name parser.add_argument("--seed", default=1, type=int) # Sets Gym, PyTorch and Numpy seeds parser.add_argument("--batch_size", default=1024, type=int) # Batch size for both actor and critic parser.add_argument("--discount", default=0.95, type=float) # Discount factor parser.add_argument("--tau", default=0.01, type=float) # Target network update rate parser.add_argument("--policy_freq", default=2, type=int) # Frequency of delayed policy updates parser.add_argument("--freq_test_mine", default=5e3, type=float) parser.add_argument("--gpu-no", default='-1', type=str) # GPU number, -1 means CPU parser.add_argument("--MI_update_freq", default=1, type=int) parser.add_argument("--max_adv_c", default=0.0, type=float) parser.add_argument("--min_adv_c", default=0.0, type=float) parser.add_argument("--discrete_action",action='store_true') args = parser.parse_args() file_name = "PMIC_%s_%s_%s_%s_%s"% (args.MI_update_freq,args.max_adv_c,args.min_adv_c,args.env_name,args.seed) writer = SummaryWriter(log_dir="./tensorboard/" + file_name) output_dir="./output/" + file_name model_dir = "./model/" + file_name if os.path.exists(output_dir) is False : os.makedirs(output_dir) if os.path.exists(model_dir) is False : os.makedirs(model_dir) print("---------------------------------------") print("Settings: %s" % (file_name)) print("---------------------------------------") import os os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_no device = torch.device("cuda" if torch.cuda.is_available() else "cpu") env = make_parallel_env(args.env_name, 1, args.seed, args.discrete_action) env = make_env(args.env_name) env = env.unwrapped #env = gym.make(args.env_name) # Set seeds env.seed(args.seed) n_agents = env.n obs_shape_n = [env.observation_space[i].shape[0] for i in range(env.n)] print("obs_shape_n ",obs_shape_n) ac = [env.action_space[i].shape for i in range(env.n)] action_shape_n = [2 for i in range(env.n)] print("env .n ",env.n) torch.cuda.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) torch.manual_seed(args.seed) np.random.seed(args.seed) policy = MA_MINE_DDPG.MA_T_DDPG(n_agents,obs_shape_n,sum(obs_shape_n), action_shape_n, 1.0, device,0.0,0.0) replay_buffer = ma_utils.ReplayBuffer(1e6) good_data_buffer = ma_utils.embedding_Buffer(1e3) bad_data_buffer = ma_utils.embedding_Buffer(1e3) total_timesteps = 0 timesteps_since_eval = 0 episode_num = 0 episode_reward = 0 done = True get_epoch_Mi = False Mi_list = [] data_recorder = [] replay_buffer_recorder =[] moving_avg_reward_list = [] embedding_recorder=[] best_reward_start = -1 reward_list =[] eposide_reward_list =[] recorder_reward = 0 best_reward = -100000000000 eposide_num = -1 current_policy_performance = -1000 episode_timesteps = 25 start_time = time.time() t1 = time.time() while total_timesteps < 40e5: if episode_timesteps == 25: eposide_num +=1 for d in replay_buffer_recorder: replay_buffer.add(d,episode_reward) if total_timesteps != 0: # walker 50 if len(good_data_buffer.pos_storage_reward) != 0: if len(moving_avg_reward_list) >=10: move_avg = np.mean(moving_avg_reward_list[-1000:]) current_policy_performance = move_avg lowest_reward = good_data_buffer.rank_storage(-100000) mean_reward = np.mean(good_data_buffer.pos_storage_reward) if len(moving_avg_reward_list) >=10: #writer.add_scalar("data/tp_lowest_reward", lowest_reward, total_timesteps) if lowest_reward < move_avg: lowest_reward = move_avg else : lowest_reward = -500 mean_reward = 0 if lowest_reward < episode_reward: Obs_list = [] State_list = [] Action_list = [] for d in data_recorder: obs = d[0] state = d[1] Action_list.append(d[2]) Obs_list.append(obs) State_list.append(state) for index in range(len(Action_list)): good_data_buffer.add_pos((Action_list[index], Obs_list[index], State_list[index]),episode_reward) else : Obs_list = [] State_list = [] Action_list = [] for d in data_recorder: obs = d[0] state = d[1] Action_list.append(d[2]) Obs_list.append(obs) State_list.append(state) for index in range(len(Action_list)): bad_data_buffer.add_pos((Action_list[index], Obs_list[index], State_list[index]),episode_reward) # org 10 if len(moving_avg_reward_list) % 10 == 0 : writer.add_scalar("data/reward", np.mean(moving_avg_reward_list[-1000:]), total_timesteps) writer.add_scalar("data/data_in_pos", np.mean(good_data_buffer.pos_storage_reward), total_timesteps) if episode_num%1000 == 0 : print('Total T:', total_timesteps, 'Episode Num:', episode_num, 'Episode T:', episode_timesteps, 'Reward:', np.mean(moving_avg_reward_list[-1000:])/3.0, " time cost:", time.time() - t1) t1 = time.time() if total_timesteps >= 1024 and total_timesteps%100 == 0: sp_actor_loss_list =[] process_Q_list = [] process_min_MI_list = [] process_max_MI_list = [] process_min_MI_loss_list = [] process_max_MI_loss_list = [] Q_grads_list =[] MI_grads_list =[] for i in range(1): if len(good_data_buffer.pos_storage)< 500: process_Q = policy.train(replay_buffer, 1, args.batch_size, args.discount, args.tau) process_min_MI = 0 process_min_MI_loss = 0 min_mi = 0.0 min_mi_loss = 0.0 process_max_MI = 0 pr_sp_loss = 0.0 Q_grads = 0.0 MI_grads =0.0 process_max_MI_loss = 0.0 else : if total_timesteps % (args.MI_update_freq*100) == 0 : if args.min_adv_c > 0.0 : process_min_MI_loss = policy.train_club(bad_data_buffer, 1, batch_size=args.batch_size) else : process_min_MI_loss = 0.0 if args.max_adv_c > 0.0 : process_max_MI_loss,_ = policy.train_mine(good_data_buffer, 1, batch_size=args.batch_size) else: process_max_MI_loss = 0.0 else : process_min_MI_loss = 0.0 process_max_MI_loss = 0.0 process_Q,process_min_MI ,process_max_MI, Q_grads,MI_grads = policy.train_actor_with_mine(replay_buffer, 1, args.batch_size,args.discount, args.tau,max_mi_c=0.0,min_mi_c=0.0 ,min_adv_c=args.min_adv_c, max_adv_c=args.max_adv_c ) process_max_MI_list.append(process_max_MI) process_Q_list.append(process_Q) Q_grads_list.append(Q_grads) MI_grads_list.append(MI_grads) process_max_MI_loss_list.append(process_max_MI_loss) process_min_MI_list.append(process_min_MI) process_min_MI_loss_list.append(process_min_MI_loss) if len(moving_avg_reward_list) % 10 == 0 : writer.add_scalar("data/MINE_lower_bound_loss", np.mean(process_max_MI_loss_list), total_timesteps) writer.add_scalar("data/process_Q", np.mean(process_Q_list), total_timesteps) writer.add_scalar("data/club_upper_bound_loss", np.mean(process_min_MI_loss_list), total_timesteps) obs = env.reset() state = np.concatenate(obs, -1) #print("ep reward ", episode_reward) moving_avg_reward_list.append(episode_reward) #obs = env.reset() #writer.add_scalar("data/run_reward", episode_reward, total_timesteps) done = False explr_pct_remaining = max(0, 25000 - episode_num) / 25000 policy.scale_noise( 0.3 * explr_pct_remaining) policy.reset_noise() episode_reward = 0 reward_list = [] eposide_reward_list = [] episode_timesteps = 0 episode_num += 1 data_recorder = [] replay_buffer_recorder =[] best_reward_start = -1 best_reward = -1000000 # FIXME 1020 Mi_list = [] # Select action randomly or according to policy scaled_a_list = [] for i in range(n_agents): a = policy.select_action(obs[i], i) scaled_a = np.multiply(a, 1.0) scaled_a_list.append(scaled_a) if args.env_name == "simple_reference": action_n = np.array([[0, a[0], 0, a[1],0, a[2],a[3]] for a in scaled_a_list]) # Perform action elif args.env_name == "simple": action_n = np.array([[a[0], a[1]] for a in scaled_a_list]) else : action_n = np.array([[0, a[0], 0, a[1],0] for a in scaled_a_list]) #print(action_n) next_obs, reward, done, _ = env.step(action_n) reward = reward[0] next_state = np.concatenate(next_obs, -1) done = all(done) terminal = (episode_timesteps + 1 >= 25) done_bool = float(done or terminal) episode_reward += reward eposide_reward_list.append(reward) # Store data in replay buffer replay_buffer_recorder.append((obs, state,next_state,next_obs, np.concatenate(scaled_a_list,-1), reward, done)) data_recorder.append([obs, state, scaled_a_list]) obs = next_obs state = next_state episode_timesteps += 1 total_timesteps += 1 timesteps_since_eval += 1 print("total time ",time.time()-start_time) policy.save(total_timesteps, "model/" + file_name) writer.close()
15,980
36.602353
251
py
PMIC
PMIC-main/algorithms/mpe_new_maxminMADDPG.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import math from collections import OrderedDict from torch.autograd import Variable import os from torch import Tensor class OUNoise: def __init__(self, action_dimension, scale=0.1, mu=0, theta=0.15, sigma=0.2): self.action_dimension = action_dimension self.scale = scale self.mu = mu self.theta = theta self.sigma = sigma self.state = np.ones(self.action_dimension) * self.mu self.reset() def reset(self): self.state = np.ones(self.action_dimension) * self.mu def noise(self): x = self.state dx = self.theta * (self.mu - x) + self.sigma * np.random.randn(len(x)) self.state = x + dx return self.state * self.scale def weight_init(m): if isinstance(m, nn.Linear): stdv = 1. / math.sqrt(m.weight.size(1)) m.weight.data.uniform_(-stdv, stdv) m.bias.data.uniform_(-stdv, stdv) # nn.init.xavier_normal_(m.weight) # nn.init.constant_(m.bias, 0) def get_negative_expectation(q_samples, measure, average=True): log_2 = math.log(2.) if measure == 'GAN': Eq = F.softplus(-q_samples) + q_samples elif measure == 'JSD': # Eq = F.softplus(-q_samples) + q_samples - log_2 # Note JSD will be shifted #Eq = F.softplus(q_samples) #+ q_samples - log_2 elif measure == 'X2': Eq = -0.5 * ((torch.sqrt(q_samples ** 2) + 1.) ** 2) elif measure == 'KL': q_samples = torch.clamp(q_samples,-1e6,9.5) #print("neg q samples ",q_samples.cpu().data.numpy()) Eq = torch.exp(q_samples - 1.) elif measure == 'RKL': Eq = q_samples - 1. elif measure == 'H2': Eq = torch.exp(q_samples) - 1. elif measure == 'W1': Eq = q_samples else: assert 1==2 if average: return Eq.mean() else: return Eq def get_positive_expectation(p_samples, measure, average=True): log_2 = math.log(2.) if measure == 'GAN': Ep = - F.softplus(-p_samples) elif measure == 'JSD': Ep = log_2 - F.softplus(-p_samples) # Note JSD will be shifted #Ep = - F.softplus(-p_samples) elif measure == 'X2': Ep = p_samples ** 2 elif measure == 'KL': Ep = p_samples elif measure == 'RKL': Ep = -torch.exp(-p_samples) elif measure == 'DV': Ep = p_samples elif measure == 'H2': Ep = 1. - torch.exp(-p_samples) elif measure == 'W1': Ep = p_samples else: assert 1==2 if average: return Ep.mean() else: return Ep def fenchel_dual_loss(l, m, measure=None): '''Computes the f-divergence distance between positive and negative joint distributions. Note that vectors should be sent as 1x1. Divergences supported are Jensen-Shannon `JSD`, `GAN` (equivalent to JSD), Squared Hellinger `H2`, Chi-squeared `X2`, `KL`, and reverse KL `RKL`. Args: l: Local feature map. m: Multiple globals feature map. measure: f-divergence measure. Returns: torch.Tensor: Loss. ''' N, units = l.size() # Outer product, we want a N x N x n_local x n_multi tensor. u = torch.mm(m, l.t()) # Since we have a big tensor with both positive and negative samples, we need to mask. mask = torch.eye(N).to(l.device) n_mask = 1 - mask # Compute the positive and negative score. Average the spatial locations. E_pos = get_positive_expectation(u, measure, average=False) E_neg = get_negative_expectation(u, measure, average=False) MI = (E_pos * mask).sum(1) #- (E_neg * n_mask).sum(1)/(N-1) # Mask positive and negative terms for positive and negative parts of loss E_pos_term = (E_pos * mask).sum(1) E_neg_term = (E_neg * n_mask).sum(1) /(N-1) loss = E_neg_term - E_pos_term return loss,MI class NEW_MINE(nn.Module): def __init__(self,state_size,com_a_size,measure ="JSD"): super(NEW_MINE, self).__init__() self.measure = measure self.com_a_size = com_a_size self.state_size = state_size self.nonlinearity = F.leaky_relu self.l1 = nn.Linear(self.state_size, 32) self.l2 = nn.Linear(self.com_a_size, 32) def forward(self, state, joint_action,params =None): em_1 = self.nonlinearity(self.l1(state),inplace=True) em_2 = self.nonlinearity(self.l2(joint_action),inplace=True) two_agent_embedding = [em_1,em_2] loss, MI = fenchel_dual_loss(two_agent_embedding[0], two_agent_embedding[1], measure=self.measure) return loss ,MI class CLUB(nn.Module): # CLUB: Mutual Information Contrastive Learning Upper Bound ''' This class provides the CLUB estimation to I(X,Y) Method: forward() : provides the estimation with input samples loglikeli() : provides the log-likelihood of the approximation q(Y|X) with input samples Arguments: x_dim, y_dim : the dimensions of samples from X, Y respectively hidden_size : the dimension of the hidden layer of the approximation network q(Y|X) x_samples, y_samples : samples from X and Y, having shape [sample_size, x_dim/y_dim] ''' def __init__(self, x_dim, y_dim, hidden_size): super(CLUB, self).__init__() # p_mu outputs mean of q(Y|X) # print("create CLUB with dim {}, {}, hiddensize {}".format(x_dim, y_dim, hidden_size)) self.p_mu = nn.Sequential(nn.Linear(x_dim, hidden_size // 2), nn.ReLU(inplace=True), nn.Linear(hidden_size // 2, y_dim)) # p_logvar outputs log of variance of q(Y|X) self.p_logvar = nn.Sequential(nn.Linear(x_dim, hidden_size // 2), nn.ReLU(inplace=True), nn.Linear(hidden_size // 2, y_dim), nn.Tanh()) def get_mu_logvar(self, x_samples): mu = self.p_mu(x_samples) logvar = self.p_logvar(x_samples) return mu, logvar def forward(self, x_samples, y_samples): mu, logvar = self.get_mu_logvar(x_samples) # log of conditional probability of positive sample pairs positive = - (mu - y_samples) ** 2 / 2. / logvar.exp() prediction_1 = mu.unsqueeze(1) # shape [nsample,1,dim] y_samples_1 = y_samples.unsqueeze(0) # shape [1,nsample,dim] # log of conditional probability of negative sample pairs negative = - ((y_samples_1 - prediction_1) ** 2).mean(dim=1) / 2. / logvar.exp() return positive.sum(dim=-1) - negative.sum(dim=-1) def loglikeli(self, x_samples, y_samples): # unnormalized loglikelihood mu, logvar = self.get_mu_logvar(x_samples) return (-(mu - y_samples) ** 2 / logvar.exp() - logvar).sum(dim=1).mean(dim=0) def learning_loss(self, x_samples, y_samples): return - self.loglikeli(x_samples, y_samples) class Actor(nn.Module): def __init__(self, state_dim, action_dim, max_action,layer_sizes=None): super(Actor, self).__init__() if layer_sizes is None : layer_sizes = [state_dim,64,64] self.nonlinearity = F.relu self.num_layers = len(layer_sizes) for i in range(1, self.num_layers): self.add_module('layer{0}'.format(i),nn.Linear(layer_sizes[i - 1], layer_sizes[i])) self.a_layer = nn.Linear(layer_sizes[-1], action_dim) self.max_action = max_action def forward(self, x,params=None): if params is None: params = OrderedDict(self.named_parameters()) output = x output_list = [] for i in range(1, self.num_layers): output = F.linear(output, weight=params['layer{0}.weight'.format(i)], bias=params['layer{0}.bias'.format(i)]) output = self.nonlinearity(output,inplace=True) output_list.append(output) obs_embedding = output_list[0] policy_embedding = output_list[1] output = F.linear(output,weight=params['a_layer.weight'],bias=params['a_layer.bias']) output = self.max_action * torch.tanh(output) #logits = output #u = torch.rand(output.shape) #output = torch.nn.functional.softmax(output - torch.log(-torch.log(u)),dim=-1) return output,obs_embedding,policy_embedding class Critic(nn.Module): def __init__(self, state_dim, action_dim): super(Critic, self).__init__() self.l1 = nn.Linear(state_dim + action_dim, 64) self.l2 = nn.Linear(64, 64) self.l3 = nn.Linear(64, 1) def forward(self, x, u): xu = torch.cat([x, u], 1) x = F.relu(self.l1(xu),inplace=True) x = F.relu(self.l2(x),inplace=True) x = self.l3(x) return x class MA_T_DDPG(object): def __init__(self, num_agent, obs_dim, state_dim, action_dim_list, max_action, deivce ,max_mi_c,min_mi_c): self.device = deivce self.num_agent = num_agent self.total_action = sum(action_dim_list) # self.pr_actor = Actor(state_dim, sum(action_dim_list), max_action).to(self.device) self.actor = [Actor(obs_dim[i], action_dim_list[i], max_action).to(self.device) for i in range(self.num_agent)] self.actor_target = [Actor(obs_dim[i], action_dim_list[i], max_action).to(self.device) for i in range(self.num_agent)] [self.actor_target[i].load_state_dict(self.actor[i].state_dict()) for i in range(self.num_agent)] # self.pr_actor_optimizer = torch.optim.Adam([{'params': self.pr_actor.parameters()}],lr=3e-5) self.actor_optimizer = torch.optim.Adam([{'params': self.actor[i].parameters()} for i in range(num_agent)], lr=1e-4) #if max_mi_c > 0.0 : self.mine_policy=NEW_MINE(state_dim,self.total_action).to(self.device) self.mine_optimizer = torch.optim.Adam([{'params': self.mine_policy.parameters()}], lr=0.0001) self.club_policy = CLUB(state_dim,self.total_action,64).to(self.device) self.club_optimizer = torch.optim.Adam([{'params': self.club_policy.parameters()}], lr=0.0001) self.critic = Critic(state_dim, self.total_action).to(self.device) self.critic_target = Critic(state_dim, self.total_action).to(self.device) self.critic_target.load_state_dict(self.critic.state_dict()) self.critic_optimizer = torch.optim.Adam(self.critic.parameters(),lr=1e-3) self.update_lr = 0.1 self.exploration = OUNoise(action_dim_list[0]) def scale_noise(self, scale): """ Scale noise for each agent Inputs: scale (float): scale of noise """ self.exploration.scale = scale def reset_noise(self): self.exploration.reset() def select_action(self, state, index,params=None): # print("????????? ") with torch.no_grad(): state = torch.FloatTensor(state.reshape(1, -1)).to(self.device) action = self.actor[index](state,params)[0] # print("ac ", action.shape,action ) noise = Variable(Tensor(self.exploration.noise()),requires_grad=False) # print("noise ",noise.shape,noise) action += noise # print("final a ", action ) action = action.clamp(-1, 1) return action.cpu().data.numpy().flatten() def train_mine(self, replay_buffer, iterations, batch_size=64): loss_list = [] Mi_loss = [] # replay_buffer.caculate_Q(self.actor,self.critic_target,device=self.device) for it in range(iterations): # Sample replay buffer pos_action, pos_obs, pos_state = replay_buffer.sample_pos(batch_size) if self.num_agent == 2: pos_action1 = [] pos_action2 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action = [pos_action1, pos_action2] elif self.num_agent == 3: pos_action1 = [] pos_action2 = [] pos_action3 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3] elif self.num_agent == 4: pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3, pos_action4] elif self.num_agent == 5: pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] pos_action5 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5] elif self.num_agent == 6: pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] pos_action5 = [] pos_action6 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action6.append(pos_action[i][5]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) pos_action6 = torch.FloatTensor(pos_action6).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6] elif self.num_agent == 9: pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] pos_action5 = [] pos_action6 = [] pos_action7 = [] pos_action8 = [] pos_action9 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action6.append(pos_action[i][5]) pos_action7.append(pos_action[i][6]) pos_action8.append(pos_action[i][7]) pos_action9.append(pos_action[i][8]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) pos_action6 = torch.FloatTensor(pos_action6).to(self.device) pos_action7 = torch.FloatTensor(pos_action7).to(self.device) pos_action8 = torch.FloatTensor(pos_action8).to(self.device) pos_action9 = torch.FloatTensor(pos_action9).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9] elif self.num_agent == 12: pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] pos_action5 = [] pos_action6 = [] pos_action7 = [] pos_action8 = [] pos_action9 = [] pos_action10 = [] pos_action11 = [] pos_action12 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action6.append(pos_action[i][5]) pos_action7.append(pos_action[i][6]) pos_action8.append(pos_action[i][7]) pos_action9.append(pos_action[i][8]) pos_action10.append(pos_action[i][9]) pos_action11.append(pos_action[i][10]) pos_action12.append(pos_action[i][11]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) pos_action6 = torch.FloatTensor(pos_action6).to(self.device) pos_action7 = torch.FloatTensor(pos_action7).to(self.device) pos_action8 = torch.FloatTensor(pos_action8).to(self.device) pos_action9 = torch.FloatTensor(pos_action9).to(self.device) pos_action10 = torch.FloatTensor(pos_action10).to(self.device) pos_action11 = torch.FloatTensor(pos_action11).to(self.device) pos_action12 = torch.FloatTensor(pos_action12).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9,pos_action10, pos_action11, pos_action12] elif self.num_agent == 24: pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] pos_action5 = [] pos_action6 = [] pos_action7 = [] pos_action8 = [] pos_action9 = [] pos_action10 = [] pos_action11 = [] pos_action12 = [] pos_action13 = [] pos_action14 = [] pos_action15 = [] pos_action16 = [] pos_action17 = [] pos_action18 = [] pos_action19 = [] pos_action20 = [] pos_action21 = [] pos_action22 = [] pos_action23 = [] pos_action24 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action6.append(pos_action[i][5]) pos_action7.append(pos_action[i][6]) pos_action8.append(pos_action[i][7]) pos_action9.append(pos_action[i][8]) pos_action10.append(pos_action[i][9]) pos_action11.append(pos_action[i][10]) pos_action12.append(pos_action[i][11]) pos_action13.append(pos_action[i][12]) pos_action14.append(pos_action[i][13]) pos_action15.append(pos_action[i][14]) pos_action16.append(pos_action[i][15]) pos_action17.append(pos_action[i][16]) pos_action18.append(pos_action[i][17]) pos_action19.append(pos_action[i][18]) pos_action20.append(pos_action[i][19]) pos_action21.append(pos_action[i][20]) pos_action22.append(pos_action[i][21]) pos_action23.append(pos_action[i][22]) pos_action24.append(pos_action[i][23]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) pos_action6 = torch.FloatTensor(pos_action6).to(self.device) pos_action7 = torch.FloatTensor(pos_action7).to(self.device) pos_action8 = torch.FloatTensor(pos_action8).to(self.device) pos_action9 = torch.FloatTensor(pos_action9).to(self.device) pos_action10 = torch.FloatTensor(pos_action10).to(self.device) pos_action11 = torch.FloatTensor(pos_action11).to(self.device) pos_action12 = torch.FloatTensor(pos_action12).to(self.device) pos_action13 = torch.FloatTensor(pos_action13).to(self.device) pos_action14 = torch.FloatTensor(pos_action14).to(self.device) pos_action15 = torch.FloatTensor(pos_action15).to(self.device) pos_action16 = torch.FloatTensor(pos_action16).to(self.device) pos_action17 = torch.FloatTensor(pos_action17).to(self.device) pos_action18 = torch.FloatTensor(pos_action18).to(self.device) pos_action19 = torch.FloatTensor(pos_action19).to(self.device) pos_action20 = torch.FloatTensor(pos_action20).to(self.device) pos_action21 = torch.FloatTensor(pos_action21).to(self.device) pos_action22 = torch.FloatTensor(pos_action22).to(self.device) pos_action23 = torch.FloatTensor(pos_action23).to(self.device) pos_action24 = torch.FloatTensor(pos_action24).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9,pos_action10, pos_action11, pos_action12,pos_action13, pos_action14, pos_action15, pos_action16, pos_action17, pos_action18,pos_action19, pos_action20, pos_action21,pos_action22, pos_action23, pos_action24] pos_state = torch.FloatTensor(pos_state).to(self.device) if self.num_agent == 2: tp_pos_action = [pos_action[0], pos_action[1]] elif self.num_agent == 3: tp_pos_action = [pos_action[0], pos_action[1], pos_action[2]] elif self.num_agent == 4: tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3]] elif self.num_agent == 5: tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4]] elif self.num_agent == 6: tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4], pos_action[5]] elif self.num_agent == 9: tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4], pos_action[5],pos_action[6], pos_action[7], pos_action[8]] elif self.num_agent == 12: tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4], pos_action[5],pos_action[6], pos_action[7], pos_action[8],pos_action[9], pos_action[10], pos_action[11]] elif self.num_agent == 24: tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4], pos_action[5],pos_action[6], pos_action[7], pos_action[8],pos_action[9], pos_action[10], pos_action[11],pos_action[12], pos_action[13], pos_action[14], pos_action[15], pos_action[16], pos_action[17],pos_action[18], pos_action[19], pos_action[20],pos_action[21], pos_action[22], pos_action[23]] pos_loaa, pos_MI = self.mine_policy(pos_state, torch.cat(tp_pos_action, -1)) loss = pos_loaa.mean() loss_list.append(loss.cpu().data.numpy()) Mi_loss.append(pos_MI.cpu().data.numpy()) self.mine_optimizer.zero_grad() loss.backward() self.mine_optimizer.step() return np.mean(loss_list), np.mean(Mi_loss) def train_club(self,replay_buffer,iterations,batch_size=64): min_MI_loss_list =[] for it in range(iterations): pos_action, pos_obs, pos_state = replay_buffer.sample_pos(batch_size) pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] pos_action5 = [] pos_action6 = [] if self.num_agent == 2: for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action = [pos_action1, pos_action2] tp_pos_action = [pos_action[0], pos_action[1]] elif self.num_agent == 3: for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action = [pos_action1, pos_action2,pos_action3] tp_pos_action = [pos_action[0],pos_action[1],pos_action[2]] elif self.num_agent == 4: for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action = [pos_action1, pos_action2,pos_action3,pos_action4] tp_pos_action = [pos_action[0], pos_action[1],pos_action[2],pos_action[3]] elif self.num_agent == 5: for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) tp_pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5] elif self.num_agent == 6 : for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action6.append(pos_action[i][5]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) pos_action6 = torch.FloatTensor(pos_action6).to(self.device) pos_action = [pos_action1, pos_action2,pos_action3, pos_action4,pos_action5, pos_action6] tp_pos_action = [pos_action[0], pos_action[1],pos_action[2], pos_action[3],pos_action[4], pos_action[5]] elif self.num_agent == 9: pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] pos_action5 = [] pos_action6 = [] pos_action7 = [] pos_action8 = [] pos_action9 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action6.append(pos_action[i][5]) pos_action7.append(pos_action[i][6]) pos_action8.append(pos_action[i][7]) pos_action9.append(pos_action[i][8]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) pos_action6 = torch.FloatTensor(pos_action6).to(self.device) pos_action7 = torch.FloatTensor(pos_action7).to(self.device) pos_action8 = torch.FloatTensor(pos_action8).to(self.device) pos_action9 = torch.FloatTensor(pos_action9).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9] tp_pos_action = [pos_action[0], pos_action[1],pos_action[2], pos_action[3],pos_action[4], pos_action[5], pos_action[6],pos_action[7], pos_action[8]] elif self.num_agent == 12: pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] pos_action5 = [] pos_action6 = [] pos_action7 = [] pos_action8 = [] pos_action9 = [] pos_action10 = [] pos_action11 = [] pos_action12 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action6.append(pos_action[i][5]) pos_action7.append(pos_action[i][6]) pos_action8.append(pos_action[i][7]) pos_action9.append(pos_action[i][8]) pos_action10.append(pos_action[i][9]) pos_action11.append(pos_action[i][10]) pos_action12.append(pos_action[i][11]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) pos_action6 = torch.FloatTensor(pos_action6).to(self.device) pos_action7 = torch.FloatTensor(pos_action7).to(self.device) pos_action8 = torch.FloatTensor(pos_action8).to(self.device) pos_action9 = torch.FloatTensor(pos_action9).to(self.device) pos_action10 = torch.FloatTensor(pos_action10).to(self.device) pos_action11 = torch.FloatTensor(pos_action11).to(self.device) pos_action12 = torch.FloatTensor(pos_action12).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9,pos_action10, pos_action11, pos_action12] tp_pos_action = [pos_action[0], pos_action[1],pos_action[2], pos_action[3],pos_action[4], pos_action[5], pos_action[6],pos_action[7], pos_action[8], pos_action[9],pos_action[10], pos_action[11]] elif self.num_agent == 24: pos_action1 = [] pos_action2 = [] pos_action3 = [] pos_action4 = [] pos_action5 = [] pos_action6 = [] pos_action7 = [] pos_action8 = [] pos_action9 = [] pos_action10 = [] pos_action11 = [] pos_action12 = [] pos_action13 = [] pos_action14 = [] pos_action15 = [] pos_action16 = [] pos_action17 = [] pos_action18 = [] pos_action19 = [] pos_action20 = [] pos_action21 = [] pos_action22 = [] pos_action23 = [] pos_action24 = [] for i in range(len(pos_action)): pos_action1.append(pos_action[i][0]) pos_action2.append(pos_action[i][1]) pos_action3.append(pos_action[i][2]) pos_action4.append(pos_action[i][3]) pos_action5.append(pos_action[i][4]) pos_action6.append(pos_action[i][5]) pos_action7.append(pos_action[i][6]) pos_action8.append(pos_action[i][7]) pos_action9.append(pos_action[i][8]) pos_action10.append(pos_action[i][9]) pos_action11.append(pos_action[i][10]) pos_action12.append(pos_action[i][11]) pos_action13.append(pos_action[i][12]) pos_action14.append(pos_action[i][13]) pos_action15.append(pos_action[i][14]) pos_action16.append(pos_action[i][15]) pos_action17.append(pos_action[i][16]) pos_action18.append(pos_action[i][17]) pos_action19.append(pos_action[i][18]) pos_action20.append(pos_action[i][19]) pos_action21.append(pos_action[i][20]) pos_action22.append(pos_action[i][21]) pos_action23.append(pos_action[i][22]) pos_action24.append(pos_action[i][23]) pos_action1 = torch.FloatTensor(pos_action1).to(self.device) pos_action2 = torch.FloatTensor(pos_action2).to(self.device) pos_action3 = torch.FloatTensor(pos_action3).to(self.device) pos_action4 = torch.FloatTensor(pos_action4).to(self.device) pos_action5 = torch.FloatTensor(pos_action5).to(self.device) pos_action6 = torch.FloatTensor(pos_action6).to(self.device) pos_action7 = torch.FloatTensor(pos_action7).to(self.device) pos_action8 = torch.FloatTensor(pos_action8).to(self.device) pos_action9 = torch.FloatTensor(pos_action9).to(self.device) pos_action10 = torch.FloatTensor(pos_action10).to(self.device) pos_action11 = torch.FloatTensor(pos_action11).to(self.device) pos_action12 = torch.FloatTensor(pos_action12).to(self.device) pos_action13 = torch.FloatTensor(pos_action13).to(self.device) pos_action14 = torch.FloatTensor(pos_action14).to(self.device) pos_action15 = torch.FloatTensor(pos_action15).to(self.device) pos_action16 = torch.FloatTensor(pos_action16).to(self.device) pos_action17 = torch.FloatTensor(pos_action17).to(self.device) pos_action18 = torch.FloatTensor(pos_action18).to(self.device) pos_action19 = torch.FloatTensor(pos_action19).to(self.device) pos_action20 = torch.FloatTensor(pos_action20).to(self.device) pos_action21 = torch.FloatTensor(pos_action21).to(self.device) pos_action22 = torch.FloatTensor(pos_action22).to(self.device) pos_action23 = torch.FloatTensor(pos_action23).to(self.device) pos_action24 = torch.FloatTensor(pos_action24).to(self.device) pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9,pos_action10, pos_action11, pos_action12,pos_action13, pos_action14, pos_action15, pos_action16, pos_action17, pos_action18,pos_action19, pos_action20, pos_action21,pos_action22, pos_action23, pos_action24] tp_pos_action = [pos_action[0], pos_action[1],pos_action[2], pos_action[3],pos_action[4], pos_action[5], pos_action[6],pos_action[7], pos_action[8], pos_action[9],pos_action[10], pos_action[11],pos_action[12], pos_action[13],pos_action[14], pos_action[15],pos_action[16], pos_action[17], pos_action[18],pos_action[19], pos_action[20], pos_action[21],pos_action[22], pos_action[23]] copy_action = torch.cat(tp_pos_action, -1) pos_state = torch.FloatTensor(pos_state).to(self.device) club_loss = self.club_policy.learning_loss(pos_state, copy_action) min_MI_loss_list.append(club_loss.cpu().data.numpy()) self.club_optimizer.zero_grad() club_loss.backward() self.club_optimizer.step() return np.mean(min_MI_loss_list) def train_actor_with_mine(self, replay_buffer, iterations, batch_size=64, discount=0.99, tau=0.001,max_mi_c = 0.0,min_mi_c =0.0,min_adv_c=0.0,max_adv_c =0.0): Q_loss_list = [] min_mi_list = [] max_mi_list = [] Q_grads_weight = [] MI_grads_weight = [] for it in range(iterations): o, x, y, o_, u, r, d ,ep_reward= replay_buffer.sample(batch_size) obs = torch.FloatTensor(o).to(self.device) next_obs = torch.FloatTensor(o_).to(self.device) state = torch.FloatTensor(x).to(self.device) action = torch.FloatTensor(u).to(self.device) next_state = torch.FloatTensor(y).to(self.device) done = torch.FloatTensor(1 - d).to(self.device) reward = torch.FloatTensor(r).to(self.device) #### TODO update Q next_action_list = [] for i in range(self.num_agent): next_action_list.append(self.actor_target[i](next_obs[:, i])[0]) with torch.no_grad(): target_Q = self.critic_target(next_state, torch.cat(next_action_list, 1)) if min_adv_c > 0.0 : with torch.no_grad(): MI_upper_bound = self.club_policy(state, action).detach() MI_upper_bound = MI_upper_bound.reshape(reward.shape) else : MI_upper_bound = 0.0 if max_adv_c > 0.0 : with torch.no_grad(): neg_MI, half_MI= self.mine_policy(state, action) neg_MI = neg_MI.detach() half_MI = half_MI.detach() MI_lower_bound = - neg_MI MI_lower_bound = MI_lower_bound.reshape(reward.shape) else : MI_lower_bound = 0.0 #print(reward.shape, MI_upper_bound.shape, MI_lower_bound.shape) #assert reward.shape[0] == MI_upper_bound.shape[0] == MI_lower_bound.shape[0] #assert reward.shape[1] == MI_upper_bound.shape[1] == MI_lower_bound.shape[1] target_Q = reward + (done * discount * target_Q ).detach() - min_adv_c*MI_upper_bound + max_adv_c * MI_lower_bound # Get current Q estimate current_Q = self.critic(state, action) # Compute critic loss critic_loss = F.mse_loss(current_Q, target_Q) # Optimize the critic self.critic_optimizer.zero_grad() critic_loss.backward() torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 0.5) self.critic_optimizer.step() gen_old_action = [] for i in range(self.num_agent): a, _,_ = self.actor[i](obs[:, i]) gen_old_action.append(a) pol_loss = (torch.cat(gen_old_action, 1)**2).mean() * 1e-3 actor_Q_loss = -self.critic(state, torch.cat(gen_old_action, 1)).mean() + 1e-3*pol_loss mi_sum_loss = 0.0 if min_mi_c > 0.0 : min_upper_bound= self.club_policy(state, torch.cat(gen_old_action, 1)) min_mi_loss = min_mi_c * torch.mean(min_upper_bound) min_mi_list.append(min_upper_bound.cpu().data.numpy()) else : min_mi_list.append(0.0) min_mi_loss = 0.0 if max_mi_c > 0.0: neg_max_lower_bound,_ = self.mine_policy(state, torch.cat(gen_old_action, 1)) max_mi_loss = - max_mi_c * torch.mean(neg_max_lower_bound) max_mi_list.append(-neg_max_lower_bound.cpu().data.numpy()) else : max_mi_loss = 0.0 max_mi_list.append(0.0) mi_sum_loss+= min_mi_loss - max_mi_loss Q_loss_list.append(actor_Q_loss.cpu().data.numpy()) if max_mi_c == 0 and min_mi_c == 0 : self.actor_optimizer.zero_grad() actor_Q_loss.backward() for i in range(self.num_agent): torch.nn.utils.clip_grad_norm_(self.actor[i].parameters(), 0.5) self.actor_optimizer.step() else : self.actor_optimizer.zero_grad() agent_1_fast_weights = OrderedDict(self.actor[0].named_parameters()) actor_Q_loss.backward(retain_graph = True) for name, param in agent_1_fast_weights.items(): if name == "a_layer.weight": Q_grads_weight.append(param.grad.cpu().data.numpy()) mi_sum_loss.backward() for name, param in agent_1_fast_weights.items(): if name == "a_layer.weight": MI_grads_weight.append(param.grad.cpu().data.numpy() - Q_grads_weight[0]) for i in range(self.num_agent): torch.nn.utils.clip_grad_norm_(self.actor[i].parameters(), 0.5) self.actor_optimizer.step() ### TODO replace ........... for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()): target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data) for i in range(self.num_agent): for param, target_param in zip(self.actor[i].parameters(), self.actor_target[i].parameters()): target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data) return np.mean(Q_loss_list),np.mean(min_mi_list),np.mean(max_mi_list),0.0,0.0 def train(self, replay_buffer, iterations, batch_size=64, discount=0.99, tau=0.001): Q_loss_list = [] for it in range(iterations): # Sample replay buffer o, x, y, o_, u, r, d ,_= replay_buffer.sample(batch_size) obs = torch.FloatTensor(o).to(self.device) next_obs = torch.FloatTensor(o_).to(self.device) state = torch.FloatTensor(x).to(self.device) action = torch.FloatTensor(u).to(self.device) next_state = torch.FloatTensor(y).to(self.device) done = torch.FloatTensor(1 - d).to(self.device) reward = torch.FloatTensor(r).to(self.device) # Compute the target Q value next_action_list = [] for i in range(self.num_agent): next_action_list.append(self.actor_target[i](next_obs[:, i])[0]) #next_action_list.append(self.actor_target(next_obs[:, i])[0]) target_Q = self.critic_target(next_state, torch.cat(next_action_list, 1)) target_Q = reward + (done * discount * target_Q).detach() # Get current Q estimate current_Q = self.critic(state, action) # Compute critic loss critic_loss = F.mse_loss(current_Q, target_Q) # Optimize the critic self.critic_optimizer.zero_grad() critic_loss.backward() torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 0.5) self.critic_optimizer.step() # Compute actor loss gen_action = [] for i in range(self.num_agent): # gen_action.append(self.actor(obs[:, i])[0]) # print("???",obs[:, i].shape) action , _ , _ = self.actor[i](obs[:, i]) gen_action.append(action) pol_loss = (torch.cat(gen_action, 1)**2).mean() * 1e-3 actor_loss = -self.critic(state, torch.cat(gen_action, 1)).mean() +1e-3*pol_loss Q_loss_list.append(actor_loss.cpu().data.numpy()) # Optimize the actor self.actor_optimizer.zero_grad() actor_loss.backward() for i in range(self.num_agent): torch.nn.utils.clip_grad_norm_(self.actor[i].parameters(), 0.5) # torch.nn.utils.clip_grad_norm(self.actor[1].parameters(), 0.5) self.actor_optimizer.step() # Update the frozen target models for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()): target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data) for i in range(self.num_agent): for param, target_param in zip(self.actor[i].parameters(), self.actor_target[i].parameters()): target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data) return np.mean(Q_loss_list) def save(self, filename, directory): if os.path.exists(directory) is False: os.makedirs(directory) for i in range(self.num_agent): torch.save(self.actor[i].state_dict(), '%s/%s_%s_actor.pth' % (directory, filename, str(i))) torch.save(self.critic.state_dict(), '%s/%s_critic.pth' % (directory, filename)) torch.save(self.mine_policy.state_dict(), '%s/%s_mine_policy.pth' % (directory, filename)) def load(self, filename, directory): for i in range(self.num_agent): self.actor[i].load_state_dict(torch.load('%s/%s_%s_actor.pth' % (directory, filename, str(i)))) #directory = "model/Org_Action_1_JSD_mi_0.05_100000_10_mine_MA_MINE_DDPG_HalfCheetah-v2_recon_100_0_1_0" self.critic.load_state_dict(torch.load('%s/%s_critic.pth' % (directory, filename))) self.critic_target.load_state_dict(self.critic.state_dict()) self.mine_policy.load_state_dict(torch.load('%s/%s_mine_policy.pth' % (directory, filename)))
50,748
48.51122
401
py
PMIC
PMIC-main/multiagent/envs/mujoco_multi.py
import numpy as np import gym from gym import spaces from gym.spaces import Box from multiagent.environment import MultiAgentEnv from multiagent.envs import obsk # using code from https://github.com/ikostrikov/pytorch-ddpg-naf class NormalizedActions(gym.ActionWrapper): def _action(self, action): action = (action + 1) / 2 # [-1, 1] => [0, 1] action *= (self.action_space.high - self.action_space.low) action += self.action_space.low return action def action(self, action_): return self._action(action_) def _reverse_action(self, action): action -= self.action_space.low action /= (self.action_space.high - self.action_space.low) action = action * 2 - 1 return action class MujocoMulti(MultiAgentEnv): def __init__(self, arglist): #super().__init__() self.mujoco_name = getattr(arglist, "mujoco_name", "HalfCheetah-v2") self.agent_conf = getattr(arglist, "agent_conf", "2x3") self.agent_partitions, self.mujoco_edges = obsk.get_parts_and_edges(self.mujoco_name, self.agent_conf) self.n_agents = len(self.agent_partitions) self.n_actions = max([len(l) for l in self.agent_partitions]) self.obs_add_global_pos = getattr(arglist, "obs_add_global_pos", False) self.agent_obsk = getattr(arglist, "agent_obsk", None) # if None, fully observable else k>=0 implies observe nearest k agents or joints self.agent_obsk_agents = getattr(arglist, "agent_obsk_agents", False) # observe full k nearest agents (True) or just single joints (False) if self.agent_obsk is not None: self.k_dicts = [obsk.get_joints_at_kdist(agent_id, self.agent_partitions, self.mujoco_edges, k=self.agent_obsk, kagents=False,) for agent_id in range(self.n_agents)] # load scenario from script self.episode_limit = arglist.max_episode_len self.env_version = getattr(arglist, "env_version", 2) if self.env_version == 2: self.wrapped_env = NormalizedActions(gym.make(self.mujoco_name)) else: assert False, "not implemented!" self.timelimit_env = self.wrapped_env.env self.timelimit_env._max_episode_steps = self.episode_limit self.env = self.timelimit_env.env self.timelimit_env.reset() self.obs_size = self.get_obs_size() # compatibility with maddpg self.n = self.n_agents self.action_space = [] self.observation_space = [] print("ENV ACTION SPACE: {}".format(self.env.action_space)) for i in range(self.n): self.observation_space.append(spaces.Box(low=-np.inf, high=+np.inf, shape=(self.obs_size,), dtype=np.float32)) acdimjoint = self.env.action_space.low.shape[0] acdim = acdimjoint // self.n_agents action_spaces = tuple([Box(self.env.action_space.low[ a * acdim:(a + 1) * acdim], self.env.action_space.high[ a * acdim:(a + 1) * acdim]) for a in range(self.n_agents)]) self.action_space = action_spaces pass def step(self, action_n): flat_actions = np.concatenate([action_n[i] for i in range(len(action_n) if isinstance(action_n, list) else action_n.shape[0])]) obs_n, reward_n, done_n, info_n = self.wrapped_env.step(flat_actions) self.steps += 1 info = {} info.update(info_n) # NOTE: Gym wraps the InvertedPendulum and HalfCheetah envs by default with TimeLimit env wrappers, # which means env._max_episode_steps=1000. The env will terminate at the 1000th timestep by default. # Here, the next state will always be masked out # terminated = done_n # if self.steps >= self.episode_limit and not done_n: # # Terminate if episode_limit is reached # terminated = True # info["episode_limit"] = getattr(self, "truncate_episodes", True) # by default True # else: # info["episode_limit"] = False if done_n: if self.steps < self.episode_limit: info["episode_limit"] = False # the next state will be masked out else: info["episode_limit"] = True # the next state will not be masked out return self._get_obs_all(), [reward_n]*self.n_agents, [done_n]*self.n_agents, info def reset(self): self.steps = 0 self.timelimit_env.reset() return self._get_obs_all() def _get_info(self, agent): pass def _get_obs_all(self): """ Returns all agent observations in a list """ obs_n = [] for a in range(self.n_agents): obs_n.append(self._get_obs(a)) return obs_n def _get_obs(self, agent_id): if self.agent_obsk is None: return self.env._get_obs() else: return obsk.build_obs(self.k_dicts[agent_id], self.env.sim.data.qpos, self.env.sim.data.qvel, vec_len=self.obs_size, add_global_pos=self.obs_add_global_pos) def get_state(self): """ Returns the global state info """ return self.env._get_obs() def get_obs_size(self): """ Returns the shape of the observation """ if self.agent_obsk is None: return self._get_obs(0).size else: return max([obsk.build_obs(self.k_dicts[agent_id], self.env.sim.data.qpos, self.env.sim.data.qvel, vec_len=None, add_global_pos=self.obs_add_global_pos).shape[0] for agent_id in range(self.n_agents)]) def _get_done(self, agent): pass def _get_reward(self, agent): pass def _set_action(self, action, agent, action_space, time=None): pass def _reset_render(self): pass def render(self, mode='human'): pass def _make_receptor_locations(self, agent): pass
6,894
38.176136
135
py
PMIC
PMIC-main/multiagent/envs/half_cheetah_multi.py
import numpy as np import gym from gym import spaces from gym.spaces import Box from multiagent.environment import MultiAgentEnv from multiagent.envs import obsk # using code from https://github.com/ikostrikov/pytorch-ddpg-naf class NormalizedActions(gym.ActionWrapper): def _action(self, action): action = (action + 1) / 2 # [-1, 1] => [0, 1] action *= (self.action_space.high - self.action_space.low) action += self.action_space.low return action def action(self, action_): return self._action(action_) def _reverse_action(self, action): action -= self.action_space.low action /= (self.action_space.high - self.action_space.low) action = action * 2 - 1 return action class MultiAgentHalfCheetah(MultiAgentEnv): def __init__(self, arglist): #super().__init__() self.agent_conf = getattr(arglist, "agent_conf", "2x3") self.agent_partitions, self.mujoco_edges = obsk.get_parts_and_edges("half_cheetah", self.agent_conf) self.n_agents = len(self.agent_partitions) self.n_actions = max([len(l) for l in self.agent_partitions]) self.obs_add_global_pos = getattr(arglist, "obs_add_global_pos", False) self.agent_obsk = getattr(arglist, "agent_obsk", None) # if None, fully observable else k>=0 implies observe nearest k agents or joints self.agent_obsk_agents = getattr(arglist, "agent_obsk_agents", False) # observe full k nearest agents (True) or just single joints (False) if self.agent_obsk is not None: self.k_dicts = [obsk.get_joints_at_kdist(agent_id, self.agent_partitions, self.mujoco_edges, k=self.agent_obsk, kagents=False,) for agent_id in range(self.n_agents)] # load scenario from script self.episode_limit = arglist.max_episode_len self.env_version = getattr(arglist, "env_version", 2) if self.env_version == 2: self.wrapped_env = NormalizedActions(gym.make('HalfCheetah-v2')) else: assert False, "not implemented!" self.wrapped_env = NormalizedActions(gym.make('HalfCheetah-v3')) self.timelimit_env = self.wrapped_env.env self.timelimit_env._max_episode_steps = self.episode_limit self.env = self.timelimit_env.env self.timelimit_env.reset() self.obs_size = self.get_obs_size() # compatibility with maddpg self.n = self.n_agents self.action_space = [] self.observation_space = [] print("ENV ACTION SPACE: {}".format(self.env.action_space)) for i in range(self.n): self.observation_space.append(spaces.Box(low=-np.inf, high=+np.inf, shape=(self.obs_size,), dtype=np.float32)) if self.agent_conf == "2x3": self.action_space = (Box(self.env.action_space.low[:3], self.env.action_space.high[:3]), Box(self.env.action_space.low[3:], self.env.action_space.high[3:]) ) elif self.agent_conf == "6x1": self.action_space = (Box(self.env.action_space.low[0:1], self.env.action_space.high[0:1]), Box(self.env.action_space.low[1:2], self.env.action_space.high[1:2]), Box(self.env.action_space.low[2:3], self.env.action_space.high[2:3]), Box(self.env.action_space.low[3:4], self.env.action_space.high[3:4]), Box(self.env.action_space.low[4:5], self.env.action_space.high[4:5]), Box(self.env.action_space.low[5:], self.env.action_space.high[5:]) ) else: raise Exception("Not implemented!", self.agent_conf) pass def step(self, action_n): flat_actions = np.concatenate([action_n[i] for i in range(len(action_n) if isinstance(action_n, list) else action_n.shape[0])]) obs_n, reward_n, done_n, info_n = self.wrapped_env.step(flat_actions) self.steps += 1 info = {} info.update(info_n) # NOTE: Gym wraps the InvertedPendulum and HalfCheetah envs by default with TimeLimit env wrappers, # which means env._max_episode_steps=1000. The env will terminate at the 1000th timestep by default. # Here, the next state will always be masked out # terminated = done_n # if self.steps >= self.episode_limit and not done_n: # # Terminate if episode_limit is reached # terminated = True # info["episode_limit"] = getattr(self, "truncate_episodes", True) # by default True # else: # info["episode_limit"] = False if done_n: if self.steps < self.episode_limit: info["episode_limit"] = False # the next state will be masked out else: info["episode_limit"] = True # the next state will not be masked out return self._get_obs_all(), [reward_n]*self.n_agents, [done_n]*self.n_agents, info def reset(self): self.steps = 0 self.timelimit_env.reset() return self._get_obs_all() def _get_info(self, agent): pass def _get_obs_all(self): """ Returns all agent observations in a list """ obs_n = [] for a in range(self.n_agents): obs_n.append(self._get_obs(a)) return obs_n def _get_obs(self, agent_id): if self.agent_obsk is None: return self.env._get_obs() else: return obsk.build_obs(self.k_dicts[agent_id], self.env.sim.data.qpos, self.env.sim.data.qvel, vec_len=self.obs_size, add_global_pos=self.obs_add_global_pos) def get_state(self): """ Returns the global state info """ return self.env._get_obs() def get_obs_size(self): """ Returns the shape of the observation """ if self.agent_obsk is None: return self._get_obs(0).size else: return max([obsk.build_obs(self.k_dicts[agent_id], self.env.sim.data.qpos, self.env.sim.data.qvel, vec_len=None, add_global_pos=self.obs_add_global_pos).shape[0] for agent_id in range(self.n_agents)]) def _get_done(self, agent): pass def _get_reward(self, agent): pass def _set_action(self, action, agent, action_space, time=None): pass def _reset_render(self): pass def render(self, mode='human'): pass def _make_receptor_locations(self, agent): pass
7,849
39.885417
135
py
PMIC
PMIC-main/maddpg/utils/agents.py
from torch import Tensor from torch.autograd import Variable from torch.optim import Adam from .networks import MLPNetwork from .misc import hard_update, gumbel_softmax, onehot_from_logits from .noise import OUNoise class DDPGAgent(object): """ General class for DDPG agents (policy, critic, target policy, target critic, exploration noise) """ def __init__(self, num_in_pol, num_out_pol, num_in_critic, hidden_dim=64, lr=0.01, discrete_action=True): """ Inputs: num_in_pol (int): number of dimensions for policy input num_out_pol (int): number of dimensions for policy output num_in_critic (int): number of dimensions for critic input """ print("num_in_pol ",num_in_pol) print("num_out_pol ",num_out_pol) print("hidden_dim " , hidden_dim) self.policy = MLPNetwork(num_in_pol, num_out_pol, hidden_dim=hidden_dim, constrain_out=True, discrete_action=discrete_action) self.critic = MLPNetwork(num_in_critic, 1, hidden_dim=hidden_dim, constrain_out=False) self.target_policy = MLPNetwork(num_in_pol, num_out_pol, hidden_dim=hidden_dim, constrain_out=True, discrete_action=discrete_action) self.target_critic = MLPNetwork(num_in_critic, 1, hidden_dim=hidden_dim, constrain_out=False) hard_update(self.target_policy, self.policy) hard_update(self.target_critic, self.critic) self.policy_optimizer = Adam(self.policy.parameters(), lr=lr) self.critic_optimizer = Adam(self.critic.parameters(), lr=lr) if not discrete_action: self.exploration = OUNoise(num_out_pol) else: self.exploration = 0.3 # epsilon for eps-greedy self.discrete_action = discrete_action def reset_noise(self): if not self.discrete_action: self.exploration.reset() def scale_noise(self, scale): if self.discrete_action: self.exploration = scale else: self.exploration.scale = scale def step(self, obs, explore=False): """ Take a step forward in environment for a minibatch of observations Inputs: obs (PyTorch Variable): Observations for this agent explore (boolean): Whether or not to add exploration noise Outputs: action (PyTorch Variable): Actions for this agent """ action = self.policy(obs) if self.discrete_action: if explore: action = gumbel_softmax(action, hard=True) else: action = onehot_from_logits(action) else: # continuous action if explore: action += Variable(Tensor(self.exploration.noise()), requires_grad=False) action = action.clamp(-1, 1) return action def get_params(self): return {'policy': self.policy.state_dict(), 'critic': self.critic.state_dict(), 'target_policy': self.target_policy.state_dict(), 'target_critic': self.target_critic.state_dict(), 'policy_optimizer': self.policy_optimizer.state_dict(), 'critic_optimizer': self.critic_optimizer.state_dict()} def load_params(self, params): self.policy.load_state_dict(params['policy']) self.critic.load_state_dict(params['critic']) self.target_policy.load_state_dict(params['target_policy']) self.target_critic.load_state_dict(params['target_critic']) self.policy_optimizer.load_state_dict(params['policy_optimizer']) self.critic_optimizer.load_state_dict(params['critic_optimizer'])
4,096
41.677083
77
py
PMIC
PMIC-main/maddpg/utils/misc.py
import os import torch import torch.nn.functional as F import torch.distributed as dist from torch.autograd import Variable import numpy as np # https://github.com/ikostrikov/pytorch-ddpg-naf/blob/master/ddpg.py#L11 def soft_update(target, source, tau): """ Perform DDPG soft update (move target params toward source based on weight factor tau) Inputs: target (torch.nn.Module): Net to copy parameters to source (torch.nn.Module): Net whose parameters to copy tau (float, 0 < x < 1): Weight factor for update """ for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau) # https://github.com/ikostrikov/pytorch-ddpg-naf/blob/master/ddpg.py#L15 def hard_update(target, source): """ Copy network parameters from source to target Inputs: target (torch.nn.Module): Net to copy parameters to source (torch.nn.Module): Net whose parameters to copy """ for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) # https://github.com/seba-1511/dist_tuto.pth/blob/gh-pages/train_dist.py def average_gradients(model): """ Gradient averaging. """ size = float(dist.get_world_size()) for param in model.parameters(): dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM, group=0) param.grad.data /= size # https://github.com/seba-1511/dist_tuto.pth/blob/gh-pages/train_dist.py def init_processes(rank, size, fn, backend='gloo'): """ Initialize the distributed environment. """ os.environ['MASTER_ADDR'] = '127.0.0.1' os.environ['MASTER_PORT'] = '29500' dist.init_process_group(backend, rank=rank, world_size=size) fn(rank, size) def onehot_from_logits(logits, eps=0.0): """ Given batch of logits, return one-hot sample using epsilon greedy strategy (based on given epsilon) """ # get best (according to current policy) actions in one-hot form argmax_acs = (logits == logits.max(1, keepdim=True)[0]).float() if eps == 0.0: return argmax_acs # get random actions in one-hot form rand_acs = Variable(torch.eye(logits.shape[1])[[np.random.choice( range(logits.shape[1]), size=logits.shape[0])]], requires_grad=False) # chooses between best and random actions using epsilon greedy return torch.stack([argmax_acs[i] if r > eps else rand_acs[i] for i, r in enumerate(torch.rand(logits.shape[0]))]) # modified for PyTorch from https://github.com/ericjang/gumbel-softmax/blob/master/Categorical%20VAE.ipynb def sample_gumbel(shape, eps=1e-20, tens_type=torch.FloatTensor): """Sample from Gumbel(0, 1)""" U = Variable(tens_type(*shape).uniform_(), requires_grad=False) return -torch.log(-torch.log(U + eps) + eps) # modified for PyTorch from https://github.com/ericjang/gumbel-softmax/blob/master/Categorical%20VAE.ipynb def gumbel_softmax_sample(logits, temperature): """ Draw a sample from the Gumbel-Softmax distribution""" y = logits + sample_gumbel(logits.shape, tens_type=type(logits.data)) return F.softmax(y / temperature, dim=1) # modified for PyTorch from https://github.com/ericjang/gumbel-softmax/blob/master/Categorical%20VAE.ipynb def gumbel_softmax(logits, temperature=1.0, hard=False): """Sample from the Gumbel-Softmax distribution and optionally discretize. Args: logits: [batch_size, n_class] unnormalized log-probs temperature: non-negative scalar hard: if True, take argmax, but differentiate w.r.t. soft sample y Returns: [batch_size, n_class] sample from the Gumbel-Softmax distribution. If hard=True, then the returned sample will be one-hot, otherwise it will be a probabilitiy distribution that sums to 1 across classes """ y = gumbel_softmax_sample(logits, temperature) if hard: y_hard = onehot_from_logits(y) y = (y_hard - y).detach() + y return y
4,043
42.483871
106
py
PMIC
PMIC-main/maddpg/utils/networks.py
import torch.nn as nn import torch.nn.functional as F class MLPNetwork(nn.Module): """ MLP network (can be used as value or policy) """ def __init__(self, input_dim, out_dim, hidden_dim=64, nonlin=F.relu, constrain_out=False, norm_in=True, discrete_action=True): """ Inputs: input_dim (int): Number of dimensions in input out_dim (int): Number of dimensions in output hidden_dim (int): Number of hidden dimensions nonlin (PyTorch function): Nonlinearity to apply to hidden layers """ super(MLPNetwork, self).__init__() if norm_in: # normalize inputs self.in_fn = nn.BatchNorm1d(input_dim) self.in_fn.weight.data.fill_(1) self.in_fn.bias.data.fill_(0) else: self.in_fn = lambda x: x self.fc1 = nn.Linear(input_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.fc3 = nn.Linear(hidden_dim, out_dim) self.nonlin = nonlin if constrain_out and not discrete_action: # initialize small to prevent saturation self.fc3.weight.data.uniform_(-3e-3, 3e-3) self.out_fn = F.tanh else: # logits for discrete action (will softmax later) self.out_fn = lambda x: x def forward(self, X): """ Inputs: X (PyTorch Matrix): Batch of observations Outputs: out (PyTorch Matrix): Output of network (actions, values, etc) """ h1 = self.nonlin(self.fc1(self.in_fn(X))) h2 = self.nonlin(self.fc2(h1)) out = self.out_fn(self.fc3(h2)) return out
1,700
35.978261
77
py
PMIC
PMIC-main/maddpg/utils/buffer.py
import numpy as np from torch import Tensor from torch.autograd import Variable class ReplayBuffer(object): """ Replay Buffer for multi-agent RL with parallel rollouts """ def __init__(self, max_steps, num_agents, obs_dims, ac_dims): """ Inputs: max_steps (int): Maximum number of timepoints to store in buffer num_agents (int): Number of agents in environment obs_dims (list of ints): number of obervation dimensions for each agent ac_dims (list of ints): number of action dimensions for each agent """ self.max_steps = max_steps self.num_agents = num_agents self.obs_buffs = [] self.ac_buffs = [] self.rew_buffs = [] self.next_obs_buffs = [] self.done_buffs = [] for odim, adim in zip(obs_dims, ac_dims): self.obs_buffs.append(np.zeros((max_steps, odim))) self.ac_buffs.append(np.zeros((max_steps, adim))) self.rew_buffs.append(np.zeros(max_steps)) self.next_obs_buffs.append(np.zeros((max_steps, odim))) self.done_buffs.append(np.zeros(max_steps)) self.filled_i = 0 # index of first empty location in buffer (last index when full) self.curr_i = 0 # current index to write to (ovewrite oldest data) def __len__(self): return self.filled_i def push(self, observations, actions, rewards, next_observations, dones): nentries = observations.shape[0] # handle multiple parallel environments if self.curr_i + nentries > self.max_steps: rollover = self.max_steps - self.curr_i # num of indices to roll over for agent_i in range(self.num_agents): self.obs_buffs[agent_i] = np.roll(self.obs_buffs[agent_i], rollover, axis=0) self.ac_buffs[agent_i] = np.roll(self.ac_buffs[agent_i], rollover, axis=0) self.rew_buffs[agent_i] = np.roll(self.rew_buffs[agent_i], rollover) self.next_obs_buffs[agent_i] = np.roll( self.next_obs_buffs[agent_i], rollover, axis=0) self.done_buffs[agent_i] = np.roll(self.done_buffs[agent_i], rollover) self.curr_i = 0 self.filled_i = self.max_steps for agent_i in range(self.num_agents): self.obs_buffs[agent_i][self.curr_i:self.curr_i + nentries] = np.vstack( observations[:, agent_i]) # actions are already batched by agent, so they are indexed differently self.ac_buffs[agent_i][self.curr_i:self.curr_i + nentries] = actions[agent_i] self.rew_buffs[agent_i][self.curr_i:self.curr_i + nentries] = rewards[:, agent_i] self.next_obs_buffs[agent_i][self.curr_i:self.curr_i + nentries] = np.vstack( next_observations[:, agent_i]) self.done_buffs[agent_i][self.curr_i:self.curr_i + nentries] = dones[:, agent_i] self.curr_i += nentries if self.filled_i < self.max_steps: self.filled_i += nentries if self.curr_i == self.max_steps: self.curr_i = 0 def sample(self, N, to_gpu=False, norm_rews=True): inds = np.random.choice(np.arange(self.filled_i), size=N, replace=False) if to_gpu: cast = lambda x: Variable(Tensor(x), requires_grad=False).cuda() else: cast = lambda x: Variable(Tensor(x), requires_grad=False) if norm_rews: ret_rews = [cast((self.rew_buffs[i][inds] - self.rew_buffs[i][:self.filled_i].mean()) / self.rew_buffs[i][:self.filled_i].std()) for i in range(self.num_agents)] else: ret_rews = [cast(self.rew_buffs[i][inds]) for i in range(self.num_agents)] return ([cast(self.obs_buffs[i][inds]) for i in range(self.num_agents)], [cast(self.ac_buffs[i][inds]) for i in range(self.num_agents)], ret_rews, [cast(self.next_obs_buffs[i][inds]) for i in range(self.num_agents)], [cast(self.done_buffs[i][inds]) for i in range(self.num_agents)]) def get_average_rewards(self, N): if self.filled_i == self.max_steps: inds = np.arange(self.curr_i - N, self.curr_i) # allow for negative indexing else: inds = np.arange(max(0, self.curr_i - N), self.curr_i) return [self.rew_buffs[i][inds].mean() for i in range(self.num_agents)]
4,794
48.43299
93
py
DeepVO-pytorch
DeepVO-pytorch-master/main.py
import torch from torch.utils.data import DataLoader import numpy as np import os import time import pandas as pd from params import par from model import DeepVO from data_helper import get_data_info, SortedRandomBatchSampler, ImageSequenceDataset, get_partition_data_info # Write all hyperparameters to record_path mode = 'a' if par.resume else 'w' with open(par.record_path, mode) as f: f.write('\n'+'='*50 + '\n') f.write('\n'.join("%s: %s" % item for item in vars(par).items())) f.write('\n'+'='*50 + '\n') # Prepare Data if os.path.isfile(par.train_data_info_path) and os.path.isfile(par.valid_data_info_path): print('Load data info from {}'.format(par.train_data_info_path)) train_df = pd.read_pickle(par.train_data_info_path) valid_df = pd.read_pickle(par.valid_data_info_path) else: print('Create new data info') if par.partition != None: partition = par.partition train_df, valid_df = get_partition_data_info(partition, par.train_video, par.seq_len, overlap=1, sample_times=par.sample_times, shuffle=True, sort=True) else: train_df = get_data_info(folder_list=par.train_video, seq_len_range=par.seq_len, overlap=1, sample_times=par.sample_times) valid_df = get_data_info(folder_list=par.valid_video, seq_len_range=par.seq_len, overlap=1, sample_times=par.sample_times) # save the data info train_df.to_pickle(par.train_data_info_path) valid_df.to_pickle(par.valid_data_info_path) train_sampler = SortedRandomBatchSampler(train_df, par.batch_size, drop_last=True) train_dataset = ImageSequenceDataset(train_df, par.resize_mode, (par.img_w, par.img_h), par.img_means, par.img_stds, par.minus_point_5) train_dl = DataLoader(train_dataset, batch_sampler=train_sampler, num_workers=par.n_processors, pin_memory=par.pin_mem) valid_sampler = SortedRandomBatchSampler(valid_df, par.batch_size, drop_last=True) valid_dataset = ImageSequenceDataset(valid_df, par.resize_mode, (par.img_w, par.img_h), par.img_means, par.img_stds, par.minus_point_5) valid_dl = DataLoader(valid_dataset, batch_sampler=valid_sampler, num_workers=par.n_processors, pin_memory=par.pin_mem) print('Number of samples in training dataset: ', len(train_df.index)) print('Number of samples in validation dataset: ', len(valid_df.index)) print('='*50) # Model M_deepvo = DeepVO(par.img_h, par.img_w, par.batch_norm) use_cuda = torch.cuda.is_available() if use_cuda: print('CUDA used.') M_deepvo = M_deepvo.cuda() # Load FlowNet weights pretrained with FlyingChairs # NOTE: the pretrained model assumes image rgb values in range [-0.5, 0.5] if par.pretrained_flownet and not par.resume: if use_cuda: pretrained_w = torch.load(par.pretrained_flownet) else: pretrained_w = torch.load(par.pretrained_flownet_flownet, map_location='cpu') print('Load FlowNet pretrained model') # Use only conv-layer-part of FlowNet as CNN for DeepVO model_dict = M_deepvo.state_dict() update_dict = {k: v for k, v in pretrained_w['state_dict'].items() if k in model_dict} model_dict.update(update_dict) M_deepvo.load_state_dict(model_dict) # Create optimizer if par.optim['opt'] == 'Adam': optimizer = torch.optim.Adam(M_deepvo.parameters(), lr=0.001, betas=(0.9, 0.999)) elif par.optim['opt'] == 'Adagrad': optimizer = torch.optim.Adagrad(M_deepvo.parameters(), lr=par.optim['lr']) elif par.optim['opt'] == 'Cosine': optimizer = torch.optim.SGD(M_deepvo.parameters(), lr=par.optim['lr']) T_iter = par.optim['T']*len(train_dl) lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_iter, eta_min=0, last_epoch=-1) # Load trained DeepVO model and optimizer if par.resume: M_deepvo.load_state_dict(torch.load(par.load_model_path)) optimizer.load_state_dict(torch.load(par.load_optimizer_path)) print('Load model from: ', par.load_model_path) print('Load optimizer from: ', par.load_optimizer_path) # Train print('Record loss in: ', par.record_path) min_loss_t = 1e10 min_loss_v = 1e10 M_deepvo.train() for ep in range(par.epochs): st_t = time.time() print('='*50) # Train M_deepvo.train() loss_mean = 0 t_loss_list = [] for _, t_x, t_y in train_dl: if use_cuda: t_x = t_x.cuda(non_blocking=par.pin_mem) t_y = t_y.cuda(non_blocking=par.pin_mem) ls = M_deepvo.step(t_x, t_y, optimizer).data.cpu().numpy() t_loss_list.append(float(ls)) loss_mean += float(ls) if par.optim == 'Cosine': lr_scheduler.step() print('Train take {:.1f} sec'.format(time.time()-st_t)) loss_mean /= len(train_dl) # Validation st_t = time.time() M_deepvo.eval() loss_mean_valid = 0 v_loss_list = [] for _, v_x, v_y in valid_dl: if use_cuda: v_x = v_x.cuda(non_blocking=par.pin_mem) v_y = v_y.cuda(non_blocking=par.pin_mem) v_ls = M_deepvo.get_loss(v_x, v_y).data.cpu().numpy() v_loss_list.append(float(v_ls)) loss_mean_valid += float(v_ls) print('Valid take {:.1f} sec'.format(time.time()-st_t)) loss_mean_valid /= len(valid_dl) f = open(par.record_path, 'a') f.write('Epoch {}\ntrain loss mean: {}, std: {:.2f}\nvalid loss mean: {}, std: {:.2f}\n'.format(ep+1, loss_mean, np.std(t_loss_list), loss_mean_valid, np.std(v_loss_list))) print('Epoch {}\ntrain loss mean: {}, std: {:.2f}\nvalid loss mean: {}, std: {:.2f}\n'.format(ep+1, loss_mean, np.std(t_loss_list), loss_mean_valid, np.std(v_loss_list))) # Save model # save if the valid loss decrease check_interval = 1 if loss_mean_valid < min_loss_v and ep % check_interval == 0: min_loss_v = loss_mean_valid print('Save model at ep {}, mean of valid loss: {}'.format(ep+1, loss_mean_valid)) # use 4.6 sec torch.save(M_deepvo.state_dict(), par.save_model_path+'.valid') torch.save(optimizer.state_dict(), par.save_optimzer_path+'.valid') # save if the training loss decrease check_interval = 1 if loss_mean < min_loss_t and ep % check_interval == 0: min_loss_t = loss_mean print('Save model at ep {}, mean of train loss: {}'.format(ep+1, loss_mean)) torch.save(M_deepvo.state_dict(), par.save_model_path+'.train') torch.save(optimizer.state_dict(), par.save_optimzer_path+'.train') f.close()
6,026
39.18
173
py
DeepVO-pytorch
DeepVO-pytorch-master/test.py
# predicted as a batch from params import par from model import DeepVO import numpy as np from PIL import Image import glob import os import time import torch from data_helper import get_data_info, ImageSequenceDataset from torch.utils.data import DataLoader from helper import eulerAnglesToRotationMatrix if __name__ == '__main__': videos_to_test = ['04', '05', '07', '10', '09'] # Path load_model_path = par.load_model_path #choose the model you want to load save_dir = 'result/' # directory to save prediction answer if not os.path.exists(save_dir): os.makedirs(save_dir) # Load model M_deepvo = DeepVO(par.img_h, par.img_w, par.batch_norm) use_cuda = torch.cuda.is_available() if use_cuda: M_deepvo = M_deepvo.cuda() M_deepvo.load_state_dict(torch.load(load_model_path)) else: M_deepvo.load_state_dict(torch.load(load_model_path, map_location={'cuda:0': 'cpu'})) print('Load model from: ', load_model_path) # Data n_workers = 1 seq_len = int((par.seq_len[0]+par.seq_len[1])/2) overlap = seq_len - 1 print('seq_len = {}, overlap = {}'.format(seq_len, overlap)) batch_size = par.batch_size fd=open('test_dump.txt', 'w') fd.write('\n'+'='*50 + '\n') for test_video in videos_to_test: df = get_data_info(folder_list=[test_video], seq_len_range=[seq_len, seq_len], overlap=overlap, sample_times=1, shuffle=False, sort=False) df = df.loc[df.seq_len == seq_len] # drop last dataset = ImageSequenceDataset(df, par.resize_mode, (par.img_w, par.img_h), par.img_means, par.img_stds, par.minus_point_5) df.to_csv('test_df.csv') dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=n_workers) gt_pose = np.load('{}{}.npy'.format(par.pose_dir, test_video)) # (n_images, 6) # Predict M_deepvo.eval() has_predict = False answer = [[0.0]*6, ] st_t = time.time() n_batch = len(dataloader) for i, batch in enumerate(dataloader): print('{} / {}'.format(i, n_batch), end='\r', flush=True) _, x, y = batch if use_cuda: x = x.cuda() y = y.cuda() batch_predict_pose = M_deepvo.forward(x) # Record answer fd.write('Batch: {}\n'.format(i)) for seq, predict_pose_seq in enumerate(batch_predict_pose): for pose_idx, pose in enumerate(predict_pose_seq): fd.write(' {} {} {}\n'.format(seq, pose_idx, pose)) batch_predict_pose = batch_predict_pose.data.cpu().numpy() if i == 0: for pose in batch_predict_pose[0]: # use all predicted pose in the first prediction for i in range(len(pose)): # Convert predicted relative pose to absolute pose by adding last pose pose[i] += answer[-1][i] answer.append(pose.tolist()) batch_predict_pose = batch_predict_pose[1:] # transform from relative to absolute for predict_pose_seq in batch_predict_pose: # predict_pose_seq[1:] = predict_pose_seq[1:] + predict_pose_seq[0:-1] ang = eulerAnglesToRotationMatrix([0, answer[-1][0], 0]) #eulerAnglesToRotationMatrix([answer[-1][1], answer[-1][0], answer[-1][2]]) location = ang.dot(predict_pose_seq[-1][3:]) predict_pose_seq[-1][3:] = location[:] # use only last predicted pose in the following prediction last_pose = predict_pose_seq[-1] for i in range(len(last_pose)): last_pose[i] += answer[-1][i] # normalize angle to -Pi...Pi over y axis last_pose[0] = (last_pose[0] + np.pi) % (2 * np.pi) - np.pi answer.append(last_pose.tolist()) print('len(answer): ', len(answer)) print('expect len: ', len(glob.glob('{}{}/*.png'.format(par.image_dir, test_video)))) print('Predict use {} sec'.format(time.time() - st_t)) # Save answer with open('{}/out_{}.txt'.format(save_dir, test_video), 'w') as f: for pose in answer: if type(pose) == list: f.write(', '.join([str(p) for p in pose])) else: f.write(str(pose)) f.write('\n') # Calculate loss gt_pose = np.load('{}{}.npy'.format(par.pose_dir, test_video)) # (n_images, 6) loss = 0 for t in range(len(gt_pose)): angle_loss = np.sum((answer[t][:3] - gt_pose[t,:3]) ** 2) translation_loss = np.sum((answer[t][3:] - gt_pose[t,3:6]) ** 2) loss = (100 * angle_loss + translation_loss) loss /= len(gt_pose) print('Loss = ', loss) print('='*50)
4,249
31.442748
140
py
DeepVO-pytorch
DeepVO-pytorch-master/Dataloader_loss.py
# %load Dataloader_loss.py # In[ ]: from params import par from model import DeepVO import cv2 import math import numpy as np import time import torch import os from torch.autograd import Variable from torch.utils.data import Dataset from torch.utils.data import DataLoader from torch.nn.modules import loss from torch import functional as F ############################################################### #Transform Rotation Matrix to Euler Angle ############################################################### # Checks if a matrix is a valid rotation matrix. def isRotationMatrix(R) : Rt = np.transpose(R) shouldBeIdentity = np.dot(Rt, R) I = np.identity(3, dtype = R.dtype) n = np.linalg.norm(I - shouldBeIdentity) return n < 1e-6 # Calculates rotation matrix to euler angles # The result is the same as MATLAB except the order # of the euler angles ( x and z are swapped ). def rotationMatrixToEulerAngles(R) : assert(isRotationMatrix(R)) sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0]) singular = sy < 1e-6 if not singular : x = math.atan2(R[2,1] , R[2,2]) y = math.atan2(-R[2,0], sy) z = math.atan2(R[1,0], R[0,0]) else : x = math.atan2(-R[1,2], R[1,1]) y = math.atan2(-R[2,0], sy) z = 0 return np.array([x, y, z]) ############################################################### #DataLoader ############################################################### #only fixed seq_len is used class KITTI_Data(Dataset): def __init__(self,folder,seq_len): #only store images address in dataloader root_train = 'KITTI/images/{}/image_03/data'.format(folder) imgs = os.listdir(root_train) self.imgs = [os.path.join(root_train,img) for img in imgs] self.imgs.sort() self.GT = readGT('KITTI/pose_GT/{}.txt'.format(folder)) self.seq_len = seq_len def __getitem__(self, index): #check index, CAUTION:the start/end of frames should be determined by GroundTruth file try: #Check the boundary, the lower boundary = frames-(seqs-1)-#StackNum self.GT[index+self.seq_len] except Exception: print("Error:Index OutofRange") filenames = [] #load path to images,read image and resemble as RGB #NumofImgs = seqs + #StackNum filenames = [self.imgs[index+i] for i in range(self.seq_len+1)] images = [np.asarray(cv2.imread(img),dtype=np.float32) for img in filenames] #resemble images as RGB images = [img[:, :, (2, 1, 0)] for img in images] #Transpose the image that channels num. as first dimension images = [np.transpose(img,(2,0,1)) for img in images] images = [torch.from_numpy(img) for img in images] #stack per 2 images images = [np.concatenate((images[k],images[k+1]),axis = 0) for k in range(len(images)-1)] #prepare ground truth poses data #Stack the images for seqs return np.stack(images,axis = 0), self.GT[index:index+par.seq_len,:] def __len__(self): return self.GT.shape[0]-1-par.seq_len-1 #read groundtruth and return np.array def readGT(root): with open(root, 'r') as posefile: #read ground truth GT = [] for one_line in posefile: one_line = one_line.split(' ') one_line = [float(pose) for pose in one_line] #r = np.empty((3,3)) #r[:] = ([one_line[0:3],one_line[4:7],one_line[8:11]]) gt = np.append(rotationMatrixToEulerAngles(np.matrix([one_line[0:3],one_line[4:7],one_line[8:11]])),np.array([one_line[3],one_line[7],one_line[11]])) GT.append(gt) return np.array(GT,dtype=np.float32) ############################################################### #Custom Loss Function ############################################################### class DeepvoLoss(loss._Loss): def __init__(self, size_average=True, reduce=True): super(DeepvoLoss, self).__init__() def forward(self, input,target): return F.mse_loss(input[0:3], target[0:3], size_average=self.size_average, reduce=self.reduce)+100 * F.mse_loss(input[3:6], target[3:6], size_average=self.size_average, reduce=self.reduce)
4,367
32.090909
196
py
DeepVO-pytorch
DeepVO-pytorch-master/model.py
import torch import torch.nn as nn from params import par from torch.autograd import Variable from torch.nn.init import kaiming_normal_, orthogonal_ import numpy as np def conv(batchNorm, in_planes, out_planes, kernel_size=3, stride=1, dropout=0): if batchNorm: return nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1)//2, bias=False), nn.BatchNorm2d(out_planes), nn.LeakyReLU(0.1, inplace=True), nn.Dropout(dropout)#, inplace=True) ) else: return nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1)//2, bias=True), nn.LeakyReLU(0.1, inplace=True), nn.Dropout(dropout)#, inplace=True) ) class DeepVO(nn.Module): def __init__(self, imsize1, imsize2, batchNorm=True): super(DeepVO,self).__init__() # CNN self.batchNorm = batchNorm self.clip = par.clip self.conv1 = conv(self.batchNorm, 6, 64, kernel_size=7, stride=2, dropout=par.conv_dropout[0]) self.conv2 = conv(self.batchNorm, 64, 128, kernel_size=5, stride=2, dropout=par.conv_dropout[1]) self.conv3 = conv(self.batchNorm, 128, 256, kernel_size=5, stride=2, dropout=par.conv_dropout[2]) self.conv3_1 = conv(self.batchNorm, 256, 256, kernel_size=3, stride=1, dropout=par.conv_dropout[3]) self.conv4 = conv(self.batchNorm, 256, 512, kernel_size=3, stride=2, dropout=par.conv_dropout[4]) self.conv4_1 = conv(self.batchNorm, 512, 512, kernel_size=3, stride=1, dropout=par.conv_dropout[5]) self.conv5 = conv(self.batchNorm, 512, 512, kernel_size=3, stride=2, dropout=par.conv_dropout[6]) self.conv5_1 = conv(self.batchNorm, 512, 512, kernel_size=3, stride=1, dropout=par.conv_dropout[7]) self.conv6 = conv(self.batchNorm, 512, 1024, kernel_size=3, stride=2, dropout=par.conv_dropout[8]) # Comput the shape based on diff image size __tmp = Variable(torch.zeros(1, 6, imsize1, imsize2)) __tmp = self.encode_image(__tmp) # RNN self.rnn = nn.LSTM( input_size=int(np.prod(__tmp.size())), hidden_size=par.rnn_hidden_size, num_layers=2, dropout=par.rnn_dropout_between, batch_first=True) self.rnn_drop_out = nn.Dropout(par.rnn_dropout_out) self.linear = nn.Linear(in_features=par.rnn_hidden_size, out_features=6) # Initilization for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d) or isinstance(m, nn.Linear): kaiming_normal_(m.weight.data) if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.LSTM): # layer 1 kaiming_normal_(m.weight_ih_l0) #orthogonal_(m.weight_ih_l0) kaiming_normal_(m.weight_hh_l0) m.bias_ih_l0.data.zero_() m.bias_hh_l0.data.zero_() # Set forget gate bias to 1 (remember) n = m.bias_hh_l0.size(0) start, end = n//4, n//2 m.bias_hh_l0.data[start:end].fill_(1.) # layer 2 kaiming_normal_(m.weight_ih_l1) #orthogonal_(m.weight_ih_l1) kaiming_normal_(m.weight_hh_l1) m.bias_ih_l1.data.zero_() m.bias_hh_l1.data.zero_() n = m.bias_hh_l1.size(0) start, end = n//4, n//2 m.bias_hh_l1.data[start:end].fill_(1.) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def forward(self, x): # x: (batch, seq_len, channel, width, height) # stack_image x = torch.cat(( x[:, :-1], x[:, 1:]), dim=2) batch_size = x.size(0) seq_len = x.size(1) # CNN x = x.view(batch_size*seq_len, x.size(2), x.size(3), x.size(4)) x = self.encode_image(x) x = x.view(batch_size, seq_len, -1) # RNN out, hc = self.rnn(x) out = self.rnn_drop_out(out) out = self.linear(out) return out def encode_image(self, x): out_conv2 = self.conv2(self.conv1(x)) out_conv3 = self.conv3_1(self.conv3(out_conv2)) out_conv4 = self.conv4_1(self.conv4(out_conv3)) out_conv5 = self.conv5_1(self.conv5(out_conv4)) out_conv6 = self.conv6(out_conv5) return out_conv6 def weight_parameters(self): return [param for name, param in self.named_parameters() if 'weight' in name] def bias_parameters(self): return [param for name, param in self.named_parameters() if 'bias' in name] def get_loss(self, x, y): predicted = self.forward(x) y = y[:, 1:, :] # (batch, seq, dim_pose) # Weighted MSE Loss angle_loss = torch.nn.functional.mse_loss(predicted[:,:,:3], y[:,:,:3]) translation_loss = torch.nn.functional.mse_loss(predicted[:,:,3:], y[:,:,3:]) loss = (100 * angle_loss + translation_loss) return loss def step(self, x, y, optimizer): optimizer.zero_grad() loss = self.get_loss(x, y) loss.backward() if self.clip != None: torch.nn.utils.clip_grad_norm(self.rnn.parameters(), self.clip) optimizer.step() return loss
5,583
40.984962
125
py
DeepVO-pytorch
DeepVO-pytorch-master/data_helper.py
import os import glob import pandas as pd import numpy as np from PIL import Image import torch from torch.utils.data import Dataset, DataLoader from torch.utils.data.sampler import Sampler from torchvision import transforms import time from params import par from helper import normalize_angle_delta def get_data_info(folder_list, seq_len_range, overlap, sample_times=1, pad_y=False, shuffle=False, sort=True): X_path, Y = [], [] X_len = [] for folder in folder_list: start_t = time.time() poses = np.load('{}{}.npy'.format(par.pose_dir, folder)) # (n_images, 6) fpaths = glob.glob('{}{}/*.png'.format(par.image_dir, folder)) fpaths.sort() # Fixed seq_len if seq_len_range[0] == seq_len_range[1]: if sample_times > 1: sample_interval = int(np.ceil(seq_len_range[0] / sample_times)) start_frames = list(range(0, seq_len_range[0], sample_interval)) print('Sample start from frame {}'.format(start_frames)) else: start_frames = [0] for st in start_frames: seq_len = seq_len_range[0] n_frames = len(fpaths) - st jump = seq_len - overlap res = n_frames % seq_len if res != 0: n_frames = n_frames - res x_segs = [fpaths[i:i+seq_len] for i in range(st, n_frames, jump)] y_segs = [poses[i:i+seq_len] for i in range(st, n_frames, jump)] Y += y_segs X_path += x_segs X_len += [len(xs) for xs in x_segs] # Random segment to sequences with diff lengths else: assert(overlap < min(seq_len_range)) n_frames = len(fpaths) min_len, max_len = seq_len_range[0], seq_len_range[1] for i in range(sample_times): start = 0 while True: n = np.random.random_integers(min_len, max_len) if start + n < n_frames: x_seg = fpaths[start:start+n] X_path.append(x_seg) if not pad_y: Y.append(poses[start:start+n]) else: pad_zero = np.zeros((max_len-n, 15)) padded = np.concatenate((poses[start:start+n], pad_zero)) Y.append(padded.tolist()) else: print('Last %d frames is not used' %(start+n-n_frames)) break start += n - overlap X_len.append(len(x_seg)) print('Folder {} finish in {} sec'.format(folder, time.time()-start_t)) # Convert to pandas dataframes data = {'seq_len': X_len, 'image_path': X_path, 'pose': Y} df = pd.DataFrame(data, columns = ['seq_len', 'image_path', 'pose']) # Shuffle through all videos if shuffle: df = df.sample(frac=1) # Sort dataframe by seq_len if sort: df = df.sort_values(by=['seq_len'], ascending=False) return df def get_partition_data_info(partition, folder_list, seq_len_range, overlap, sample_times=1, pad_y=False, shuffle=False, sort=True): X_path = [[], []] Y = [[], []] X_len = [[], []] df_list = [] for part in range(2): for folder in folder_list: start_t = time.time() poses = np.load('{}{}.npy'.format(par.pose_dir, folder)) # (n_images, 6) fpaths = glob.glob('{}{}/*.png'.format(par.image_dir, folder)) fpaths.sort() # Get the middle section as validation set n_val = int((1-partition)*len(fpaths)) st_val = int((len(fpaths)-n_val)/2) ed_val = st_val + n_val print('st_val: {}, ed_val:{}'.format(st_val, ed_val)) if part == 1: fpaths = fpaths[st_val:ed_val] poses = poses[st_val:ed_val] else: fpaths = fpaths[:st_val] + fpaths[ed_val:] poses = np.concatenate((poses[:st_val], poses[ed_val:]), axis=0) # Random Segment assert(overlap < min(seq_len_range)) n_frames = len(fpaths) min_len, max_len = seq_len_range[0], seq_len_range[1] for i in range(sample_times): start = 0 while True: n = np.random.random_integers(min_len, max_len) if start + n < n_frames: x_seg = fpaths[start:start+n] X_path[part].append(x_seg) if not pad_y: Y[part].append(poses[start:start+n]) else: pad_zero = np.zeros((max_len-n, 6)) padded = np.concatenate((poses[start:start+n], pad_zero)) Y[part].append(padded.tolist()) else: print('Last %d frames is not used' %(start+n-n_frames)) break start += n - overlap X_len[part].append(len(x_seg)) print('Folder {} finish in {} sec'.format(folder, time.time()-start_t)) # Convert to pandas dataframes data = {'seq_len': X_len[part], 'image_path': X_path[part], 'pose': Y[part]} df = pd.DataFrame(data, columns = ['seq_len', 'image_path', 'pose']) # Shuffle through all videos if shuffle: df = df.sample(frac=1) # Sort dataframe by seq_len if sort: df = df.sort_values(by=['seq_len'], ascending=False) df_list.append(df) return df_list class SortedRandomBatchSampler(Sampler): def __init__(self, info_dataframe, batch_size, drop_last=False): self.df = info_dataframe self.batch_size = batch_size self.drop_last = drop_last self.unique_seq_lens = sorted(self.df.iloc[:].seq_len.unique(), reverse=True) # Calculate len (num of batches, not num of samples) self.len = 0 for v in self.unique_seq_lens: n_sample = len(self.df.loc[self.df.seq_len == v]) n_batch = int(n_sample / self.batch_size) if not self.drop_last and n_sample % self.batch_size != 0: n_batch += 1 self.len += n_batch def __iter__(self): # Calculate number of sameples in each group (grouped by seq_len) list_batch_indexes = [] start_idx = 0 for v in self.unique_seq_lens: n_sample = len(self.df.loc[self.df.seq_len == v]) n_batch = int(n_sample / self.batch_size) if not self.drop_last and n_sample % self.batch_size != 0: n_batch += 1 rand_idxs = (start_idx + torch.randperm(n_sample)).tolist() tmp = [rand_idxs[s*self.batch_size: s*self.batch_size+self.batch_size] for s in range(0, n_batch)] list_batch_indexes += tmp start_idx += n_sample return iter(list_batch_indexes) def __len__(self): return self.len class ImageSequenceDataset(Dataset): def __init__(self, info_dataframe, resize_mode='crop', new_sizeize=None, img_mean=None, img_std=(1,1,1), minus_point_5=False): # Transforms transform_ops = [] if resize_mode == 'crop': transform_ops.append(transforms.CenterCrop((new_sizeize[0], new_sizeize[1]))) elif resize_mode == 'rescale': transform_ops.append(transforms.Resize((new_sizeize[0], new_sizeize[1]))) transform_ops.append(transforms.ToTensor()) #transform_ops.append(transforms.Normalize(mean=img_mean, std=img_std)) self.transformer = transforms.Compose(transform_ops) self.minus_point_5 = minus_point_5 self.normalizer = transforms.Normalize(mean=img_mean, std=img_std) self.data_info = info_dataframe self.seq_len_list = list(self.data_info.seq_len) self.image_arr = np.asarray(self.data_info.image_path) # image paths self.groundtruth_arr = np.asarray(self.data_info.pose) def __getitem__(self, index): raw_groundtruth = np.hsplit(self.groundtruth_arr[index], np.array([6])) groundtruth_sequence = raw_groundtruth[0] groundtruth_rotation = raw_groundtruth[1][0].reshape((3, 3)).T # opposite rotation of the first frame groundtruth_sequence = torch.FloatTensor(groundtruth_sequence) # groundtruth_sequence[1:] = groundtruth_sequence[1:] - groundtruth_sequence[0:-1] # get relative pose w.r.t. previois frame groundtruth_sequence[1:] = groundtruth_sequence[1:] - groundtruth_sequence[0] # get relative pose w.r.t. the first frame in the sequence # print('Item before transform: ' + str(index) + ' ' + str(groundtruth_sequence)) # here we rotate the sequence relative to the first frame for gt_seq in groundtruth_sequence[1:]: location = torch.FloatTensor(groundtruth_rotation.dot(gt_seq[3:].numpy())) gt_seq[3:] = location[:] # print(location) # get relative pose w.r.t. previous frame groundtruth_sequence[2:] = groundtruth_sequence[2:] - groundtruth_sequence[1:-1] # here we consider cases when rotation angles over Y axis go through PI -PI discontinuity for gt_seq in groundtruth_sequence[1:]: gt_seq[0] = normalize_angle_delta(gt_seq[0]) # print('Item after transform: ' + str(index) + ' ' + str(groundtruth_sequence)) image_path_sequence = self.image_arr[index] sequence_len = torch.tensor(self.seq_len_list[index]) #sequence_len = torch.tensor(len(image_path_sequence)) image_sequence = [] for img_path in image_path_sequence: img_as_img = Image.open(img_path) img_as_tensor = self.transformer(img_as_img) if self.minus_point_5: img_as_tensor = img_as_tensor - 0.5 # from [0, 1] -> [-0.5, 0.5] img_as_tensor = self.normalizer(img_as_tensor) img_as_tensor = img_as_tensor.unsqueeze(0) image_sequence.append(img_as_tensor) image_sequence = torch.cat(image_sequence, 0) return (sequence_len, image_sequence, groundtruth_sequence) def __len__(self): return len(self.data_info.index) # Example of usage if __name__ == '__main__': start_t = time.time() # Gernerate info dataframe overlap = 1 sample_times = 1 folder_list = ['00'] seq_len_range = [5, 7] df = get_data_info(folder_list, seq_len_range, overlap, sample_times) print('Elapsed Time (get_data_info): {} sec'.format(time.time()-start_t)) # Customized Dataset, Sampler n_workers = 4 resize_mode = 'crop' new_size = (150, 600) img_mean = (-0.14968217427134656, -0.12941663107068363, -0.1320610301921484) dataset = ImageSequenceDataset(df, resize_mode, new_size, img_mean) sorted_sampler = SortedRandomBatchSampler(df, batch_size=4, drop_last=True) dataloader = DataLoader(dataset, batch_sampler=sorted_sampler, num_workers=n_workers) print('Elapsed Time (dataloader): {} sec'.format(time.time()-start_t)) for batch in dataloader: s, x, y = batch print('='*50) print('len:{}\nx:{}\ny:{}'.format(s, x.shape, y.shape)) print('Elapsed Time: {} sec'.format(time.time()-start_t)) print('Number of workers = ', n_workers)
11,628
41.753676
145
py
DeepVO-pytorch
DeepVO-pytorch-master/preprocess.py
import os import glob import numpy as np import time from helper import R_to_angle from params import par from torchvision import transforms from PIL import Image import torch import math def clean_unused_images(): seq_frame = {'00': ['000', '004540'], '01': ['000', '001100'], '02': ['000', '004660'], '03': ['000', '000800'], '04': ['000', '000270'], '05': ['000', '002760'], '06': ['000', '001100'], '07': ['000', '001100'], '08': ['001100', '005170'], '09': ['000', '001590'], '10': ['000', '001200'] } for dir_id, img_ids in seq_frame.items(): dir_path = '{}{}/'.format(par.image_dir, dir_id) if not os.path.exists(dir_path): continue print('Cleaning {} directory'.format(dir_id)) start, end = img_ids start, end = int(start), int(end) for idx in range(0, start): img_name = '{:010d}.png'.format(idx) img_path = '{}{}/{}'.format(par.image_dir, dir_id, img_name) if os.path.isfile(img_path): os.remove(img_path) for idx in range(end+1, 10000): img_name = '{:010d}.png'.format(idx) img_path = '{}{}/{}'.format(par.image_dir, dir_id, img_name) if os.path.isfile(img_path): os.remove(img_path) # transform poseGT [R|t] to [theta_x, theta_y, theta_z, x, y, z] # save as .npy file def create_pose_data(): info = {'00': [0, 4540], '01': [0, 1100], '02': [0, 4660], '03': [0, 800], '04': [0, 270], '05': [0, 2760], '06': [0, 1100], '07': [0, 1100], '08': [1100, 5170], '09': [0, 1590], '10': [0, 1200]} start_t = time.time() for video in info.keys(): fn = '{}{}.txt'.format(par.pose_dir, video) print('Transforming {}...'.format(fn)) with open(fn) as f: lines = [line.split('\n')[0] for line in f.readlines()] poses = [ R_to_angle([float(value) for value in l.split(' ')]) for l in lines] # list of pose (pose=list of 12 floats) poses = np.array(poses) base_fn = os.path.splitext(fn)[0] np.save(base_fn+'.npy', poses) print('Video {}: shape={}'.format(video, poses.shape)) print('elapsed time = {}'.format(time.time()-start_t)) def calculate_rgb_mean_std(image_path_list, minus_point_5=False): n_images = len(image_path_list) cnt_pixels = 0 print('Numbers of frames in training dataset: {}'.format(n_images)) mean_np = [0, 0, 0] mean_tensor = [0, 0, 0] to_tensor = transforms.ToTensor() image_sequence = [] for idx, img_path in enumerate(image_path_list): print('{} / {}'.format(idx, n_images), end='\r') img_as_img = Image.open(img_path) img_as_tensor = to_tensor(img_as_img) if minus_point_5: img_as_tensor = img_as_tensor - 0.5 img_as_np = np.array(img_as_img) img_as_np = np.rollaxis(img_as_np, 2, 0) cnt_pixels += img_as_np.shape[1]*img_as_np.shape[2] for c in range(3): mean_tensor[c] += float(torch.sum(img_as_tensor[c])) mean_np[c] += float(np.sum(img_as_np[c])) mean_tensor = [v / cnt_pixels for v in mean_tensor] mean_np = [v / cnt_pixels for v in mean_np] print('mean_tensor = ', mean_tensor) print('mean_np = ', mean_np) std_tensor = [0, 0, 0] std_np = [0, 0, 0] for idx, img_path in enumerate(image_path_list): print('{} / {}'.format(idx, n_images), end='\r') img_as_img = Image.open(img_path) img_as_tensor = to_tensor(img_as_img) if minus_point_5: img_as_tensor = img_as_tensor - 0.5 img_as_np = np.array(img_as_img) img_as_np = np.rollaxis(img_as_np, 2, 0) for c in range(3): tmp = (img_as_tensor[c] - mean_tensor[c])**2 std_tensor[c] += float(torch.sum(tmp)) tmp = (img_as_np[c] - mean_np[c])**2 std_np[c] += float(np.sum(tmp)) std_tensor = [math.sqrt(v / cnt_pixels) for v in std_tensor] std_np = [math.sqrt(v / cnt_pixels) for v in std_np] print('std_tensor = ', std_tensor) print('std_np = ', std_np) if __name__ == '__main__': clean_unused_images() create_pose_data() # Calculate RGB means of images in training videos train_video = ['00', '02', '08', '09', '06', '04', '10'] image_path_list = [] for folder in train_video: image_path_list += glob.glob('KITTI/images/{}/*.png'.format(folder)) calculate_rgb_mean_std(image_path_list, minus_point_5=True)
4,086
32.77686
196
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/inference_webcam.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch, argparse from models import UNet from base import VideoInference #------------------------------------------------------------------------------ # Argument parsing #------------------------------------------------------------------------------ parser = argparse.ArgumentParser(description="Arguments for the script") parser.add_argument('--use_cuda', action='store_true', default=False, help='Use GPU acceleration') parser.add_argument('--input_size', type=int, default=320, help='Input size') parser.add_argument('--checkpoint', type=str, default="model_best.pth", help='Path to the trained model file') args = parser.parse_args() #------------------------------------------------------------------------------ # Main execution #------------------------------------------------------------------------------ # Build model model = UNet(backbone="resnet18", num_classes=2) trained_dict = torch.load(args.checkpoint, map_location="cpu")['state_dict'] model.load_state_dict(trained_dict, strict=False) if args.use_cuda: model.cuda() model.eval() # Inference inference = VideoInference( model=model, video_path=0, input_size=args.input_size, use_cuda=args.use_cuda, draw_mode='matting', ) inference.run()
1,479
31.173913
79
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/measure_model.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import os os.environ['CUDA_VISIBLE_DEVICES'] = '-1' import models import argparse from time import time import torch from torchsummary import summary #------------------------------------------------------------------------------ # Argument parsing #------------------------------------------------------------------------------ parser = argparse.ArgumentParser(description="Arguments for the script") parser.add_argument('--use_cuda', action='store_true', default=False, help='Use GPU acceleration') parser.add_argument('--input_sz', type=int, default=224, help='Size of the input') parser.add_argument('--n_measures', type=int, default=1, help='Number of time measurements') args = parser.parse_args() #------------------------------------------------------------------------------ # Create model #------------------------------------------------------------------------------ # UNet model = models.UNet( backbone="mobilenetv2", num_classes=2, ) # # DeepLabV3+ # model = DeepLabV3Plus( # backbone='resnet18', # output_stride=16, # num_classes=2, # pretrained_backbone=None, # ) # # BiSeNet # model = BiSeNet( # backbone='resnet18', # num_classes=2, # pretrained_backbone=None, # ) # # PSPNet # model = PSPNet( # backbone='resnet18', # num_classes=2, # pretrained_backbone=None, # ) # # ICNet # model = ICNet( # backbone='resnet18', # num_classes=2, # pretrained_backbone=None, # ) # #------------------------------------------------------------------------------ # # Summary network # #------------------------------------------------------------------------------ model.train() model.summary(input_shape=(3, args.input_sz, args.input_sz), device='cpu') # #------------------------------------------------------------------------------ # # Measure time # #------------------------------------------------------------------------------ # input = torch.randn([1, 3, args.input_sz, args.input_sz], dtype=torch.float) # if args.use_cuda: # model.cuda() # input = input.cuda() # for _ in range(10): # model(input) # start_time = time() # for _ in range(args.n_measures): # model(input) # finish_time = time() # if args.use_cuda: # print("Inference time on cuda: %.2f [ms]" % ((finish_time-start_time)*1000/args.n_measures)) # print("Inference fps on cuda: %.2f [fps]" % (1 / ((finish_time-start_time)/args.n_measures))) # else: # print("Inference time on cpu: %.2f [ms]" % ((finish_time-start_time)*1000/args.n_measures)) # print("Inference fps on cpu: %.2f [fps]" % (1 / ((finish_time-start_time)/args.n_measures)))
2,782
26.554455
96
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/train.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import os, json, argparse, torch, warnings warnings.filterwarnings("ignore") import models as module_arch import evaluation.losses as module_loss import evaluation.metrics as module_metric import dataloaders.dataloader as module_data from utils.logger import Logger from trainer.trainer import Trainer #------------------------------------------------------------------------------ # Get instance #------------------------------------------------------------------------------ def get_instance(module, name, config, *args): return getattr(module, config[name]['type'])(*args, **config[name]['args']) #------------------------------------------------------------------------------ # Main function #------------------------------------------------------------------------------ def main(config, resume): train_logger = Logger() # Build model architecture model = get_instance(module_arch, 'arch', config) img_sz = config["train_loader"]["args"]["resize"] model.summary(input_shape=(3, img_sz, img_sz)) # Setup data_loader instances train_loader = get_instance(module_data, 'train_loader', config).loader valid_loader = get_instance(module_data, 'valid_loader', config).loader # Get function handles of loss and metrics loss = getattr(module_loss, config['loss']) metrics = [getattr(module_metric, met) for met in config['metrics']] # Build optimizer, learning rate scheduler. trainable_params = filter(lambda p: p.requires_grad, model.parameters()) optimizer = get_instance(torch.optim, 'optimizer', config, trainable_params) lr_scheduler = get_instance(torch.optim.lr_scheduler, 'lr_scheduler', config, optimizer) # Create trainer and start training trainer = Trainer(model, loss, metrics, optimizer, resume=resume, config=config, data_loader=train_loader, valid_data_loader=valid_loader, lr_scheduler=lr_scheduler, train_logger=train_logger) trainer.train() #------------------------------------------------------------------------------ # Main execution #------------------------------------------------------------------------------ if __name__ == '__main__': # Argument parsing parser = argparse.ArgumentParser(description='Train model') parser.add_argument('-c', '--config', default=None, type=str, help='config file path (default: None)') parser.add_argument('-r', '--resume', default=None, type=str, help='path to latest checkpoint (default: None)') parser.add_argument('-d', '--device', default=None, type=str, help='indices of GPUs to enable (default: all)') args = parser.parse_args() # Load config file if args.config: config = json.load(open(args.config)) path = os.path.join(config['trainer']['save_dir'], config['name']) # Load config file from checkpoint, in case new config file is not given. # Use '--config' and '--resume' arguments together to load trained model and train more with changed config. elif args.resume: config = torch.load(args.resume)['config'] # AssertionError else: raise AssertionError("Configuration file need to be specified. Add '-c config.json', for example.") # Set visible devices if args.device: os.environ["CUDA_VISIBLE_DEVICES"]=args.device # Run the main function main(config, args.resume)
3,462
32.95098
109
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/inference_video.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import cv2, torch, argparse from time import time import numpy as np from torch.nn import functional as F from models import UNet from dataloaders import transforms from utils import utils #------------------------------------------------------------------------------ # Argument parsing #------------------------------------------------------------------------------ parser = argparse.ArgumentParser(description="Arguments for the script") parser.add_argument('--use_cuda', action='store_true', default=False, help='Use GPU acceleration') parser.add_argument('--bg', type=str, default=None, help='Path to the background image file') parser.add_argument('--watch', action='store_true', default=False, help='Indicate show result live') parser.add_argument('--input_sz', type=int, default=320, help='Input size') parser.add_argument('--checkpoint', type=str, default="/media/antiaegis/storing/FORGERY/segmentation/checkpoints/HumanSeg/UNet_MobileNetV2/model_best.pth", help='Path to the trained model file') parser.add_argument('--video', type=str, default="/media/antiaegis/storing/FORGERY/segmentation/videos/Directions.54138969.mp4", help='Path to the input video') parser.add_argument('--output', type=str, default="/media/antiaegis/storing/FORGERY/segmentation/videos/Directions.54138969.output.mp4", help='Path to the output video') args = parser.parse_args() #------------------------------------------------------------------------------ # Parameters #------------------------------------------------------------------------------ # Video input cap = cv2.VideoCapture(args.video) _, frame = cap.read() H, W = frame.shape[:2] # Video output fourcc = cv2.VideoWriter_fourcc(*'DIVX') out = cv2.VideoWriter(args.output, fourcc, 30, (W,H)) font = cv2.FONT_HERSHEY_SIMPLEX # Background if args.bg is not None: BACKGROUND = cv2.imread(args.bg)[...,::-1] BACKGROUND = cv2.resize(BACKGROUND, (W,H), interpolation=cv2.INTER_LINEAR) KERNEL_SZ = 25 SIGMA = 0 # Alpha transperency else: COLOR1 = [255, 0, 0] COLOR2 = [0, 0, 255] #------------------------------------------------------------------------------ # Create model and load weights #------------------------------------------------------------------------------ model = UNet( backbone="mobilenetv2", num_classes=2, pretrained_backbone=None ) if args.use_cuda: model = model.cuda() trained_dict = torch.load(args.checkpoint, map_location="cpu")['state_dict'] model.load_state_dict(trained_dict, strict=False) model.eval() #------------------------------------------------------------------------------ # Predict frames #------------------------------------------------------------------------------ i = 0 while(cap.isOpened()): # Read frame from camera start_time = time() _, frame = cap.read() # image = cv2.transpose(frame[...,::-1]) image = frame[...,::-1] h, w = image.shape[:2] read_cam_time = time() # Predict mask X, pad_up, pad_left, h_new, w_new = utils.preprocessing(image, expected_size=args.input_sz, pad_value=0) preproc_time = time() with torch.no_grad(): if args.use_cuda: mask = model(X.cuda()) mask = mask[..., pad_up: pad_up+h_new, pad_left: pad_left+w_new] mask = F.interpolate(mask, size=(h,w), mode='bilinear', align_corners=True) mask = F.softmax(mask, dim=1) mask = mask[0,1,...].cpu().numpy() else: mask = model(X) mask = mask[..., pad_up: pad_up+h_new, pad_left: pad_left+w_new] mask = F.interpolate(mask, size=(h,w), mode='bilinear', align_corners=True) mask = F.softmax(mask, dim=1) mask = mask[0,1,...].numpy() predict_time = time() # Draw result if args.bg is None: image_alpha = utils.draw_matting(image, mask) # image_alpha = utils.draw_transperency(image, mask, COLOR1, COLOR2) else: image_alpha = utils.draw_fore_to_back(image, mask, BACKGROUND, kernel_sz=KERNEL_SZ, sigma=SIGMA) draw_time = time() # Print runtime read = read_cam_time-start_time preproc = preproc_time-read_cam_time pred = predict_time-preproc_time draw = draw_time-predict_time total = read + preproc + pred + draw fps = 1 / total print("read: %.3f [s]; preproc: %.3f [s]; pred: %.3f [s]; draw: %.3f [s]; total: %.3f [s]; fps: %.2f [Hz]" % (read, preproc, pred, draw, total, fps)) # Wait for interupt cv2.putText(image_alpha, "%.2f [fps]" % (fps), (10, 50), font, 1.5, (0, 255, 0), 2, cv2.LINE_AA) out.write(image_alpha[..., ::-1]) if args.watch: cv2.imshow('webcam', image_alpha[..., ::-1]) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
4,860
32.993007
155
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/trainer/trainer.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import warnings warnings.filterwarnings("ignore") import torch import numpy as np from tqdm import tqdm import torch.nn.functional as F from torchvision.utils import make_grid from base.base_trainer import BaseTrainer #------------------------------------------------------------------------------ # Poly learning-rate Scheduler #------------------------------------------------------------------------------ def poly_lr_scheduler(optimizer, init_lr, curr_iter, max_iter, power=0.9): for g in optimizer.param_groups: g['lr'] = init_lr * (1 - curr_iter/max_iter)**power #------------------------------------------------------------------------------ # Class of Trainer #------------------------------------------------------------------------------ class Trainer(BaseTrainer): """ Trainer class Note: Inherited from BaseTrainer. """ def __init__(self, model, loss, metrics, optimizer, resume, config, data_loader, valid_data_loader=None, lr_scheduler=None, train_logger=None): super(Trainer, self).__init__(model, loss, metrics, optimizer, resume, config, train_logger) self.config = config self.data_loader = data_loader self.valid_data_loader = valid_data_loader self.do_validation = self.valid_data_loader is not None self.lr_scheduler = lr_scheduler self.max_iter = len(self.data_loader) * self.epochs self.init_lr = optimizer.param_groups[0]['lr'] def _eval_metrics(self, output, target): acc_metrics = np.zeros(len(self.metrics)) for i, metric in enumerate(self.metrics): acc_metrics[i] += metric(output, target) return acc_metrics def _train_epoch(self, epoch): """ Training logic for an epoch :param epoch: Current training epoch. :return: A log that contains all information you want to save. Note: If you have additional information to record, for example: > additional_log = {"x": x, "y": y} merge it with log before return. i.e. > log = {**log, **additional_log} > return log The metrics in log must have the key 'metrics'. """ print("Train on epoch...") self.model.train() self.writer_train.set_step(epoch) # Perform training total_loss = 0 total_metrics = np.zeros(len(self.metrics)) n_iter = len(self.data_loader) for batch_idx, (data, target) in tqdm(enumerate(self.data_loader), total=n_iter): curr_iter = batch_idx + (epoch-1)*n_iter data, target = data.to(self.device), target.to(self.device) self.optimizer.zero_grad() output = self.model(data) loss = self.loss(output, target) loss.backward() self.optimizer.step() total_loss += loss.item() total_metrics += self._eval_metrics(output, target) if (batch_idx==n_iter-2) and (self.verbosity>=2): self.writer_train.add_image('train/input', make_grid(data[:,:3,:,:].cpu(), nrow=4, normalize=True)) self.writer_train.add_image('train/label', make_grid(target.unsqueeze(1).cpu(), nrow=4, normalize=True)) if type(output)==tuple or type(output)==list: self.writer_train.add_image('train/output', make_grid(F.softmax(output[0], dim=1)[:,1:2,:,:].cpu(), nrow=4, normalize=True)) else: # self.writer_train.add_image('train/output', make_grid(output.cpu(), nrow=4, normalize=True)) self.writer_train.add_image('train/output', make_grid(F.softmax(output, dim=1)[:,1:2,:,:].cpu(), nrow=4, normalize=True)) poly_lr_scheduler(self.optimizer, self.init_lr, curr_iter, self.max_iter, power=0.9) # Record log total_loss /= len(self.data_loader) total_metrics /= len(self.data_loader) log = { 'train_loss': total_loss, 'train_metrics': total_metrics.tolist(), } # Write training result to TensorboardX self.writer_train.add_scalar('loss', total_loss) for i, metric in enumerate(self.metrics): self.writer_train.add_scalar('metrics/%s'%(metric.__name__), total_metrics[i]) if self.verbosity>=2: for i in range(len(self.optimizer.param_groups)): self.writer_train.add_scalar('lr/group%d'%(i), self.optimizer.param_groups[i]['lr']) # Perform validating if self.do_validation: print("Validate on epoch...") val_log = self._valid_epoch(epoch) log = {**log, **val_log} # Learning rate scheduler if self.lr_scheduler is not None: self.lr_scheduler.step() return log def _valid_epoch(self, epoch): """ Validate after training an epoch :return: A log that contains information about validation Note: The validation metrics in log must have the key 'valid_metrics'. """ self.model.eval() total_val_loss = 0 total_val_metrics = np.zeros(len(self.metrics)) n_iter = len(self.valid_data_loader) self.writer_valid.set_step(epoch) with torch.no_grad(): # Validate for batch_idx, (data, target) in tqdm(enumerate(self.valid_data_loader), total=n_iter): data, target = data.to(self.device), target.to(self.device) output = self.model(data) loss = self.loss(output, target) total_val_loss += loss.item() total_val_metrics += self._eval_metrics(output, target) if (batch_idx==n_iter-2) and(self.verbosity>=2): self.writer_valid.add_image('valid/input', make_grid(data[:,:3,:,:].cpu(), nrow=4, normalize=True)) self.writer_valid.add_image('valid/label', make_grid(target.unsqueeze(1).cpu(), nrow=4, normalize=True)) if type(output)==tuple or type(output)==list: self.writer_valid.add_image('valid/output', make_grid(F.softmax(output[0], dim=1)[:,1:2,:,:].cpu(), nrow=4, normalize=True)) else: # self.writer_valid.add_image('valid/output', make_grid(output.cpu(), nrow=4, normalize=True)) self.writer_valid.add_image('valid/output', make_grid(F.softmax(output, dim=1)[:,1:2,:,:].cpu(), nrow=4, normalize=True)) # Record log total_val_loss /= len(self.valid_data_loader) total_val_metrics /= len(self.valid_data_loader) val_log = { 'valid_loss': total_val_loss, 'valid_metrics': total_val_metrics.tolist(), } # Write validating result to TensorboardX self.writer_valid.add_scalar('loss', total_val_loss) for i, metric in enumerate(self.metrics): self.writer_valid.add_scalar('metrics/%s'%(metric.__name__), total_val_metrics[i]) return val_log
6,325
34.943182
130
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/evaluation/losses.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn.functional as F #------------------------------------------------------------------------------ # Fundamental losses #------------------------------------------------------------------------------ def dice_loss(logits, targets, smooth=1.0): """ logits: (torch.float32) shape (N, C, H, W) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ outputs = F.softmax(logits, dim=1) targets = torch.unsqueeze(targets, dim=1) targets = torch.zeros_like(logits).scatter_(dim=1, index=targets.type(torch.int64), src=torch.tensor(1.0)) inter = outputs * targets dice = 1 - ((2*inter.sum(dim=(2,3)) + smooth) / (outputs.sum(dim=(2,3))+targets.sum(dim=(2,3)) + smooth)) return dice.mean() def dice_loss_with_sigmoid(sigmoid, targets, smooth=1.0): """ sigmoid: (torch.float32) shape (N, 1, H, W) targets: (torch.float32) shape (N, H, W), value {0,1} """ outputs = torch.squeeze(sigmoid, dim=1) inter = outputs * targets dice = 1 - ((2*inter.sum(dim=(1,2)) + smooth) / (outputs.sum(dim=(1,2))+targets.sum(dim=(1,2)) + smooth)) dice = dice.mean() return dice def ce_loss(logits, targets): """ logits: (torch.float32) shape (N, C, H, W) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ targets = targets.type(torch.int64) ce_loss = F.cross_entropy(logits, targets) return ce_loss #------------------------------------------------------------------------------ # Custom loss for BiSeNet #------------------------------------------------------------------------------ def custom_bisenet_loss(logits, targets): """ logits: (torch.float32) (main_out, feat_os16_sup, feat_os32_sup) of shape (N, C, H, W) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ if type(logits)==tuple: main_loss = ce_loss(logits[0], targets) os16_loss = ce_loss(logits[1], targets) os32_loss = ce_loss(logits[2], targets) return main_loss + os16_loss + os32_loss else: return ce_loss(logits, targets) #------------------------------------------------------------------------------ # Custom loss for PSPNet #------------------------------------------------------------------------------ def custom_pspnet_loss(logits, targets, alpha=0.4): """ logits: (torch.float32) (main_out, aux_out) of shape (N, C, H, W), (N, C, H/8, W/8) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ if type(logits)==tuple: with torch.no_grad(): _targets = torch.unsqueeze(targets, dim=1) aux_targets = F.interpolate(_targets, size=logits[1].shape[-2:], mode='bilinear', align_corners=True)[:,0,...] main_loss = ce_loss(logits[0], targets) aux_loss = ce_loss(logits[1], aux_targets) return main_loss + alpha*aux_loss else: return ce_loss(logits, targets) #------------------------------------------------------------------------------ # Custom loss for ICNet #------------------------------------------------------------------------------ def custom_icnet_loss(logits, targets, alpha=[0.4, 0.16]): """ logits: (torch.float32) [train_mode] (x_124_cls, x_12_cls, x_24_cls) of shape (N, C, H/4, W/4), (N, C, H/8, W/8), (N, C, H/16, W/16) [valid_mode] x_124_cls of shape (N, C, H, W) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ if type(logits)==tuple: with torch.no_grad(): targets = torch.unsqueeze(targets, dim=1) target1 = F.interpolate(targets, size=logits[0].shape[-2:], mode='bilinear', align_corners=True)[:,0,...] target2 = F.interpolate(targets, size=logits[1].shape[-2:], mode='bilinear', align_corners=True)[:,0,...] target3 = F.interpolate(targets, size=logits[2].shape[-2:], mode='bilinear', align_corners=True)[:,0,...] loss1 = ce_loss(logits[0], target1) loss2 = ce_loss(logits[1], target2) loss3 = ce_loss(logits[2], target3) return loss1 + alpha[0]*loss2 + alpha[1]*loss3 else: return ce_loss(logits, targets)
4,073
35.702703
113
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/evaluation/metrics.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch from torch.nn import functional as F #------------------------------------------------------------------------------ # Fundamental metrics #------------------------------------------------------------------------------ def miou(logits, targets, eps=1e-6): """ logits: (torch.float32) shape (N, C, H, W) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ outputs = torch.argmax(logits, dim=1, keepdim=True).type(torch.int64) targets = torch.unsqueeze(targets, dim=1).type(torch.int64) outputs = torch.zeros_like(logits).scatter_(dim=1, index=outputs, src=torch.tensor(1.0)).type(torch.int8) targets = torch.zeros_like(logits).scatter_(dim=1, index=targets, src=torch.tensor(1.0)).type(torch.int8) inter = (outputs & targets).type(torch.float32).sum(dim=(2,3)) union = (outputs | targets).type(torch.float32).sum(dim=(2,3)) iou = inter / (union + eps) return iou.mean() def iou_with_sigmoid(sigmoid, targets, eps=1e-6): """ sigmoid: (torch.float32) shape (N, 1, H, W) targets: (torch.float32) shape (N, H, W), value {0,1} """ outputs = torch.squeeze(sigmoid, dim=1).type(torch.int8) targets = targets.type(torch.int8) inter = (outputs & targets).type(torch.float32).sum(dim=(1,2)) union = (outputs | targets).type(torch.float32).sum(dim=(1,2)) iou = inter / (union + eps) return iou.mean() #------------------------------------------------------------------------------ # Custom IoU for BiSeNet #------------------------------------------------------------------------------ def custom_bisenet_miou(logits, targets): """ logits: (torch.float32) (main_out, feat_os16_sup, feat_os32_sup) of shape (N, C, H, W) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ if type(logits)==tuple: return miou(logits[0], targets) else: return miou(logits, targets) #------------------------------------------------------------------------------ # Custom IoU for PSPNet #------------------------------------------------------------------------------ def custom_pspnet_miou(logits, targets): """ logits: (torch.float32) (main_out, aux_out) of shape (N, C, H, W), (N, C, H/8, W/8) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ if type(logits)==tuple: return miou(logits[0], targets) else: return miou(logits, targets) #------------------------------------------------------------------------------ # Custom IoU for BiSeNet #------------------------------------------------------------------------------ def custom_icnet_miou(logits, targets): """ logits: (torch.float32) [train_mode] (x_124_cls, x_12_cls, x_24_cls) of shape (N, C, H/4, W/4), (N, C, H/8, W/8), (N, C, H/16, W/16) [valid_mode] x_124_cls of shape (N, C, H, W) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ if type(logits)==tuple: targets = torch.unsqueeze(targets, dim=1) targets = F.interpolate(targets, size=logits[0].shape[-2:], mode='bilinear', align_corners=True)[:,0,...] return miou(logits[0], targets) else: return miou(logits, targets)
3,235
36.195402
107
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/ICNet.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from base.base_model import BaseModel from models.backbonds import ResNet #------------------------------------------------------------------------------ # Convolutional block #------------------------------------------------------------------------------ class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True): super(ConvBlock, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=bias) self.bn = nn.BatchNorm2d(out_channels) def forward(self, input): x = self.conv(input) x = self.bn(x) x = F.relu(x, inplace=True) return x #------------------------------------------------------------------------------ # Pyramid Pooling Module #------------------------------------------------------------------------------ class PyramidPoolingModule(nn.Module): def __init__(self, pyramids=[1,2,3,6]): super(PyramidPoolingModule, self).__init__() self.pyramids = pyramids def forward(self, input): feat = input height, width = input.shape[2:] for bin_size in self.pyramids: x = F.adaptive_avg_pool2d(input, output_size=bin_size) x = F.interpolate(x, size=(height, width), mode='bilinear', align_corners=True) feat = feat + x return feat #------------------------------------------------------------------------------ # Cascade Feature Fusion #------------------------------------------------------------------------------ class CascadeFeatFusion(nn.Module): def __init__(self, low_channels, high_channels, out_channels, num_classes): super(CascadeFeatFusion, self).__init__() self.conv_low = nn.Sequential(OrderedDict([ ('conv', nn.Conv2d(low_channels, out_channels, kernel_size=3, dilation=2, padding=2, bias=False)), ('bn', nn.BatchNorm2d(out_channels)) ])) self.conv_high = nn.Sequential(OrderedDict([ ('conv', nn.Conv2d(high_channels, out_channels, kernel_size=1, bias=False)), ('bn', nn.BatchNorm2d(out_channels)) ])) self.conv_low_cls = nn.Conv2d(out_channels, num_classes, kernel_size=1, bias=False) def forward(self, input_low, input_high): input_low = F.interpolate(input_low, size=input_high.shape[2:], mode='bilinear', align_corners=True) x_low = self.conv_low(input_low) x_high = self.conv_high(input_high) x = x_low + x_high x = F.relu(x, inplace=True) if self.training: x_low_cls = self.conv_low_cls(input_low) return x, x_low_cls else: return x #------------------------------------------------------------------------------ # ICNet #------------------------------------------------------------------------------ class ICNet(BaseModel): pyramids = [1, 2, 3, 6] backbone_os = 8 def __init__(self, backbone='resnet18', num_classes=2, pretrained_backbone=None): super(ICNet, self).__init__() if 'resnet' in backbone: if backbone=='resnet18': n_layers = 18 stage5_channels = 512 elif backbone=='resnet34': n_layers = 34 stage5_channels = 512 elif backbone=='resnet50': n_layers = 50 stage5_channels = 2048 elif backbone=='resnet101': n_layers = 101 stage5_channels = 2048 else: raise NotImplementedError # Sub1 self.conv_sub1 = nn.Sequential(OrderedDict([ ('conv1', ConvBlock(in_channels=3, out_channels=32, kernel_size=3, stride=2, padding=1, bias=False)), ('conv2', ConvBlock(in_channels=32, out_channels=32, kernel_size=3, stride=2, padding=1, bias=False)), ('conv3', ConvBlock(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1, bias=False)) ])) # Sub2 and Sub4 self.backbone = ResNet.get_resnet(n_layers, output_stride=self.backbone_os, num_classes=None) self.ppm = PyramidPoolingModule(pyramids=self.pyramids) self.conv_sub4_reduce = ConvBlock(stage5_channels, stage5_channels//4, kernel_size=1, bias=False) # Cascade Feature Fusion self.cff_24 = CascadeFeatFusion(low_channels=stage5_channels//4, high_channels=128, out_channels=128, num_classes=num_classes) self.cff_12 = CascadeFeatFusion(low_channels=128, high_channels=64, out_channels=128, num_classes=num_classes) # Classification self.conv_cls = nn.Conv2d(in_channels=128, out_channels=num_classes, kernel_size=1, bias=False) else: raise NotImplementedError self._init_weights() if pretrained_backbone is not None: self.backbone._load_pretrained_model(pretrained_backbone) def forward(self, input): # Sub1 x_sub1 = self.conv_sub1(input) # Sub2 x_sub2 = F.interpolate(input, scale_factor=0.5, mode='bilinear', align_corners=True) x_sub2 = self._run_backbone_sub2(x_sub2) # Sub4 x_sub4 = F.interpolate(x_sub2, scale_factor=0.5, mode='bilinear', align_corners=True) x_sub4 = self._run_backbone_sub4(x_sub4) x_sub4 = self.ppm(x_sub4) x_sub4 = self.conv_sub4_reduce(x_sub4) # Output if self.training: # Cascade Feature Fusion x_cff_24, x_24_cls = self.cff_24(x_sub4, x_sub2) x_cff_12, x_12_cls = self.cff_12(x_cff_24, x_sub1) # Classification x_cff_12 = F.interpolate(x_cff_12, scale_factor=2, mode='bilinear', align_corners=True) x_124_cls = self.conv_cls(x_cff_12) return x_124_cls, x_12_cls, x_24_cls else: # Cascade Feature Fusion x_cff_24 = self.cff_24(x_sub4, x_sub2) x_cff_12 = self.cff_12(x_cff_24, x_sub1) # Classification x_cff_12 = F.interpolate(x_cff_12, scale_factor=2, mode='bilinear', align_corners=True) x_124_cls = self.conv_cls(x_cff_12) x_124_cls = F.interpolate(x_124_cls, scale_factor=4, mode='bilinear', align_corners=True) return x_124_cls def _run_backbone_sub2(self, input): # Stage1 x = self.backbone.conv1(input) x = self.backbone.bn1(x) x = self.backbone.relu(x) # Stage2 x = self.backbone.maxpool(x) x = self.backbone.layer1(x) # Stage3 x = self.backbone.layer2(x) return x def _run_backbone_sub4(self, input): # Stage4 x = self.backbone.layer3(input) # Stage5 x = self.backbone.layer4(x) return x def _init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0)
6,572
32.707692
129
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/BiSeNet.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from base.base_model import BaseModel from models.backbonds import ResNet #------------------------------------------------------------------------------ # Convolutional block #------------------------------------------------------------------------------ class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True): super(ConvBlock, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=bias) self.bn = nn.BatchNorm2d(out_channels) def forward(self, input): x = self.conv(input) x = self.bn(x) x = F.relu(x, inplace=True) return x #------------------------------------------------------------------------------ # Spatial Path #------------------------------------------------------------------------------ class SpatialPath(nn.Module): def __init__(self, basic_channels=64): super(SpatialPath, self).__init__() self.conv1 = ConvBlock(in_channels=3, out_channels=basic_channels , kernel_size=3, stride=2, padding=1) self.conv2 = ConvBlock(in_channels=basic_channels, out_channels=2*basic_channels, kernel_size=3, stride=2, padding=1) self.conv3 = ConvBlock(in_channels=2*basic_channels, out_channels=4*basic_channels, kernel_size=3, stride=2, padding=1) def forward(self, input): x = self.conv1(input) x = self.conv2(x) x = self.conv3(x) return x #------------------------------------------------------------------------------ # Attention Refinement Module #------------------------------------------------------------------------------ class Attention(nn.Module): def __init__(self, in_channels): super(Attention, self).__init__() self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=1, bias=False) def forward(self, input): x = F.adaptive_avg_pool2d(input, (1,1)) x = self.conv(x) x = torch.sigmoid(x) x = torch.mul(input, x) return x #------------------------------------------------------------------------------ # Feature Fusion Module #------------------------------------------------------------------------------ class Fusion(nn.Module): def __init__(self, in_channels1, in_channels2, num_classes, kernel_size=3): super(Fusion, self).__init__() in_channels = in_channels1 + in_channels2 self.convblock = ConvBlock(in_channels, num_classes, kernel_size, padding=1) self.conv1 = nn.Conv2d(num_classes, num_classes, kernel_size=1, bias=False) self.conv2 = nn.Conv2d(num_classes, num_classes, kernel_size=1, bias=False) def forward(self, input1, input2): input = torch.cat([input1, input2], dim=1) input = self.convblock(input) x = F.adaptive_avg_pool2d(input, (1,1)) x = self.conv1(x) x = F.relu(x, inplace=True) x = self.conv2(x) x = torch.sigmoid(x) x = torch.mul(input, x) x = torch.add(input, x) return x #------------------------------------------------------------------------------ # BiSeNet #------------------------------------------------------------------------------ class BiSeNet(BaseModel): def __init__(self, backbone='resnet18', num_classes=2, pretrained_backbone=None): super(BiSeNet, self).__init__() if backbone=='resnet18': self.spatial_path = SpatialPath(basic_channels=64) self.context_path = ResNet.resnet18(num_classes=None) self.arm_os16 = Attention(in_channels=256) self.arm_os32 = Attention(in_channels=512) self.ffm = Fusion(in_channels1=256, in_channels2=768, num_classes=num_classes, kernel_size=3) self.conv_final = nn.Conv2d(in_channels=num_classes, out_channels=num_classes, kernel_size=1) self.sup_os16 = nn.Conv2d(in_channels=256, out_channels=num_classes, kernel_size=1) self.sup_os32 = nn.Conv2d(in_channels=512, out_channels=num_classes, kernel_size=1) else: raise NotImplementedError self._init_weights() if pretrained_backbone is not None: self.context_path._load_pretrained_model(pretrained_backbone) def forward(self, input): # Spatial path feat_spatial = self.spatial_path(input) # Context path feat_os32, feat_os16 = self._run_context_path(input) feat_gap = F.adaptive_avg_pool2d(feat_os32, (1,1)) feat_os16 = self.arm_os16(feat_os16) feat_os32 = self.arm_os32(feat_os32) feat_os32 = torch.mul(feat_os32, feat_gap) feat_os16 = F.interpolate(feat_os16, scale_factor=2, mode='bilinear', align_corners=True) feat_os32 = F.interpolate(feat_os32, scale_factor=4, mode='bilinear', align_corners=True) feat_context = torch.cat([feat_os16, feat_os32], dim=1) # Supervision if self.training: feat_os16_sup = self.sup_os16(feat_os16) feat_os32_sup = self.sup_os32(feat_os32) feat_os16_sup = F.interpolate(feat_os16_sup, scale_factor=8, mode='bilinear', align_corners=True) feat_os32_sup = F.interpolate(feat_os32_sup, scale_factor=8, mode='bilinear', align_corners=True) # Fusion x = self.ffm(feat_spatial, feat_context) x = F.interpolate(x, scale_factor=8, mode='bilinear', align_corners=True) x = self.conv_final(x) # Output if self.training: return x, feat_os16_sup, feat_os32_sup else: return x def _run_context_path(self, input): # Stage1 x1 = self.context_path.conv1(input) x1 = self.context_path.bn1(x1) x1 = self.context_path.relu(x1) # Stage2 x2 = self.context_path.maxpool(x1) x2 = self.context_path.layer1(x2) # Stage3 x3 = self.context_path.layer2(x2) # Stage4 x4 = self.context_path.layer3(x3) # Stage5 x5 = self.context_path.layer4(x4) # Output return x5, x4 def _init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0)
6,044
34.769231
121
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/DeepLab.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from base.base_model import BaseModel from models.backbonds import ResNet, VGG #------------------------------------------------------------------------------ # ASSP #------------------------------------------------------------------------------ class _ASPPModule(nn.Module): def __init__(self, inplanes, planes, kernel_size, padding, dilation): super(_ASPPModule, self).__init__() self.atrous_conv = nn.Conv2d(inplanes, planes, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, bias=False) self.bn = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) def forward(self, x): x = self.atrous_conv(x) x = self.bn(x) return self.relu(x) class ASPP(nn.Module): def __init__(self, output_stride, inplanes): super(ASPP, self).__init__() if output_stride == 16: dilations = [1, 6, 12, 18] elif output_stride == 8: dilations = [1, 12, 24, 36] self.aspp1 = _ASPPModule(inplanes, 256, 1, padding=0, dilation=dilations[0]) self.aspp2 = _ASPPModule(inplanes, 256, 3, padding=dilations[1], dilation=dilations[1]) self.aspp3 = _ASPPModule(inplanes, 256, 3, padding=dilations[2], dilation=dilations[2]) self.aspp4 = _ASPPModule(inplanes, 256, 3, padding=dilations[3], dilation=dilations[3]) self.global_avg_pool = nn.Sequential( nn.AdaptiveAvgPool2d((1, 1)), nn.Conv2d(inplanes, 256, 1, stride=1, bias=False), nn.BatchNorm2d(256), nn.ReLU(inplace=True), ) self.conv1 = nn.Conv2d(1280, 256, 1, bias=False) self.bn1 = nn.BatchNorm2d(256) self.relu = nn.ReLU(inplace=True) self.dropout = nn.Dropout(0.5) def forward(self, x): x1 = self.aspp1(x) x2 = self.aspp2(x) x3 = self.aspp3(x) x4 = self.aspp4(x) x5 = self.global_avg_pool(x) x5 = F.interpolate(x5, size=x4.size()[2:], mode='bilinear', align_corners=True) x = torch.cat((x1, x2, x3, x4, x5), dim=1) x = self.conv1(x) x = self.bn1(x) x = self.relu(x) return self.dropout(x) #------------------------------------------------------------------------------ # Decoder #------------------------------------------------------------------------------ class Decoder(nn.Module): def __init__(self, num_classes, low_level_inplanes): super(Decoder, self).__init__() self.conv1 = nn.Conv2d(low_level_inplanes, 48, 1, bias=False) self.bn1 = nn.BatchNorm2d(48) self.relu = nn.ReLU(inplace=True) self.last_conv = nn.Sequential( nn.Conv2d(304, 256, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(256), nn.ReLU(inplace=True), nn.Dropout(0.5), nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(256), nn.ReLU(inplace=True), nn.Dropout(0.1), nn.Conv2d(256, num_classes, kernel_size=1, stride=1), ) def forward(self, x, low_level_feat): low_level_feat = self.conv1(low_level_feat) low_level_feat = self.bn1(low_level_feat) low_level_feat = self.relu(low_level_feat) x = F.interpolate(x, size=low_level_feat.size()[2:], mode='bilinear', align_corners=True) x = torch.cat((x, low_level_feat), dim=1) x = self.last_conv(x) return x #------------------------------------------------------------------------------ # DeepLabV3Plus #------------------------------------------------------------------------------ class DeepLabV3Plus(BaseModel): def __init__(self, backbone='resnet50', output_stride=16, num_classes=2, freeze_bn=False, pretrained_backbone=None): super(DeepLabV3Plus, self).__init__() if 'resnet' in backbone: if backbone=='resnet18': num_layers = 18 inplanes = 512 low_level_inplanes = 64 elif backbone=='resnet34': num_layers = 34 inplanes = 512 low_level_inplanes = 64 elif backbone=='resnet50': num_layers = 50 inplanes = 2048 low_level_inplanes = 256 elif backbone=='resnet101': num_layers = 101 inplanes = 2048 low_level_inplanes = 256 self.backbone = ResNet.get_resnet(num_layers=num_layers, num_classes=None) self._run_backbone = self._run_backbone_resnet self.aspp = ASPP(output_stride, inplanes=inplanes) self.decoder = Decoder(num_classes, low_level_inplanes=low_level_inplanes) elif backbone=='vgg16': self.backbone = VGG.vgg16_bn(output_stride=output_stride) self.aspp = ASPP(output_stride, inplanes=512) self.decoder = Decoder(num_classes, low_level_inplanes=256) else: raise NotImplementedError self._init_weights() if pretrained_backbone is not None: self.backbone._load_pretrained_model(pretrained_backbone) if freeze_bn: self._freeze_bn() def forward(self, input): x, low_feat = self._run_backbone(input) x = self.aspp(x) x = self.decoder(x, low_feat) x = F.interpolate(x, size=input.shape[-2:], mode='bilinear', align_corners=True) return x def _run_backbone_resnet(self, input): # Stage1 x1 = self.backbone.conv1(input) x1 = self.backbone.bn1(x1) x1 = self.backbone.relu(x1) # Stage2 x2 = self.backbone.maxpool(x1) x2 = self.backbone.layer1(x2) # Stage3 x3 = self.backbone.layer2(x2) # Stage4 x4 = self.backbone.layer3(x3) # Stage5 x5 = self.backbone.layer4(x4) # Output return x5, x2 def _freeze_bn(self): for m in self.modules(): if isinstance(m, nn.BatchNorm2d): m.eval() def _init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0)
5,781
30.254054
131
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/UNet.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from functools import reduce from base import BaseModel from models.backbonds import MobileNetV2, ResNet #------------------------------------------------------------------------------ # Decoder block #------------------------------------------------------------------------------ class DecoderBlock(nn.Module): def __init__(self, in_channels, out_channels, block_unit): super(DecoderBlock, self).__init__() self.deconv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, padding=1, stride=2) self.block_unit = block_unit def forward(self, input, shortcut): x = self.deconv(input) x = torch.cat([x, shortcut], dim=1) x = self.block_unit(x) return x #------------------------------------------------------------------------------ # Class of UNet #------------------------------------------------------------------------------ class UNet(BaseModel): def __init__(self, backbone="mobilenetv2", num_classes=2, pretrained_backbone=None): super(UNet, self).__init__() if backbone=='mobilenetv2': alpha = 1.0 expansion = 6 self.backbone = MobileNetV2.MobileNetV2(alpha=alpha, expansion=expansion, num_classes=None) self._run_backbone = self._run_backbone_mobilenetv2 # Stage 1 channel1 = MobileNetV2._make_divisible(int(96*alpha), 8) block_unit = MobileNetV2.InvertedResidual(2*channel1, channel1, 1, expansion) self.decoder1 = DecoderBlock(self.backbone.last_channel, channel1, block_unit) # Stage 2 channel2 = MobileNetV2._make_divisible(int(32*alpha), 8) block_unit = MobileNetV2.InvertedResidual(2*channel2, channel2, 1, expansion) self.decoder2 = DecoderBlock(channel1, channel2, block_unit) # Stage 3 channel3 = MobileNetV2._make_divisible(int(24*alpha), 8) block_unit = MobileNetV2.InvertedResidual(2*channel3, channel3, 1, expansion) self.decoder3 = DecoderBlock(channel2, channel3, block_unit) # Stage 4 channel4 = MobileNetV2._make_divisible(int(16*alpha), 8) block_unit = MobileNetV2.InvertedResidual(2*channel4, channel4, 1, expansion) self.decoder4 = DecoderBlock(channel3, channel4, block_unit) elif 'resnet' in backbone: if backbone=='resnet18': n_layers = 18 elif backbone=='resnet34': n_layers = 34 elif backbone=='resnet50': n_layers = 50 elif backbone=='resnet101': n_layers = 101 else: raise NotImplementedError filters = 64 self.backbone = ResNet.get_resnet(n_layers, num_classes=None) self._run_backbone = self._run_backbone_resnet block = ResNet.BasicBlock if (n_layers==18 or n_layers==34) else ResNet.Bottleneck # Stage 1 last_channel = 8*filters if (n_layers==18 or n_layers==34) else 32*filters channel1 = 4*filters if (n_layers==18 or n_layers==34) else 16*filters downsample = nn.Sequential(ResNet.conv1x1(2*channel1, channel1), nn.BatchNorm2d(channel1)) block_unit = block(2*channel1, int(channel1/block.expansion), 1, downsample) self.decoder1 = DecoderBlock(last_channel, channel1, block_unit) # Stage 2 channel2 = 2*filters if (n_layers==18 or n_layers==34) else 8*filters downsample = nn.Sequential(ResNet.conv1x1(2*channel2, channel2), nn.BatchNorm2d(channel2)) block_unit = block(2*channel2, int(channel2/block.expansion), 1, downsample) self.decoder2 = DecoderBlock(channel1, channel2, block_unit) # Stage 3 channel3 = filters if (n_layers==18 or n_layers==34) else 4*filters downsample = nn.Sequential(ResNet.conv1x1(2*channel3, channel3), nn.BatchNorm2d(channel3)) block_unit = block(2*channel3, int(channel3/block.expansion), 1, downsample) self.decoder3 = DecoderBlock(channel2, channel3, block_unit) # Stage 4 channel4 = filters downsample = nn.Sequential(ResNet.conv1x1(2*channel4, channel4), nn.BatchNorm2d(channel4)) block_unit = block(2*channel4, int(channel4/block.expansion), 1, downsample) self.decoder4 = DecoderBlock(channel3, channel4, block_unit) else: raise NotImplementedError self.conv_last = nn.Sequential( nn.Conv2d(channel4, 3, kernel_size=3, padding=1), nn.Conv2d(3, num_classes, kernel_size=3, padding=1), ) # Initialize self._init_weights() if pretrained_backbone is not None: self.backbone._load_pretrained_model(pretrained_backbone) def forward(self, input): x1, x2, x3, x4, x5 = self._run_backbone(input) x = self.decoder1(x5, x4) x = self.decoder2(x, x3) x = self.decoder3(x, x2) x = self.decoder4(x, x1) x = self.conv_last(x) x = F.interpolate(x, size=input.shape[-2:], mode='bilinear', align_corners=True) return x def _run_backbone_mobilenetv2(self, input): x = input # Stage1 x = reduce(lambda x, n: self.backbone.features[n](x), list(range(0,2)), x) x1 = x # Stage2 x = reduce(lambda x, n: self.backbone.features[n](x), list(range(2,4)), x) x2 = x # Stage3 x = reduce(lambda x, n: self.backbone.features[n](x), list(range(4,7)), x) x3 = x # Stage4 x = reduce(lambda x, n: self.backbone.features[n](x), list(range(7,14)), x) x4 = x # Stage5 x5 = reduce(lambda x, n: self.backbone.features[n](x), list(range(14,19)), x) return x1, x2, x3, x4, x5 def _run_backbone_resnet(self, input): # Stage1 x1 = self.backbone.conv1(input) x1 = self.backbone.bn1(x1) x1 = self.backbone.relu(x1) # Stage2 x2 = self.backbone.maxpool(x1) x2 = self.backbone.layer1(x2) # Stage3 x3 = self.backbone.layer2(x2) # Stage4 x4 = self.backbone.layer3(x3) # Stage5 x5 = self.backbone.layer4(x4) return x1, x2, x3, x4, x5 def _init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0)
6,045
35.865854
97
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/PSPNet.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from base.base_model import BaseModel from models.backbonds import ResNet #------------------------------------------------------------------------------ # Convolutional block #------------------------------------------------------------------------------ class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True): super(ConvBlock, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=bias) self.bn = nn.BatchNorm2d(out_channels) def forward(self, input): x = self.conv(input) x = self.bn(x) x = F.relu(x, inplace=True) return x #------------------------------------------------------------------------------ # Pyramid Pooling Module #------------------------------------------------------------------------------ class PyramidPoolingModule(nn.Module): def __init__(self, in_channels, pyramids=[1,2,3,6]): super(PyramidPoolingModule, self).__init__() self.pyramids = pyramids out_channels = in_channels // len(pyramids) self.convs = nn.ModuleList() for _ in pyramids: conv = ConvBlock(in_channels, out_channels, kernel_size=1, bias=False) self.convs.append(conv) def forward(self, input): feat = [input] height, width = input.shape[2:] for i, bin_size in enumerate(self.pyramids): x = F.adaptive_avg_pool2d(input, output_size=bin_size) x = self.convs[i](x) x = F.interpolate(x, size=(height, width), mode='bilinear', align_corners=True) feat.append(x) x = torch.cat(feat, dim=1) return x #------------------------------------------------------------------------------ # PSPNet #------------------------------------------------------------------------------ class PSPNet(BaseModel): dropout = 0.1 pyramids = [1, 2, 3, 6] backbone_os = 8 def __init__(self, backbone='resnet18', num_classes=2, pretrained_backbone=None): super(PSPNet, self).__init__() if 'resnet' in backbone: if backbone=='resnet18': n_layers = 18 stage5_channels = 512 elif backbone=='resnet34': n_layers = 34 stage5_channels = 512 elif backbone=='resnet50': n_layers = 50 stage5_channels = 2048 elif backbone=='resnet101': n_layers = 101 stage5_channels = 2048 else: raise NotImplementedError self.run_backbone = self._run_backbone_resnet self.backbone = ResNet.get_resnet(n_layers, output_stride=self.backbone_os, num_classes=None) self.pyramid = PyramidPoolingModule(in_channels=stage5_channels, pyramids=self.pyramids) self.main_output = nn.Sequential(OrderedDict([ ("conv1", ConvBlock(2*stage5_channels, stage5_channels//4, kernel_size=3, padding=1, bias=False)), ("dropout", nn.Dropout2d(p=self.dropout)), ("conv2", nn.Conv2d(stage5_channels//4, num_classes, kernel_size=1, bias=False)), ])) self.aux_output = nn.Sequential(OrderedDict([ ("conv1", ConvBlock(stage5_channels//2, stage5_channels//8, kernel_size=3, padding=1, bias=False)), ("dropout", nn.Dropout2d(p=self.dropout)), ("conv2", nn.Conv2d(stage5_channels//8, num_classes, kernel_size=1, bias=False)), ])) else: raise NotImplementedError self.init_weights() if pretrained_backbone is not None: self.backbone.load_pretrained_model(pretrained_backbone) def forward(self, input): inp_shape = input.shape[2:] if self.training: feat_stage5, feat_stage4 = self.run_backbone(input) feat_pyramid = self.pyramid(feat_stage5) main_out = self.main_output(feat_pyramid) main_out = F.interpolate(main_out, size=inp_shape, mode='bilinear', align_corners=True) aux_out = self.aux_output(feat_stage4) return main_out, aux_out else: feat_stage5 = self.run_backbone(input) feat_pyramid = self.pyramid(feat_stage5) main_out = self.main_output(feat_pyramid) main_out = F.interpolate(main_out, size=inp_shape, mode='bilinear', align_corners=True) return main_out def _run_backbone_resnet(self, input): # Stage1 x1 = self.backbone.conv1(input) x1 = self.backbone.bn1(x1) x1 = self.backbone.relu(x1) # Stage2 x2 = self.backbone.maxpool(x1) x2 = self.backbone.layer1(x2) # Stage3 x3 = self.backbone.layer2(x2) # Stage4 x4 = self.backbone.layer3(x3) # Stage5 x5 = self.backbone.layer4(x4) # Output if self.training: return x5, x4 else: return x5
4,624
32.759124
106
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/UNetPlus.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from base import BaseModel from models import backbones #------------------------------------------------------------------------------ # DecoderBlock #------------------------------------------------------------------------------ class DecoderBlock(nn.Module): def __init__(self, in_channels, out_channels, block, use_deconv=True, squeeze=1, dropout=0.2): super(DecoderBlock, self).__init__() self.use_deconv = use_deconv # Deconvolution if self.use_deconv: if squeeze==1: self.upsampler = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=2, padding=1) else: hid_channels = int(in_channels/squeeze) self.upsampler = nn.Sequential(OrderedDict([ ('conv1', nn.Conv2d(in_channels, hid_channels, kernel_size=1, bias=False)), ('bn1', nn.BatchNorm2d(hid_channels)), ('relu1', nn.ReLU(inplace=True)), ('dropout1', nn.Dropout2d(p=dropout)), ('conv2', nn.ConvTranspose2d(hid_channels, hid_channels, kernel_size=4, stride=2, padding=1, bias=False)), ('bn2', nn.BatchNorm2d(hid_channels)), ('relu2', nn.ReLU(inplace=True)), ('dropout2', nn.Dropout2d(p=dropout)), ('conv3', nn.Conv2d(hid_channels, out_channels, kernel_size=1, bias=False)), ('bn3', nn.BatchNorm2d(out_channels)), ('relu3', nn.ReLU(inplace=True)), ('dropout3', nn.Dropout2d(p=dropout)), ])) else: self.upsampler = nn.Sequential(OrderedDict([ ('conv', nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)), ('bn', nn.BatchNorm2d(out_channels)), ('relu', nn.ReLU(inplace=True)), ])) # Block self.block = nn.Sequential(OrderedDict([ ('bottleneck', block(2*out_channels, out_channels)), ('dropout', nn.Dropout(p=dropout)) ])) def forward(self, x, shortcut): if not self.use_deconv: x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=True) x = self.upsampler(x) x = torch.cat([x, shortcut], dim=1) x = self.block(x) return x #------------------------------------------------------------------------------ # UNetPlus #------------------------------------------------------------------------------ class UNetPlus(BaseModel): def __init__(self, backbone='resnet18', num_classes=2, in_channels=3, use_deconv=False, squeeze=4, dropout=0.2, frozen_stages=-1, norm_eval=True, init_backbone_from_imagenet=False): # Instantiate super(UNetPlus, self).__init__() self.in_channels = in_channels # Build Backbone and Decoder if ('resnet' in backbone) or ('resnext' in backbone) or ('wide_resnet' in backbone): self.backbone = getattr(backbones, backbone)(in_chans=in_channels, frozen_stages=frozen_stages, norm_eval=norm_eval) inplanes = 64 block = backbones.ResNetBasicBlock if '18' in backbone or '34' in backbone else backbones.ResNetBottleneckBlock expansion = block.expansion self.decoder = nn.Module() self.decoder.layer1 = DecoderBlock(8*inplanes*expansion, 4*inplanes*expansion, block, squeeze=squeeze, dropout=dropout, use_deconv=use_deconv) self.decoder.layer2 = DecoderBlock(4*inplanes*expansion, 2*inplanes*expansion, block, squeeze=squeeze, dropout=dropout, use_deconv=use_deconv) self.decoder.layer3 = DecoderBlock(2*inplanes*expansion, inplanes*expansion, block, squeeze=squeeze, dropout=dropout, use_deconv=use_deconv) self.decoder.layer4 = DecoderBlock(inplanes*expansion, inplanes, block, squeeze=squeeze, dropout=dropout, use_deconv=use_deconv) out_channels = inplanes elif 'efficientnet' in backbone: self.backbone = getattr(backbones, backbone)(in_chans=in_channels, frozen_stages=frozen_stages, norm_eval=norm_eval) block = backbones.EfficientNetBlock num_channels = self.backbone.stage_features[self.backbone.model_name] self.decoder = nn.Module() self.decoder.layer1 = DecoderBlock(num_channels[4], num_channels[3], block, squeeze=squeeze, dropout=dropout, use_deconv=use_deconv) self.decoder.layer2 = DecoderBlock(num_channels[3], num_channels[2], block, squeeze=squeeze, dropout=dropout, use_deconv=use_deconv) self.decoder.layer3 = DecoderBlock(num_channels[2], num_channels[1], block, squeeze=squeeze, dropout=dropout, use_deconv=use_deconv) self.decoder.layer4 = DecoderBlock(num_channels[1], num_channels[0], block, squeeze=squeeze, dropout=dropout, use_deconv=use_deconv) out_channels = num_channels[0] else: raise NotImplementedError # Build Head self.mask = nn.Sequential(OrderedDict([ ('conv1', nn.Conv2d(out_channels, 32, kernel_size=3, padding=1, bias=False)), ('bn1', nn.BatchNorm2d(num_features=32)), ('relu1', nn.ReLU(inplace=True)), ('dropout1', nn.Dropout2d(p=dropout)), ('conv2', nn.Conv2d(32, 16, kernel_size=3, padding=1, bias=False)), ('bn2', nn.BatchNorm2d(num_features=16)), ('relu2', nn.ReLU(inplace=True)), ('dropout2', nn.Dropout2d(p=dropout)), ('conv3', nn.Conv2d(16, num_classes, kernel_size=3, padding=1)), ])) # Initialize weights self.init_weights() if init_backbone_from_imagenet: self.backbone.init_from_imagenet(archname=backbone) def forward(self, images, **kargs): # Encoder x1, x2, x3, x4, x5 = self.backbone(images) # Decoder y = self.decoder.layer1(x5, x4) y = self.decoder.layer2(y, x3) y = self.decoder.layer3(y, x2) y = self.decoder.layer4(y, x1) y = F.interpolate(y, scale_factor=2, mode='bilinear', align_corners=True) # Output return self.mask(y)
5,685
40.202899
145
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/backbonds/ResNet.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn as nn from base import BaseBackbone #------------------------------------------------------------------------------ # Util functions #------------------------------------------------------------------------------ def conv3x3(in_planes, out_planes, stride=1, dilation=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False) def conv1x1(in_planes, out_planes, stride=1): return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) #------------------------------------------------------------------------------ # Class of Basic block #------------------------------------------------------------------------------ class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride, dilation=dilation) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes, dilation=dilation) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out #------------------------------------------------------------------------------ # Class of Residual bottleneck #------------------------------------------------------------------------------ class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck, self).__init__() self.conv1 = conv1x1(inplanes, planes) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes, stride, dilation=dilation) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = conv1x1(planes, planes * self.expansion) self.bn3 = nn.BatchNorm2d(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out #------------------------------------------------------------------------------ # Class of ResNet #------------------------------------------------------------------------------ class ResNet(BaseBackbone): basic_inplanes = 64 def __init__(self, block, layers, output_stride=32, num_classes=1000): super(ResNet, self).__init__() self.inplanes = self.basic_inplanes self.output_stride = output_stride self.num_classes = num_classes if output_stride==8: strides = [1, 2, 1, 1] dilations = [1, 1, 2, 4] elif output_stride==16: strides = [1, 2, 2, 1] dilations = [1, 1, 1, 2] elif output_stride==32: strides = [1, 2, 2, 2] dilations = [1, 1, 1, 1] else: raise NotImplementedError self.conv1 = nn.Conv2d(3, self.basic_inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(self.basic_inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2) self.layer1 = self._make_layer(block, 1*self.basic_inplanes, num_layers=layers[0], stride=strides[0], dilation=dilations[0]) self.layer2 = self._make_layer(block, 2*self.basic_inplanes, num_layers=layers[1], stride=strides[1], dilation=dilations[1]) self.layer3 = self._make_layer(block, 4*self.basic_inplanes, num_layers=layers[2], stride=strides[2], dilation=dilations[2]) self.layer4 = self._make_layer(block, 8*self.basic_inplanes, num_layers=layers[3], stride=strides[3], dilation=dilations[3]) if self.num_classes is not None: self.fc = nn.Linear(8*self.basic_inplanes * block.expansion, num_classes) self.init_weights() def forward(self, x): # Stage1 x = self.conv1(x) x = self.bn1(x) x = self.relu(x) # Stage2 x = self.maxpool(x) x = self.layer1(x) # Stage3 x = self.layer2(x) # Stage4 x = self.layer3(x) # Stage5 x = self.layer4(x) # Classification if self.num_classes is not None: x = x.mean(dim=(2,3)) x = self.fc(x) # Output return x def _make_layer(self, block, planes, num_layers, stride=1, dilation=1, grids=None): # Downsampler downsample = None if (stride != 1) or (self.inplanes != planes * block.expansion): downsample = nn.Sequential( conv1x1(self.inplanes, planes * block.expansion, stride), nn.BatchNorm2d(planes * block.expansion)) # Multi-grids if dilation!=1: dilations = [dilation*(2**layer_idx) for layer_idx in range(num_layers)] else: dilations = num_layers*[dilation] # Construct layers layers = [] layers.append(block(self.inplanes, planes, stride, downsample, dilations[0])) self.inplanes = planes * block.expansion for i in range(1, num_layers): layers.append(block(self.inplanes, planes, dilation=dilations[i])) return nn.Sequential(*layers) #------------------------------------------------------------------------------ # Instances of ResNet #------------------------------------------------------------------------------ def resnet18(pretrained=None, **kwargs): model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained is not None: model._load_pretrained_model(pretrained) return model def resnet34(pretrained=None, **kwargs): model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained is not None: model._load_pretrained_model(pretrained) return model def resnet50(pretrained=None, **kwargs): model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained is not None: model._load_pretrained_model(pretrained) return model def resnet101(pretrained=None, **kwargs): model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained is not None: model._load_pretrained_model(pretrained) return model def resnet152(pretrained=None, **kwargs): model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained is not None: model._load_pretrained_model(pretrained) return model def get_resnet(num_layers, **kwargs): if num_layers==18: return resnet18(**kwargs) elif num_layers==34: return resnet34(**kwargs) elif num_layers==50: return resnet50(**kwargs) elif num_layers==101: return resnet101(**kwargs) elif num_layers==152: return resnet152(**kwargs) else: raise NotImplementedError
6,894
28.216102
126
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/backbonds/Xception.py
""" Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Keras implementation. Achieves the following performance on the validation set: Loss:0.9173 Prec@1:78.892 Prec@5:94.292 REMEMBER to set your image size to 3x299x299 for both test and validation normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299 """ #------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch, math import torch.nn as nn from torch.nn import init import torch.nn.functional as F import torch.utils.model_zoo as model_zoo model_urls = { 'xception':'https://www.dropbox.com/s/1hplpzet9d7dv29/xception-c0a72b38.pth.tar?dl=1' } #------------------------------------------------------------------------------ # Depthwise Separable Convolution #------------------------------------------------------------------------------ class DWSConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=False): super(DWSConv2d, self).__init__() self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride, padding, dilation, groups=in_channels, bias=bias) self.pointwise = nn.Conv2d(in_channels, out_channels, 1, 1, 0, 1, 1, bias=bias) def forward(self,x): x = self.conv1(x) x = self.pointwise(x) return x #------------------------------------------------------------------------------ # Xception block #------------------------------------------------------------------------------ class Block(nn.Module): def __init__(self, in_filters, out_filters, reps, strides=1, start_with_relu=True, grow_first=True): super(Block, self).__init__() if out_filters != in_filters or strides!=1: self.skip = nn.Conv2d(in_filters,out_filters,1,stride=strides, bias=False) self.skipbn = nn.BatchNorm2d(out_filters) else: self.skip=None self.relu = nn.ReLU(inplace=True) rep=[] filters=in_filters if grow_first: rep.append(self.relu) rep.append(DWSConv2d(in_filters,out_filters,3,stride=1,padding=1,bias=False)) rep.append(nn.BatchNorm2d(out_filters)) filters = out_filters for i in range(reps-1): rep.append(self.relu) rep.append(DWSConv2d(filters,filters,3,stride=1,padding=1,bias=False)) rep.append(nn.BatchNorm2d(filters)) if not grow_first: rep.append(self.relu) rep.append(DWSConv2d(in_filters,out_filters,3,stride=1,padding=1,bias=False)) rep.append(nn.BatchNorm2d(out_filters)) if not start_with_relu: rep = rep[1:] else: rep[0] = nn.ReLU(inplace=False) if strides != 1: rep.append(nn.MaxPool2d(3,strides,1)) self.rep = nn.Sequential(*rep) def forward(self,inp): x = self.rep(inp) if self.skip is not None: skip = self.skip(inp) skip = self.skipbn(skip) else: skip = inp x+=skip return x #------------------------------------------------------------------------------ # Xception #------------------------------------------------------------------------------ class Xception(nn.Module): def __init__(self, num_classes=1000): super(Xception, self).__init__() self.num_classes = num_classes self.conv1 = nn.Conv2d(3, 32, 3,2, 0, bias=False) self.bn1 = nn.BatchNorm2d(32) self.relu = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(32,64,3,bias=False) self.bn2 = nn.BatchNorm2d(64) #do relu here self.block1=Block(64,128,2,2,start_with_relu=False,grow_first=True) self.block2=Block(128,256,2,2,start_with_relu=True,grow_first=True) self.block3=Block(256,728,2,2,start_with_relu=True,grow_first=True) self.block4=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block5=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block6=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block7=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block8=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block9=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block10=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block11=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block12=Block(728,1024,2,2,start_with_relu=True,grow_first=False) self.conv3 = DWSConv2d(1024,1536,3,1,1) self.bn3 = nn.BatchNorm2d(1536) #do relu here self.conv4 = DWSConv2d(1536,2048,3,1,1) self.bn4 = nn.BatchNorm2d(2048) self.fc = nn.Linear(2048, num_classes) # Init weights for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.conv2(x) x = self.bn2(x) x = self.relu(x) x = self.block1(x) x = self.block2(x) x = self.block3(x) x = self.block4(x) x = self.block5(x) x = self.block6(x) x = self.block7(x) x = self.block8(x) x = self.block9(x) x = self.block10(x) x = self.block11(x) x = self.block12(x) x = self.conv3(x) x = self.bn3(x) x = self.relu(x) x = self.conv4(x) x = self.bn4(x) x = self.relu(x) x = F.adaptive_avg_pool2d(x, (1, 1)) x = x.view(x.size(0), -1) x = self.fc(x) return x #------------------------------------------------------------------------------ # Instance #------------------------------------------------------------------------------ def xception(pretrained=False,**kwargs): model = Xception(**kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['xception'])) return model
6,776
32.885
127
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/backbonds/VGG.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn as nn #------------------------------------------------------------------------------ # Class of VGG #------------------------------------------------------------------------------ class VGG(nn.Module): def __init__(self, blocks, input_sz=224, num_classes=1000, output_stride=32): super(VGG, self).__init__() self.output_stride = output_stride if output_stride==8: strides = [2, 2, 2, 1, 1] dilations = [1, 1, 1, 2, 4] elif output_stride==16: strides = [2, 2, 2, 2, 1] dilations = [1, 1, 1, 1, 2] elif output_stride==32: strides = [2, 2, 2, 2, 2] dilations = [1, 1, 1, 1, 1] else: raise NotImplementedError self.layer1 = self._build_block(in_channels=3, block=blocks[0], dilation=dilations[0]) self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2) if strides[0]==2 else nn.Sequential() self.layer2 = self._build_block(in_channels=blocks[0][-1], block=blocks[1], dilation=dilations[1]) self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2) if strides[1]==2 else nn.Sequential() self.layer3 = self._build_block(in_channels=blocks[1][-1], block=blocks[2], dilation=dilations[2]) self.maxpool3 = nn.MaxPool2d(kernel_size=2, stride=2) if strides[2]==2 else nn.Sequential() self.layer4 = self._build_block(in_channels=blocks[2][-1], block=blocks[3], dilation=dilations[3]) self.maxpool4 = nn.MaxPool2d(kernel_size=2, stride=2) if strides[3]==2 else nn.Sequential() self.layer5 = self._build_block(in_channels=blocks[3][-1], block=blocks[4], dilation=dilations[4]) self.maxpool5 = nn.MaxPool2d(kernel_size=2, stride=2) if strides[4]==2 else nn.Sequential() if output_stride==32: linear_out_channels = 512 * int(input_sz/32)**2 self.classifier = nn.Sequential( nn.Linear(linear_out_channels, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, num_classes), ) self._init_weights() def forward(self, x, feature_names=None): low_features = {} x = self.layer1(x) x = self.maxpool1(x) x = self.layer2(x) x = self.maxpool2(x) x = self.layer3(x) low_features['layer3'] = x x = self.maxpool3(x) x = self.layer4(x) x = self.maxpool4(x) x = self.layer5(x) x = self.maxpool5(x) if self.output_stride==32: x = x.view(x.size(0), -1) x = self.classifier(x) if feature_names is not None: if type(feature_names)==str: return x, low_features[feature_names] elif type(feature_names)==list: return tuple([x] + [low_features[name] for name in feature_names]) else: return x def _build_block(self, in_channels, block, dilation): layers = [] for layer_idx, out_channels in enumerate(block): if dilation!=1: grid = 2**layer_idx dilation *= grid conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=dilation, dilation=dilation) layers += [conv2d, nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True)] in_channels = out_channels return nn.Sequential(*layers) def _load_pretrained_model(self, pretrained_file): pretrain_dict = torch.load(pretrained_file, map_location='cpu') model_dict = {} state_dict = self.state_dict() print("[VGG] Loading pretrained model...") for k, v in pretrain_dict.items(): if k in state_dict: model_dict[k] = v else: print(k, "is ignored") state_dict.update(model_dict) self.load_state_dict(state_dict) def _init_weights(self): 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.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01) m.bias.data.zero_() #------------------------------------------------------------------------------ # Instances of VGG #------------------------------------------------------------------------------ blocks = { 'A': [1*[64], 1*[128], 2*[256], 2*[512], 2*[512]], 'B': [2*[64], 2*[128], 2*[256], 2*[512], 2*[512]], 'D': [2*[64], 2*[128], 3*[256], 3*[512], 3*[512]], 'E': [2*[64], 2*[128], 4*[256], 4*[512], 4*[512]], } def vgg11_bn(pretrained=None, **kwargs): model = VGG(blocks['A'], **kwargs) if pretrained: model._load_pretrained_model(pretrained) return model def vgg13_bn(pretrained=None, **kwargs): model = VGG(blocks['B'], **kwargs) if pretrained: model._load_pretrained_model(pretrained) return model def vgg16_bn(pretrained=None, **kwargs): model = VGG(blocks['D'], **kwargs) if pretrained: model._load_pretrained_model(pretrained) return model def vgg19_bn(pretrained=None, **kwargs): model = VGG(blocks['E'], **kwargs) if pretrained: model._load_pretrained_model(pretrained) return model def get_vgg(n_layers, **kwargs): if n_layers==11: return vgg11_bn(**kwargs) elif n_layers==13: return vgg13_bn(**kwargs) elif n_layers==16: return vgg16_bn(**kwargs) elif n_layers==19: return vgg19_bn(**kwargs) else: raise NotImplementedError
5,231
29.596491
100
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/backbonds/MobileNetV2.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import math, torch, json import torch.nn as nn from functools import reduce #------------------------------------------------------------------------------ # Useful functions #------------------------------------------------------------------------------ def _make_divisible(v, divisor, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v def conv_bn(inp, oup, stride): return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.ReLU6(inplace=True) ) def conv_1x1_bn(inp, oup): return nn.Sequential( nn.Conv2d(inp, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), nn.ReLU6(inplace=True) ) #------------------------------------------------------------------------------ # Class of Inverted Residual block #------------------------------------------------------------------------------ class InvertedResidual(nn.Module): def __init__(self, inp, oup, stride, expansion, dilation=1): super(InvertedResidual, self).__init__() self.stride = stride assert stride in [1, 2] hidden_dim = round(inp * expansion) self.use_res_connect = self.stride == 1 and inp == oup if expansion == 1: self.conv = nn.Sequential( # dw nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, dilation=dilation, bias=False), nn.BatchNorm2d(hidden_dim), nn.ReLU6(inplace=True), # pw-linear nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), ) else: self.conv = nn.Sequential( # pw nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False), nn.BatchNorm2d(hidden_dim), nn.ReLU6(inplace=True), # dw nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, dilation=dilation, bias=False), nn.BatchNorm2d(hidden_dim), nn.ReLU6(inplace=True), # pw-linear nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), ) def forward(self, x): if self.use_res_connect: return x + self.conv(x) else: return self.conv(x) #------------------------------------------------------------------------------ # Class of MobileNetV2 #------------------------------------------------------------------------------ class MobileNetV2(nn.Module): def __init__(self, alpha=1.0, expansion=6, num_classes=1000): super(MobileNetV2, self).__init__() self.num_classes = num_classes input_channel = 32 last_channel = 1280 interverted_residual_setting = [ # t, c, n, s [1 , 16, 1, 1], [expansion, 24, 2, 2], [expansion, 32, 3, 2], [expansion, 64, 4, 2], [expansion, 96, 3, 1], [expansion, 160, 3, 2], [expansion, 320, 1, 1], ] # building first layer input_channel = _make_divisible(input_channel*alpha, 8) self.last_channel = _make_divisible(last_channel*alpha, 8) if alpha > 1.0 else last_channel self.features = [conv_bn(3, input_channel, 2)] # building inverted residual blocks for t, c, n, s in interverted_residual_setting: output_channel = _make_divisible(int(c*alpha), 8) for i in range(n): if i == 0: self.features.append(InvertedResidual(input_channel, output_channel, s, expansion=t)) else: self.features.append(InvertedResidual(input_channel, output_channel, 1, expansion=t)) input_channel = output_channel # building last several layers self.features.append(conv_1x1_bn(input_channel, self.last_channel)) # make it nn.Sequential self.features = nn.Sequential(*self.features) # building classifier if self.num_classes is not None: self.classifier = nn.Sequential( nn.Dropout(0.2), nn.Linear(self.last_channel, num_classes), ) # Initialize weights self._init_weights() def forward(self, x, feature_names=None): # Stage1 x = reduce(lambda x, n: self.features[n](x), list(range(0,2)), x) # Stage2 x = reduce(lambda x, n: self.features[n](x), list(range(2,4)), x) # Stage3 x = reduce(lambda x, n: self.features[n](x), list(range(4,7)), x) # Stage4 x = reduce(lambda x, n: self.features[n](x), list(range(7,14)), x) # Stage5 x = reduce(lambda x, n: self.features[n](x), list(range(14,19)), x) # Classification if self.num_classes is not None: x = x.mean(dim=(2,3)) x = self.classifier(x) # Output return x def _load_pretrained_model(self, pretrained_file): pretrain_dict = torch.load(pretrained_file, map_location='cpu') model_dict = {} state_dict = self.state_dict() print("[MobileNetV2] Loading pretrained model...") for k, v in pretrain_dict.items(): if k in state_dict: model_dict[k] = v else: print(k, "is ignored") state_dict.update(model_dict) self.load_state_dict(state_dict) def _init_weights(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)) if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): n = m.weight.size(1) m.weight.data.normal_(0, 0.01) m.bias.data.zero_()
5,462
28.370968
102
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/backbones/efficientnet.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ from base import BaseBackbone from timm.models.gen_efficientnet import ( InvertedResidual, default_cfgs, load_pretrained, _round_channels, _decode_arch_def, _resolve_bn_args, swish, ) from timm.models.gen_efficientnet import GenEfficientNet as BaseEfficientNet import torch import torch.nn as nn from torch.nn import functional as F from collections import OrderedDict #------------------------------------------------------------------------------ # EfficientNetBlock #------------------------------------------------------------------------------ class EfficientNetBlock(nn.Module): def __init__(self, in_channels, out_channels, num_blocks=1, kernel_size=3): super(EfficientNetBlock, self).__init__() if num_blocks==2: self.block = nn.Sequential( InvertedResidual( in_channels, in_channels, dw_kernel_size=kernel_size, act_fn=swish, exp_ratio=6.0, se_ratio=0.25), InvertedResidual( in_channels, out_channels, dw_kernel_size=kernel_size, act_fn=swish, exp_ratio=6.0, se_ratio=0.25)) else: self.block = nn.Sequential( InvertedResidual( in_channels, out_channels, dw_kernel_size=kernel_size, act_fn=swish, exp_ratio=6.0, se_ratio=0.25)) def forward(self, x): x = self.block(x) return x #------------------------------------------------------------------------------ # EfficientNet #------------------------------------------------------------------------------ class EfficientNet(BaseEfficientNet, BaseBackbone): stage_indices = { "tf_efficientnet_b0": [0, 1, 2, 4, 6], "tf_efficientnet_b1": [0, 1, 2, 4, 6], "tf_efficientnet_b2": [0, 1, 2, 4, 6], "tf_efficientnet_b3": [0, 1, 2, 4, 6], "tf_efficientnet_b4": [0, 1, 2, 4, 6], "tf_efficientnet_b5": [0, 1, 2, 4, 6], "tf_efficientnet_b6": [0, 1, 2, 4, 6], "tf_efficientnet_b7": [0, 1, 2, 4, 6], } stage_features = { "tf_efficientnet_b0": [16, 24, 40, 112, 320], "tf_efficientnet_b1": [16, 24, 40, 112, 320], "tf_efficientnet_b2": [16, 24, 48, 120, 352], "tf_efficientnet_b3": [24, 32, 48, 136, 384], "tf_efficientnet_b4": [24, 32, 56, 160, 448], "tf_efficientnet_b5": [24, 40, 64, 176, 512], "tf_efficientnet_b6": [32, 40, 72, 200, 576], "tf_efficientnet_b7": [32, 48, 80, 224, 640], } def __init__(self, block_args, model_name, frozen_stages=-1, norm_eval=False, **kargs): super(EfficientNet, self).__init__(block_args=block_args, **kargs) self.frozen_stages = frozen_stages self.norm_eval = norm_eval self.model_name = model_name def forward(self, input): # Stem x = self.conv_stem(input) x = self.bn1(x) x = self.act_fn(x, inplace=True) # Blocks outs = [] for idx, block in enumerate(self.blocks): x = block(x) if idx in self.stage_indices[self.model_name]: outs.append(x) return tuple(outs) def init_from_imagenet(self, archname): print("[%s] Load pretrained weights from ImageNet" % (self.__class__.__name__)) load_pretrained(self, default_cfgs["tf_%s"%(archname)], self.num_classes) def _freeze_stages(self): # Freeze stem if self.frozen_stages>=0: self.bn1.eval() for module in [self.conv_stem, self.bn1]: for param in module.parameters(): param.requires_grad = False # Chosen subsequent blocks are also frozen gradient frozen_stages = list(range(1, self.frozen_stages+1)) for idx, block in enumerate(self.blocks): if idx <= self.stage_indices[self.model_name][0]: stage = 1 elif self.stage_indices[self.model_name][0] < idx <= self.stage_indices[self.model_name][1]: stage = 2 elif self.stage_indices[self.model_name][1] < idx <= self.stage_indices[self.model_name][2]: stage = 3 elif self.stage_indices[self.model_name][2] < idx <= self.stage_indices[self.model_name][3]: stage = 4 if stage in frozen_stages: block.eval() for param in block.parameters(): param.requires_grad = False else: break #------------------------------------------------------------------------------ # Versions of EfficientNet #------------------------------------------------------------------------------ def _gen_efficientnet(model_name, channel_multiplier=1.0, depth_multiplier=1.0, num_classes=1000, **kwargs): """ EfficientNet params name: (channel_multiplier, depth_multiplier, resolution, dropout_rate) 'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 'efficientnet-b2': (1.1, 1.2, 260, 0.3), 'efficientnet-b3': (1.2, 1.4, 300, 0.3), 'efficientnet-b4': (1.4, 1.8, 380, 0.4), 'efficientnet-b5': (1.6, 2.2, 456, 0.4), 'efficientnet-b6': (1.8, 2.6, 528, 0.5), 'efficientnet-b7': (2.0, 3.1, 600, 0.5), Args: channel_multiplier: multiplier to number of channels per layer depth_multiplier: multiplier to number of repeats per stage """ arch_def = [ ['ds_r1_k3_s1_e1_c16_se0.25'], ['ir_r2_k3_s2_e6_c24_se0.25'], ['ir_r2_k5_s2_e6_c40_se0.25'], ['ir_r3_k3_s2_e6_c80_se0.25'], ['ir_r3_k5_s1_e6_c112_se0.25'], ['ir_r4_k5_s2_e6_c192_se0.25'], ['ir_r1_k3_s1_e6_c320_se0.25'], ] # NOTE: other models in the family didn't scale the feature count num_features = _round_channels(1280, channel_multiplier, 8, None) model = EfficientNet( _decode_arch_def(arch_def, depth_multiplier), model_name=model_name, num_classes=num_classes, stem_size=32, channel_multiplier=channel_multiplier, num_features=num_features, bn_args=_resolve_bn_args(kwargs), act_fn=swish, **kwargs ) return model def efficientnet_b0(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """ EfficientNet-B0 """ model_name = "tf_efficientnet_b0" default_cfg = default_cfgs[model_name] # NOTE for train, drop_rate should be 0.2 #kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg model = _gen_efficientnet( model_name=model_name, channel_multiplier=1.0, depth_multiplier=1.0, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfgs[model_name], num_classes) return model def efficientnet_b1(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """ EfficientNet-B1 """ model_name = "tf_efficientnet_b1" default_cfg = default_cfgs[model_name] # NOTE for train, drop_rate should be 0.2 #kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg model = _gen_efficientnet( model_name=model_name, channel_multiplier=1.0, depth_multiplier=1.1, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfgs[model_name], num_classes) return model def efficientnet_b2(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """ EfficientNet-B2 """ model_name = "tf_efficientnet_b2" default_cfg = default_cfgs[model_name] # NOTE for train, drop_rate should be 0.3 #kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg model = _gen_efficientnet( model_name=model_name, channel_multiplier=1.1, depth_multiplier=1.2, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfgs[model_name], num_classes) return model def efficientnet_b3(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """ EfficientNet-B3 """ model_name = "tf_efficientnet_b3" default_cfg = default_cfgs[model_name] # NOTE for train, drop_rate should be 0.3 #kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg model = _gen_efficientnet( model_name=model_name, channel_multiplier=1.2, depth_multiplier=1.4, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfgs[model_name], num_classes) return model def efficientnet_b4(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """ EfficientNet-B4 """ model_name = "tf_efficientnet_b4" default_cfg = default_cfgs[model_name] # NOTE for train, drop_rate should be 0.4 #kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg model = _gen_efficientnet( model_name=model_name, channel_multiplier=1.4, depth_multiplier=1.8, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfgs[model_name], num_classes) return model def efficientnet_b5(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """ EfficientNet-B5 """ # NOTE for train, drop_rate should be 0.4 #kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg model_name = "tf_efficientnet_b5" default_cfg = default_cfgs[model_name] model = _gen_efficientnet( model_name=model_name, channel_multiplier=1.6, depth_multiplier=2.2, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfgs[model_name], num_classes) return model def efficientnet_b6(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """ EfficientNet-B6 """ # NOTE for train, drop_rate should be 0.5 #kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg model_name = "tf_efficientnet_b6" default_cfg = default_cfgs[model_name] model = _gen_efficientnet( model_name=model_name, channel_multiplier=1.8, depth_multiplier=2.6, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfgs[model_name], num_classes) return model def efficientnet_b7(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """ EfficientNet-B7 """ # NOTE for train, drop_rate should be 0.5 #kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg model_name = "tf_efficientnet_b7" default_cfg = default_cfgs[model_name] model = _gen_efficientnet( model_name=model_name, channel_multiplier=2.0, depth_multiplier=3.1, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfgs[model_name], num_classes) return model
10,267
36.889299
108
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/models/backbones/resnet.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ from base import BaseBackboneWrapper from timm.models.resnet import ResNet as BaseResNet from timm.models.resnet import default_cfgs, load_pretrained, BasicBlock, Bottleneck import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict #------------------------------------------------------------------------------ # ResNetBlock #------------------------------------------------------------------------------ class ResNetBasicBlock(nn.Module): expansion = 1 def __init__(self, in_channels, out_channels): super(ResNetBasicBlock, self).__init__() downsample = nn.Sequential(OrderedDict([ ("conv", nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)), ("bn", nn.BatchNorm2d(out_channels)) ])) self.block = BasicBlock( in_channels, int(out_channels/BasicBlock.expansion), downsample=downsample, ) def forward(self, x): x = self.block(x) return x class ResNetBottleneckBlock(nn.Module): expansion = 4 def __init__(self, in_channels, out_channels): super(ResNetBottleneckBlock, self).__init__() downsample = nn.Sequential(OrderedDict([ ("conv", nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)), ("bn", nn.BatchNorm2d(out_channels)) ])) self.block = Bottleneck( in_channels, int(out_channels/Bottleneck.expansion), downsample=downsample, ) def forward(self, x): x = self.block(x) return x #------------------------------------------------------------------------------ # ResNet #------------------------------------------------------------------------------ class ResNet(BaseResNet, BaseBackboneWrapper): def __init__(self, block, layers, frozen_stages=-1, norm_eval=False, **kargs): super(ResNet, self).__init__(block=block, layers=layers, **kargs) self.frozen_stages = frozen_stages self.norm_eval = norm_eval def forward(self, input): # Stem x1 = self.conv1(input) x1 = self.bn1(x1) x1 = self.relu(x1) # Stage1 x2 = self.maxpool(x1) x2 = self.layer1(x2) # Stage2 x3 = self.layer2(x2) # Stage3 x4 = self.layer3(x3) # Stage4 x5 = self.layer4(x4) # Output return x1, x2, x3, x4, x5 def init_from_imagenet(self, archname): load_pretrained(self, default_cfgs[archname], self.num_classes) def _freeze_stages(self): # Freeze stem if self.frozen_stages>=0: self.bn1.eval() for module in [self.conv1, self.bn1]: for param in module.parameters(): param.requires_grad = False # Chosen subsequent blocks are also frozen for stage_idx in range(1, self.frozen_stages+1): for module in getattr(self, "layer%d"%(stage_idx)): module.eval() for param in module.parameters(): param.requires_grad = False #------------------------------------------------------------------------------ # Versions of ResNet #------------------------------------------------------------------------------ def resnet18(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNet-18 model. """ default_cfg = default_cfgs['resnet18'] model = ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnet34(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNet-34 model. """ default_cfg = default_cfgs['resnet34'] model = ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnet26(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNet-26 model. """ default_cfg = default_cfgs['resnet26'] model = ResNet(Bottleneck, [2, 2, 2, 2], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnet26d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNet-26 v1d model. This is technically a 28 layer ResNet, sticking with 'd' modifier from Gluon for now. """ default_cfg = default_cfgs['resnet26d'] model = ResNet( Bottleneck, [2, 2, 2, 2], stem_width=32, deep_stem=True, avg_down=True, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnet50(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNet-50 model. """ default_cfg = default_cfgs['resnet50'] model = ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnet101(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNet-101 model. """ default_cfg = default_cfgs['resnet101'] model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnet152(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNet-152 model. """ default_cfg = default_cfgs['resnet152'] model = ResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def tv_resnet34(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNet-34 model with original Torchvision weights. """ model = ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfgs['tv_resnet34'] if pretrained: load_pretrained(model, model.default_cfg, num_classes, in_chans) return model def tv_resnet50(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNet-50 model with original Torchvision weights. """ model = ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfgs['tv_resnet50'] if pretrained: load_pretrained(model, model.default_cfg, num_classes, in_chans) return model def wide_resnet50_2(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a Wide ResNet-50-2 model. The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 channels, and in Wide ResNet-50-2 has 2048-1024-2048. """ model = ResNet( Bottleneck, [3, 4, 6, 3], base_width=128, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfgs['wide_resnet50_2'] if pretrained: load_pretrained(model, model.default_cfg, num_classes, in_chans) return model def wide_resnet101_2(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a Wide ResNet-101-2 model. The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same. """ model = ResNet( Bottleneck, [3, 4, 23, 3], base_width=128, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfgs['wide_resnet101_2'] if pretrained: load_pretrained(model, model.default_cfg, num_classes, in_chans) return model def resnext50_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt50-32x4d model. """ default_cfg = default_cfgs['resnext50_32x4d'] model = ResNet( Bottleneck, [3, 4, 6, 3], cardinality=32, base_width=4, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnext50d_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt50d-32x4d model. ResNext50 w/ deep stem & avg pool downsample """ default_cfg = default_cfgs['resnext50d_32x4d'] model = ResNet( Bottleneck, [3, 4, 6, 3], cardinality=32, base_width=4, stem_width=32, deep_stem=True, avg_down=True, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnext101_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt-101 32x4d model. """ default_cfg = default_cfgs['resnext101_32x4d'] model = ResNet( Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=4, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnext101_32x8d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt-101 32x8d model. """ default_cfg = default_cfgs['resnext101_32x8d'] model = ResNet( Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=8, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def resnext101_64x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt101-64x4d model. """ default_cfg = default_cfgs['resnext101_32x4d'] model = ResNet( Bottleneck, [3, 4, 23, 3], cardinality=64, base_width=4, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def tv_resnext50_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt50-32x4d model with original Torchvision weights. """ default_cfg = default_cfgs['tv_resnext50_32x4d'] model = ResNet( Bottleneck, [3, 4, 6, 3], cardinality=32, base_width=4, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def ig_resnext101_32x8d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt-101 32x8 model pre-trained on weakly-supervised data and finetuned on ImageNet from Figure 5 in `"Exploring the Limits of Weakly Supervised Pretraining" <https://arxiv.org/abs/1805.00932>`_ Weights from https://pytorch.org/hub/facebookresearch_WSL-Images_resnext/ Args: pretrained (bool): load pretrained weights num_classes (int): number of classes for classifier (default: 1000 for pretrained) in_chans (int): number of input planes (default: 3 for pretrained / color) """ default_cfg = default_cfgs['ig_resnext101_32x8d'] model = ResNet(Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=8, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def ig_resnext101_32x16d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt-101 32x16 model pre-trained on weakly-supervised data and finetuned on ImageNet from Figure 5 in `"Exploring the Limits of Weakly Supervised Pretraining" <https://arxiv.org/abs/1805.00932>`_ Weights from https://pytorch.org/hub/facebookresearch_WSL-Images_resnext/ Args: pretrained (bool): load pretrained weights num_classes (int): number of classes for classifier (default: 1000 for pretrained) in_chans (int): number of input planes (default: 3 for pretrained / color) """ default_cfg = default_cfgs['ig_resnext101_32x16d'] model = ResNet(Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=16, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def ig_resnext101_32x32d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt-101 32x32 model pre-trained on weakly-supervised data and finetuned on ImageNet from Figure 5 in `"Exploring the Limits of Weakly Supervised Pretraining" <https://arxiv.org/abs/1805.00932>`_ Weights from https://pytorch.org/hub/facebookresearch_WSL-Images_resnext/ Args: pretrained (bool): load pretrained weights num_classes (int): number of classes for classifier (default: 1000 for pretrained) in_chans (int): number of input planes (default: 3 for pretrained / color) """ default_cfg = default_cfgs['ig_resnext101_32x32d'] model = ResNet(Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=32, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model def ig_resnext101_32x48d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a ResNeXt-101 32x48 model pre-trained on weakly-supervised data and finetuned on ImageNet from Figure 5 in `"Exploring the Limits of Weakly Supervised Pretraining" <https://arxiv.org/abs/1805.00932>`_ Weights from https://pytorch.org/hub/facebookresearch_WSL-Images_resnext/ Args: pretrained (bool): load pretrained weights num_classes (int): number of classes for classifier (default: 1000 for pretrained) in_chans (int): number of input planes (default: 3 for pretrained / color) """ default_cfg = default_cfgs['ig_resnext101_32x48d'] model = ResNet(Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=48, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, num_classes, in_chans) return model
13,998
37.353425
96
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/dataloaders/dataloader.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import warnings warnings.filterwarnings('ignore') import cv2, os import numpy as np from random import shuffle import torch from torch.utils.data import Dataset, DataLoader from dataloaders import transforms # import transforms #------------------------------------------------------------------------------ # DataLoader for Semantic Segmentation #------------------------------------------------------------------------------ class SegmentationDataLoader(object): def __init__(self, pairs_file, color_channel="RGB", resize=224, padding_value=0, crop_range=[0.75, 1.0], flip_hor=0.5, rotate=0.3, angle=10, noise_std=5, normalize=True, one_hot=False, is_training=True, shuffle=True, batch_size=1, n_workers=1, pin_memory=True): # Storage parameters super(SegmentationDataLoader, self).__init__() self.pairs_file = pairs_file self.color_channel = color_channel self.resize = resize self.padding_value = padding_value self.crop_range = crop_range self.flip_hor = flip_hor self.rotate = rotate self.angle = angle self.noise_std = noise_std self.normalize = normalize self.one_hot = one_hot self.is_training = is_training self.shuffle = shuffle self.batch_size = batch_size self.n_workers = n_workers self.pin_memory = pin_memory # Dataset self.dataset = SegmentationDataset( pairs_file=self.pairs_file, color_channel=self.color_channel, resize=self.resize, padding_value=self.padding_value, crop_range=self.crop_range, flip_hor=self.flip_hor, rotate=self.rotate, angle=self.angle, noise_std=self.noise_std, normalize=self.normalize, one_hot=self.one_hot, is_training=self.is_training, ) @property def loader(self): return DataLoader( self.dataset, batch_size=self.batch_size, shuffle=self.shuffle, num_workers=self.n_workers, pin_memory=self.pin_memory, ) #------------------------------------------------------------------------------ # Dataset for Semantic Segmentation #------------------------------------------------------------------------------ class SegmentationDataset(Dataset): """ The dataset requires label is a grayscale image with value {0,1,...,C-1}, where C is the number of classes. """ def __init__(self, pairs_file, color_channel="RGB", resize=512, padding_value=0, is_training=True, noise_std=5, crop_range=[0.75, 1.0], flip_hor=0.5, rotate=0.3, angle=10, one_hot=False, normalize=True, mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]): # Get list of image and label files self.image_files, self.label_files = [], [] fp = open(pairs_file, "r") lines = fp.read().split("\n") lines = [line.strip() for line in lines if len(line)] lines = [line.split(", ") for line in lines] print("[Dataset] Checking file paths...") error_flg = False for line in lines: image_file, label_file = line if not os.path.exists(image_file): print("%s does not exist!" % (image_file)) error_flg = True if not os.path.exists(label_file): print("%s does not exist!" % (label_file)) error_flg = True self.image_files.append(image_file) self.label_files.append(label_file) if error_flg: raise ValueError("Some file paths are corrupted! Please re-check your file paths!") print("[Dataset] Number of sample pairs:", len(self.image_files)) # Parameters self.color_channel = color_channel self.resize = resize self.padding_value = padding_value self.is_training = is_training self.noise_std = noise_std self.crop_range = crop_range self.flip_hor = flip_hor self.rotate = rotate self.angle = angle self.one_hot = one_hot self.normalize = normalize self.mean = np.array(mean)[None,None,:] self.std = np.array(std)[None,None,:] def __len__(self): return len(self.image_files) def __getitem__(self, idx): # Read image and label img_file, label_file = self.image_files[idx], self.label_files[idx] image = cv2.imread(img_file)[...,::-1] label = cv2.imread(label_file, 0) # Augmentation if in training phase if self.is_training: image = transforms.random_noise(image, std=self.noise_std) image, label = transforms.flip_horizon(image, label, self.flip_hor) image, label = transforms.rotate_90(image, label, self.rotate) image, label = transforms.rotate_angle(image, label, self.angle) image, label = transforms.random_crop(image, label, self.crop_range) # Resize: the greater side is refered, the rest is padded image = transforms.resize_image(image, expected_size=self.resize, pad_value=self.padding_value, mode=cv2.INTER_LINEAR) label = transforms.resize_image(label, expected_size=self.resize, pad_value=self.padding_value, mode=cv2.INTER_NEAREST) # Preprocess image if self.normalize: image = image.astype(np.float32) / 255.0 image = (image - self.mean) / self.std image = np.transpose(image, axes=(2, 0, 1)) # Preprocess label label[label>0] = 1 if self.one_hot: label = (np.arange(label.max()+1) == label[...,None]).astype(int) # Convert to tensor and return image = torch.tensor(image.copy(), dtype=torch.float32) label = torch.tensor(label.copy(), dtype=torch.float32) return image, label
5,338
32.791139
121
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/base/base_model.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import torch import torch.nn as nn import torchsummary import os, warnings, sys from utils import add_flops_counting_methods, flops_to_string #------------------------------------------------------------------------------ # BaseModel #------------------------------------------------------------------------------ class BaseModel(nn.Module): def __init__(self): super(BaseModel, self).__init__() def summary(self, input_shape, batch_size=1, device='cpu', print_flops=False): print("[%s] Network summary..." % (self.__class__.__name__)) torchsummary.summary(self, input_size=input_shape, batch_size=batch_size, device=device) if print_flops: input = torch.randn([1, *input_shape], dtype=torch.float) counter = add_flops_counting_methods(self) counter.eval().start_flops_count() counter(input) print('Flops: {}'.format(flops_to_string(counter.compute_average_flops_cost()))) print('----------------------------------------------------------------') def init_weights(self): print("[%s] Initialize weights..." % (self.__class__.__name__)) for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: m.bias.data.zero_() elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01) m.bias.data.zero_() def load_pretrained_model(self, pretrained): if isinstance(pretrained, str): print("[%s] Load pretrained model from %s" % (self.__class__.__name__, pretrained)) pretrain_dict = torch.load(pretrained, map_location='cpu') if 'state_dict' in pretrain_dict: pretrain_dict = pretrain_dict['state_dict'] elif isinstance(pretrained, dict): print("[%s] Load pretrained model" % (self.__class__.__name__)) pretrain_dict = pretrained model_dict = {} state_dict = self.state_dict() for k, v in pretrain_dict.items(): if k in state_dict: if state_dict[k].shape==v.shape: model_dict[k] = v else: print("[%s]"%(self.__class__.__name__), k, "is ignored due to not matching shape") else: print("[%s]"%(self.__class__.__name__), k, "is ignored due to not matching key") state_dict.update(model_dict) self.load_state_dict(state_dict) #------------------------------------------------------------------------------ # BaseBackbone #------------------------------------------------------------------------------ class BaseBackbone(BaseModel): def __init__(self): super(BaseBackbone, self).__init__() def load_pretrained_model_extended(self, pretrained): """ This function is specifically designed for loading pretrain with different in_channels """ if isinstance(pretrained, str): print("[%s] Load pretrained model from %s" % (self.__class__.__name__, pretrained)) pretrain_dict = torch.load(pretrained, map_location='cpu') if 'state_dict' in pretrain_dict: pretrain_dict = pretrain_dict['state_dict'] elif isinstance(pretrained, dict): print("[%s] Load pretrained model" % (self.__class__.__name__)) pretrain_dict = pretrained model_dict = {} state_dict = self.state_dict() for k, v in pretrain_dict.items(): if k in state_dict: if state_dict[k].shape!=v.shape: model_dict[k] = state_dict[k] model_dict[k][:,:3,...] = v else: model_dict[k] = v else: print("[%s]"%(self.__class__.__name__), k, "is ignored") state_dict.update(model_dict) self.load_state_dict(state_dict) #------------------------------------------------------------------------------ # BaseBackboneWrapper #------------------------------------------------------------------------------ class BaseBackboneWrapper(BaseBackbone): def __init__(self): super(BaseBackboneWrapper, self).__init__() def train(self, mode=True): if mode: print("[%s] Switch to train mode" % (self.__class__.__name__)) else: print("[%s] Switch to eval mode" % (self.__class__.__name__)) super(BaseBackboneWrapper, self).train(mode) self._freeze_stages() if mode and self.norm_eval: for module in self.modules(): # trick: eval have effect on BatchNorm only if isinstance(module, nn.BatchNorm2d): module.eval() elif isinstance(module, nn.Sequential): for m in module: if isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)): m.eval() def init_from_imagenet(self, archname): pass def _freeze_stages(self): pass
4,728
34.556391
90
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/base/base_trainer.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ from time import time import os, math, json, logging, datetime, torch from utils.visualization import WriterTensorboardX #------------------------------------------------------------------------------ # Class of BaseTrainer #------------------------------------------------------------------------------ class BaseTrainer: """ Base class for all trainers """ def __init__(self, model, loss, metrics, optimizer, resume, config, train_logger=None): self.config = config # Setup directory for checkpoint saving start_time = datetime.datetime.now().strftime('%m%d_%H%M%S') self.checkpoint_dir = os.path.join(config['trainer']['save_dir'], config['name'], start_time) os.makedirs(self.checkpoint_dir, exist_ok=True) # Setup logger logging.basicConfig( level=logging.INFO, format="%(asctime)s %(message)s", handlers=[ logging.FileHandler(os.path.join(self.checkpoint_dir, "train.log")), logging.StreamHandler(), ]) self.logger = logging.getLogger(self.__class__.__name__) # Setup GPU device if available, move model into configured device self.device, device_ids = self._prepare_device(config['n_gpu']) self.model = model.to(self.device) if len(device_ids) > 1: self.model = torch.nn.DataParallel(model, device_ids=device_ids) self.loss = loss self.metrics = metrics self.optimizer = optimizer self.epochs = config['trainer']['epochs'] self.save_freq = config['trainer']['save_freq'] self.verbosity = config['trainer']['verbosity'] self.train_logger = train_logger # configuration to monitor model performance and save best self.monitor = config['trainer']['monitor'] self.monitor_mode = config['trainer']['monitor_mode'] assert self.monitor_mode in ['min', 'max', 'off'] self.monitor_best = math.inf if self.monitor_mode == 'min' else -math.inf self.start_epoch = 1 # setup visualization writer instance writer_train_dir = os.path.join(config['visualization']['log_dir'], config['name'], start_time, "train") writer_valid_dir = os.path.join(config['visualization']['log_dir'], config['name'], start_time, "valid") self.writer_train = WriterTensorboardX(writer_train_dir, self.logger, config['visualization']['tensorboardX']) self.writer_valid = WriterTensorboardX(writer_valid_dir, self.logger, config['visualization']['tensorboardX']) # Save configuration file into checkpoint directory config_save_path = os.path.join(self.checkpoint_dir, 'config.json') with open(config_save_path, 'w') as handle: json.dump(config, handle, indent=4, sort_keys=False) # Resume if resume: self._resume_checkpoint(resume) def _prepare_device(self, n_gpu_use): """ setup GPU device if available, move model into configured device """ n_gpu = torch.cuda.device_count() if n_gpu_use > 0 and n_gpu == 0: self.logger.warning("Warning: There\'s no GPU available on this machine, training will be performed on CPU.") n_gpu_use = 0 if n_gpu_use > n_gpu: msg = "Warning: The number of GPU\'s configured to use is {}, but only {} are available on this machine.".format(n_gpu_use, n_gpu) self.logger.warning(msg) n_gpu_use = n_gpu device = torch.device('cuda:0' if n_gpu_use > 0 else 'cpu') list_ids = list(range(n_gpu_use)) return device, list_ids def train(self): for epoch in range(self.start_epoch, self.epochs + 1): self.logger.info("\n----------------------------------------------------------------") self.logger.info("[EPOCH %d]" % (epoch)) start_time = time() result = self._train_epoch(epoch) finish_time = time() self.logger.info("Finish at {}, Runtime: {:.3f} [s]".format(datetime.datetime.now(), finish_time-start_time)) # save logged informations into log dict log = {} for key, value in result.items(): if key == 'train_metrics': log.update({'train_' + mtr.__name__ : value[i] for i, mtr in enumerate(self.metrics)}) elif key == 'valid_metrics': log.update({'valid_' + mtr.__name__ : value[i] for i, mtr in enumerate(self.metrics)}) else: log[key] = value # print logged informations to the screen if self.train_logger is not None: self.train_logger.add_entry(log) if self.verbosity >= 1: for key, value in sorted(list(log.items())): self.logger.info('{:25s}: {}'.format(str(key), value)) # evaluate model performance according to configured metric, save best checkpoint as model_best best = False if self.monitor_mode != 'off': try: if (self.monitor_mode == 'min' and log[self.monitor] < self.monitor_best) or\ (self.monitor_mode == 'max' and log[self.monitor] > self.monitor_best): self.logger.info("Monitor improved from %f to %f" % (self.monitor_best, log[self.monitor])) self.monitor_best = log[self.monitor] best = True except KeyError: if epoch == 1: msg = "Warning: Can\'t recognize metric named '{}' ".format(self.monitor)\ + "for performance monitoring. model_best checkpoint won\'t be updated." self.logger.warning(msg) # Save checkpoint self._save_checkpoint(epoch, save_best=best) def _train_epoch(self, epoch): """ Training logic for an epoch :param epoch: Current epoch number """ raise NotImplementedError def _save_checkpoint(self, epoch, save_best=False): """ Saving checkpoints :param epoch: current epoch number :param log: logging information of the epoch :param save_best: if True, rename the saved checkpoint to 'model_best.pth' """ # Construct savedict arch = type(self.model).__name__ state = { 'arch': arch, 'epoch': epoch, 'logger': self.train_logger, 'state_dict': self.model.state_dict(), 'optimizer': self.optimizer.state_dict(), 'monitor_best': self.monitor_best, 'config': self.config } # Save checkpoint for each epoch if self.save_freq is not None: # Use None mode to avoid over disk space with large models if epoch % self.save_freq == 0: filename = os.path.join(self.checkpoint_dir, 'epoch{}.pth'.format(epoch)) torch.save(state, filename) self.logger.info("Saving checkpoint at {}".format(filename)) # Save the best checkpoint if save_best: best_path = os.path.join(self.checkpoint_dir, 'model_best.pth') torch.save(state, best_path) self.logger.info("Saving current best at {}".format(best_path)) else: self.logger.info("Monitor is not improved from %f" % (self.monitor_best)) def _resume_checkpoint(self, resume_path): """ Resume from saved checkpoints :param resume_path: Checkpoint path to be resumed """ self.logger.info("Loading checkpoint: {}".format(resume_path)) checkpoint = torch.load(resume_path) self.start_epoch = checkpoint['epoch'] + 1 self.monitor_best = checkpoint['monitor_best'] # load architecture params from checkpoint. if checkpoint['config']['arch'] != self.config['arch']: self.logger.warning('Warning: Architecture configuration given in config file is different from that of checkpoint. ' + \ 'This may yield an exception while state_dict is being loaded.') self.model.load_state_dict(checkpoint['state_dict'], strict=True) # # load optimizer state from checkpoint only when optimizer type is not changed. # if checkpoint['config']['optimizer']['type'] != self.config['optimizer']['type']: # self.logger.warning('Warning: Optimizer type given in config file is different from that of checkpoint. ' + \ # 'Optimizer parameters not being resumed.') # else: # self.optimizer.load_state_dict(checkpoint['optimizer']) self.train_logger = checkpoint['logger'] self.logger.info("Checkpoint '{}' (epoch {}) loaded".format(resume_path, self.start_epoch-1))
7,855
37.321951
133
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/base/base_data_loader.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import numpy as np from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate from torch.utils.data.sampler import SubsetRandomSampler #------------------------------------------------------------------------------ # BaseDataLoader #------------------------------------------------------------------------------ class BaseDataLoader(DataLoader): def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate): self.validation_split = validation_split self.shuffle = shuffle self.batch_idx = 0 self.n_samples = len(dataset) self.sampler, self.valid_sampler = self._split_sampler(self.validation_split) self.init_kwargs = { 'dataset': dataset, 'batch_size': batch_size, 'shuffle': self.shuffle, 'collate_fn': collate_fn, 'num_workers': num_workers } super(BaseDataLoader, self).__init__(sampler=self.sampler, **self.init_kwargs) def _split_sampler(self, split): if split == 0.0: return None, None idx_full = np.arange(self.n_samples) np.random.seed(0) np.random.shuffle(idx_full) len_valid = int(self.n_samples * split) valid_idx = idx_full[0:len_valid] train_idx = np.delete(idx_full, np.arange(0, len_valid)) train_sampler = SubsetRandomSampler(train_idx) valid_sampler = SubsetRandomSampler(valid_idx) # turn off shuffle option which is mutually exclusive with sampler self.shuffle = False self.n_samples = len(train_idx) return train_sampler, valid_sampler def split_validation(self): if self.valid_sampler is None: return None else: return DataLoader(sampler=self.valid_sampler, **self.init_kwargs)
2,097
32.83871
112
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/base/base_inference.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import cv2, torch import numpy as np from time import time from torch.nn import functional as F #------------------------------------------------------------------------------ # BaseInference #------------------------------------------------------------------------------ class BaseInference(object): def __init__(self, model, color_f=[255,0,0], color_b=[0,0,255], kernel_sz=25, sigma=0, background_path=None): self.model = model self.color_f = color_f self.color_b = color_b self.kernel_sz = kernel_sz self.sigma = sigma self.background_path = background_path if background_path is not None: self.background = cv2.imread(background_path)[...,::-1] self.background = self.background.astype(np.float32) def load_image(self): raise NotImplementedError def preprocess(self, image, *args): raise NotImplementedError def predict(self, X): raise NotImplementedError def draw_matting(self, image, mask): """ image (np.uint8) shape (H,W,3) mask (np.float32) range from 0 to 1, shape (H,W) """ mask = 255*(1.0-mask) mask = np.expand_dims(mask, axis=2) mask = np.tile(mask, (1,1,3)) mask = mask.astype(np.uint8) image_alpha = cv2.add(image, mask) return image_alpha def draw_transperency(self, image, mask): """ image (np.uint8) shape (H,W,3) mask (np.float32) range from 0 to 1, shape (H,W) """ mask = mask.round() alpha = np.zeros_like(image, dtype=np.uint8) alpha[mask==1, :] = self.color_f alpha[mask==0, :] = self.color_b image_alpha = cv2.add(image, alpha) return image_alpha def draw_background(self, image, mask): """ image (np.uint8) shape (H,W,3) mask (np.float32) range from 0 to 1, shape (H,W) """ image = image.astype(np.float32) mask_filtered = cv2.GaussianBlur(mask, (self.kernel_sz, self.kernel_sz), self.sigma) mask_filtered = np.expand_dims(mask_filtered, axis=2) mask_filtered = np.tile(mask_filtered, (1,1,3)) image_alpha = image*mask_filtered + self.background*(1-mask_filtered) return image_alpha.astype(np.uint8) #------------------------------------------------------------------------------ # VideoInference #------------------------------------------------------------------------------ class VideoInference(BaseInference): def __init__(self, model, video_path, input_size, use_cuda=True, draw_mode='matting', color_f=[255,0,0], color_b=[0,0,255], kernel_sz=25, sigma=0, background_path=None): # Initialize super(VideoInference, self).__init__(model, color_f, color_b, kernel_sz, sigma, background_path) self.input_size = input_size self.use_cuda = use_cuda self.draw_mode = draw_mode if draw_mode=='matting': self.draw_func = self.draw_matting elif draw_mode=='transperency': self.draw_func = self.draw_transperency elif draw_mode=='background': self.draw_func = self.draw_background else: raise NotImplementedError # Preprocess self.mean = np.array([0.485,0.456,0.406])[None,None,:] self.std = np.array([0.229,0.224,0.225])[None,None,:] # Read video self.video_path = video_path self.cap = cv2.VideoCapture(video_path) _, frame = self.cap.read() self.H, self.W = frame.shape[:2] def load_image(self): _, frame = self.cap.read() image = frame[...,::-1] return image def preprocess(self, image): image = cv2.resize(image, (self.input_size,self.input_size), interpolation=cv2.INTER_LINEAR) image = image.astype(np.float32) / 255.0 image = (image - self.mean) / self.std X = np.transpose(image, axes=(2, 0, 1)) X = np.expand_dims(X, axis=0) X = torch.tensor(X, dtype=torch.float32) return X def predict(self, X): with torch.no_grad(): if self.use_cuda: mask = self.model(X.cuda()) mask = F.interpolate(mask, size=(self.H, self.W), mode='bilinear', align_corners=True) mask = F.softmax(mask, dim=1) mask = mask[0,1,...].cpu().numpy() else: mask = self.model(X) mask = F.interpolate(mask, size=(self.H, self.W), mode='bilinear', align_corners=True) mask = F.softmax(mask, dim=1) mask = mask[0,1,...].numpy() return mask def run(self): while(True): # Read frame from camera start_time = time() image = self.load_image() read_cam_time = time() # Preprocess X = self.preprocess(image) preproc_time = time() # Predict mask = self.predict(X) predict_time = time() # Draw result image_alpha = self.draw_func(image, mask) draw_time = time() # Wait for interupt cv2.imshow('webcam', image_alpha[..., ::-1]) if cv2.waitKey(1) & 0xFF == ord('q'): break # Print runtime read = read_cam_time-start_time preproc = preproc_time-read_cam_time pred = predict_time-preproc_time draw = draw_time-predict_time total = read + preproc + pred + draw fps = 1 / total print("read: %.3f [s]; preproc: %.3f [s]; pred: %.3f [s]; draw: %.3f [s]; total: %.3f [s]; fps: %.2f [Hz]" % (read, preproc, pred, draw, total, fps))
5,113
28.560694
112
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/utils/utils.py
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ import os, cv2, torch import numpy as np from dataloaders import transforms #------------------------------------------------------------------------------ # Preprocessing #------------------------------------------------------------------------------ mean = np.array([0.485, 0.456, 0.406])[None,None,:] std = np.array([0.229, 0.224, 0.225])[None,None,:] def preprocessing(image, expected_size=224, pad_value=0): image, pad_up, pad_left, h_new, w_new = transforms.resize_image(image, expected_size, pad_value, ret_params=True) image = image.astype(np.float32) / 255.0 image = (image - mean) / std X = np.transpose(image, axes=(2, 0, 1)) X = np.expand_dims(X, axis=0) X = torch.tensor(X, dtype=torch.float32) return X, pad_up, pad_left, h_new, w_new #------------------------------------------------------------------------------ # Draw image with transperency #------------------------------------------------------------------------------ def draw_transperency(image, mask, color_f, color_b): """ image (np.uint8) mask (np.float32) range from 0 to 1 """ mask = mask.round() alpha = np.zeros_like(image, dtype=np.uint8) alpha[mask==1, :] = color_f alpha[mask==0, :] = color_b image_alpha = cv2.add(image, alpha) return image_alpha #------------------------------------------------------------------------------ # Draw matting #------------------------------------------------------------------------------ def draw_matting(image, mask): """ image (np.uint8) mask (np.float32) range from 0 to 1 """ mask = 255*(1.0-mask) mask = np.expand_dims(mask, axis=2) mask = np.tile(mask, (1,1,3)) mask = mask.astype(np.uint8) image_matting = cv2.add(image, mask) return image_matting #------------------------------------------------------------------------------ # Draw foreground pasted into background #------------------------------------------------------------------------------ def draw_fore_to_back(image, mask, background, kernel_sz=13, sigma=0): """ image (np.uint8) mask (np.float32) range from 0 to 1 """ mask_filtered = cv2.GaussianBlur(mask, (kernel_sz, kernel_sz), sigma) mask_filtered = np.expand_dims(mask_filtered, axis=2) mask_filtered = np.tile(mask_filtered, (1,1,3)) image_alpha = image*mask_filtered + background*(1-mask_filtered) return image_alpha.astype(np.uint8)
2,506
35.333333
114
py
Human-Segmentation-PyTorch
Human-Segmentation-PyTorch-master/utils/flops_counter.py
import torch.nn as nn import torch import numpy as np def flops_to_string(flops): if flops // 10**9 > 0: return str(round(flops / 10.**9, 2)) + 'GMac' elif flops // 10**6 > 0: return str(round(flops / 10.**6, 2)) + 'MMac' elif flops // 10**3 > 0: return str(round(flops / 10.**3, 2)) + 'KMac' return str(flops) + 'Mac' def get_model_parameters_number(model, as_string=True): params_num = sum(p.numel() for p in model.parameters() if p.requires_grad) if not as_string: return params_num if params_num // 10 ** 6 > 0: return str(round(params_num / 10 ** 6, 2)) + 'M' elif params_num // 10 ** 3: return str(round(params_num / 10 ** 3, 2)) + 'k' return str(params_num) def add_flops_counting_methods(net_main_module): # adding additional methods to the existing module object, # this is done this way so that each function has access to self object net_main_module.start_flops_count = start_flops_count.__get__(net_main_module) net_main_module.stop_flops_count = stop_flops_count.__get__(net_main_module) net_main_module.reset_flops_count = reset_flops_count.__get__(net_main_module) net_main_module.compute_average_flops_cost = compute_average_flops_cost.__get__(net_main_module) net_main_module.reset_flops_count() # Adding variables necessary for masked flops computation net_main_module.apply(add_flops_mask_variable_or_reset) return net_main_module def compute_average_flops_cost(self): """ A method that will be available after add_flops_counting_methods() is called on a desired net object. Returns current mean flops consumption per image. """ batches_count = self.__batch_counter__ flops_sum = 0 for module in self.modules(): if is_supported_instance(module): flops_sum += module.__flops__ return flops_sum / batches_count def start_flops_count(self): """ A method that will be available after add_flops_counting_methods() is called on a desired net object. Activates the computation of mean flops consumption per image. Call it before you run the network. """ add_batch_counter_hook_function(self) self.apply(add_flops_counter_hook_function) def stop_flops_count(self): """ A method that will be available after add_flops_counting_methods() is called on a desired net object. Stops computing the mean flops consumption per image. Call whenever you want to pause the computation. """ remove_batch_counter_hook_function(self) self.apply(remove_flops_counter_hook_function) def reset_flops_count(self): """ A method that will be available after add_flops_counting_methods() is called on a desired net object. Resets statistics computed so far. """ add_batch_counter_variables_or_reset(self) self.apply(add_flops_counter_variable_or_reset) def add_flops_mask(module, mask): def add_flops_mask_func(module): if isinstance(module, torch.nn.Conv2d): module.__mask__ = mask module.apply(add_flops_mask_func) def remove_flops_mask(module): module.apply(add_flops_mask_variable_or_reset) # ---- Internal functions def is_supported_instance(module): if isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.ReLU) \ or isinstance(module, torch.nn.PReLU) or isinstance(module, torch.nn.ELU) \ or isinstance(module, torch.nn.LeakyReLU) or isinstance(module, torch.nn.ReLU6) \ or isinstance(module, torch.nn.Linear) or isinstance(module, torch.nn.MaxPool2d) \ or isinstance(module, torch.nn.AvgPool2d) or isinstance(module, torch.nn.BatchNorm2d) \ or isinstance(module, torch.nn.Upsample): return True return False def empty_flops_counter_hook(module, input, output): module.__flops__ += 0 def upsample_flops_counter_hook(module, input, output): output_size = output[0] batch_size = output_size.shape[0] output_elements_count = batch_size for val in output_size.shape[1:]: output_elements_count *= val module.__flops__ += output_elements_count def relu_flops_counter_hook(module, input, output): input = input[0] batch_size = input.shape[0] active_elements_count = batch_size for val in input.shape[1:]: active_elements_count *= val module.__flops__ += active_elements_count def linear_flops_counter_hook(module, input, output): input = input[0] batch_size = input.shape[0] module.__flops__ += batch_size * input.shape[1] * output.shape[1] def pool_flops_counter_hook(module, input, output): input = input[0] module.__flops__ += np.prod(input.shape) def bn_flops_counter_hook(module, input, output): module.affine input = input[0] batch_flops = np.prod(input.shape) if module.affine: batch_flops *= 2 module.__flops__ += batch_flops def conv_flops_counter_hook(conv_module, input, output): # Can have multiple inputs, getting the first one input = input[0] batch_size = input.shape[0] output_height, output_width = output.shape[2:] kernel_height, kernel_width = conv_module.kernel_size in_channels = conv_module.in_channels out_channels = conv_module.out_channels groups = conv_module.groups filters_per_channel = out_channels // groups conv_per_position_flops = kernel_height * kernel_width * in_channels * filters_per_channel active_elements_count = batch_size * output_height * output_width if conv_module.__mask__ is not None: # (b, 1, h, w) flops_mask = conv_module.__mask__.expand(batch_size, 1, output_height, output_width) active_elements_count = flops_mask.sum() overall_conv_flops = conv_per_position_flops * active_elements_count bias_flops = 0 if conv_module.bias is not None: bias_flops = out_channels * active_elements_count overall_flops = overall_conv_flops + bias_flops conv_module.__flops__ += overall_flops def batch_counter_hook(module, input, output): # Can have multiple inputs, getting the first one input = input[0] batch_size = input.shape[0] module.__batch_counter__ += batch_size def add_batch_counter_variables_or_reset(module): module.__batch_counter__ = 0 def add_batch_counter_hook_function(module): if hasattr(module, '__batch_counter_handle__'): return handle = module.register_forward_hook(batch_counter_hook) module.__batch_counter_handle__ = handle def remove_batch_counter_hook_function(module): if hasattr(module, '__batch_counter_handle__'): module.__batch_counter_handle__.remove() del module.__batch_counter_handle__ def add_flops_counter_variable_or_reset(module): if is_supported_instance(module): module.__flops__ = 0 def add_flops_counter_hook_function(module): if is_supported_instance(module): if hasattr(module, '__flops_handle__'): return if isinstance(module, torch.nn.Conv2d): handle = module.register_forward_hook(conv_flops_counter_hook) elif isinstance(module, torch.nn.ReLU) or isinstance(module, torch.nn.PReLU) \ or isinstance(module, torch.nn.ELU) or isinstance(module, torch.nn.LeakyReLU) \ or isinstance(module, torch.nn.ReLU6): handle = module.register_forward_hook(relu_flops_counter_hook) elif isinstance(module, torch.nn.Linear): handle = module.register_forward_hook(linear_flops_counter_hook) elif isinstance(module, torch.nn.AvgPool2d) or isinstance(module, torch.nn.MaxPool2d): handle = module.register_forward_hook(pool_flops_counter_hook) elif isinstance(module, torch.nn.BatchNorm2d): handle = module.register_forward_hook(bn_flops_counter_hook) elif isinstance(module, torch.nn.Upsample): handle = module.register_forward_hook(upsample_flops_counter_hook) else: handle = module.register_forward_hook(empty_flops_counter_hook) module.__flops_handle__ = handle def remove_flops_counter_hook_function(module): if is_supported_instance(module): if hasattr(module, '__flops_handle__'): module.__flops_handle__.remove() del module.__flops_handle__ # --- Masked flops counting # Also being run in the initialization def add_flops_mask_variable_or_reset(module): if is_supported_instance(module): module.__mask__ = None
8,546
31.131579
100
py
CDTrans
CDTrans-master/train.py
import os from torch.backends import cudnn from utils.logger import setup_logger from datasets import make_dataloader from model import make_model from solver import make_optimizer, create_scheduler from loss import make_loss from processor import do_train_pretrain, do_train_uda import random import torch import numpy as np import os import argparse # from timm.scheduler import create_scheduler from config import cfg from timm.data import Mixup def set_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True if __name__ == '__main__': parser = argparse.ArgumentParser(description="ReID Baseline Training") parser.add_argument( "--config_file", default="", help="path to config file", type=str ) parser.add_argument("opts", help="Modify config options using the command-line", default=None, nargs=argparse.REMAINDER) # parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER', # help='LR scheduler (default: "cosine"') # parser.add_argument('--lr', type=float, default=0.01, metavar='LR', # help='learning rate (default: 5e-4)') # parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', # help='learning rate noise on/off epoch percentages') # parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', # help='learning rate noise limit percent (default: 0.67)') # parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', # help='learning rate noise std-dev (default: 1.0)') # parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR', # help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') # parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N', # help='epochs to cooldown LR at min_lr, after cyclic schedule ends') # parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', # help='LR decay rate (default: 0.1)') # parser.add_argument('--epochs', default=120, type=int) parser.add_argument("--local_rank", default=0, type=int) args = parser.parse_args() if args.config_file != "": cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.freeze() set_seed(cfg.SOLVER.SEED) if cfg.MODEL.DIST_TRAIN: torch.cuda.set_device(args.local_rank) else: pass output_dir = cfg.OUTPUT_DIR if output_dir and not os.path.exists(output_dir): os.makedirs(output_dir) logger = setup_logger("reid_baseline", output_dir, if_train=True) logger.info("Saving model in the path :{}".format(cfg.OUTPUT_DIR)) logger.info(args) if args.config_file != "": logger.info("Loaded configuration file {}".format(args.config_file)) with open(args.config_file, 'r') as cf: config_str = "\n" + cf.read() logger.info(config_str) logger.info("Running with config:\n{}".format(cfg)) if cfg.MODEL.DIST_TRAIN: torch.distributed.init_process_group(backend='nccl', init_method='env://') os.environ['CUDA_VISIBLE_DEVICES'] = cfg.MODEL.DEVICE_ID if cfg.MODEL.UDA_STAGE == 'UDA': train_loader, train_loader_normal, val_loader, num_query, num_classes, camera_num, view_num, train_loader1, train_loader2, img_num1, img_num2, s_dataset, t_dataset = make_dataloader(cfg) else: train_loader, train_loader_normal, val_loader, num_query, num_classes, camera_num, view_num = make_dataloader(cfg) model = make_model(cfg, num_class=num_classes, camera_num=camera_num, view_num = view_num) loss_func, center_criterion = make_loss(cfg, num_classes=num_classes) optimizer, optimizer_center = make_optimizer(cfg, model, center_criterion) scheduler = create_scheduler(cfg, optimizer) if cfg.MODEL.UDA_STAGE == 'UDA': do_train_uda( cfg, model, center_criterion, train_loader, train_loader1, train_loader2, img_num1, img_num2, val_loader, s_dataset, t_dataset, optimizer, optimizer_center, scheduler, loss_func, num_query, args.local_rank ) else: print('pretrain train') do_train_pretrain( cfg, model, center_criterion, train_loader, val_loader, optimizer, optimizer_center, scheduler, loss_func, num_query, args.local_rank )
4,936
36.401515
194
py
CDTrans
CDTrans-master/solver/lr_scheduler.py
# encoding: utf-8 """ @author: liaoxingyu @contact: sherlockliao01@gmail.com """ from bisect import bisect_right import torch # FIXME ideally this would be achieved with a CombinedLRScheduler, # separating MultiStepLR with WarmupLR # but the current LRScheduler design doesn't allow it # from .scheduler import Scheduler class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler): def __init__( self, optimizer, milestones, # steps gamma=0.1, warmup_factor=1.0 / 3, warmup_iters=500, warmup_method="linear", last_epoch=-1, ): if not list(milestones) == sorted(milestones): raise ValueError( "Milestones should be a list of" " increasing integers. Got {}", milestones, ) if warmup_method not in ("constant", "linear"): raise ValueError( "Only 'constant' or 'linear' warmup_method accepted" "got {}".format(warmup_method) ) self.milestones = milestones self.gamma = gamma self.warmup_factor = warmup_factor self.warmup_iters = warmup_iters self.warmup_method = warmup_method super(WarmupMultiStepLR, self).__init__(optimizer, last_epoch) def get_lr(self): warmup_factor = 1 if self.last_epoch < self.warmup_iters: if self.warmup_method == "constant": warmup_factor = self.warmup_factor elif self.warmup_method == "linear": alpha = self.last_epoch / self.warmup_iters warmup_factor = self.warmup_factor * (1 - alpha) + alpha # print('learning rate is',[ # base_lr # * warmup_factor # * self.gamma ** bisect_right(self.milestones, self.last_epoch) # for base_lr in self.base_lrs # ]) return [ base_lr * warmup_factor * self.gamma ** bisect_right(self.milestones, self.last_epoch) for base_lr in self.base_lrs ]
2,119
31.615385
80
py
CDTrans
CDTrans-master/solver/cosine_lr.py
""" Cosine Scheduler Cosine LR schedule with warmup, cycle/restarts, noise. Hacked together by / Copyright 2020 Ross Wightman """ import logging import math import torch from .scheduler import Scheduler _logger = logging.getLogger(__name__) class CosineLRScheduler(Scheduler): """ Cosine decay with restarts. This is described in the paper https://arxiv.org/abs/1608.03983. Inspiration from https://github.com/allenai/allennlp/blob/master/allennlp/training/learning_rate_schedulers/cosine.py """ def __init__(self, optimizer: torch.optim.Optimizer, t_initial: int, t_mul: float = 1., lr_min: float = 0., decay_rate: float = 1., warmup_t=0, warmup_lr_init=0, warmup_prefix=False, cycle_limit=0, t_in_epochs=True, noise_range_t=None, noise_pct=0.67, noise_std=1.0, noise_seed=42, initialize=True) -> None: super().__init__( optimizer, param_group_field="lr", noise_range_t=noise_range_t, noise_pct=noise_pct, noise_std=noise_std, noise_seed=noise_seed, initialize=initialize) assert t_initial > 0 assert lr_min >= 0 if t_initial == 1 and t_mul == 1 and decay_rate == 1: _logger.warning("Cosine annealing scheduler will have no effect on the learning " "rate since t_initial = t_mul = eta_mul = 1.") self.t_initial = t_initial self.t_mul = t_mul self.lr_min = lr_min self.decay_rate = decay_rate self.cycle_limit = cycle_limit self.warmup_t = warmup_t self.warmup_lr_init = warmup_lr_init self.warmup_prefix = warmup_prefix self.t_in_epochs = t_in_epochs if self.warmup_t: self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values] super().update_groups(self.warmup_lr_init) else: self.warmup_steps = [1 for _ in self.base_values] def _get_lr(self, t): if t < self.warmup_t: lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps] else: if self.warmup_prefix: t = t - self.warmup_t if self.t_mul != 1: i = math.floor(math.log(1 - t / self.t_initial * (1 - self.t_mul), self.t_mul)) t_i = self.t_mul ** i * self.t_initial t_curr = t - (1 - self.t_mul ** i) / (1 - self.t_mul) * self.t_initial else: i = t // self.t_initial t_i = self.t_initial t_curr = t - (self.t_initial * i) gamma = self.decay_rate ** i lr_min = self.lr_min * gamma lr_max_values = [v * gamma for v in self.base_values] if self.cycle_limit == 0 or (self.cycle_limit > 0 and i < self.cycle_limit): lrs = [ lr_min + 0.5 * (lr_max - lr_min) * (1 + math.cos(math.pi * t_curr / t_i)) for lr_max in lr_max_values ] else: lrs = [self.lr_min for _ in self.base_values] return lrs def get_epoch_values(self, epoch: int): if self.t_in_epochs: return self._get_lr(epoch) else: return None def get_update_values(self, num_updates: int): if not self.t_in_epochs: return self._get_lr(num_updates) else: return None def get_cycle_length(self, cycles=0): if not cycles: cycles = self.cycle_limit cycles = max(1, cycles) if self.t_mul == 1.0: return self.t_initial * cycles else: return int(math.floor(-self.t_initial * (self.t_mul ** cycles - 1) / (1 - self.t_mul)))
3,954
34.3125
121
py
CDTrans
CDTrans-master/solver/scheduler.py
from typing import Dict, Any import torch class Scheduler: """ Parameter Scheduler Base Class A scheduler base class that can be used to schedule any optimizer parameter groups. Unlike the builtin PyTorch schedulers, this is intended to be consistently called * At the END of each epoch, before incrementing the epoch count, to calculate next epoch's value * At the END of each optimizer update, after incrementing the update count, to calculate next update's value The schedulers built on this should try to remain as stateless as possible (for simplicity). This family of schedulers is attempting to avoid the confusion of the meaning of 'last_epoch' and -1 values for special behaviour. All epoch and update counts must be tracked in the training code and explicitly passed in to the schedulers on the corresponding step or step_update call. Based on ideas from: * https://github.com/pytorch/fairseq/tree/master/fairseq/optim/lr_scheduler * https://github.com/allenai/allennlp/tree/master/allennlp/training/learning_rate_schedulers """ def __init__(self, optimizer: torch.optim.Optimizer, param_group_field: str, noise_range_t=None, noise_type='normal', noise_pct=0.67, noise_std=1.0, noise_seed=None, initialize: bool = True) -> None: self.optimizer = optimizer self.param_group_field = param_group_field self._initial_param_group_field = f"initial_{param_group_field}" if initialize: for i, group in enumerate(self.optimizer.param_groups): if param_group_field not in group: raise KeyError(f"{param_group_field} missing from param_groups[{i}]") group.setdefault(self._initial_param_group_field, group[param_group_field]) else: for i, group in enumerate(self.optimizer.param_groups): if self._initial_param_group_field not in group: raise KeyError(f"{self._initial_param_group_field} missing from param_groups[{i}]") self.base_values = [group[self._initial_param_group_field] for group in self.optimizer.param_groups] self.metric = None # any point to having this for all? self.noise_range_t = noise_range_t self.noise_pct = noise_pct self.noise_type = noise_type self.noise_std = noise_std self.noise_seed = noise_seed if noise_seed is not None else 42 self.update_groups(self.base_values) def state_dict(self) -> Dict[str, Any]: return {key: value for key, value in self.__dict__.items() if key != 'optimizer'} def load_state_dict(self, state_dict: Dict[str, Any]) -> None: self.__dict__.update(state_dict) def get_epoch_values(self, epoch: int): return None def get_update_values(self, num_updates: int): return None def step(self, epoch: int, metric: float = None) -> None: self.metric = metric values = self.get_epoch_values(epoch) if values is not None: values = self._add_noise(values, epoch) self.update_groups(values) def step_update(self, num_updates: int, metric: float = None): self.metric = metric values = self.get_update_values(num_updates) if values is not None: values = self._add_noise(values, num_updates) self.update_groups(values) def update_groups(self, values): if not isinstance(values, (list, tuple)): values = [values] * len(self.optimizer.param_groups) for param_group, value in zip(self.optimizer.param_groups, values): param_group[self.param_group_field] = value def _add_noise(self, lrs, t): if self.noise_range_t is not None: if isinstance(self.noise_range_t, (list, tuple)): apply_noise = self.noise_range_t[0] <= t < self.noise_range_t[1] else: apply_noise = t >= self.noise_range_t if apply_noise: g = torch.Generator() g.manual_seed(self.noise_seed + t) if self.noise_type == 'normal': while True: # resample if noise out of percent limit, brute force but shouldn't spin much noise = torch.randn(1, generator=g).item() if abs(noise) < self.noise_pct: break else: noise = 2 * (torch.rand(1, generator=g).item() - 0.5) * self.noise_pct lrs = [v + v * noise for v in lrs] return lrs
4,745
45.990099
112
py
CDTrans
CDTrans-master/solver/make_optimizer.py
import torch def make_optimizer(cfg, model, center_criterion): params = [] for key, value in model.named_parameters(): if not value.requires_grad: continue lr = cfg.SOLVER.BASE_LR weight_decay = cfg.SOLVER.WEIGHT_DECAY if "bias" in key: lr = cfg.SOLVER.BASE_LR * cfg.SOLVER.BIAS_LR_FACTOR weight_decay = cfg.SOLVER.WEIGHT_DECAY_BIAS if cfg.SOLVER.LARGE_FC_LR: if "classifier" in key or "arcface" in key: lr = cfg.SOLVER.BASE_LR * 2 print('Using two times learning rate for fc ') # if 'pos_embed' in key or 'cls_token' in key or 'cam_embed' in key: # print(key, 'key with no weight decay') # weight_decay = 0. params += [{"params": [value], "lr": lr, "weight_decay": weight_decay}] if cfg.SOLVER.OPTIMIZER_NAME == 'SGD': optimizer = getattr(torch.optim, cfg.SOLVER.OPTIMIZER_NAME)(params, momentum=cfg.SOLVER.MOMENTUM) elif cfg.SOLVER.OPTIMIZER_NAME == 'AdamW': optimizer = torch.optim.AdamW(params, lr=cfg.SOLVER.BASE_LR, weight_decay=cfg.SOLVER.WEIGHT_DECAY) else: optimizer = getattr(torch.optim, cfg.SOLVER.OPTIMIZER_NAME)(params) optimizer_center = torch.optim.SGD(center_criterion.parameters(), lr=cfg.SOLVER.CENTER_LR) return optimizer, optimizer_center
1,376
42.03125
106
py
CDTrans
CDTrans-master/processor/processor_uda.py
import logging from typing import OrderedDict import numpy as np import os import time import torch import torch.nn as nn import cv2 from utils.meter import AverageMeter from utils.metrics import R1_mAP, R1_mAP_eval, R1_mAP_Pseudo, R1_mAP_query_mining, R1_mAP_save_feature, R1_mAP_draw_figure, Class_accuracy_eval from utils.reranking import re_ranking, re_ranking_numpy from torch.nn.parallel import DistributedDataParallel from torch.cuda import amp import torch.distributed as dist from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from timm.utils import accuracy from itertools import cycle import os.path as osp import torch.nn.functional as F import random, pdb, math, copy from scipy.spatial.distance import cdist from sklearn.metrics import confusion_matrix import torchvision.transforms as T from datasets.make_dataloader import train_collate_fn, source_target_train_collate_fn from datasets.sampler import RandomIdentitySampler from datasets.bases import ImageDataset from torch.utils.data import DataLoader from tqdm import tqdm from scipy.optimize import linear_sum_assignment from collections import defaultdict def obtain_label(logger, val_loader, model, distance='cosine', threshold=0): device = "cuda" start_test = True print('obtain label') model.eval() for n_iter, (img, vid, _, _, _) in enumerate(tqdm(val_loader)): with torch.no_grad(): img = img.to(device) labels = torch.tensor(vid) probs = model(**dict(x = img, x2 = img, return_feat_prob=True)) outputs, _, feas = probs[1] if start_test: all_fea = feas.float().cpu() all_output = outputs.float().cpu() all_label = labels.float() start_test = False else: all_fea = torch.cat((all_fea, feas.float().cpu()), 0) all_output = torch.cat((all_output, outputs.float().cpu()), 0) all_label = torch.cat((all_label, labels.float()), 0) all_output = nn.Softmax(dim=1)(all_output) _, predict = torch.max(all_output, 1) accuracy = torch.sum(torch.squeeze(predict).float() == all_label).item() / float(all_label.size()[0]) if distance == 'cosine': all_fea = torch.cat((all_fea, torch.ones(all_fea.size(0), 1)), 1) all_fea = (all_fea.t() / torch.norm(all_fea, p=2, dim=1)).t() ### all_fea: extractor feature [bs,N] all_fea = all_fea.float().cpu().numpy() K = all_output.size(1) aff = all_output.float().cpu().numpy() ### aff: softmax output [bs,c] initc = aff.transpose().dot(all_fea) initc = initc / (1e-8 + aff.sum(axis=0)[:, None]) cls_count = np.eye(K)[predict].sum(axis=0) labelset = np.where(cls_count > threshold) labelset = labelset[0] dd = cdist(all_fea, initc[labelset], distance) pred_label = dd.argmin(axis=1) pred_label = labelset[pred_label] acc = np.sum(pred_label == all_label.float().numpy()) / len(all_fea) log_str = 'Fisrt Accuracy = {:.2f}% -> {:.2f}%'.format(accuracy * 100, acc * 100) logger.info(log_str) for round in range(1): aff = np.eye(K)[pred_label] initc = aff.transpose().dot(all_fea) initc = initc / (1e-8 + aff.sum(axis=0)[:, None]) dd = cdist(all_fea, initc[labelset], distance) pred_label = dd.argmin(axis=1) pred_label = labelset[pred_label] acc = np.sum(pred_label == all_label.float().numpy()) / len(all_fea) log_str = 'Second Accuracy = {:.2f}% -> {:.2f}%'.format(accuracy * 100, acc * 100) logger.info(log_str) return pred_label.astype('int') def update_feat(cfg, epoch, model, train_loader1,train_loader2, device,feat_memory1,feat_memory2, label_memory1,label_memory2): model.eval() for n_iter, (img, vid, _, _, idx) in enumerate(tqdm(train_loader1)): with torch.no_grad(): img = img.to(device) feats = model(img, img) feat = feats[1]/(torch.norm(feats[1],2,1,True)+1e-8) feat_memory1[idx] = feat.detach().cpu() label_memory1[idx] = vid for n_iter, (img, vid, _, _, idx) in enumerate(tqdm(train_loader2)): with torch.no_grad(): img = img.to(device) feats = model(img, img) feat = feats[1]/(torch.norm(feats[1],2,1,True)+1e-8) feat_memory2[idx] = feat.detach().cpu() label_memory2[idx] = vid return feat_memory1, feat_memory2, label_memory1, label_memory2 # def filter_knnidx(tensor_x, indexs, threshold): # return torch.where(tensor_x >=threshold, indexs, (-torch.ones(indexs.size())).long() ) def compute_knn_idx(logger, model, train_loader1, train_loader2, feat_memory1, feat_memory2, label_memory1, label_memory2, img_num1, img_num2, target_sample_num=2, topk=1, reliable_threshold=0.0): #assert((torch.sum(feat_memory2,axis=1)!=0).all()) simmat = torch.matmul(feat_memory1,feat_memory2.T) _, knnidx = torch.max(simmat,1) if topk == 1: target_knnsim, target_knnidx = torch.max(simmat, 0) else: target_knnsim, target_knnidx = torch.topk(simmat,dim=0,k=topk) target_knnsim, target_knnidx = target_knnsim[topk-1, :], target_knnidx[topk-1, :] _, knnidx_topk = torch.topk(simmat,k=target_sample_num,dim=1) del simmat count_target_usage(logger, knnidx, label_memory1, label_memory2, img_num1, img_num2) target_label = obtain_label(logger, train_loader2, model) target_label = torch.from_numpy(target_label).cuda() return target_label, knnidx, knnidx_topk, target_knnidx def count_target_usage(logger, idxs, label_memory1, label_memory2, img_num1, img_num2, source_idxs=None): unique_knnidx = torch.unique(idxs) logger.info('target number usage: {}'.format(len(unique_knnidx)/img_num2)) if source_idxs is not None: source_unique_knnidx = torch.unique(source_idxs) logger.info('source number usage: {}'.format(len(source_unique_knnidx)/img_num1)) else: logger.info('source number usage: 100%') per_class_num = torch.bincount(label_memory2) per_class_select_num = torch.bincount(label_memory2[unique_knnidx]) logger.info('target each class usage: {} '.format(per_class_select_num/per_class_num[:len(per_class_select_num)])) if len(per_class_num) != len(per_class_select_num): logger.info('target last {} class usage is 0%'.format(len(per_class_num) - len(per_class_select_num))) target_labels = label_memory2[idxs] if source_idxs is not None: # sample should filter source_labels = label_memory1[source_idxs] else: source_labels = label_memory1 logger.info('match right rate: {}'.format((target_labels==source_labels).int().sum()/len(target_labels))) matrix = confusion_matrix(target_labels, source_labels) acc = matrix.diagonal()/matrix.sum(axis=1) * 100 aa = [str(np.round(i, 2)) for i in acc] logger.info('each target class match right rate: {}'.format(aa)) def generate_new_dataset(cfg, logger, label_memory2, s_dataset, t_dataset, knnidx, target_knnidx, target_pseudo_label, label_memory1, img_num1, img_num2, with_pseudo_label_filter=True): # generate new dataset train_set = [] new_target_knnidx = [] new_targetidx = [] source_dataset = s_dataset.train target_dataset = t_dataset.train # combine_target_sample: for idx, data in enumerate(tqdm(target_dataset)): t_img_path, _, _, _,t_idx = data curidx = target_knnidx[t_idx] if curidx<0: continue source_data = source_dataset[curidx] s_img_path, label, camid, trackid, _ = source_data mask = label == target_pseudo_label[t_idx] if (with_pseudo_label_filter and mask) or not with_pseudo_label_filter: new_targetidx.append(t_idx) new_target_knnidx.append(curidx) train_set.append(((s_img_path, t_img_path), (label, target_pseudo_label[t_idx].item()), camid, trackid, (curidx, t_idx))) logger.info('target match accuracy') count_target_usage(logger, torch.tensor(new_targetidx), label_memory1, label_memory2, img_num1, img_num2, source_idxs=torch.tensor(new_target_knnidx)) # combine_source_sample: new_source_knnidx = [] new_source_idx = [] for idx, data in enumerate(tqdm(source_dataset)): s_img_path, label, camid, trackid,s_idx = data curidx = knnidx[s_idx] if curidx<0:continue target_data = target_dataset[curidx] t_img_path, _, _, _, _ = target_data mask = target_pseudo_label[curidx] == label if (with_pseudo_label_filter and mask) or not with_pseudo_label_filter: new_source_idx.append(s_idx) new_source_knnidx.append(curidx) train_set.append(((s_img_path, t_img_path), (label,target_pseudo_label[curidx].item()), camid, trackid, (s_idx, curidx.item()))) logger.info('source match accuracy') count_target_usage(logger, torch.tensor(new_source_knnidx), label_memory1, label_memory2, img_num1, img_num2, source_idxs=torch.tensor(new_source_idx)) new_target_knnidx = new_target_knnidx + new_source_idx new_targetidx = new_targetidx + new_source_knnidx count_target_usage(logger, torch.tensor(new_targetidx), label_memory1, label_memory2, img_num1, img_num2, source_idxs=torch.tensor(new_target_knnidx)) train_transforms = T.Compose([ T.Resize((256, 256)), T.RandomCrop((224, 224)), T.RandomHorizontalFlip(), T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ]) new_dataset = ImageDataset(train_set, train_transforms) num_workers = cfg.DATALOADER.NUM_WORKERS train_loader = DataLoader( new_dataset, batch_size=cfg.SOLVER.IMS_PER_BATCH, shuffle=True, drop_last = True, num_workers=num_workers, collate_fn=source_target_train_collate_fn, pin_memory=True, persistent_workers=True, ) return train_loader def do_train_uda(cfg, model, center_criterion, train_loader, train_loader1, train_loader2, img_num1, img_num2, val_loader, s_dataset, t_dataset, optimizer, optimizer_center, scheduler, loss_fn, num_query, local_rank): log_period = cfg.SOLVER.LOG_PERIOD checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD eval_period = cfg.SOLVER.EVAL_PERIOD device = "cuda" epochs = cfg.SOLVER.MAX_EPOCHS logger = logging.getLogger("reid_baseline.train") logger.info('start training') _LOCAL_PROCESS_GROUP = None if device: model.to(local_rank) if cfg.MODEL.DIST_TRAIN: print('Using {} GPUs for training'.format(torch.cuda.device_count())) model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank], find_unused_parameters=True) elif torch.cuda.device_count() > 1: model = nn.DataParallel(model).to(device) else: model.to(device) loss1_meter = AverageMeter() loss2_meter = AverageMeter() loss13_meter = AverageMeter() loss3_meter = AverageMeter() acc_meter = AverageMeter() acc_2_meter = AverageMeter() acc_2_pse_meter = AverageMeter() if cfg.MODEL.TASK_TYPE == 'classify_DA': evaluator = Class_accuracy_eval(logger=logger, dataset=cfg.DATASETS.NAMES) else: evaluator = R1_mAP_eval(num_query, max_rank=50, feat_norm=cfg.TEST.FEAT_NORM) scaler = amp.GradScaler() label_memory1 = torch.zeros((img_num1),dtype=torch.long) label_memory2 = torch.zeros((img_num2),dtype=torch.long) if '384' in cfg.MODEL.Transformer_TYPE or 'small' in cfg.MODEL.Transformer_TYPE: feat_memory1 = torch.zeros((img_num1,384),dtype=torch.float32) feat_memory2 = torch.zeros((img_num2,384),dtype=torch.float32) else: feat_memory1 = torch.zeros((img_num1,768),dtype=torch.float32) feat_memory2 = torch.zeros((img_num2,768),dtype=torch.float32) update_epoch = 10 #10 best_model_mAP = 0 min_mean_ent = 1e5 # train for epoch in range(1, epochs + 1): start_time = time.time() loss1_meter.reset() loss2_meter.reset() loss13_meter.reset() loss3_meter.reset() acc_meter.reset() acc_2_meter.reset() acc_2_pse_meter.reset() evaluator.reset() scheduler.step(epoch) if (epoch-1) % update_epoch == 0: feat_memory1, feat_memory2, label_memory1, label_memory2 = update_feat(cfg, epoch, model, train_loader1,train_loader2, device,feat_memory1,feat_memory2, label_memory1,label_memory2) dynamic_top = 1 print('source and target topk==',dynamic_top) target_label, knnidx, knnidx_topk, target_knnidx = compute_knn_idx(logger, model, train_loader1, train_loader2, feat_memory1, feat_memory2, label_memory1, label_memory2, img_num1, img_num2, topk=dynamic_top, reliable_threshold=0.0) del train_loader train_loader = generate_new_dataset(cfg, logger, label_memory2, s_dataset, t_dataset, knnidx, target_knnidx, target_label, label_memory1, img_num1, img_num2, with_pseudo_label_filter = cfg.SOLVER.WITH_PSEUDO_LABEL_FILTER) model.train() for n_iter, (imgs, vid, target_cam, target_view, file_name, idx) in enumerate(train_loader): img = imgs[0].to(device) t_img = imgs[1].to(device) #target img target = vid[0].to(device) t_pseudo_target = vid[1].to(device) s_idx,t_idx = idx label_knn = label_memory2[t_idx].cuda() optimizer.zero_grad() optimizer_center.zero_grad() target_cam = target_cam.to(device) target_view = target_view.to(device) with amp.autocast(enabled=True): def distill_loss(teacher_output, student_out): teacher_out = F.softmax(teacher_output, dim=-1) loss = torch.sum( -teacher_out * F.log_softmax(student_out, dim=-1), dim=-1) return loss.mean() (self_score1, self_feat1, _), (score2, feat2, _), (score_fusion, _, _), aux_data = model(img, t_img, target, cam_label=target_cam, view_label=target_view ) # output: source , target , source_target_fusion loss1 = loss_fn(self_score1, self_feat1, target, target_cam) loss2 = loss_fn(score2, feat2, t_pseudo_target, target_cam) loss3 = distill_loss(score_fusion, score2) loss = loss2 + loss3 + loss1 scaler.scale(loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) scaler.step(optimizer) scaler.update() if 'center' in cfg.MODEL.METRIC_LOSS_TYPE: for param in center_criterion.parameters(): param.grad.data *= (1. / cfg.SOLVER.CENTER_LOSS_WEIGHT) scaler.step(optimizer_center) scaler.update() if isinstance(self_score1, list): acc = (self_score1[0].max(1)[1] == target).float().mean() else: acc = (self_score1.max(1)[1] == target).float().mean() if isinstance(score2, list): acc2 = (score2[0].max(1)[1] == label_knn).float().mean() else: acc2 = (score2.max(1)[1] == label_knn).float().mean() if isinstance(score2, list): acc2_pse = (score2[0].max(1)[1] == t_pseudo_target).float().mean() else: acc2_pse = (score2.max(1)[1] == t_pseudo_target).float().mean() loss1_meter.update(loss1.item(), img.shape[0]) loss2_meter.update(loss2.item(), img.shape[0]) loss3_meter.update(loss3.item(), img.shape[0]) acc_meter.update(acc, 1) acc_2_meter.update(acc2, 1) acc_2_pse_meter.update(acc2_pse, 1) torch.cuda.synchronize() if (n_iter + 1) % log_period == 0: logger.info("Epoch[{}] Iteration[{}/{}] Loss1: {:.3f}, Loss2: {:.3f}, Loss3: {:.3f}, Acc: {:.3f}, Acc2: {:.3f}, Acc2_pse: {:.3f}, Base Lr: {:.2e}" .format(epoch, (n_iter + 1), len(train_loader), loss1_meter.avg, loss2_meter.avg, loss3_meter.avg, acc_meter.avg, acc_2_meter.avg, acc_2_pse_meter.avg, scheduler._get_lr(epoch)[0])) end_time = time.time() time_per_batch = (end_time - start_time) / (n_iter + 1) if cfg.MODEL.DIST_TRAIN: if dist.get_rank() == 0: logger.info("Epoch {} done. Time per batch: {:.3f}[s] Speed: {:.1f}[samples/s]" .format(epoch, time_per_batch, train_loader.batch_size / time_per_batch)) else: logger.info("Epoch {} done. Time per batch: {:.3f}[s] Speed: {:.1f}[samples/s]" .format(epoch, time_per_batch, train_loader.batch_size / time_per_batch)) if epoch % checkpoint_period == 0: if cfg.MODEL.DIST_TRAIN: if dist.get_rank() == 0: torch.save(model.state_dict(), os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_{}.pth'.format(epoch))) else: torch.save(model.state_dict(), os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_{}.pth'.format(epoch))) if epoch % eval_period == 0: if cfg.MODEL.DIST_TRAIN: if dist.get_rank() == 0: model.eval() for n_iter, (img, vid, camid, camids, target_view, _) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) feat = model(img, cam_label=camids, view_label=target_view) evaluator.update((feat, vid, camid)) cmc, mAP, _, _, _, _, _ = evaluator.compute() logger.info("Validation Results - Epoch: {}".format(epoch)) logger.info("mAP: {:.1%}".format(mAP)) for r in [1, 5, 10]: logger.info("CMC curve, Rank-{:<3}:{:.1%}".format(r, cmc[r - 1])) torch.cuda.empty_cache() elif cfg.MODEL.TASK_TYPE == 'classify_DA': model.eval() # evaluate the imgknn and img for n_iter, (img, vid, camid, camids, target_view, idex) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) output_probs = model(img, img, cam_label=camids, view_label=target_view, return_logits=True, cls_embed_specific=False) # try output prob and output_prob2 evaluator.update((output_probs[1], vid)) accuracy, mean_ent = evaluator.compute() if accuracy > best_model_mAP: # if mean_ent <= min_mean_ent: min_mean_ent = mean_ent best_model_mAP = accuracy torch.save(model.state_dict(), os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_best_model.pth')) logger.info("Classify Domain Adapatation Validation Results - Epoch: {}".format(epoch)) logger.info("Accuracy: {:.1%}, best Accuracy: {:.1%}, min Mean_entropy: {:.1}".format(accuracy, best_model_mAP, min_mean_ent)) torch.cuda.empty_cache() else: model.eval() for n_iter, (img, vid, camid, camids, target_view, _) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) feat, feat2 = model(img, img, cam_label=camids, view_label=target_view) evaluator.update((feat2, vid, camid)) cmc, mAP, _, _, _, _, _ = evaluator.compute() if mAP > best_model_mAP: best_model_mAP = mAP torch.save(model.state_dict(), os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_best_model.pth')) logger.info("Validation Results - Epoch: {}".format(epoch)) logger.info("mAP: {:.1%}".format(mAP)) for r in [1, 5, 10]: logger.info("CMC curve, Rank-{:<3}:{:.1%}".format(r, cmc[r - 1])) torch.cuda.empty_cache() # inference print('best model preformance is {}'.format(best_model_mAP)) if torch.cuda.device_count() > 1: model.module.load_param_finetune(os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_best_model.pth')) else: model.load_param_finetune(os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_best_model.pth')) model.eval() evaluator.reset() for n_iter, (img, vid, camid, camids, target_view, _) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) if cfg.MODEL.TASK_TYPE == 'classify_DA': feats = model(img, img, cam_label=camids, view_label=target_view, return_logits=True) evaluator.update((feats[1], vid)) else: feat = model(img, img, cam_label=camids, view_label=target_view, return_logits=True) evaluator.update((feat, vid, camid)) if cfg.MODEL.TASK_TYPE == 'classify_DA': accuracy, _ = evaluator.compute() logger.info("Classify Domain Adapatation Validation Results - Best model") logger.info("Accuracy: {:.1%}".format(accuracy)) else: cmc, mAP, _, _, _, _, _ = evaluator.compute() logger.info("Best Model Validation Results ") logger.info("mAP: {:.1%}".format(mAP)) for r in [1, 5, 10]: logger.info("CMC curve, Rank-{:<3}:{:.1%}".format(r, cmc[r - 1])) def do_inference_uda(cfg, model, val_loader, num_query): device = "cuda" logger = logging.getLogger("reid_baseline.test") logger.info("Enter inferencing") if cfg.MODEL.TASK_TYPE == 'classify_DA': evaluator = Class_accuracy_eval(dataset=cfg.DATASETS.NAMES, logger= logger) elif cfg.TEST.EVAL: evaluator = R1_mAP_eval(num_query, max_rank=50, feat_norm=cfg.TEST.FEAT_NORM) else: evaluator = R1_mAP_draw_figure(cfg, num_query, max_rank=50, feat_norm=True, reranking=cfg.TEST.RE_RANKING) # evaluator = R1_mAP_save_feature(num_query, max_rank=50, feat_norm=cfg.TEST.FEAT_NORM, # reranking=cfg.TEST.RE_RANKING) evaluator.reset() if device: if torch.cuda.device_count() > 1: print('Using {} GPUs for inference'.format(torch.cuda.device_count())) model = nn.DataParallel(model) model.to(device) model.eval() img_path_list = [] for n_iter, (img, vid, camid, camids, target_view, _) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) target = torch.tensor(vid).to(device) if cfg.MODEL.TASK_TYPE == 'classify_DA': probs = model(img, img, cam_label=camids, view_label=target_view, return_logits=True) evaluator.update((probs[1], vid)) else: feat1, feat2 = model(img, img, cam_label=camids, view_label=target_view, return_logits=False) evaluator.update((feat2, vid, camid)) if cfg.TEST.EVAL: if cfg.MODEL.TASK_TYPE == 'classify_DA': accuracy, mean_ent = evaluator.compute() logger.info("Classify Domain Adapatation Validation Results - In the source trained model") logger.info("Accuracy: {:.1%}".format(accuracy)) return else: cmc, mAP, _, _, _, _, _ = evaluator.compute() logger.info("Validation Results ") logger.info("mAP: {:.1%}".format(mAP)) for r in [1, 5, 10]: logger.info("CMC curve, Rank-{:<3}:{:.1%}".format(r, cmc[r - 1])) return cmc[0], cmc[4] else: print('yes begin saving feature') feats, distmats, pids, camids, viewids, img_name_path = evaluator.compute() torch.save(feats, os.path.join(cfg.OUTPUT_DIR, 'features.pth')) np.save(os.path.join(cfg.OUTPUT_DIR, 'distmat.npy'), distmats) np.save(os.path.join(cfg.OUTPUT_DIR, 'label.npy'), pids) np.save(os.path.join(cfg.OUTPUT_DIR, 'camera_label.npy'), camids) np.save(os.path.join(cfg.OUTPUT_DIR, 'image_name.npy'), img_name_path) np.save(os.path.join(cfg.OUTPUT_DIR, 'view_label.npy'), viewids) print('over')
25,813
45.178891
243
py
CDTrans
CDTrans-master/processor/processor.py
import logging import numpy as np import os import time import torch import torch.nn as nn import cv2 from utils.meter import AverageMeter from utils.metrics import R1_mAP, R1_mAP_eval, R1_mAP_Pseudo, R1_mAP_query_mining, R1_mAP_save_feature, R1_mAP_draw_figure, Class_accuracy_eval from torch.nn.parallel import DistributedDataParallel from torch.cuda import amp import torch.distributed as dist from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from timm.utils import accuracy def do_train_pretrain(cfg, model, center_criterion, train_loader, val_loader, optimizer, optimizer_center, scheduler, loss_fn, num_query, local_rank): log_period = cfg.SOLVER.LOG_PERIOD checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD eval_period = cfg.SOLVER.EVAL_PERIOD device = "cuda" epochs = cfg.SOLVER.MAX_EPOCHS logger = logging.getLogger("reid_baseline.train") logger.info('start training') _LOCAL_PROCESS_GROUP = None if device: model.to(local_rank) if torch.cuda.device_count() > 1 and cfg.MODEL.DIST_TRAIN: print('Using {} GPUs for training'.format(torch.cuda.device_count())) model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank], find_unused_parameters=True) loss_meter = AverageMeter() acc_meter = AverageMeter() if cfg.MODEL.TASK_TYPE == 'classify_DA': evaluator = Class_accuracy_eval(dataset=cfg.DATASETS.NAMES, logger=logger) else: evaluator = R1_mAP_eval(num_query, max_rank=50, feat_norm=cfg.TEST.FEAT_NORM) scaler = amp.GradScaler() best_model_mAP = 0 min_mean_ent = 1e5 # train for epoch in range(1, epochs + 1): start_time = time.time() loss_meter.reset() acc_meter.reset() evaluator.reset() scheduler.step(epoch) model.train() for n_iter, (img, vid, target_cam, target_view, _) in enumerate(train_loader): # print('aaaaaa!!!') if(len(img)==1):continue optimizer.zero_grad() optimizer_center.zero_grad() img = img.to(device) target = vid.to(device) target_cam = target_cam.to(device) target_view = target_view.to(device) with amp.autocast(enabled=True): score, feat = model(img, target, cam_label=target_cam, view_label=target_view ) loss = loss_fn(score, feat, target, target_cam) scaler.scale(loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) scaler.step(optimizer) scaler.update() if 'center' in cfg.MODEL.METRIC_LOSS_TYPE: for param in center_criterion.parameters(): param.grad.data *= (1. / cfg.SOLVER.CENTER_LOSS_WEIGHT) scaler.step(optimizer_center) scaler.update() if isinstance(score, list): acc = (score[0].max(1)[1] == target).float().mean() else: acc = (score.max(1)[1] == target).float().mean() loss_meter.update(loss.item(), img.shape[0]) acc_meter.update(acc, 1) torch.cuda.synchronize() if (n_iter + 1) % log_period == 0: logger.info("Epoch[{}] Iteration[{}/{}] Loss: {:.3f}, Acc: {:.3f}, Base Lr: {:.2e}" .format(epoch, (n_iter + 1), len(train_loader), loss_meter.avg, acc_meter.avg, scheduler._get_lr(epoch)[0])) end_time = time.time() time_per_batch = (end_time - start_time) / (n_iter + 1) if cfg.MODEL.DIST_TRAIN: pass else: logger.info("Epoch {} done. Time per batch: {:.3f}[s] Speed: {:.1f}[samples/s]" .format(epoch, time_per_batch, train_loader.batch_size / time_per_batch)) if epoch % checkpoint_period == 0: if cfg.MODEL.DIST_TRAIN: if dist.get_rank() == 0: torch.save(model.state_dict(), os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_{}.pth'.format(epoch))) else: torch.save(model.state_dict(), os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_{}.pth'.format(epoch))) if epoch % eval_period == 0: if cfg.MODEL.DIST_TRAIN: if dist.get_rank() == 0: model.eval() for n_iter, (img, vid, camid, camids, target_view, _) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) feat = model(img, cam_label=camids, view_label=target_view) evaluator.update((feat, vid, camid)) cmc, mAP, _, _, _, _, _ = evaluator.compute() logger.info("Validation Results - Epoch: {}".format(epoch)) logger.info("mAP: {:.1%}".format(mAP)) for r in [1, 5, 10]: logger.info("CMC curve, Rank-{:<3}:{:.1%}".format(r, cmc[r - 1])) torch.cuda.empty_cache() elif cfg.MODEL.TASK_TYPE == 'classify_DA': model.eval() for n_iter, (img, vid, camid, camids, target_view, _) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) output_prob = model(img, cam_label=camids, view_label=target_view, return_logits=True) evaluator.update((output_prob, vid)) accuracy,mean_ent = evaluator.compute() if mean_ent < min_mean_ent: best_model_mAP = accuracy min_mean_ent = mean_ent torch.save(model.state_dict(), os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_best_model.pth')) logger.info("Classify Domain Adapatation Validation Results - Epoch: {}".format(epoch)) logger.info("Accuracy: {:.1%} Mean Entropy: {:.1%}".format(accuracy, mean_ent)) # logger.info("Per-class accuracy: {}".format(acc)) torch.cuda.empty_cache() else: model.eval() for n_iter, (img, vid, camid, camids, target_view, _) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) feat = model(img, cam_label=camids, view_label=target_view) evaluator.update((feat, vid, camid)) cmc, mAP, _, _, _, _, _ = evaluator.compute() logger.info("Validation Results - Epoch: {}".format(epoch)) logger.info("mAP: {:.1%}".format(mAP)) for r in [1, 5, 10]: logger.info("CMC curve, Rank-{:<3}:{:.1%}".format(r, cmc[r - 1])) torch.cuda.empty_cache() # inference model.load_param_finetune(os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_best_model.pth')) model.eval() evaluator.reset() for n_iter, (img, vid, camid, camids, target_view, _) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) feat = model(img, img, cam_label=camids, view_label=target_view, return_logits=True) if cfg.MODEL.TASK_TYPE == 'classify_DA': evaluator.update((feat, vid)) else: evaluator.update((feat, vid, camid)) if cfg.MODEL.TASK_TYPE == 'classify_DA': accuracy,_ = evaluator.compute() logger.info("Classify Domain Adapatation Validation Results - Best Model") logger.info("Accuracy: {:.1%}".format(accuracy)) else: cmc, mAP, _, _, _, _, _ = evaluator.compute() logger.info("Best Model Validation Results ") logger.info("mAP: {:.1%}".format(mAP)) for r in [1, 5, 10]: logger.info("CMC curve, Rank-{:<3}:{:.1%}".format(r, cmc[r - 1])) def do_inference(cfg, model, val_loader, num_query): device = "cuda" logger = logging.getLogger("reid_baseline.test") logger.info("Enter inferencing") if cfg.TEST.EVAL: if cfg.MODEL.TASK_TYPE == 'classify_DA': evaluator = Class_accuracy_eval(dataset=cfg.DATASETS.NAMES, logger= logger) else: evaluator = R1_mAP_eval(num_query, max_rank=50, feat_norm=cfg.TEST.FEAT_NORM) else: evaluator = R1_mAP_draw_figure(cfg, num_query, max_rank=50, feat_norm=True, reranking=cfg.TEST.RE_RANKING) evaluator.reset() if device: if torch.cuda.device_count() > 1: print('Using {} GPUs for inference'.format(torch.cuda.device_count())) model = nn.DataParallel(model) model.to(device) model.eval() img_path_list = [] for n_iter, (img, pid, camid, camids, target_view, imgpath) in enumerate(val_loader): with torch.no_grad(): img = img.to(device) camids = camids.to(device) target_view = target_view.to(device) if cfg.TEST.EVAL: if cfg.MODEL.TASK_TYPE == 'classify_DA': probs = model(img, cam_label=camids, view_label=target_view, return_logits=True) evaluator.update((probs, pid)) else: feat = model(img, cam_label=camids, view_label=target_view) evaluator.update((feat, pid, camid)) else: feat = model(img, cam_label=camids, view_label=target_view) evaluator.update((feat, pid, camid, target_view, imgpath)) img_path_list.extend(imgpath) if cfg.TEST.EVAL: if cfg.MODEL.TASK_TYPE == 'classify_DA': accuracy, mean_ent = evaluator.compute() logger.info("Classify Domain Adapatation Validation Results - In the source trained model") logger.info("Accuracy: {:.1%}".format(accuracy)) return else: cmc, mAP, _, _, _, _, _ = evaluator.compute() logger.info("Validation Results ") logger.info("mAP: {:.1%}".format(mAP)) for r in [1, 5, 10]: logger.info("CMC curve, Rank-{:<3}:{:.1%}".format(r, cmc[r - 1])) return cmc[0], cmc[4] else: print('yes begin saving feature') feats, distmats, pids, camids, viewids, img_name_path = evaluator.compute() torch.save(feats, os.path.join(cfg.OUTPUT_DIR, 'features.pth')) np.save(os.path.join(cfg.OUTPUT_DIR, 'distmat.npy'), distmats) np.save(os.path.join(cfg.OUTPUT_DIR, 'label.npy'), pids) np.save(os.path.join(cfg.OUTPUT_DIR, 'camera_label.npy'), camids) np.save(os.path.join(cfg.OUTPUT_DIR, 'image_name.npy'), img_name_path) np.save(os.path.join(cfg.OUTPUT_DIR, 'view_label.npy'), viewids) print('over')
11,714
43.041353
143
py
CDTrans
CDTrans-master/datasets/make_dataloader.py
# from transformer_normal_DA_v0.datasets.office import Office import torch import torchvision.transforms as T from torch.utils.data import DataLoader from .bases import ImageDataset from .preprocessing import RandomErasing # from timm.data.random_erasing import RandomErasing from .sampler import RandomIdentitySampler from .sampler_ddp import RandomIdentitySampler_DDP import torch.distributed as dist from .ourapi import OURAPI from .office_home import OfficeHome from .visda import VisDA from .domainnet import DomainNet from .office import Office __factory = { 'OURAPI': OURAPI, 'OfficeHome': OfficeHome, 'VisDA': VisDA, 'DomainNet': DomainNet, 'Office': Office, } def train_collate_fn(batch): """ # collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果 """ imgs, pids, camids, viewids , _ , idx= zip(*batch) # print('train collate fn' , imgs) pids = torch.tensor(pids, dtype=torch.int64) viewids = torch.tensor(viewids, dtype=torch.int64) camids = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, viewids, idx def val_collate_fn(batch):##### revised by luo imgs, pids, camids, viewids, img_paths, idx = zip(*batch) viewids = torch.tensor(viewids, dtype=torch.int64) camids_batch = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, camids_batch, viewids, img_paths def source_target_train_collate_fn(batch): """ # collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果 """ b_data = zip(*batch) # print('b_data is {}'.format(b_data)) # if len(b_data) == 8: s_imgs, t_imgs, s_pids, t_pids, camids, viewids , s_file_name, t_file_name , s_idx, t_idx = b_data # print('make dataloader collate_fn {}'.format(pids)) # print(pids) s_pid = torch.tensor(s_pids, dtype=torch.int64) t_pid = torch.tensor(t_pids, dtype=torch.int64) pids = (s_pid, t_pid) file_name = (s_file_name, t_file_name) viewids = torch.tensor(viewids, dtype=torch.int64) camids = torch.tensor(camids, dtype=torch.int64) s_idx = torch.tensor(s_idx, dtype=torch.int64) t_idx = torch.tensor(t_idx, dtype=torch.int64) idx = (s_idx, t_idx) img1 = torch.stack(s_imgs, dim=0) img2 = torch.stack(t_imgs, dim=0) return (img1, img2), pids, camids, viewids, file_name, idx from .autoaugment import AutoAugment def make_dataloader(cfg): train_transforms = T.Compose([ T.Resize((256, 256)), T.RandomCrop((224, 224)), T.RandomHorizontalFlip(), T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) val_transforms = T.Compose([ T.Resize((256, 256)), T.CenterCrop((224, 224)), T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) num_workers = cfg.DATALOADER.NUM_WORKERS dataset = __factory[cfg.DATASETS.NAMES](root_train=cfg.DATASETS.ROOT_TRAIN_DIR,root_val=cfg.DATASETS.ROOT_TEST_DIR, plus_num_id=cfg.DATASETS.PLUS_NUM_ID) train_set = ImageDataset(dataset.train, train_transforms) train_set1 = ImageDataset(dataset.train, val_transforms) train_set_normal = ImageDataset(dataset.train, val_transforms) img_num1 = len(dataset.train) if cfg.MODEL.UDA_STAGE == 'UDA': dataset2 = __factory[cfg.DATASETS.NAMES2](root_train=cfg.DATASETS.ROOT_TRAIN_DIR2,root_val=cfg.DATASETS.ROOT_TEST_DIR, plus_num_id=cfg.DATASETS.PLUS_NUM_ID) train_set2 = ImageDataset(dataset2.train, val_transforms) img_num2 = len(dataset2.train) num_classes = max(dataset.num_train_pids, dataset.num_test_pids) cam_num = dataset.num_train_cams view_num = dataset.num_train_vids if cfg.MODEL.DIST_TRAIN: print('DIST_TRAIN START') mini_batch_size = cfg.SOLVER.IMS_PER_BATCH // dist.get_world_size() data_sampler = RandomIdentitySampler_DDP(dataset.train, cfg.SOLVER.IMS_PER_BATCH, cfg.DATALOADER.NUM_INSTANCE) batch_sampler = torch.utils.data.sampler.BatchSampler(data_sampler, mini_batch_size, True) train_loader = torch.utils.data.DataLoader( train_set, num_workers=num_workers, batch_sampler=batch_sampler, collate_fn=train_collate_fn, pin_memory=True, ) elif cfg.MODEL.UDA_STAGE == 'UDA': train_loader = DataLoader( train_set, batch_size=cfg.SOLVER.IMS_PER_BATCH, sampler=RandomIdentitySampler(dataset.train, cfg.SOLVER.IMS_PER_BATCH, cfg.DATALOADER.NUM_INSTANCE), num_workers=num_workers, collate_fn=train_collate_fn ) train_loader1 = DataLoader( train_set1, batch_size=cfg.TEST.IMS_PER_BATCH, shuffle=False, num_workers=num_workers, collate_fn=train_collate_fn, persistent_workers=True, pin_memory=True, ) train_loader2 = DataLoader( train_set2, batch_size=cfg.TEST.IMS_PER_BATCH, shuffle=False, num_workers=num_workers, collate_fn=train_collate_fn, pin_memory=True, persistent_workers=True, ) else: print('use shuffle sampler strategy') train_loader = DataLoader( train_set, batch_size=cfg.SOLVER.IMS_PER_BATCH, shuffle=True, num_workers=num_workers, collate_fn=train_collate_fn ) if cfg.DATASETS.QUERY_MINING: if cfg.MODEL.TASK_TYPE == 'classify_DA': val_set = ImageDataset(dataset.test, val_transforms) else: val_set = ImageDataset(dataset.query + dataset.query, val_transforms) else: if cfg.MODEL.TASK_TYPE == 'classify_DA': val_set = ImageDataset(dataset.test, val_transforms) else: val_set = ImageDataset(dataset.query + dataset.gallery, val_transforms) val_loader = DataLoader( val_set, batch_size=cfg.TEST.IMS_PER_BATCH, shuffle=False, num_workers=num_workers, collate_fn=val_collate_fn ) train_loader_normal = DataLoader( train_set_normal, batch_size=cfg.TEST.IMS_PER_BATCH, shuffle=False, num_workers=num_workers, collate_fn=val_collate_fn ) if cfg.MODEL.TASK_TYPE == 'classify_DA': if cfg.MODEL.UDA_STAGE == 'UDA': return train_loader, train_loader_normal, val_loader, None, num_classes, cam_num, view_num, train_loader1, train_loader2, img_num1, img_num2, dataset,dataset2 else: return train_loader, train_loader_normal, val_loader, None, num_classes, cam_num, view_num else: return train_loader, train_loader_normal, val_loader, len(dataset.query), num_classes, cam_num, view_num def make_dataloader_Pseudo(cfg): train_transforms = T.Compose([ T.Resize(cfg.INPUT.SIZE_TRAIN), T.RandomHorizontalFlip(p=cfg.INPUT.PROB), T.Pad(cfg.INPUT.PADDING), T.RandomCrop(cfg.INPUT.SIZE_TRAIN), T.ToTensor(), T.Normalize(mean=cfg.INPUT.PIXEL_MEAN, std=cfg.INPUT.PIXEL_STD), RandomErasing(probability=cfg.INPUT.RE_PROB, mean=cfg.INPUT.PIXEL_MEAN) ]) val_transforms = T.Compose([ T.Resize(cfg.INPUT.SIZE_TEST), T.ToTensor(), T.Normalize(mean=cfg.INPUT.PIXEL_MEAN, std=cfg.INPUT.PIXEL_STD) ]) print('using size :{} for training'.format(cfg.INPUT.SIZE_TRAIN)) num_workers = cfg.DATALOADER.NUM_WORKERS dataset = __factory[cfg.DATASETS.NAMES](root=cfg.DATASETS.ROOT_DIR,plus_num_id=cfg.DATASETS.PLUS_NUM_ID) num_classes = dataset.num_train_pids train_set = ImageDataset(dataset.train, train_transforms) if 'triplet' in cfg.DATALOADER.SAMPLER: train_loader = DataLoader( train_set, batch_size=cfg.SOLVER.IMS_PER_BATCH, sampler=RandomIdentitySampler(dataset.train, cfg.SOLVER.IMS_PER_BATCH, cfg.DATALOADER.NUM_INSTANCE), num_workers=num_workers, collate_fn=train_collate_fn ) elif cfg.DATALOADER.SAMPLER == 'softmax': print('using softmax sampler') train_loader = DataLoader( train_set, batch_size=cfg.SOLVER.IMS_PER_BATCH, shuffle=True, num_workers=num_workers, collate_fn=train_collate_fn ) else: print('unsupported sampler! expected softmax or triplet but got {}'.format(cfg.SAMPLER)) val_set = ImageDataset(dataset.query + dataset.gallery, val_transforms) val_loader = DataLoader( val_set, batch_size=cfg.TEST.IMS_PER_BATCH, shuffle=False, num_workers=num_workers, collate_fn=val_collate_fn ) return train_loader, val_loader, len(dataset.query), num_classes, dataset, train_set, train_transforms
8,793
39.525346
170
py
CDTrans
CDTrans-master/datasets/sampler.py
from torch.utils.data.sampler import Sampler from collections import defaultdict import copy import random import numpy as np class RandomIdentitySampler(Sampler): """ Randomly sample N identities, then for each identity, randomly sample K instances, therefore batch size is N*K. Args: - data_source (list): list of (img_path, pid, camid). - num_instances (int): number of instances per identity in a batch. - batch_size (int): number of examples in a batch. """ def __init__(self, data_source, batch_size, num_instances): self.data_source = data_source self.batch_size = batch_size self.num_instances = num_instances self.num_pids_per_batch = self.batch_size // self.num_instances self.index_dic = defaultdict(list) #dict with list value #{783: [0, 5, 116, 876, 1554, 2041],...,} for index, (_, pid, _, _, _) in enumerate(self.data_source): if isinstance(pid, tuple): pid = pid[1] self.index_dic[pid].append(index) self.pids = list(self.index_dic.keys()) # print('self.pids', self.pids) # estimate number of examples in an epoch self.length = 0 for pid in self.pids: idxs = self.index_dic[pid] num = len(idxs) if num < self.num_instances: num = self.num_instances self.length += num - num % self.num_instances def __iter__(self): batch_idxs_dict = defaultdict(list) for pid in self.pids: idxs = copy.deepcopy(self.index_dic[pid]) if len(idxs) < self.num_instances: idxs = np.random.choice(idxs, size=self.num_instances, replace=True) random.shuffle(idxs) batch_idxs = [] for idx in idxs: batch_idxs.append(idx) if len(batch_idxs) == self.num_instances: batch_idxs_dict[pid].append(batch_idxs) batch_idxs = [] avai_pids = copy.deepcopy(self.pids) final_idxs = [] while len(avai_pids) >= self.num_pids_per_batch: selected_pids = random.sample(avai_pids, self.num_pids_per_batch) for pid in selected_pids: batch_idxs = batch_idxs_dict[pid].pop(0) final_idxs.extend(batch_idxs) if len(batch_idxs_dict[pid]) == 0: avai_pids.remove(pid) return iter(final_idxs) def __len__(self): return self.length
2,543
35.342857
84
py
CDTrans
CDTrans-master/datasets/sampler_ddp.py
from torch.utils.data.sampler import Sampler from collections import defaultdict import copy import random import numpy as np import math import torch.distributed as dist _LOCAL_PROCESS_GROUP = None import torch import pickle def _get_global_gloo_group(): """ Return a process group based on gloo backend, containing all the ranks The result is cached. """ if dist.get_backend() == "nccl": return dist.new_group(backend="gloo") else: return dist.group.WORLD def _serialize_to_tensor(data, group): backend = dist.get_backend(group) assert backend in ["gloo", "nccl"] device = torch.device("cpu" if backend == "gloo" else "cuda") buffer = pickle.dumps(data) if len(buffer) > 1024 ** 3: print( "Rank {} trying to all-gather {:.2f} GB of data on device {}".format( dist.get_rank(), len(buffer) / (1024 ** 3), device ) ) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to(device=device) return tensor def _pad_to_largest_tensor(tensor, group): """ Returns: list[int]: size of the tensor, on each rank Tensor: padded tensor that has the max size """ world_size = dist.get_world_size(group=group) assert ( world_size >= 1 ), "comm.gather/all_gather must be called from ranks within the given group!" local_size = torch.tensor([tensor.numel()], dtype=torch.int64, device=tensor.device) size_list = [ torch.zeros([1], dtype=torch.int64, device=tensor.device) for _ in range(world_size) ] dist.all_gather(size_list, local_size, group=group) size_list = [int(size.item()) for size in size_list] max_size = max(size_list) # we pad the tensor because torch all_gather does not support # gathering tensors of different shapes if local_size != max_size: padding = torch.zeros((max_size - local_size,), dtype=torch.uint8, device=tensor.device) tensor = torch.cat((tensor, padding), dim=0) return size_list, tensor def all_gather(data, group=None): """ Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: list of data gathered from each rank """ if dist.get_world_size() == 1: return [data] if group is None: group = _get_global_gloo_group() if dist.get_world_size(group) == 1: return [data] tensor = _serialize_to_tensor(data, group) size_list, tensor = _pad_to_largest_tensor(tensor, group) max_size = max(size_list) # receiving Tensor from all ranks tensor_list = [ torch.empty((max_size,), dtype=torch.uint8, device=tensor.device) for _ in size_list ] dist.all_gather(tensor_list, tensor, group=group) data_list = [] for size, tensor in zip(size_list, tensor_list): buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer)) return data_list def shared_random_seed(): """ Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock. """ ints = np.random.randint(2 ** 31) all_ints = all_gather(ints) return all_ints[0] class RandomIdentitySampler_DDP(Sampler): """ Randomly sample N identities, then for each identity, randomly sample K instances, therefore batch size is N*K. Args: - data_source (list): list of (img_path, pid, camid). - num_instances (int): number of instances per identity in a batch. - batch_size (int): number of examples in a batch. """ def __init__(self, data_source, batch_size, num_instances): self.data_source = data_source self.batch_size = batch_size self.world_size = dist.get_world_size() self.num_instances = num_instances self.mini_batch_size = self.batch_size // self.world_size self.num_pids_per_batch = self.mini_batch_size // self.num_instances self.index_dic = defaultdict(list) for index, (_, pid, _, _) in enumerate(self.data_source): self.index_dic[pid].append(index) self.pids = list(self.index_dic.keys()) # estimate number of examples in an epoch self.length = 0 for pid in self.pids: idxs = self.index_dic[pid] num = len(idxs) if num < self.num_instances: num = self.num_instances self.length += num - num % self.num_instances self.rank = dist.get_rank() #self.world_size = dist.get_world_size() self.length //= self.world_size def __iter__(self): seed = shared_random_seed() np.random.seed(seed) self._seed = int(seed) final_idxs = self.sample_list() length = int(math.ceil(len(final_idxs) * 1.0 / self.world_size)) #final_idxs = final_idxs[self.rank * length:(self.rank + 1) * length] final_idxs = self.__fetch_current_node_idxs(final_idxs, length) self.length = len(final_idxs) return iter(final_idxs) def __fetch_current_node_idxs(self, final_idxs, length): total_num = len(final_idxs) block_num = (length // self.mini_batch_size) index_target = [] for i in range(0, block_num * self.world_size, self.world_size): index = range(self.mini_batch_size * self.rank + self.mini_batch_size * i, min(self.mini_batch_size * self.rank + self.mini_batch_size * (i+1), total_num)) index_target.extend(index) index_target_npy = np.array(index_target) final_idxs = list(np.array(final_idxs)[index_target_npy]) return final_idxs def sample_list(self): #np.random.seed(self._seed) avai_pids = copy.deepcopy(self.pids) batch_idxs_dict = {} batch_indices = [] while len(avai_pids) >= self.num_pids_per_batch: selected_pids = np.random.choice(avai_pids, self.num_pids_per_batch, replace=False).tolist() for pid in selected_pids: if pid not in batch_idxs_dict: idxs = copy.deepcopy(self.index_dic[pid]) if len(idxs) < self.num_instances: idxs = np.random.choice(idxs, size=self.num_instances, replace=True).tolist() np.random.shuffle(idxs) batch_idxs_dict[pid] = idxs avai_idxs = batch_idxs_dict[pid] for _ in range(self.num_instances): batch_indices.append(avai_idxs.pop(0)) if len(avai_idxs) < self.num_instances: avai_pids.remove(pid) return batch_indices def __len__(self): return self.length
7,051
34.616162
167
py
CDTrans
CDTrans-master/datasets/bases.py
from PIL import Image, ImageFile from torch.utils.data import Dataset import os.path as osp ImageFile.LOAD_TRUNCATED_IMAGES = True def read_image(img_path): """Keep reading image until succeed. This can avoid IOError incurred by heavy IO process.""" got_img = False if not osp.exists(img_path): raise IOError("{} does not exist".format(img_path)) while not got_img: try: img = Image.open(img_path).convert('RGB') got_img = True except IOError: print("IOError incurred when reading '{}'. Will redo. Don't worry. Just chill.".format(img_path)) pass return img class BaseDataset(object): """ Base class of reid dataset """ ##### revised by luo def get_imagedata_info(self, data): pids, cams, tracks = [], [], [] for _, pid, camid, trackid, _ in data: pids += [pid] cams += [camid] tracks += [trackid] pids = set(pids) cams = set(cams) tracks = set(tracks) num_pids = len(pids) num_cams = len(cams) num_imgs = len(data) num_views = len(tracks) return num_pids, num_imgs, num_cams, num_views def print_dataset_statistics(self): raise NotImplementedError class BaseImageDataset(BaseDataset): """ Base class of image reid dataset """ def print_dataset_statistics(self, train, query, gallery): num_train_pids, num_train_imgs, num_train_cams, num_train_views = self.get_imagedata_info(train) num_query_pids, num_query_imgs, num_query_cams, num_train_views = self.get_imagedata_info(query) num_gallery_pids, num_gallery_imgs, num_gallery_cams, num_train_views = self.get_imagedata_info(gallery) print("Dataset statistics:") print(" ----------------------------------------") print(" subset | # ids | # images | # cameras") print(" ----------------------------------------") print(" train | {:5d} | {:8d} | {:9d}".format(num_train_pids, num_train_imgs, num_train_cams)) print(" query | {:5d} | {:8d} | {:9d}".format(num_query_pids, num_query_imgs, num_query_cams)) print(" gallery | {:5d} | {:8d} | {:9d}".format(num_gallery_pids, num_gallery_imgs, num_gallery_cams)) print(" ----------------------------------------") class ImageDataset(Dataset): def __init__(self, dataset, transform=None): self.dataset = dataset self.transform = transform def __len__(self): return len(self.dataset) def __getitem__(self, index): img_path, pid, camid,trackid, idx = self.dataset[index] if isinstance(img_path,tuple): all_imgs = [] all_imgs_path = [] for i_path in img_path: i_img = read_image(i_path) if self.transform is not None: i_img = self.transform(i_img) all_imgs.append(i_img) all_imgs_path.append(i_path) # all_imgs_path.append(i_path.split('/')[-1]) img = tuple(all_imgs) # print('data base pid ',pid) if isinstance(pid, tuple): if isinstance(idx, tuple): return img + pid + (camid, trackid)+ tuple(all_imgs_path)+ idx else: return img + pid + (camid, trackid, tuple(all_imgs_path), idx) else: return img + (pid, camid, trackid, tuple(all_imgs_path), idx) else: img = read_image(img_path) if self.transform is not None: img = self.transform(img) return img, pid, camid, trackid, img_path.split('/')[-1],idx
3,770
34.575472
112
py
CDTrans
CDTrans-master/loss/metric_learning.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.autograd from torch.nn import Parameter import math class ContrastiveLoss(nn.Module): def __init__(self, margin=0.3, **kwargs): super(ContrastiveLoss, self).__init__() self.margin = margin def forward(self, inputs, targets): n = inputs.size(0) # Compute similarity matrix sim_mat = torch.matmul(inputs, inputs.t()) targets = targets loss = list() c = 0 for i in range(n): pos_pair_ = torch.masked_select(sim_mat[i], targets == targets[i]) # move itself pos_pair_ = torch.masked_select(pos_pair_, pos_pair_ < 1) neg_pair_ = torch.masked_select(sim_mat[i], targets != targets[i]) pos_pair_ = torch.sort(pos_pair_)[0] neg_pair_ = torch.sort(neg_pair_)[0] neg_pair = torch.masked_select(neg_pair_, neg_pair_ > self.margin) neg_loss = 0 pos_loss = torch.sum(-pos_pair_ + 1) if len(neg_pair) > 0: neg_loss = torch.sum(neg_pair) loss.append(pos_loss + neg_loss) loss = sum(loss) / n return loss class CircleLoss(nn.Module): def __init__(self, in_features, num_classes, s=256, m=0.25): super(CircleLoss, self).__init__() self.weight = Parameter(torch.Tensor(num_classes, in_features)) self.s = s self.m = m self._num_classes = num_classes self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) def __call__(self, bn_feat, targets): sim_mat = F.linear(F.normalize(bn_feat), F.normalize(self.weight)) alpha_p = torch.clamp_min(-sim_mat.detach() + 1 + self.m, min=0.) alpha_n = torch.clamp_min(sim_mat.detach() + self.m, min=0.) delta_p = 1 - self.m delta_n = self.m s_p = self.s * alpha_p * (sim_mat - delta_p) s_n = self.s * alpha_n * (sim_mat - delta_n) targets = F.one_hot(targets, num_classes=self._num_classes) pred_class_logits = targets * s_p + (1.0 - targets) * s_n return pred_class_logits class Arcface(nn.Module): r"""Implement of large margin arc distance: : Args: in_features: size of each input sample out_features: size of each output sample s: norm of input feature m: margin cos(theta + m) """ def __init__(self, in_features, out_features, s=30.0, m=0.30, easy_margin=False, ls_eps=0.0): super(Arcface, self).__init__() self.in_features = in_features self.out_features = out_features self.s = s self.m = m self.ls_eps = ls_eps # label smoothing self.weight = Parameter(torch.FloatTensor(out_features, in_features)) nn.init.xavier_uniform_(self.weight) self.easy_margin = easy_margin self.cos_m = math.cos(m) self.sin_m = math.sin(m) self.th = math.cos(math.pi - m) self.mm = math.sin(math.pi - m) * m def forward(self, input, label): # --------------------------- cos(theta) & phi(theta) --------------------------- cosine = F.linear(F.normalize(input), F.normalize(self.weight)) sine = torch.sqrt(1.0 - torch.pow(cosine, 2)) phi = cosine * self.cos_m - sine * self.sin_m phi = phi.type_as(cosine) if self.easy_margin: phi = torch.where(cosine > 0, phi, cosine) else: phi = torch.where(cosine > self.th, phi, cosine - self.mm) # --------------------------- convert label to one-hot --------------------------- # one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda') one_hot = torch.zeros(cosine.size(), device='cuda') one_hot.scatter_(1, label.view(-1, 1).long(), 1) if self.ls_eps > 0: one_hot = (1 - self.ls_eps) * one_hot + self.ls_eps / self.out_features # -------------torch.where(out_i = {x_i if condition_i else y_i) ------------- output = (one_hot * phi) + ((1.0 - one_hot) * cosine) output *= self.s return output class Cosface(nn.Module): r"""Implement of large margin cosine distance: : Args: in_features: size of each input sample out_features: size of each output sample s: norm of input feature m: margin cos(theta) - m """ def __init__(self, in_features, out_features, s=30.0, m=0.30): super(Cosface, self).__init__() self.in_features = in_features self.out_features = out_features self.s = s self.m = m self.weight = Parameter(torch.FloatTensor(out_features, in_features)) nn.init.xavier_uniform_(self.weight) def forward(self, input, label): # --------------------------- cos(theta) & phi(theta) --------------------------- cosine = F.linear(F.normalize(input), F.normalize(self.weight)) phi = cosine - self.m # --------------------------- convert label to one-hot --------------------------- one_hot = torch.zeros(cosine.size(), device='cuda') # one_hot = one_hot.cuda() if cosine.is_cuda else one_hot one_hot.scatter_(1, label.view(-1, 1).long(), 1) # -------------torch.where(out_i = {x_i if condition_i else y_i) ------------- output = (one_hot * phi) + ((1.0 - one_hot) * cosine) # you can use torch.where if your torch.__version__ is 0.4 output *= self.s # print(output) return output def __repr__(self): return self.__class__.__name__ + '(' \ + 'in_features=' + str(self.in_features) \ + ', out_features=' + str(self.out_features) \ + ', s=' + str(self.s) \ + ', m=' + str(self.m) + ')' class AMSoftmax(nn.Module): def __init__(self, in_features, out_features, s=30.0, m=0.30): super(AMSoftmax, self).__init__() self.m = m self.s = s self.in_feats = in_features self.W = torch.nn.Parameter(torch.randn(in_features, out_features), requires_grad=True) self.ce = nn.CrossEntropyLoss() nn.init.xavier_normal_(self.W, gain=1) def forward(self, x, lb): assert x.size()[0] == lb.size()[0] assert x.size()[1] == self.in_feats x_norm = torch.norm(x, p=2, dim=1, keepdim=True).clamp(min=1e-12) x_norm = torch.div(x, x_norm) w_norm = torch.norm(self.W, p=2, dim=0, keepdim=True).clamp(min=1e-12) w_norm = torch.div(self.W, w_norm) costh = torch.mm(x_norm, w_norm) # print(x_norm.shape, w_norm.shape, costh.shape) lb_view = lb.view(-1, 1) delt_costh = torch.zeros(costh.size(), device='cuda').scatter_(1, lb_view, self.m) costh_m = costh - delt_costh costh_m_s = self.s * costh_m return costh_m_s
7,001
36.047619
121
py
CDTrans
CDTrans-master/loss/softmax_loss.py
import torch import torch.nn as nn class CrossEntropyLabelSmooth(nn.Module): """Cross entropy loss with label smoothing regularizer. Reference: Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016. Equation: y = (1 - epsilon) * y + epsilon / K. Args: num_classes (int): number of classes. epsilon (float): weight. """ def __init__(self, num_classes, epsilon=0.1, use_gpu=True): super(CrossEntropyLabelSmooth, self).__init__() self.num_classes = num_classes self.epsilon = epsilon self.use_gpu = use_gpu self.logsoftmax = nn.LogSoftmax(dim=1) def forward(self, inputs, targets): """ Args: inputs: prediction matrix (before softmax) with shape (batch_size, num_classes) targets: ground truth labels with shape (num_classes) """ log_probs = self.logsoftmax(inputs) targets = torch.zeros(log_probs.size()).scatter_(1, targets.unsqueeze(1).data.cpu(), 1) if self.use_gpu: targets = targets.cuda() targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes loss = (- targets * log_probs).mean(0).sum() return loss
1,241
35.529412
95
py
CDTrans
CDTrans-master/loss/mmd_loss.py
import torch import torch.nn as nn class MMD_loss(nn.Module): def __init__(self, kernel_mul = 2.0, kernel_num = 5): super(MMD_loss, self).__init__() self.kernel_num = kernel_num self.kernel_mul = kernel_mul self.fix_sigma = None return def guassian_kernel(self, source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None): n_samples = int(source.size()[0])+int(target.size()[0]) total = torch.cat([source, target], dim=0) total0 = total.unsqueeze(0).expand(int(total.size(0)), int(total.size(0)), int(total.size(1))) total1 = total.unsqueeze(1).expand(int(total.size(0)), int(total.size(0)), int(total.size(1))) L2_distance = ((total0-total1)**2).sum(2) if fix_sigma: bandwidth = fix_sigma else: bandwidth = torch.sum(L2_distance.data) / (n_samples**2-n_samples) bandwidth /= kernel_mul ** (kernel_num // 2) bandwidth_list = [bandwidth * (kernel_mul**i) for i in range(kernel_num)] kernel_val = [torch.exp(-L2_distance / bandwidth_temp) for bandwidth_temp in bandwidth_list] return sum(kernel_val) def forward(self, source, target): batch_size = int(source.size()[0]) kernels = self.guassian_kernel(source, target, kernel_mul=self.kernel_mul, kernel_num=self.kernel_num, fix_sigma=self.fix_sigma) XX = kernels[:batch_size, :batch_size] YY = kernels[batch_size:, batch_size:] XY = kernels[:batch_size, batch_size:] YX = kernels[batch_size:, :batch_size] loss = torch.mean(XX + YY - XY -YX) return loss
1,636
43.243243
136
py
CDTrans
CDTrans-master/loss/triplet_loss.py
import torch from torch import nn def normalize(x, axis=-1): """Normalizing to unit length along the specified dimension. Args: x: pytorch Variable Returns: x: pytorch Variable, same shape as input """ x = 1. * x / (torch.norm(x, 2, axis, keepdim=True).expand_as(x) + 1e-12) return x def euclidean_dist(x, y): """ Args: x: pytorch Variable, with shape [m, d] y: pytorch Variable, with shape [n, d] Returns: dist: pytorch Variable, with shape [m, n] """ m, n = x.size(0), y.size(0) xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t() dist = xx + yy dist = dist - 2 * torch.matmul(x, y.t()) # dist.addmm_(1, -2, x, y.t()) dist = dist.clamp(min=1e-12).sqrt() # for numerical stability return dist def cosine_dist(x, y): """ Args: x: pytorch Variable, with shape [m, d] y: pytorch Variable, with shape [n, d] Returns: dist: pytorch Variable, with shape [m, n] """ m, n = x.size(0), y.size(0) x_norm = torch.pow(x, 2).sum(1, keepdim=True).sqrt().expand(m, n) y_norm = torch.pow(y, 2).sum(1, keepdim=True).sqrt().expand(n, m).t() xy_intersection = torch.mm(x, y.t()) dist = xy_intersection/(x_norm * y_norm) dist = (1. - dist) / 2 return dist def hard_example_mining(dist_mat, labels, return_inds=False): """For each anchor, find the hardest positive and negative sample. Args: dist_mat: pytorch Variable, pair wise distance between samples, shape [N, N] labels: pytorch LongTensor, with shape [N] return_inds: whether to return the indices. Save time if `False`(?) Returns: dist_ap: pytorch Variable, distance(anchor, positive); shape [N] dist_an: pytorch Variable, distance(anchor, negative); shape [N] p_inds: pytorch LongTensor, with shape [N]; indices of selected hard positive samples; 0 <= p_inds[i] <= N - 1 n_inds: pytorch LongTensor, with shape [N]; indices of selected hard negative samples; 0 <= n_inds[i] <= N - 1 NOTE: Only consider the case in which all labels have same num of samples, thus we can cope with all anchors in parallel. """ assert len(dist_mat.size()) == 2 assert dist_mat.size(0) == dist_mat.size(1) N = dist_mat.size(0) # shape [N, N] is_pos = labels.expand(N, N).eq(labels.expand(N, N).t()) is_neg = labels.expand(N, N).ne(labels.expand(N, N).t()) # `dist_ap` means distance(anchor, positive) # both `dist_ap` and `relative_p_inds` with shape [N, 1] dist_ap, relative_p_inds = torch.max( dist_mat[is_pos].contiguous().view(N, -1), 1, keepdim=True) # print(dist_mat[is_pos].shape) # `dist_an` means distance(anchor, negative) # both `dist_an` and `relative_n_inds` with shape [N, 1] dist_an, relative_n_inds = torch.min( dist_mat[is_neg].contiguous().view(N, -1), 1, keepdim=True) # shape [N] dist_ap = dist_ap.squeeze(1) dist_an = dist_an.squeeze(1) if return_inds: # shape [N, N] ind = (labels.new().resize_as_(labels) .copy_(torch.arange(0, N).long()) .unsqueeze(0).expand(N, N)) # shape [N, 1] p_inds = torch.gather( ind[is_pos].contiguous().view(N, -1), 1, relative_p_inds.data) n_inds = torch.gather( ind[is_neg].contiguous().view(N, -1), 1, relative_n_inds.data) # shape [N] p_inds = p_inds.squeeze(1) n_inds = n_inds.squeeze(1) return dist_ap, dist_an, p_inds, n_inds return dist_ap, dist_an class TripletLoss(object): """ Triplet loss using HARDER example mining, modified based on original triplet loss using hard example mining """ def __init__(self, margin=None, hard_factor=0.0): self.margin = margin self.hard_factor = hard_factor if margin is not None: self.ranking_loss = nn.MarginRankingLoss(margin=margin) else: self.ranking_loss = nn.SoftMarginLoss() def __call__(self, global_feat, labels, normalize_feature=False): if normalize_feature: global_feat = normalize(global_feat, axis=-1) dist_mat = euclidean_dist(global_feat, global_feat) dist_ap, dist_an = hard_example_mining(dist_mat, labels) dist_ap *= (1.0 + self.hard_factor) dist_an *= (1.0 - self.hard_factor) y = dist_an.new().resize_as_(dist_an).fill_(1) if self.margin is not None: loss = self.ranking_loss(dist_an, dist_ap, y) else: loss = self.ranking_loss(dist_an - dist_ap, y) return loss, dist_ap, dist_an
4,748
33.413043
82
py
CDTrans
CDTrans-master/loss/arcface.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter import math class ArcFace(nn.Module): def __init__(self, in_features, out_features, s=30.0, m=0.50, bias=False): super(ArcFace, self).__init__() self.in_features = in_features self.out_features = out_features self.s = s self.m = m self.cos_m = math.cos(m) self.sin_m = math.sin(m) self.th = math.cos(math.pi - m) self.mm = math.sin(math.pi - m) * m self.weight = Parameter(torch.Tensor(out_features, in_features)) if bias: self.bias = Parameter(torch.Tensor(out_features)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def forward(self, input, label): cosine = F.linear(F.normalize(input), F.normalize(self.weight)) sine = torch.sqrt((1.0 - torch.pow(cosine, 2)).clamp(0, 1)) phi = cosine * self.cos_m - sine * self.sin_m phi = torch.where(cosine > self.th, phi, cosine - self.mm) # --------------------------- convert label to one-hot --------------------------- # one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda') one_hot = torch.zeros(cosine.size(), device='cuda') one_hot.scatter_(1, label.view(-1, 1).long(), 1) # -------------torch.where(out_i = {x_i if condition_i else y_i) ------------- output = (one_hot * phi) + ( (1.0 - one_hot) * cosine) # you can use torch.where if your torch.__version__ is 0.4 output *= self.s # print(output) return output class CircleLoss(nn.Module): def __init__(self, in_features, num_classes, s=256, m=0.25): super(CircleLoss, self).__init__() self.weight = Parameter(torch.Tensor(num_classes, in_features)) self.s = s self.m = m self._num_classes = num_classes self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) def __call__(self, bn_feat, targets): sim_mat = F.linear(F.normalize(bn_feat), F.normalize(self.weight)) alpha_p = torch.clamp_min(-sim_mat.detach() + 1 + self.m, min=0.) alpha_n = torch.clamp_min(sim_mat.detach() + self.m, min=0.) delta_p = 1 - self.m delta_n = self.m s_p = self.s * alpha_p * (sim_mat - delta_p) s_n = self.s * alpha_n * (sim_mat - delta_n) targets = F.one_hot(targets, num_classes=self._num_classes) pred_class_logits = targets * s_p + (1.0 - targets) * s_n return pred_class_logits
2,975
36.2
105
py
CDTrans
CDTrans-master/loss/center_loss.py
from __future__ import absolute_import import torch from torch import nn class CenterLoss(nn.Module): """Center loss. Reference: Wen et al. A Discriminative Feature Learning Approach for Deep Face Recognition. ECCV 2016. Args: num_classes (int): number of classes. feat_dim (int): feature dimension. """ def __init__(self, num_classes=751, feat_dim=2048, use_gpu=True): super(CenterLoss, self).__init__() self.num_classes = num_classes self.feat_dim = feat_dim self.use_gpu = use_gpu if self.use_gpu: self.centers = nn.Parameter(torch.randn(self.num_classes, self.feat_dim).cuda()) else: self.centers = nn.Parameter(torch.randn(self.num_classes, self.feat_dim)) def forward(self, x, labels): """ Args: x: feature matrix with shape (batch_size, feat_dim). labels: ground truth labels with shape (num_classes). """ assert x.size(0) == labels.size(0), "features.size(0) is not equal to labels.size(0)" batch_size = x.size(0) distmat = torch.pow(x, 2).sum(dim=1, keepdim=True).expand(batch_size, self.num_classes) + \ torch.pow(self.centers, 2).sum(dim=1, keepdim=True).expand(self.num_classes, batch_size).t() distmat.addmm_(1, -2, x, self.centers.t()) classes = torch.arange(self.num_classes).long() if self.use_gpu: classes = classes.cuda() labels = labels.unsqueeze(1).expand(batch_size, self.num_classes) mask = labels.eq(classes.expand(batch_size, self.num_classes)) dist = [] for i in range(batch_size): value = distmat[i][mask[i]] value = value.clamp(min=1e-12, max=1e+12) # for numerical stability dist.append(value) dist = torch.cat(dist) loss = dist.mean() return loss if __name__ == '__main__': use_gpu = False center_loss = CenterLoss(use_gpu=use_gpu) features = torch.rand(16, 2048) targets = torch.Tensor([0, 1, 2, 3, 2, 3, 1, 4, 5, 3, 2, 1, 0, 0, 5, 4]).long() if use_gpu: features = torch.rand(16, 2048).cuda() targets = torch.Tensor([0, 1, 2, 3, 2, 3, 1, 4, 5, 3, 2, 1, 0, 0, 5, 4]).cuda() loss = center_loss(features, targets) print(loss)
2,335
33.352941
110
py
CDTrans
CDTrans-master/loss/make_loss.py
# encoding: utf-8 """ @author: liaoxingyu @contact: sherlockliao01@gmail.com """ import torch import torch.nn.functional as F from .softmax_loss import CrossEntropyLabelSmooth from .triplet_loss import TripletLoss from .center_loss import CenterLoss from .mmd_loss import MMD_loss def make_loss(cfg, num_classes): sampler = cfg.DATALOADER.SAMPLER feat_dim = 2048 center_criterion = CenterLoss(num_classes=num_classes, feat_dim=feat_dim, use_gpu=True) # center loss if cfg.MODEL.IF_LABELSMOOTH == 'on': xent = CrossEntropyLabelSmooth(num_classes=num_classes) print("label smooth on, numclasses:", num_classes) if sampler == 'softmax': def loss_func(score, feat, target, target_cam): if cfg.MODEL.IF_LABELSMOOTH == 'on': ID_LOSS = xent(score, target) else: ID_LOSS = F.cross_entropy(score, target) return ID_LOSS elif cfg.DATALOADER.SAMPLER == 'softmax_center': def loss_func(score, feat, target): if cfg.MODEL.IF_LABELSMOOTH == 'on': return xent(score, target) + \ cfg.SOLVER.CENTER_LOSS_WEIGHT * center_criterion(feat, target) else: return F.cross_entropy(score, target) + \ cfg.SOLVER.CENTER_LOSS_WEIGHT * center_criterion(feat, target) else: print('expected sampler should be softmax, or softmax_center' 'but got {}'.format(cfg.DATALOADER.SAMPLER)) return loss_func, center_criterion
1,569
35.511628
106
py
CDTrans
CDTrans-master/utils/reranking.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri, 25 May 2018 20:29:09 @author: luohao """ """ CVPR2017 paper:Zhong Z, Zheng L, Cao D, et al. Re-ranking Person Re-identification with k-reciprocal Encoding[J]. 2017. url:http://openaccess.thecvf.com/content_cvpr_2017/papers/Zhong_Re-Ranking_Person_Re-Identification_CVPR_2017_paper.pdf Matlab version: https://github.com/zhunzhong07/person-re-ranking """ """ API probFea: all feature vectors of the query set (torch tensor) probFea: all feature vectors of the gallery set (torch tensor) k1,k2,lambda: parameters, the original paper is (k1=20,k2=6,lambda=0.3) MemorySave: set to 'True' when using MemorySave mode Minibatch: avaliable when 'MemorySave' is 'True' """ import numpy as np import torch from scipy.spatial.distance import cdist def re_ranking(probFea, galFea, k1, k2, lambda_value, local_distmat=None, only_local=False): # if feature vector is numpy, you should use 'torch.tensor' transform it to tensor query_num = probFea.size(0) all_num = query_num + galFea.size(0) if only_local: original_dist = local_distmat else: feat = torch.cat([probFea, galFea]) # print('using GPU to compute original distance') distmat = torch.pow(feat, 2).sum(dim=1, keepdim=True).expand(all_num, all_num) + \ torch.pow(feat, 2).sum(dim=1, keepdim=True).expand(all_num, all_num).t() distmat.addmm_(1, -2, feat, feat.t()) original_dist = distmat.cpu().numpy() del feat if not local_distmat is None: original_dist = original_dist + local_distmat gallery_num = original_dist.shape[0] original_dist = np.transpose(original_dist / np.max(original_dist, axis=0)) V = np.zeros_like(original_dist).astype(np.float16) initial_rank = np.argsort(original_dist).astype(np.int32) # print('starting re_ranking') for i in range(all_num): # k-reciprocal neighbors forward_k_neigh_index = initial_rank[i, :k1 + 1] backward_k_neigh_index = initial_rank[forward_k_neigh_index, :k1 + 1] fi = np.where(backward_k_neigh_index == i)[0] k_reciprocal_index = forward_k_neigh_index[fi] k_reciprocal_expansion_index = k_reciprocal_index for j in range(len(k_reciprocal_index)): candidate = k_reciprocal_index[j] candidate_forward_k_neigh_index = initial_rank[candidate, :int(np.around(k1 / 2)) + 1] candidate_backward_k_neigh_index = initial_rank[candidate_forward_k_neigh_index, :int(np.around(k1 / 2)) + 1] fi_candidate = np.where(candidate_backward_k_neigh_index == candidate)[0] candidate_k_reciprocal_index = candidate_forward_k_neigh_index[fi_candidate] if len(np.intersect1d(candidate_k_reciprocal_index, k_reciprocal_index)) > 2 / 3 * len( candidate_k_reciprocal_index): k_reciprocal_expansion_index = np.append(k_reciprocal_expansion_index, candidate_k_reciprocal_index) k_reciprocal_expansion_index = np.unique(k_reciprocal_expansion_index) weight = np.exp(-original_dist[i, k_reciprocal_expansion_index]) V[i, k_reciprocal_expansion_index] = weight / np.sum(weight) original_dist = original_dist[:query_num, ] if k2 != 1: V_qe = np.zeros_like(V, dtype=np.float16) for i in range(all_num): V_qe[i, :] = np.mean(V[initial_rank[i, :k2], :], axis=0) V = V_qe del V_qe del initial_rank invIndex = [] for i in range(gallery_num): invIndex.append(np.where(V[:, i] != 0)[0]) jaccard_dist = np.zeros_like(original_dist, dtype=np.float16) for i in range(query_num): temp_min = np.zeros(shape=[1, gallery_num], dtype=np.float16) indNonZero = np.where(V[i, :] != 0)[0] indImages = [invIndex[ind] for ind in indNonZero] for j in range(len(indNonZero)): temp_min[0, indImages[j]] = temp_min[0, indImages[j]] + np.minimum(V[i, indNonZero[j]], V[indImages[j], indNonZero[j]]) jaccard_dist[i] = 1 - temp_min / (2 - temp_min) final_dist = jaccard_dist * (1 - lambda_value) + original_dist * lambda_value del original_dist del V del jaccard_dist final_dist = final_dist[:query_num, query_num:] return final_dist def re_ranking_numpy(probFea, galFea, k1, k2, lambda_value, local_distmat=None, only_local=False): query_num = probFea.shape[0] all_num = query_num + galFea.shape[0] if only_local: original_dist = local_distmat else: q_g_dist = cdist(probFea, galFea) q_q_dist = cdist(probFea, probFea) g_g_dist = cdist(galFea, galFea) original_dist = np.concatenate( [np.concatenate([q_q_dist, q_g_dist], axis=1), np.concatenate([q_g_dist.T, g_g_dist], axis=1)], axis=0) original_dist = np.power(original_dist, 2).astype(np.float32) original_dist = np.transpose(1. * original_dist / np.max(original_dist, axis=0)) if not local_distmat is None: original_dist = original_dist + local_distmat gallery_num = original_dist.shape[0] original_dist = np.transpose(original_dist / np.max(original_dist, axis=0)) V = np.zeros_like(original_dist).astype(np.float16) initial_rank = np.argsort(original_dist).astype(np.int32) print('starting re_ranking') for i in range(all_num): # k-reciprocal neighbors forward_k_neigh_index = initial_rank[i, :k1 + 1] backward_k_neigh_index = initial_rank[forward_k_neigh_index, :k1 + 1] fi = np.where(backward_k_neigh_index == i)[0] k_reciprocal_index = forward_k_neigh_index[fi] k_reciprocal_expansion_index = k_reciprocal_index for j in range(len(k_reciprocal_index)): candidate = k_reciprocal_index[j] candidate_forward_k_neigh_index = initial_rank[candidate, :int(np.around(k1 / 2)) + 1] candidate_backward_k_neigh_index = initial_rank[candidate_forward_k_neigh_index, :int(np.around(k1 / 2)) + 1] fi_candidate = np.where(candidate_backward_k_neigh_index == candidate)[0] candidate_k_reciprocal_index = candidate_forward_k_neigh_index[fi_candidate] if len(np.intersect1d(candidate_k_reciprocal_index, k_reciprocal_index)) > 2 / 3 * len( candidate_k_reciprocal_index): k_reciprocal_expansion_index = np.append(k_reciprocal_expansion_index, candidate_k_reciprocal_index) k_reciprocal_expansion_index = np.unique(k_reciprocal_expansion_index) weight = np.exp(-original_dist[i, k_reciprocal_expansion_index]) V[i, k_reciprocal_expansion_index] = weight / np.sum(weight) original_dist = original_dist[:query_num, ] if k2 != 1: V_qe = np.zeros_like(V, dtype=np.float16) for i in range(all_num): V_qe[i, :] = np.mean(V[initial_rank[i, :k2], :], axis=0) V = V_qe del V_qe del initial_rank invIndex = [] for i in range(gallery_num): invIndex.append(np.where(V[:, i] != 0)[0]) jaccard_dist = np.zeros_like(original_dist, dtype=np.float16) for i in range(query_num): temp_min = np.zeros(shape=[1, gallery_num], dtype=np.float16) indNonZero = np.where(V[i, :] != 0)[0] indImages = [invIndex[ind] for ind in indNonZero] for j in range(len(indNonZero)): temp_min[0, indImages[j]] = temp_min[0, indImages[j]] + np.minimum(V[i, indNonZero[j]], V[indImages[j], indNonZero[j]]) jaccard_dist[i] = 1 - temp_min / (2 - temp_min) final_dist = jaccard_dist * (1 - lambda_value) + original_dist * lambda_value del original_dist del V del jaccard_dist final_dist = final_dist[:query_num, query_num:] return final_dist
8,071
45.65896
119
py
CDTrans
CDTrans-master/utils/metrics.py
import torch import numpy as np import torch.nn as nn import os from utils.reranking import re_ranking,re_ranking_numpy from scipy.spatial.distance import cdist import torch.nn.functional as F from sklearn.metrics import confusion_matrix def euclidean_distance(qf, gf): m = qf.shape[0] n = gf.shape[0] dist_mat = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \ torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, m).t() dist_mat.addmm_(1, -2, qf, gf.t()) return dist_mat.cpu().numpy() def euclidean_distance_gpu(qf, gf): m = qf.shape[0] n = gf.shape[0] dist_mat = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \ torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, m).t() dist_mat.addmm_(1, -2, qf, gf.t()) return dist_mat def cosine_similarity(qf, gf): epsilon = 0.00001 dist_mat = qf.mm(gf.t()) qf_norm = torch.norm(qf, p=2, dim=1, keepdim=True) # mx1 gf_norm = torch.norm(gf, p=2, dim=1, keepdim=True) # nx1 qg_normdot = qf_norm.mm(gf_norm.t()) dist_mat = dist_mat.mul(1 / qg_normdot).cpu().numpy() dist_mat = np.clip(dist_mat, -1 + epsilon, 1 - epsilon) dist_mat = np.arccos(dist_mat) return dist_mat def compute_cosine_distance(qf, gf): """Computes cosine distance. Args: features (torch.Tensor): 2-D feature matrix. others (torch.Tensor): 2-D feature matrix. Returns: torch.Tensor: distance matrix. """ features = F.normalize(qf, p=2, dim=1) others = F.normalize(gf, p=2, dim=1) dist_m = 1 - torch.mm(features, others.t()) epsilon = 0.00001 dist_m = dist_m.cpu().numpy() return np.clip(dist_m, epsilon, 1 - epsilon) def cosine_similarity_xiaohe(qf, gf): """Computes cosine distance. Args: features (torch.Tensor): 2-D feature matrix. others (torch.Tensor): 2-D feature matrix. Returns: torch.Tensor: distance matrix. """ features = F.normalize(qf, p=2, dim=1) others = F.normalize(gf, p=2, dim=1) dist_m = torch.mm(features, others.t()) epsilon = 0.00001 dist_m = dist_m.cpu().numpy() return np.clip(dist_m, epsilon, 1 - epsilon) def eval_func(distmat, q_pids, g_pids, q_camids, g_camids, max_rank=50): """Evaluation with market1501 metric Key: for each query identity, its gallery images from the same camera view are discarded. """ num_q, num_g = distmat.shape # distmat g # q 1 3 2 4 # 4 1 2 3 if num_g < max_rank: max_rank = num_g print("Note: number of gallery samples is quite small, got {}".format(num_g)) indices = np.argsort(distmat, axis=1) # 0 2 1 3 # 1 2 3 0 matches = (g_pids[indices] == q_pids[:, np.newaxis]).astype(np.int32) # compute cmc curve for each query all_cmc = [] all_AP = [] num_valid_q = 0. # number of valid query for q_idx in range(num_q): # get query pid and camid q_pid = q_pids[q_idx] q_camid = q_camids[q_idx] # remove gallery samples that have the same pid and camid with query order = indices[q_idx] # select one row remove = (g_pids[order] == q_pid) & (g_camids[order] == q_camid) keep = np.invert(remove) # compute cmc curve # binary vector, positions with value 1 are correct matches orig_cmc = matches[q_idx][keep] if not np.any(orig_cmc): # this condition is true when query identity does not appear in gallery continue cmc = orig_cmc.cumsum() cmc[cmc > 1] = 1 all_cmc.append(cmc[:max_rank]) num_valid_q += 1. # compute average precision # reference: https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision num_rel = orig_cmc.sum() tmp_cmc = orig_cmc.cumsum() #tmp_cmc = [x / (i + 1.) for i, x in enumerate(tmp_cmc)] y = np.arange(1, tmp_cmc.shape[0] + 1) * 1.0 tmp_cmc = tmp_cmc / y tmp_cmc = np.asarray(tmp_cmc) * orig_cmc AP = tmp_cmc.sum() / num_rel all_AP.append(AP) assert num_valid_q > 0, "Error: all query identities do not appear in gallery" all_cmc = np.asarray(all_cmc).astype(np.float32) all_cmc = all_cmc.sum(0) / num_valid_q mAP = np.mean(all_AP) return all_cmc, mAP class Class_accuracy_eval(): def __init__(self, logger, dataset='office-home'): super(Class_accuracy_eval, self).__init__() self.dataset = dataset self.class_num = None self.logger = logger def reset(self): self.output_prob = [] self.pids = [] def update(self, output): # called once for each batch prob, pid = output self.output_prob.append(prob) self.pids.extend(np.asarray(pid)) def Entropy(self, input_): bs = input_.size(0) epsilon = 1e-5 entropy = -input_ * torch.log(input_ + epsilon) entropy = torch.sum(entropy, dim=1) return entropy def compute(self): # called after each epoch self.class_num = len(set(self.pids)) output_prob = torch.cat(self.output_prob, dim=0) # if self.feat_norm: # print("The test feature is normalized") # feats = torch.nn.functional.normalize(feats, dim=1, p=2) # along channel _, predict = torch.max(output_prob, 1) labels = torch.tensor(self.pids) if self.dataset == 'VisDA': output_prob = nn.Softmax(dim=1)(output_prob) _ent = self.Entropy(output_prob) mean_ent = 0 for ci in range(self.class_num ): mean_ent += _ent[predict==ci].mean() mean_ent /= self.class_num matrix = confusion_matrix(labels, torch.squeeze(predict).float().cpu()) acc = matrix.diagonal()/matrix.sum(axis=1) * 100 # aacc is the mean value of all the accuracy of the each claccse aacc = acc.mean() / 100 aa = [str(np.round(i, 2)) for i in acc] self.logger.info('Per-class accuracy is :') acc = ' '.join(aa) self.logger.info(acc) return aacc, mean_ent else: accuracy = torch.sum((torch.squeeze(predict).float().cpu() == labels)).item() / float(labels.size()[0]) output_prob = nn.Softmax(dim=1)(output_prob) mean_ent = torch.mean(self.Entropy(output_prob)) acc = '' self.logger.info('normal accuracy {} {} {}'.format(accuracy, mean_ent, acc)) return accuracy, mean_ent class R1_mAP_eval(): def __init__(self, num_query, max_rank=50, feat_norm=True, reranking=False): super(R1_mAP_eval, self).__init__() self.num_query = num_query self.max_rank = max_rank self.feat_norm = feat_norm self.reranking=reranking def reset(self): self.feats = [] self.pids = [] self.camids = [] def update(self, output): # called once for each batch feat, pid, camid = output self.feats.append(feat) self.pids.extend(np.asarray(pid)) self.camids.extend(np.asarray(camid)) def compute(self): # called after each epoch feats = torch.cat(self.feats, dim=0) if self.feat_norm: print("The test feature is normalized") feats = torch.nn.functional.normalize(feats, dim=1, p=2) # along channel # query qf = feats[:self.num_query] q_pids = np.asarray(self.pids[:self.num_query]) q_camids = np.asarray(self.camids[:self.num_query]) # gallery gf = feats[self.num_query:] g_pids = np.asarray(self.pids[self.num_query:]) g_camids = np.asarray(self.camids[self.num_query:]) if self.reranking: print('=> Enter reranking') # distmat = re_ranking(qf, gf, k1=20, k2=6, lambda_value=0.3) distmat = re_ranking(qf, gf, k1=50, k2=15, lambda_value=0.3) else: print('=> Computing DistMat with euclidean_distance') distmat = euclidean_distance(qf, gf) cmc, mAP = eval_func(distmat, q_pids, g_pids, q_camids, g_camids) return cmc, mAP, distmat, self.pids, self.camids, qf, gf class R1_mAP_save_feature(): def __init__(self, num_query, max_rank=50, feat_norm=True, reranking=False): super(R1_mAP_save_feature, self).__init__() self.num_query = num_query self.max_rank = max_rank self.feat_norm = feat_norm self.reranking=reranking def reset(self): self.feats = [] self.pids = [] self.camids = [] self.img_name_path = [] def update(self, output): # called once for each batch feat, pid, camid, imgpath = output self.feats.append(feat) self.pids.extend(np.asarray(pid)) self.camids.extend(np.asarray(camid)) self.img_name_path.extend(imgpath) def compute(self): # called after each epoch feats = torch.cat(self.feats, dim=0) if self.feat_norm: print("The test feature is normalized") feats = torch.nn.functional.normalize(feats, dim=1, p=2) # along channel # query return feats, self.pids, self.camids, self.img_name_path class R1_mAP_draw_figure(): def __init__(self, cfg, num_query, max_rank=50, feat_norm=False, reranking=False): super(R1_mAP_draw_figure, self).__init__() self.num_query = num_query self.max_rank = max_rank self.feat_norm = feat_norm self.reranking = reranking self.cfg = cfg def reset(self): self.feats = [] self.pids = [] self.camids = [] self.img_name_path = [] self.viewids = [] def update(self, output): # called once for each batch feat, pid, camid, view, imgpath = output self.feats.append(feat) self.pids.extend(np.asarray(pid)) self.camids.extend(np.asarray(camid)) self.viewids.append(view) self.img_name_path.extend(imgpath) def compute(self): # called after each epoch feats = torch.cat(self.feats, dim=0) if self.feat_norm: print("The test feature is normalized") feats = torch.nn.functional.normalize(feats, dim=1, p=2) # along channel # query debug_tsne = False if debug_tsne: print('debug_tsne is True') self.viewids = torch.cat(self.viewids, dim=0) self.viewids = self.viewids.cpu().numpy().tolist() return feats, self.pids, self.camids, self.viewids, self.img_name_path else: distmat = euclidean_distance(feats, feats) self.viewids = torch.cat(self.viewids, dim=0) self.viewids = self.viewids.cpu().numpy().tolist() print('saving viewids') print(self.num_query, 'self.num_query') print(distmat, 'distmat after') print(distmat.shape, 'distmat.shape') return feats, distmat, self.pids, self.camids, self.viewids, self.img_name_path class R1_mAP(): def __init__(self, num_query, max_rank=50, feat_norm=True, reranking=False, reranking_track=False): super(R1_mAP, self).__init__() self.num_query = num_query self.max_rank = max_rank self.feat_norm = feat_norm self.reranking = reranking self.reranking_track = reranking_track def reset(self): self.feats = [] self.pids = [] self.camids = [] self.tids = [] self.img_path_list = [] def update(self, output): # called once for each batch feat, pid, camid, trackid, imgpath = output self.feats.append(feat) self.tids.extend(np.asarray(trackid)) self.unique_tids = list(set(self.tids)) self.img_path_list.extend(imgpath) def track_ranking(self, qf, gf, gallery_tids, unique_tids): origin_dist = cdist(qf, gf) m, n = qf.shape[0], gf.shape[0] feature_dim = qf.shape[1] gallery_tids = np.asarray(gallery_tids) unique_tids = np.asarray(unique_tids) track_gf = np.zeros((len(unique_tids), feature_dim)) dist = np.zeros((m, n)) gf_tids = sorted(list(set(gallery_tids))) for i, tid in enumerate(gf_tids): track_gf[i, :] = np.mean(gf[gallery_tids == tid, :], axis=0) # track_dist = cdist(qf, track_gf) track_dist = re_ranking_numpy(qf, track_gf, k1=7, k2=2, lambda_value=0.6) print(' re_ranking_numpy(qf, track_gf, k1=7, k2=2, lambda_value=0.6)') for i, tid in enumerate(gf_tids): dist[:, gallery_tids == tid] = track_dist[:, i:(i + 1)] for i in range(m): for tid in gf_tids: min_value = np.min(origin_dist[i][gallery_tids == tid]) min_index = np.where(origin_dist[i] == min_value) min_value = dist[i][min_index[0][0]] dist[i][gallery_tids == tid] = min_value + 0.000001 dist[i][min_index] = min_value return dist def compute(self,save_dir): # called after each epoch feats = torch.cat(self.feats, dim=0) if self.feat_norm: print("The test feature is normalized") feats = torch.nn.functional.normalize(feats, dim=1, p=2) # along channel # query qf = feats[:self.num_query] # gallery gf = feats[self.num_query:] img_name_q=self.img_path_list[:self.num_query] img_name_g = self.img_path_list[self.num_query:] gallery_tids = np.asarray(self.tids[self.num_query:]) if self.reranking_track: print('=> Enter track reranking') # distmat = re_ranking(qf, gf, k1=20, k2=6, lambda_value=0.3) qf = qf.cpu().numpy() gf = gf.cpu().numpy() distmat = self.track_ranking(qf, gf, gallery_tids, self.unique_tids) elif self.reranking: print('=> Enter reranking') # distmat = re_ranking(qf, gf, k1=20, k2=6, lambda_value=0.3) distmat = re_ranking(qf, gf, k1=50, k2=15, lambda_value=0.3) else: print('=> Computing DistMat with cosine similarity') distmat = cosine_similarity(qf, gf) sort_distmat_index = np.argsort(distmat, axis=1) print(sort_distmat_index.shape,'sort_distmat_index.shape') print(sort_distmat_index,'sort_distmat_index') with open(os.path.join(save_dir, 'track2.txt'), 'w') as f: for item in sort_distmat_index: for i in range(99): f.write(str(item[i] + 1) + ' ') f.write(str(item[99] + 1) + '\n') print('writing result to {}'.format(os.path.join(save_dir, 'track2.txt'))) return distmat, img_name_q, img_name_g, qf, gf class R1_mAP_Pseudo(): def __init__(self, num_query, max_rank=50, feat_norm=True): super(R1_mAP_Pseudo, self).__init__() self.num_query = num_query self.max_rank = max_rank self.feat_norm = feat_norm def reset(self): self.feats = [] self.pids = [] self.camids = [] self.tids = [] self.img_path_list = [] def update(self, output): # called once for each batch feat, pid, camid, trackid, imgpath = output self.feats.append(feat) self.tids.extend(np.asarray(trackid)) self.unique_tids = list(set(self.tids)) self.img_path_list.extend(imgpath) def track_ranking(self, qf, gf, gallery_tids, unique_tids): origin_dist = cdist(qf, gf) m, n = qf.shape[0], gf.shape[0] feature_dim = qf.shape[1] gallery_tids = np.asarray(gallery_tids) unique_tids = np.asarray(unique_tids) track_gf = np.zeros((len(unique_tids), feature_dim)) dist = np.zeros((m, n)) gf_tids = sorted(list(set(gallery_tids))) for i, tid in enumerate(gf_tids): track_gf[i, :] = np.mean(gf[gallery_tids == tid, :], axis=0) # track_dist = cdist(qf, track_gf) #track_dist = re_ranking_numpy(qf, track_gf, k1=8, k2=3, lambda_value=0.3) track_dist = re_ranking_numpy(qf, track_gf, k1=7, k2=2, lambda_value=0.6) # track_dist = re_ranking_numpy(qf, track_gf, k1=5, k2=3, lambda_value=0.3) for i, tid in enumerate(gf_tids): dist[:, gallery_tids == tid] = track_dist[:, i:(i + 1)] for i in range(m): for tid in gf_tids: min_value = np.min(origin_dist[i][gallery_tids == tid]) min_index = np.where(origin_dist[i] == min_value) min_value = dist[i][min_index[0][0]] dist[i][gallery_tids == tid] = min_value + 0.000001 dist[i][min_index] = min_value return dist def compute(self,save_dir,): # called after each epoch feats = torch.cat(self.feats, dim=0) if self.feat_norm: print("The test feature is normalized") feats = torch.nn.functional.normalize(feats, dim=1, p=2) # along channel # query qf = feats[:self.num_query] # gallery gf = feats[self.num_query:] img_name_q=self.img_path_list[:self.num_query] img_name_g = self.img_path_list[self.num_query:] gallery_tids = np.asarray(self.tids[self.num_query:]) m, n = qf.shape[0], gf.shape[0] qf = qf.cpu().numpy() gf = gf.cpu().numpy() distmat = self.track_ranking(qf, gf, gallery_tids, self.unique_tids) return distmat, img_name_q, img_name_g, qf, gf class R1_mAP_query_mining(): def __init__(self, num_query, max_rank=50, feat_norm=True, reranking=False, reranking_track=False): super(R1_mAP_query_mining, self).__init__() self.num_query = num_query self.max_rank = max_rank self.feat_norm = feat_norm self.reranking = reranking self.reranking_track = reranking_track def reset(self): self.feats = [] self.pids = [] self.camids = [] self.tids = [] self.img_path_list = [] def update(self, output): # called once for each batch feat, pid, camid, trackid, imgpath = output self.feats.append(feat) self.tids.extend(np.asarray(trackid)) self.unique_tids = list(set(self.tids)) self.img_path_list.extend(imgpath) def compute(self,save_dir): # called after each epoch feats = torch.cat(self.feats, dim=0) if self.feat_norm: print("The test feature is normalized") feats = torch.nn.functional.normalize(feats, dim=1, p=2) # along channel # query qf = feats[:self.num_query] # gallery gf = feats[self.num_query:] img_name_q=self.img_path_list[:self.num_query] img_name_g = self.img_path_list[self.num_query:] gallery_tids = np.asarray(self.tids[self.num_query:]) if self.reranking: print('=> Enter reranking') # distmat = re_ranking(qf, gf, k1=20, k2=6, lambda_value=0.3) distmat = re_ranking(qf, gf, k1=50, k2=15, lambda_value=0.3) else: print('=> Computing DistMat with cosine similarity') distmat = cosine_similarity(qf, gf) return distmat, img_name_q, img_name_g, qf, gf
19,489
36.625483
115
py
CDTrans
CDTrans-master/model/make_model.py
import torch import torch.nn as nn from .backbones.resnet import ResNet, BasicBlock, Bottleneck from loss.arcface import ArcFace from .backbones.resnet_ibn_a import resnet50_ibn_a,resnet101_ibn_a from .backbones.se_resnet_ibn_a import se_resnet101_ibn_a from .backbones.vit_pytorch import vit_base_patch16_224_TransReID, vit_small_patch16_224_TransReID from .backbones.vit_pytorch_uda import uda_vit_base_patch16_224_TransReID, uda_vit_small_patch16_224_TransReID import torch.nn.functional as F from loss.metric_learning import Arcface, Cosface, AMSoftmax, CircleLoss def weights_init_kaiming(m): classname = m.__class__.__name__ if classname.find('Linear') != -1: nn.init.kaiming_normal_(m.weight, a=0, mode='fan_out') nn.init.constant_(m.bias, 0.0) elif classname.find('Conv') != -1: nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in') if m.bias is not None: nn.init.constant_(m.bias, 0.0) elif classname.find('BatchNorm') != -1: if m.affine: nn.init.constant_(m.weight, 1.0) nn.init.constant_(m.bias, 0.0) def weights_init_classifier(m): classname = m.__class__.__name__ if classname.find('Linear') != -1: nn.init.normal_(m.weight, std=0.001) if m.bias: nn.init.constant_(m.bias, 0.0) class Backbone(nn.Module): def __init__(self, num_classes, cfg): super(Backbone, self).__init__() last_stride = cfg.MODEL.LAST_STRIDE model_path = cfg.MODEL.PRETRAIN_PATH model_name = cfg.MODEL.NAME pretrain_choice = cfg.MODEL.PRETRAIN_CHOICE self.cos_layer = cfg.MODEL.COS_LAYER self.neck = cfg.MODEL.NECK self.neck_feat = cfg.TEST.NECK_FEAT self.task_type = cfg.MODEL.TASK_TYPE if model_name == 'resnet50': self.in_planes = 2048 self.base = ResNet(last_stride=last_stride, block=Bottleneck, frozen_stages=cfg.MODEL.FROZEN, layers=[3, 4, 6, 3]) print('using resnet50 as a backbone') elif model_name == 'resnet101': self.in_planes = 2048 self.base = ResNet(last_stride=last_stride, block=Bottleneck, frozen_stages=cfg.MODEL.FROZEN, layers=[3, 4, 23, 3]) print('using resnet101 as a backbone') elif model_name == 'resnet50_ibn_a': self.in_planes = 2048 self.base = resnet50_ibn_a(last_stride) print('using resnet50_ibn_a as a backbone') elif model_name == 'resnet101_ibn_a': self.in_planes = 2048 self.base = resnet101_ibn_a(last_stride, frozen_stages=cfg.MODEL.FROZEN) print('using resnet101_ibn_a as a backbone') elif model_name == 'se_resnet101_ibn_a': self.in_planes = 2048 self.base = se_resnet101_ibn_a(last_stride,frozen_stages=cfg.MODEL.FROZEN) print('using se_resnet101_ibn_a as a backbone') else: print('unsupported backbone! but got {}'.format(model_name)) if pretrain_choice == 'imagenet': self.base.load_param(model_path) print('Loading pretrained ImageNet model......from {}'.format(model_path)) elif pretrain_choice == 'un_pretrain': self.base.load_un_param(model_path) print('Loading un_pretrain model......from {}'.format(model_path)) self.gap = nn.AdaptiveAvgPool2d(1) self.num_classes = num_classes if self.cos_layer: print('using cosine layer') self.arcface = ArcFace(self.in_planes, self.num_classes, s=30.0, m=0.50) else: self.classifier = nn.Linear(self.in_planes, self.num_classes, bias=False) self.classifier.apply(weights_init_classifier) self.bottleneck = nn.BatchNorm1d(self.in_planes) self.bottleneck.bias.requires_grad_(False) self.bottleneck.apply(weights_init_kaiming) self.bottleneck_2 = nn.LayerNorm(self.in_planes) def forward(self, x, label=None, cam_label=None, view_label=None, return_logits=False): # label is unused if self.cos_layer == 'no' x = self.base(x, cam_label=cam_label) global_feat = nn.functional.avg_pool2d(x, x.shape[2:4]) global_feat = global_feat.view(global_feat.shape[0], -1) # flatten to (bs, 2048) if self.neck == 'no': feat = global_feat elif self.neck == 'bnneck': feat = self.bottleneck(global_feat) if return_logits: cls_score = self.classifier(feat) return cls_score if self.training: if self.cos_layer: cls_score = self.arcface(feat, label) else: cls_score = self.classifier(feat) return cls_score, global_feat # global feature for triplet loss elif self.task_type == 'classify_DA': # test for classify domain adapatation if self.cos_layer: cls_score = self.arcface(feat, label) else: cls_score = self.classifier(feat) return cls_score else: if self.neck_feat == 'after': # print("Test with feature after BN") return feat else: # print("Test with feature before BN") return global_feat def load_param(self, trained_path): param_dict = torch.load(trained_path) if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for i in param_dict: # if 'classifier' in i or 'arcface' in i: # continue self.state_dict()[i].copy_(param_dict[i]) print('Loading pretrained model from revise {}'.format(trained_path)) def load_un_param(self, trained_path): param_dict = torch.load(trained_path) if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for i in self.state_dict(): if 'classifier' in i or 'arcface' in i: continue self.state_dict()[i].copy_(param_dict[i]) print('Loading pretrained model from {}'.format(trained_path)) def load_param_finetune(self, model_path): param_dict = torch.load(model_path) for i in param_dict: self.state_dict()[i].copy_(param_dict[i]) print('Loading pretrained model for finetuning from {}'.format(model_path)) class build_transformer(nn.Module): def __init__(self, num_classes, camera_num, view_num, cfg, factory): super(build_transformer, self).__init__() last_stride = cfg.MODEL.LAST_STRIDE model_path = cfg.MODEL.PRETRAIN_PATH model_name = cfg.MODEL.NAME pretrain_choice = cfg.MODEL.PRETRAIN_CHOICE self.cos_layer = cfg.MODEL.COS_LAYER self.neck = cfg.MODEL.NECK self.neck_feat = cfg.TEST.NECK_FEAT self.task_type = cfg.MODEL.TASK_TYPE if '384' in cfg.MODEL.Transformer_TYPE or 'small' in cfg.MODEL.Transformer_TYPE: self.in_planes = 384 else: self.in_planes = 768 self.bottleneck_dim = 256 print('using Transformer_type: {} as a backbone'.format(cfg.MODEL.Transformer_TYPE)) if cfg.MODEL.TASK_TYPE == 'classify_DA': self.base = factory[cfg.MODEL.Transformer_TYPE](img_size=cfg.INPUT.SIZE_CROP, aie_xishu=cfg.MODEL.AIE_COE,local_feature=cfg.MODEL.LOCAL_F, stride_size=cfg.MODEL.STRIDE_SIZE, drop_path_rate=cfg.MODEL.DROP_PATH) else: self.base = factory[cfg.MODEL.Transformer_TYPE](img_size=cfg.INPUT.SIZE_TRAIN, aie_xishu=cfg.MODEL.AIE_COE,local_feature=cfg.MODEL.LOCAL_F, stride_size=cfg.MODEL.STRIDE_SIZE, drop_path_rate=cfg.MODEL.DROP_PATH) self.gap = nn.AdaptiveAvgPool2d(1) self.num_classes = num_classes self.ID_LOSS_TYPE = cfg.MODEL.ID_LOSS_TYPE if self.ID_LOSS_TYPE == 'arcface': print('using {} with s:{}, m: {}'.format(self.ID_LOSS_TYPE,cfg.SOLVER.COSINE_SCALE,cfg.SOLVER.COSINE_MARGIN)) self.classifier = Arcface(self.in_planes, self.num_classes, s=cfg.SOLVER.COSINE_SCALE, m=cfg.SOLVER.COSINE_MARGIN) elif self.ID_LOSS_TYPE == 'cosface': print('using {} with s:{}, m: {}'.format(self.ID_LOSS_TYPE,cfg.SOLVER.COSINE_SCALE,cfg.SOLVER.COSINE_MARGIN)) self.classifier = Cosface(self.in_planes, self.num_classes, s=cfg.SOLVER.COSINE_SCALE, m=cfg.SOLVER.COSINE_MARGIN) elif self.ID_LOSS_TYPE == 'amsoftmax': print('using {} with s:{}, m: {}'.format(self.ID_LOSS_TYPE,cfg.SOLVER.COSINE_SCALE,cfg.SOLVER.COSINE_MARGIN)) self.classifier = AMSoftmax(self.in_planes, self.num_classes, s=cfg.SOLVER.COSINE_SCALE, m=cfg.SOLVER.COSINE_MARGIN) elif self.ID_LOSS_TYPE == 'circle': print('using {} with s:{}, m: {}'.format(self.ID_LOSS_TYPE, cfg.SOLVER.COSINE_SCALE, cfg.SOLVER.COSINE_MARGIN)) self.classifier = CircleLoss(self.in_planes, self.num_classes, s=cfg.SOLVER.COSINE_SCALE, m=cfg.SOLVER.COSINE_MARGIN) else: self.classifier = nn.Linear(self.in_planes, self.num_classes, bias=False) self.classifier.apply(weights_init_classifier) self.bottleneck = nn.BatchNorm1d(self.in_planes) self.bottleneck.bias.requires_grad_(False) self.bottleneck.apply(weights_init_kaiming) self._load_parameter(pretrain_choice, model_path) def _load_parameter(self, pretrain_choice, model_path): if pretrain_choice == 'imagenet': self.base.load_param(model_path) print('Loading pretrained ImageNet model......from {}'.format(model_path)) elif pretrain_choice == 'un_pretrain': self.base.load_un_param(model_path) print('Loading trans_tune model......from {}'.format(model_path)) elif pretrain_choice == 'pretrain': self.load_param_finetune(model_path) print('Loading pretrained model......from {}'.format(model_path)) def forward(self, x, label=None, cam_label= None, view_label=None, return_logits=False): # label is unused if self.cos_layer == 'no' global_feat = self.base(x, cam_label=cam_label, view_label=view_label) feat = self.bottleneck(global_feat) if return_logits: if self.cos_layer: cls_score = self.arcface(feat, label) else: cls_score = self.classifier(feat) return cls_score elif self.training: if self.ID_LOSS_TYPE in ('arcface', 'cosface', 'amsoftmax', 'circle'): cls_score = self.classifier(feat, label) else: cls_score = self.classifier(feat) return cls_score, global_feat # global feature for triplet loss else: if self.neck_feat == 'after': # print("Test with feature after BN") return feat else: # print("Test with feature before BN") return global_feat def load_param(self, trained_path): param_dict = torch.load(trained_path) for i in param_dict: if 'classifier' in i or 'arcface' in i or 'bottleneck' in i or 'gap' in i: continue self.state_dict()[i.replace('module.', '')].copy_(param_dict[i]) print('Loading pretrained model from {}'.format(trained_path)) def load_param_finetune(self, model_path): param_dict = torch.load(model_path) for i in param_dict: if 'module.' in i: new_i = i.replace('module.','') else: new_i = i if new_i not in self.state_dict().keys(): print('model parameter: {} not match'.format(new_i)) continue self.state_dict()[new_i].copy_(param_dict[i]) print('Loading pretrained model for finetuning from {}'.format(model_path)) class build_uda_transformer(nn.Module): def __init__(self, num_classes, camera_num, view_num, cfg, factory): super(build_uda_transformer, self).__init__() last_stride = cfg.MODEL.LAST_STRIDE model_path = cfg.MODEL.PRETRAIN_PATH pretrain_choice = cfg.MODEL.PRETRAIN_CHOICE self.cos_layer = cfg.MODEL.COS_LAYER self.neck = cfg.MODEL.NECK self.neck_feat = cfg.TEST.NECK_FEAT self.task_type = cfg.MODEL.TASK_TYPE self.in_planes = 384 if 'small' in cfg.MODEL.Transformer_TYPE else 768 print('using Transformer_type: {} as a backbone'.format(cfg.MODEL.Transformer_TYPE)) if cfg.MODEL.TASK_TYPE == 'classify_DA': self.base = factory[cfg.MODEL.Transformer_TYPE](img_size=cfg.INPUT.SIZE_CROP, aie_xishu=cfg.MODEL.AIE_COE,local_feature=cfg.MODEL.LOCAL_F, stride_size=cfg.MODEL.STRIDE_SIZE, drop_path_rate=cfg.MODEL.DROP_PATH, block_pattern=cfg.MODEL.BLOCK_PATTERN) else: self.base = factory[cfg.MODEL.Transformer_TYPE](img_size=cfg.INPUT.SIZE_TRAIN, aie_xishu=cfg.MODEL.AIE_COE,local_feature=cfg.MODEL.LOCAL_F, stride_size=cfg.MODEL.STRIDE_SIZE, drop_path_rate=cfg.MODEL.DROP_PATH, use_cross=cfg.MODEL.USE_CROSS, use_attn=cfg.MODEL.USE_ATTN, block_pattern=cfg.MODEL.BLOCK_PATTERN) self.gap = nn.AdaptiveAvgPool2d(1) self.num_classes = num_classes self.ID_LOSS_TYPE = cfg.MODEL.ID_LOSS_TYPE if self.ID_LOSS_TYPE == 'arcface': print('using {} with s:{}, m: {}'.format(self.ID_LOSS_TYPE,cfg.SOLVER.COSINE_SCALE,cfg.SOLVER.COSINE_MARGIN)) self.classifier = Arcface(self.in_planes, self.num_classes, s=cfg.SOLVER.COSINE_SCALE, m=cfg.SOLVER.COSINE_MARGIN) elif self.ID_LOSS_TYPE == 'cosface': print('using {} with s:{}, m: {}'.format(self.ID_LOSS_TYPE,cfg.SOLVER.COSINE_SCALE,cfg.SOLVER.COSINE_MARGIN)) self.classifier = Cosface(self.in_planes, self.num_classes, s=cfg.SOLVER.COSINE_SCALE, m=cfg.SOLVER.COSINE_MARGIN) elif self.ID_LOSS_TYPE == 'amsoftmax': print('using {} with s:{}, m: {}'.format(self.ID_LOSS_TYPE,cfg.SOLVER.COSINE_SCALE,cfg.SOLVER.COSINE_MARGIN)) self.classifier = AMSoftmax(self.in_planes, self.num_classes, s=cfg.SOLVER.COSINE_SCALE, m=cfg.SOLVER.COSINE_MARGIN) elif self.ID_LOSS_TYPE == 'circle': print('using {} with s:{}, m: {}'.format(self.ID_LOSS_TYPE, cfg.SOLVER.COSINE_SCALE, cfg.SOLVER.COSINE_MARGIN)) self.classifier = CircleLoss(self.in_planes, self.num_classes, s=cfg.SOLVER.COSINE_SCALE, m=cfg.SOLVER.COSINE_MARGIN) else: self.classifier = nn.Linear(self.in_planes, self.num_classes, bias=False) self.classifier.apply(weights_init_classifier) self.bottleneck = nn.BatchNorm1d(self.in_planes) self.bottleneck.bias.requires_grad_(False) self.bottleneck.apply(weights_init_kaiming) if pretrain_choice == 'imagenet': self.base.load_param(model_path) print('Loading pretrained ImageNet model......from {}'.format(model_path)) elif pretrain_choice == 'un_pretrain': self.base.load_un_param(model_path) print('Loading trans_tune model......from {}'.format(model_path)) elif pretrain_choice == 'pretrain': if model_path == '': print('make model without initialization') else: self.load_param_finetune(model_path) print('Loading pretrained model......from {}'.format(model_path)) def forward(self, x, x2, label=None, cam_label= None, view_label=None, domain_norm=False, return_logits=False, return_feat_prob=False, cls_embed_specific=False): # label is unused if self.cos_layer == 'no' inference_flag = not self.training global_feat, global_feat2, global_feat3, cross_attn = self.base(x, x2, cam_label=cam_label, view_label=view_label, domain_norm=domain_norm, cls_embed_specific=cls_embed_specific, inference_target_only=inference_flag) if self.neck == '': feat = global_feat feat2 = global_feat2 feat3 = global_feat3 else: feat = self.bottleneck(global_feat) if self.training else None feat3 = self.bottleneck(global_feat3) if self.training else None feat2 = self.bottleneck(global_feat2) if return_logits: if self.ID_LOSS_TYPE in ('arcface', 'cosface', 'amsoftmax', 'circle'): cls_score = self.classifier(feat, label) cls_score2 = self.classifier(feat2, label) cls_score3 = self.classifier(feat3, label) if global_feat3 is not None else None else: cls_score = self.classifier(feat) if global_feat is not None else None cls_score2 = self.classifier(feat2) cls_score3 = self.classifier(feat3) if global_feat3 is not None else None return cls_score, cls_score2, cls_score3 if self.training or return_feat_prob: if self.ID_LOSS_TYPE in ('arcface', 'cosface', 'amsoftmax', 'circle'): cls_score = self.classifier(feat, label) if self.training else None cls_score2 = self.classifier(feat2, label) cls_score3 = self.classifier(feat3, label) if self.training else None else: cls_score = self.classifier(feat) if self.training else None cls_score2 = self.classifier(feat2) cls_score3 = self.classifier(feat3) if self.training else None return (cls_score, global_feat, feat), (cls_score2, global_feat2, feat2), (cls_score3, global_feat3, feat3), cross_attn # source , target , source_target_fusion else: if self.neck_feat == 'after' and self.neck != '': # print("Test with feature after BN") return feat, feat2, feat3 else: # print("Test with feature before BN") return global_feat, global_feat2, global_feat3 # source , target , source_target_fusion def load_param(self, trained_path): param_dict = torch.load(trained_path) for i in param_dict: if 'classifier' in i or 'arcface' in i or 'bottleneck' in i or 'gap' in i: continue self.state_dict()[i.replace('module.', '')].copy_(param_dict[i]) print('Loading pretrained model from {}'.format(trained_path)) def load_param_finetune(self, model_path): param_dict = torch.load(model_path) for i in param_dict: if 'module.' in i: new_i = i.replace('module.','') else: new_i = i if new_i not in self.state_dict().keys(): print('model parameter: {} not match'.format(new_i)) continue self.state_dict()[new_i].copy_(param_dict[i]) print('Loading pretrained model for finetuning from {}'.format(model_path)) __factory_hh = { 'vit_base_patch16_224_TransReID': vit_base_patch16_224_TransReID, 'vit_small_patch16_224_TransReID': vit_small_patch16_224_TransReID, 'uda_vit_small_patch16_224_TransReID': uda_vit_small_patch16_224_TransReID, 'uda_vit_base_patch16_224_TransReID': uda_vit_base_patch16_224_TransReID, # 'resnet101': resnet101, } def make_model(cfg, num_class, camera_num, view_num): if cfg.MODEL.NAME == 'transformer': if cfg.MODEL.BLOCK_PATTERN == '3_branches': model = build_uda_transformer(num_class, camera_num, view_num, cfg, __factory_hh) print('===========building uda transformer===========') else: model = build_transformer(num_class, camera_num, view_num, cfg, __factory_hh) print('===========building transformer===========') else: print('===========ResNet===========') model = Backbone(num_class, cfg) return model
20,400
48.040865
322
py
CDTrans
CDTrans-master/model/backbones/vit_pytorch.py
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 The official jax code is released and available at https://github.com/google-research/vision_transformer Status/TODO: * Models updated to be compatible with official impl. Args added to support backward compat for old PyTorch weights. * Weights ported from official jax impl for 384x384 base and small models, 16x16 and 32x32 patches. * Trained (supervised on ImageNet-1k) my custom 'small' patch model to 77.9, 'base' to 79.4 top-1 with this code. * Hopefully find time and GPUs for SSL or unsupervised pretraining on OpenImages w/ ImageNet fine-tune in future. Acknowledgments: * The paper authors for releasing code and weights, thanks! * I fixed my class token impl based on Phil Wang's https://github.com/lucidrains/vit-pytorch ... check it out for some einops/einsum fun * Simple transformer style inspired by Andrej Karpathy's https://github.com/karpathy/minGPT * Bert reference code checks against Huggingface Transformers and Tensorflow Bert Hacked together by / Copyright 2020 Ross Wightman """ import math from functools import partial from itertools import repeat import torch import torch.nn as nn import torch.nn.functional as F from torch._six import container_abcs # From PyTorch internals def _ntuple(n): def parse(x): if isinstance(x, container_abcs.Iterable): return x return tuple(repeat(x, n)) return parse IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) to_2tuple = _ntuple(2) def drop_path(x, drop_prob: float = 0., training: bool = False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. """ if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) random_tensor.floor_() # binarize output = x.div(keep_prob) * random_tensor return output class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training) def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'patch_embed.proj', 'classifier': 'head', **kwargs } default_cfgs = { # patch models 'vit_small_patch16_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/vit_small_p16_224-15ec54c9.pth', ), 'vit_base_patch16_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_224-80ecf9dd.pth', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), ), 'vit_base_patch16_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_384-83fb41ba.pth', input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), 'vit_base_patch32_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p32_384-830016f5.pth', input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), 'vit_large_patch16_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p16_224-4ee7a4dc.pth', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), 'vit_large_patch16_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p16_384-b3be5167.pth', input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), 'vit_large_patch32_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p32_384-9b920ba8.pth', input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), 'vit_huge_patch16_224': _cfg(), 'vit_huge_patch32_384': _cfg(input_size=(3, 384, 384)), # hybrid models 'vit_small_resnet26d_224': _cfg(), 'vit_small_resnet50d_s3_224': _cfg(), 'vit_base_resnet26d_224': _cfg(), 'vit_base_resnet50d_224': _cfg(), } class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.attn = None def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) self.attn = attn attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class Block(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, x): x = x + self.drop_path(self.attn(self.norm1(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x class PatchEmbed(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) self.img_size = img_size self.patch_size = patch_size self.num_patches = num_patches self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) def forward(self, x): B, C, H, W = x.shape # FIXME look at relaxing size constraints assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x).flatten(2).transpose(1, 2) return x class HybridEmbed(nn.Module): """ CNN Feature Map Embedding Extract feature map from CNN, flatten, project to embedding dim. """ def __init__(self, backbone, img_size=224, feature_size=None, in_chans=3, embed_dim=768): super().__init__() assert isinstance(backbone, nn.Module) img_size = to_2tuple(img_size) self.img_size = img_size self.backbone = backbone if feature_size is None: with torch.no_grad(): # FIXME this is hacky, but most reliable way of determining the exact dim of the output feature # map for all networks, the feature metadata has reliable channel and stride info, but using # stride to calc feature dim requires info about padding of each stage that isn't captured. training = backbone.training if training: backbone.eval() o = self.backbone(torch.zeros(1, in_chans, img_size[0], img_size[1]))[-1] feature_size = o.shape[-2:] feature_dim = o.shape[1] backbone.train(training) else: feature_size = to_2tuple(feature_size) feature_dim = self.backbone.feature_info.channels()[-1] self.num_patches = feature_size[0] * feature_size[1] self.proj = nn.Linear(feature_dim, embed_dim) def forward(self, x): x = self.backbone(x)[-1] x = x.flatten(2).transpose(1, 2) x = self.proj(x) return x class VisionTransformer(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., hybrid_backbone=None, norm_layer=nn.LayerNorm): super().__init__() self.num_classes = num_classes self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models if hybrid_backbone is not None: self.patch_embed = HybridEmbed( hybrid_backbone, img_size=img_size, in_chans=in_chans, embed_dim=embed_dim) else: self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) # self.pos_embed_2 = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) # print('pos_embed_2') self.pos_drop = nn.Dropout(p=drop_rate) print(drop_path_rate, 'drop_path_rate') print(drop_rate, 'drop_rate') dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule self.blocks = nn.ModuleList([ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer) for i in range(depth)]) self.norm = norm_layer(embed_dim) # NOTE as per official impl, we could have a pre-logits representation dense layer + tanh here # Classifier head self.fc = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() trunc_normal_(self.pos_embed, std=.02) trunc_normal_(self.cls_token, std=.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token'} def get_classifier(self): return self.head def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.fc = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x): B = x.shape[0] x = self.patch_embed(x) cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks x = torch.cat((cls_tokens, x), dim=1) # x = x + self.pos_embed + self.pos_embed_2 x = x + self.pos_embed x = self.pos_drop(x) for blk in self.blocks: x = blk(x) x = self.norm(x) return x[:, 0] def forward(self, x, cam_label=None): x = self.forward_features(x) #x = self.fc(x) return x def load_param(self, model_path): param_dict = torch.load(model_path, map_location='cpu') if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for i in param_dict: # if 'head' in i: # continue if 'head' in i or 'attn.qkv.bias' in i: print('{} parameter is ignore'.format(i)) continue try: self.state_dict()[i].copy_(param_dict[i]) except: print('===========================ERROR=========================') print('shape do not match in i :{}: param_dict{} vs self.state_dict(){}'.format(i, param_dict[i].shape, self.state_dict()[i].shape)) def load_un_param(self, trained_path): param_dict = torch.load(trained_path) if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for k in list(param_dict.keys()): # retain only encoder_q up to before the embedding layer if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'): # remove prefix param_dict[k[len("module.encoder_q."):]] = param_dict[k] # delete renamed or unused k del param_dict[k] for i in param_dict: if 'fc' in i or 'head' in i: continue self.state_dict()[i].copy_(param_dict[i]) import random class VisionTransformer_mask(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., hybrid_backbone=None, norm_layer=nn.LayerNorm, thresh=0.0, prob=0.0): super().__init__() self.num_classes = num_classes self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models if hybrid_backbone is not None: self.patch_embed = HybridEmbed( hybrid_backbone, img_size=img_size, in_chans=in_chans, embed_dim=embed_dim) else: self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) self.thresh = thresh print(thresh, 'thresh') self.prob = prob print(prob, 'prob') self.pos_drop = nn.Dropout(p=drop_rate) print(drop_path_rate, 'drop_path_rate') print(drop_rate, 'drop_rate') dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule self.blocks = nn.ModuleList([ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer) for i in range(depth)]) self.norm = norm_layer(embed_dim) # Classifier head self.fc = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() trunc_normal_(self.pos_embed, std=.02) trunc_normal_(self.cls_token, std=.02) self.apply(self._init_weights) self.mask_embedding = nn.Parameter(torch.zeros(64, num_patches, embed_dim)) # 【768】 trunc_normal_(self.mask_embedding, std=.02) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token'} def get_classifier(self): return self.head def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.fc = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x): B = x.shape[0] x = self.patch_embed(x) if self.training: prob = random.random() if prob < self.prob: mask = torch.rand(1, 128, 1).cuda() mask = torch.where(mask > self.thresh, torch.Tensor([1]).cuda(), torch.Tensor([0]).cuda()) # [64, 16, 8] x = mask * x + (1 - mask) * self.mask_embedding cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks x = torch.cat((cls_tokens, x), dim=1) x = x + self.pos_embed x = self.pos_drop(x) for blk in self.blocks: x = blk(x) x = self.norm(x) return x[:, 0] def forward(self, x, cam_label=None): x = self.forward_features(x) return x def load_param(self, model_path): param_dict = torch.load(model_path, map_location='cpu') if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for i in param_dict: if 'head' in i: continue try: self.state_dict()[i].copy_(param_dict[i]) except: print('===========================ERROR=========================') print('shape do not match in i :{}: param_dict{} vs self.state_dict(){}'.format(i, param_dict[i].shape, self.state_dict()[i].shape)) def load_un_param(self, trained_path): param_dict = torch.load(trained_path) if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for k in list(param_dict.keys()): # retain only encoder_q up to before the embedding layer if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'): # remove prefix param_dict[k[len("module.encoder_q."):]] = param_dict[k] # delete renamed or unused k del param_dict[k] for i in param_dict: if 'fc' in i or 'head' in i: continue self.state_dict()[i].copy_(param_dict[i]) class PatchEmbed_stride(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, stride_size=20, in_chans=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) stride_size_tuple = to_2tuple(stride_size) self.num_x = (img_size[1] - patch_size[1]) // stride_size_tuple[1] + 1 self.num_y = (img_size[0] - patch_size[0]) // stride_size_tuple[0] + 1 print('using stride: {}, and part number is num_y{} * num_x{}'.format(stride_size, self.num_y, self.num_x)) num_patches = self.num_x * self.num_y self.img_size = img_size self.patch_size = patch_size self.num_patches = num_patches self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride_size) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.InstanceNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def forward(self, x): B, C, H, W = x.shape # FIXME look at relaxing size constraints assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x) x = x.flatten(2).transpose(1, 2) # [64, 8, 768] return x class TransReID(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__(self, img_size=224, patch_size=16, stride_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., hybrid_backbone=None, norm_layer=nn.LayerNorm,local_feature=False, aie_xishu =1.0): super().__init__() self.num_classes = num_classes self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models self.local_feature = local_feature if hybrid_backbone is not None: self.patch_embed = HybridEmbed( hybrid_backbone, img_size=img_size, in_chans=in_chans, embed_dim=embed_dim) else: self.patch_embed = PatchEmbed_stride( img_size=img_size, patch_size=patch_size, stride_size=stride_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) print('using drop_path_rate is : {}'.format(drop_path_rate)) print('using aie_xishu is : {}'.format(aie_xishu)) self.pos_drop = nn.Dropout(p=drop_rate) print('embed_diim {} mlp_ratio {}'.format(embed_dim, mlp_ratio)) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule self.blocks = nn.ModuleList([ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer) for i in range(depth)]) self.norm = norm_layer(embed_dim) self.AIE_MULTI = aie_xishu # Classifier head self.fc = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() trunc_normal_(self.cls_token, std=.02) # 0.01 better trunc_normal_(self.pos_embed, std=.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) # 0.01 bette # 0.01 betterr if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token'} def get_classifier(self): return self.head def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.fc = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x, camera_id, view_id): B = x.shape[0] x = self.patch_embed(x) cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks x = torch.cat((cls_tokens, x), dim=1) x = x + self.pos_embed x = self.pos_drop(x) if self.local_feature: for blk in self.blocks[:-1]: x = blk(x) return x else: for blk in self.blocks: x = blk(x) x = self.norm(x) return x[:, 0] def forward(self, x, cam_label=None, view_label=None): x = self.forward_features(x, cam_label, view_label) return x def load_param(self, model_path): param_dict = torch.load(model_path, map_location='cpu') if 'model' in param_dict: param_dict = param_dict['model'] if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for k, v in param_dict.items(): if 'head' in k or 'dist' in k: continue if 'patch_embed.proj.weight' in k and len(v.shape) < 4: # For old models that I trained prior to conv based patchification O, I, H, W = self.patch_embed.proj.weight.shape v = v.reshape(O, -1, H, W) elif k == 'pos_embed' and v.shape != self.pos_embed.shape: # To resize pos embedding when using model at different size from pretrained weights if 'distilled' in model_path: print('distill need to choose right cls token in the pth') v = torch.cat([v[:, 0:1], v[:, 2:]], dim=1) v = resize_pos_embed(v, self.pos_embed, self.patch_embed.num_y, self.patch_embed.num_x) # self.state_dict()[k].copy_(revise) try: self.state_dict()[k].copy_(v) except: print('===========================ERROR=========================') print('shape do not match in k :{}: param_dict{} vs self.state_dict(){}'.format(k, v.shape, self.state_dict()[k].shape)) def load_un_param(self, trained_path): param_dict = torch.load(trained_path) if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for k in list(param_dict.keys()): # retain only encoder_q up to before the embedding layer if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'): # remove prefix param_dict[k[len("module.encoder_q."):]] = param_dict[k] # delete renamed or unused k del param_dict[k] for i in param_dict: if 'fc' in i or 'head' in i: continue self.state_dict()[i].copy_(param_dict[i]) def resize_pos_embed(posemb, posemb_new, hight, width): # Rescale the grid of position embeddings when loading from state_dict. Adapted from # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224 print('Resized position embedding: %s to %s', posemb.shape, posemb_new.shape) ntok_new = posemb_new.shape[1] if True: posemb_tok, posemb_grid = posemb[:, :1], posemb[0, 1:] ntok_new -= 1 else: posemb_tok, posemb_grid = posemb[:, :0], posemb[0] gs_old = int(math.sqrt(len(posemb_grid))) print('Position embedding resize to height:{} width: {}'.format(hight, width)) posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) posemb_grid = F.interpolate(posemb_grid, size=(hight, width), mode='bilinear') # posemb_grid = F.interpolate(posemb_grid, size=(width, hight), mode='bilinear') posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, hight * width, -1) posemb = torch.cat([posemb_tok, posemb_grid], dim=1) return posemb def _conv_filter(state_dict, patch_size=16): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v return out_dict def vit_small_patch16_224_TransReID(img_size=(256, 128), stride_size=16, drop_path_rate=0.1, drop_rate=0.0, attn_drop_rate=0.0, local_feature=False, aie_xishu=1.5, **kwargs): model = TransReID( img_size=img_size, patch_size=16, stride_size=stride_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4, qkv_bias=True, drop_path_rate=drop_path_rate, drop_rate=drop_rate, attn_drop_rate=attn_drop_rate, aie_xishu=aie_xishu, local_feature=local_feature, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) return model def vit_base_patch16_224_TransReID(img_size=(256, 128), stride_size=16, drop_path_rate=0.1, local_feature=False,aie_xishu=1.5, **kwargs): model = TransReID( img_size=img_size, patch_size=16, stride_size=stride_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, drop_path_rate = drop_path_rate,\ norm_layer=partial(nn.LayerNorm, eps=1e-6), aie_xishu=aie_xishu, local_feature=local_feature, **kwargs) return model def _no_grad_trunc_normal_(tensor, mean, std, a, b): # Cut & paste from PyTorch official master until it's in a few official releases - RW # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf def norm_cdf(x): # Computes standard normal cumulative distribution function return (1. + math.erf(x / math.sqrt(2.))) / 2. if (mean < a - 2 * std) or (mean > b + 2 * std): print("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " "The distribution of values may be incorrect.",) with torch.no_grad(): # Values are generated by using a truncated uniform distribution and # then using the inverse CDF for the normal distribution. # Get upper and lower cdf values l = norm_cdf((a - mean) / std) u = norm_cdf((b - mean) / std) # Uniformly fill tensor with values from [l, u], then translate to # [2l-1, 2u-1]. tensor.uniform_(2 * l - 1, 2 * u - 1) # Use inverse cdf transform for normal distribution to get truncated # standard normal tensor.erfinv_() # Transform to proper mean, std tensor.mul_(std * math.sqrt(2.)) tensor.add_(mean) # Clamp to ensure it's in the proper range tensor.clamp_(min=a, max=b) return tensor def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): # type: (Tensor, float, float, float, float) -> Tensor r"""Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random values works best when :math:`a \leq \text{mean} \leq b`. Args: tensor: an n-dimensional `torch.Tensor` mean: the mean of the normal distribution std: the standard deviation of the normal distribution a: the minimum cutoff value b: the maximum cutoff value Examples: >>> w = torch.empty(3, 5) >>> nn.init.trunc_normal_(w) """ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
32,752
42.554521
174
py
CDTrans
CDTrans-master/model/backbones/se_module.py
from torch import nn class SELayer(nn.Module): def __init__(self, channel, reduction=16): super(SELayer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(channel, int(channel/reduction), bias=False), nn.ReLU(inplace=True), nn.Linear(int(channel/reduction), channel, bias=False), nn.Sigmoid() ) def forward(self, x): b, c, _, _ = x.size() y = self.avg_pool(x).view(b, c) y = self.fc(y).view(b, c, 1, 1) return x * y.expand_as(x)
609
31.105263
71
py
CDTrans
CDTrans-master/model/backbones/resnet.py
import math import torch from torch import nn def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) 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, last_stride=2, block=Bottleneck, frozen_stages=-1,layers=[3, 4, 6, 3]): self.inplanes = 64 super().__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) # self.relu = nn.ReLU(inplace=True) # add missed relu self.maxpool = nn.MaxPool2d(kernel_size=2, stride=None, padding=0) self.frozen_stages = frozen_stages self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=last_stride) def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def _freeze_stages(self): if self.frozen_stages >= 0: self.bn1.eval() for m in [self.conv1, self.bn1]: for param in m.parameters(): param.requires_grad = False for i in range(1, self.frozen_stages + 1): m = getattr(self, 'layer{}'.format(i)) print('layer{}'.format(i)) m.eval() for param in m.parameters(): param.requires_grad = False def forward(self, x, cam_label=None): x = self.conv1(x) # [64, 64, 128, 64] x = self.bn1(x) # x = self.relu(x) # add missed relu x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) return x def load_param(self, model_path): param_dict = torch.load(model_path) for i in param_dict: if 'fc' in i: continue self.state_dict()[i].copy_(param_dict[i]) def load_un_param(self, trained_path): param_dict = torch.load(trained_path) if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for k in list(param_dict.keys()): # retain only encoder_q up to before the embedding layer if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'): # remove prefix param_dict[k[len("module.encoder_q."):]] = param_dict[k] # delete renamed or unused k del param_dict[k] for i in param_dict: if 'fc' in i: continue self.state_dict()[i].copy_(param_dict[i]) def random_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.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()
5,721
31.885057
95
py
CDTrans
CDTrans-master/model/backbones/vit_pytorch_uda.py
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 The official jax code is released and available at https://github.com/google-research/vision_transformer Status/TODO: * Models updated to be compatible with official impl. Args added to support backward compat for old PyTorch weights. * Weights ported from official jax impl for 384x384 base and small models, 16x16 and 32x32 patches. * Trained (supervised on ImageNet-1k) my custom 'small' patch model to 77.9, 'base' to 79.4 top-1 with this code. * Hopefully find time and GPUs for SSL or unsupervised pretraining on OpenImages w/ ImageNet fine-tune in future. Acknowledgments: * The paper authors for releasing code and weights, thanks! * I fixed my class token impl based on Phil Wang's https://github.com/lucidrains/vit-pytorch ... check it out for some einops/einsum fun * Simple transformer style inspired by Andrej Karpathy's https://github.com/karpathy/minGPT * Bert reference code checks against Huggingface Transformers and Tensorflow Bert Hacked together by / Copyright 2020 Ross Wightman """ import math from functools import partial from itertools import repeat import torch import torch.nn as nn import torch.nn.functional as F from torch._six import container_abcs # From PyTorch internals def _ntuple(n): def parse(x): if isinstance(x, container_abcs.Iterable): return x return tuple(repeat(x, n)) return parse IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) to_2tuple = _ntuple(2) def drop_path(x, drop_prob: float = 0., training: bool = False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. """ if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) random_tensor.floor_() # binarize output = x.div(keep_prob) * random_tensor return output class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training) def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'patch_embed.proj', 'classifier': 'head', **kwargs } default_cfgs = { # patch models 'vit_small_patch16_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/vit_small_p16_224-15ec54c9.pth', ), 'vit_base_patch16_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_224-80ecf9dd.pth', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), ), 'vit_base_patch16_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_384-83fb41ba.pth', input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), 'vit_base_patch32_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p32_384-830016f5.pth', input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), 'vit_large_patch16_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p16_224-4ee7a4dc.pth', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), 'vit_large_patch16_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p16_384-b3be5167.pth', input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), 'vit_large_patch32_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p32_384-9b920ba8.pth', input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), 'vit_huge_patch16_224': _cfg(), 'vit_huge_patch32_384': _cfg(input_size=(3, 384, 384)), # hybrid models 'vit_small_resnet26d_224': _cfg(), 'vit_small_resnet50d_s3_224': _cfg(), 'vit_base_resnet26d_224': _cfg(), 'vit_base_resnet50d_224': _cfg(), } class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class Attention_3_branches(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.attn = None def forward(self, x, x2, use_attn=True, inference_target_only=False): B, N, C = x2.shape if inference_target_only: qkv2 = self.qkv(x2).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q2, k2, v2 = qkv2[0], qkv2[1], qkv2[2] # make torchscript happy (cannot use tensor as tuple) attn2 = (q2 @ k2.transpose(-2, -1)) * self.scale attn2 = attn2.softmax(dim=-1) self.attn = attn2 attn2 = self.attn_drop(attn2) x2 = ( attn2 @ v2 ) if use_attn else v2 x2 = x2.transpose(1, 2).reshape(B, N, C) x2 = self.proj(x2) x2 = self.proj_drop(x2) attn3 = None x, x3 = None, None else: qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) qkv2 = self.qkv(x2).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q2, k2, v2 = qkv2[0], qkv2[1], qkv2[2] # make torchscript happy (cannot use tensor as tuple) attn = (q @ k.transpose(-2, -1)) * self.scale attn2 = (q2 @ k2.transpose(-2, -1)) * self.scale attn3 = (q @ k2.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn2 = attn2.softmax(dim=-1) attn3 = attn3.softmax(dim=-1) self.attn = attn attn = self.attn_drop(attn) attn2 = self.attn_drop(attn2) attn3 = self.attn_drop(attn3) x = ( attn @ v ) if use_attn else v x2 = ( attn2 @ v2 ) if use_attn else v2 x3 = ( attn3 @ v2 ) if use_attn else v2 x = x.transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) x2 = x2.transpose(1, 2).reshape(B, N, C) x2 = self.proj(x2) x2 = self.proj_drop(x2) x3 = x3.transpose(1, 2).reshape(B, N, C) x3 = self.proj(x3) x3 = self.proj_drop(x3) return x, x2, x3, None # return x, x2, x3, attn3 class Block_3_branches(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention_3_branches( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, x, x2, x1_x2_fusion, use_cross=False, use_attn=True, domain_norm=False,inference_target_only=False): if inference_target_only: _, xa_attn2, _, _ = self.attn(None,self.norm1(x2), inference_target_only=inference_target_only) xb = x2 + self.drop_path(xa_attn2) xb = xb + self.drop_path(self.mlp(self.norm2(xb))) xa, xab, cross_attn = None, None, None else: xa_attn, xa_attn2, xa_attn3, cross_attn = self.attn(self.norm1(x),self.norm1(x2), inference_target_only=inference_target_only) xa = x + self.drop_path(xa_attn) xa = xa + self.drop_path(self.mlp(self.norm2(xa))) xb = x2 + self.drop_path(xa_attn2) xb = xb + self.drop_path(self.mlp(self.norm2(xb))) xab = x1_x2_fusion + self.drop_path(xa_attn3) xab = xab + self.drop_path(self.mlp(self.norm2(xab))) return xa, xb, xab, cross_attn class PatchEmbed(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) self.img_size = img_size self.patch_size = patch_size self.num_patches = num_patches self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) def forward(self, x): B, C, H, W = x.shape # FIXME look at relaxing size constraints assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x).flatten(2).transpose(1, 2) return x class HybridEmbed(nn.Module): """ CNN Feature Map Embedding Extract feature map from CNN, flatten, project to embedding dim. """ def __init__(self, backbone, img_size=224, feature_size=None, in_chans=3, embed_dim=768): super().__init__() assert isinstance(backbone, nn.Module) img_size = to_2tuple(img_size) self.img_size = img_size self.backbone = backbone if feature_size is None: with torch.no_grad(): # FIXME this is hacky, but most reliable way of determining the exact dim of the output feature # map for all networks, the feature metadata has reliable channel and stride info, but using # stride to calc feature dim requires info about padding of each stage that isn't captured. training = backbone.training if training: backbone.eval() o = self.backbone(torch.zeros(1, in_chans, img_size[0], img_size[1]))[-1] feature_size = o.shape[-2:] feature_dim = o.shape[1] backbone.train(training) else: feature_size = to_2tuple(feature_size) feature_dim = self.backbone.feature_info.channels()[-1] self.num_patches = feature_size[0] * feature_size[1] self.proj = nn.Linear(feature_dim, embed_dim) def forward(self, x): x = self.backbone(x)[-1] x = x.flatten(2).transpose(1, 2) x = self.proj(x) return x class PatchEmbed_stride(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, stride_size=20, in_chans=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) stride_size_tuple = to_2tuple(stride_size) self.num_x = (img_size[1] - patch_size[1]) // stride_size_tuple[1] + 1 self.num_y = (img_size[0] - patch_size[0]) // stride_size_tuple[0] + 1 print('using stride: {}, and part number is num_y{} * num_x{}'.format(stride_size, self.num_y, self.num_x)) num_patches = self.num_x * self.num_y self.img_size = img_size self.patch_size = patch_size self.num_patches = num_patches self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride_size) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.InstanceNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def forward(self, x): B, C, H, W = x.shape # FIXME look at relaxing size constraints assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x) x = x.flatten(2).transpose(1, 2) # [64, 8, 768] return x class ConvStemEmbed_stride(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, stride_size=20, in_chans=3, conv_channel= [24, 48, 96, 192], embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) stride_size_tuple = to_2tuple(stride_size) self.num_x = (img_size[1] - patch_size[1]) // stride_size_tuple[1] + 1 self.num_y = (img_size[0] - patch_size[0]) // stride_size_tuple[0] + 1 print('using stride: {}, and part number is num_y{} * num_x{}'.format(stride_size, self.num_y, self.num_x)) num_patches = self.num_x * self.num_y self.img_size = img_size self.patch_size = patch_size self.num_patches = num_patches self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride_size) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.InstanceNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def forward(self, x): B, C, H, W = x.shape # FIXME look at relaxing size constraints assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x) x = x.flatten(2).transpose(1, 2) # [64, 8, 768] return x class TransReID(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__(self, img_size=224, patch_size=16, stride_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., camera=0, view=0, drop_path_rate=0., hybrid_backbone=None, norm_layer=nn.LayerNorm,local_feature=False, aie_xishu =1.0, use_cross=False, use_attn=True, block_pattern='normal'): super().__init__() self.use_cross = use_cross self.use_attn = use_attn self.num_classes = num_classes self.block_pattern = block_pattern self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models self.local_feature = local_feature if hybrid_backbone is not None: self.patch_embed = HybridEmbed( hybrid_backbone, img_size=img_size, in_chans=in_chans, embed_dim=embed_dim) else: self.patch_embed = PatchEmbed_stride( img_size=img_size, patch_size=patch_size, stride_size=stride_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) self.cam_num = camera self.view_num = view if camera > 0 and view > 0: self.aux_embed = nn.Parameter(torch.zeros(camera * view, 1, embed_dim)) trunc_normal_(self.aux_embed, std=.02) print('camera number is : {} and viewpoint number is : {}'.format(camera, view)) elif camera > 0: self.aux_embed = nn.Parameter(torch.zeros(camera, 1, embed_dim)) trunc_normal_(self.aux_embed, std=.02) print('camera number is : {}'.format(camera)) elif view > 0: self.aux_embed = nn.Parameter(torch.zeros(view, 1, embed_dim)) trunc_normal_(self.aux_embed, std=.02) print('viewpoint number is : {}'.format(view)) print('using drop_path_rate is : {}'.format(drop_path_rate)) print('using aie_xishu is : {}'.format(aie_xishu)) self.pos_drop = nn.Dropout(p=drop_rate) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule print('using 3branches blocks') self.blocks = nn.ModuleList([ Block_3_branches( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer) for i in range(depth)]) self.norm = norm_layer(embed_dim) self.AIE_MULTI = aie_xishu # Classifier head self.fc = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() trunc_normal_(self.cls_token, std=.02) trunc_normal_(self.pos_embed, std=.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token'} def get_classifier(self): return self.head def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.fc = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x, x2, camera_id, view_id, domain_norm=False, cls_embed_specific=False,inference_target_only=False): B = x.shape[0] # print('x size is {} x2 size is {}'.format(x.size(), x2.size())) x = self.patch_embed(x) x2 = self.patch_embed(x2) cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks x = torch.cat((cls_tokens, x), dim=1) x2 = torch.cat((cls_tokens, x2), dim=1) if self.cam_num > 0 and self.view_num > 0: x = x + self.pos_embed + self.AIE_MULTI * self.aux_embed[camera_id * self.view_num + view_id] elif self.cam_num > 0: x = x + self.pos_embed + self.AIE_MULTI * self.aux_embed[camera_id] elif self.view_num > 0: x = x + self.pos_embed + self.AIE_MULTI * self.aux_embed[view_id] else: x = x + self.pos_embed x2 = x2 + self.pos_embed x = self.pos_drop(x) x2 = self.pos_drop(x2) if self.local_feature: for blk in self.blocks[:-1]: x = blk(x) return x else: if self.block_pattern == '3_branches': x1_x2_fusion = x2 cross_attn_list = [] for i, blk in enumerate(self.blocks): x,x2,x1_x2_fusion, cross_attn = blk(x,x2,x1_x2_fusion,use_cross=self.use_cross,use_attn=self.use_attn, domain_norm=domain_norm, inference_target_only=inference_target_only) cross_attn_list.append(cross_attn) if inference_target_only: x2 = self.norm(x2) return None, x2[:, 0], None, None else: x = self.norm(x) x2 = self.norm(x2) x1_x2_fusion = self.norm(x1_x2_fusion) return x[:, 0], x2[:, 0], x1_x2_fusion[:, 0], cross_attn_list else: for i, blk in enumerate(self.blocks): x,x2 = blk(x,x2,use_cross=self.use_cross,use_attn=self.use_attn, domain_norm=domain_norm) x = self.norm(x) x2 = self.norm(x2) return x[:, 0], x2[:, 0] def forward(self, x, x2, cam_label=None, view_label=None, domain_norm=False, cls_embed_specific=False,inference_target_only=False): x = self.forward_features(x, x2, cam_label, view_label, domain_norm, cls_embed_specific,inference_target_only) return x def load_param(self, model_path): param_dict = torch.load(model_path, map_location='cpu') if 'model' in param_dict: param_dict = param_dict['model'] if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for k, v in param_dict.items(): # print('k v is {} {}'.format(k,v)) if 'head' in k or 'dist' in k: continue if 'patch_embed.proj.weight' in k and len(v.shape) < 4: # For old models that I trained prior to conv based patchification O, I, H, W = self.patch_embed.proj.weight.shape v = v.reshape(O, -1, H, W) elif k == 'pos_embed' and v.shape != self.pos_embed.shape: # To resize pos embedding when using model at different size from pretrained weights if 'distilled' in model_path: print('distill need to choose right cls token in the pth') v = torch.cat([v[:, 0:1], v[:, 2:]], dim=1) v = resize_pos_embed(v, self.pos_embed, self.patch_embed.num_y, self.patch_embed.num_x) # self.state_dict()[k].copy_(revise) try: self.state_dict()[k].copy_(v) except: print('===========================ERROR=========================') print('shape do not match in k :{}: param_dict{} vs self.state_dict(){}'.format(k, v.shape, self.state_dict()[k].shape)) def load_un_param(self, trained_path): param_dict = torch.load(trained_path) if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for k in list(param_dict.keys()): # retain only encoder_q up to before the embedding layer if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'): # remove prefix param_dict[k[len("module.encoder_q."):]] = param_dict[k] # delete renamed or unused k del param_dict[k] for i in param_dict: if 'fc' in i or 'head' in i: continue self.state_dict()[i].copy_(param_dict[i]) def resize_pos_embed(posemb, posemb_new, hight, width): # Rescale the grid of position embeddings when loading from state_dict. Adapted from # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224 print('Resized position embedding: %s to %s', posemb.shape, posemb_new.shape) ntok_new = posemb_new.shape[1] if True: posemb_tok, posemb_grid = posemb[:, :1], posemb[0, 1:] ntok_new -= 1 else: posemb_tok, posemb_grid = posemb[:, :0], posemb[0] gs_old = int(math.sqrt(len(posemb_grid))) print('Position embedding resize to height:{} width: {}'.format(hight, width)) posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) posemb_grid = F.interpolate(posemb_grid, size=(hight, width), mode='bilinear') # posemb_grid = F.interpolate(posemb_grid, size=(width, hight), mode='bilinear') posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, hight * width, -1) posemb = torch.cat([posemb_tok, posemb_grid], dim=1) return posemb def _conv_filter(state_dict, patch_size=16): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v return out_dict def uda_vit_small_patch16_224_TransReID(img_size=(256, 128), stride_size=16, drop_path_rate=0.1, drop_rate=0.0, attn_drop_rate=0.0, local_feature=False, aie_xishu=1.5, **kwargs): model = TransReID( img_size=img_size, patch_size=16, stride_size=stride_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4, qkv_bias=True, drop_path_rate=drop_path_rate, drop_rate=drop_rate, attn_drop_rate=attn_drop_rate, aie_xishu=aie_xishu, local_feature=local_feature, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) return model def uda_vit_base_patch16_224_TransReID(img_size=(256, 128), stride_size=16, drop_path_rate=0.1, local_feature=False,aie_xishu=1.5,use_cross=False, use_attn=True, **kwargs): model = TransReID( img_size=img_size, patch_size=16, stride_size=stride_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, drop_path_rate = drop_path_rate,\ norm_layer=partial(nn.LayerNorm, eps=1e-6), aie_xishu=aie_xishu, local_feature=local_feature, use_cross=use_cross, use_attn=use_attn, **kwargs) return model def _no_grad_trunc_normal_(tensor, mean, std, a, b): # Cut & paste from PyTorch official master until it's in a few official releases - RW # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf def norm_cdf(x): # Computes standard normal cumulative distribution function return (1. + math.erf(x / math.sqrt(2.))) / 2. if (mean < a - 2 * std) or (mean > b + 2 * std): print("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " "The distribution of values may be incorrect.",) with torch.no_grad(): # Values are generated by using a truncated uniform distribution and # then using the inverse CDF for the normal distribution. # Get upper and lower cdf values l = norm_cdf((a - mean) / std) u = norm_cdf((b - mean) / std) # Uniformly fill tensor with values from [l, u], then translate to # [2l-1, 2u-1]. tensor.uniform_(2 * l - 1, 2 * u - 1) # Use inverse cdf transform for normal distribution to get truncated # standard normal tensor.erfinv_() # Transform to proper mean, std tensor.mul_(std * math.sqrt(2.)) tensor.add_(mean) # Clamp to ensure it's in the proper range tensor.clamp_(min=a, max=b) return tensor def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): # type: (Tensor, float, float, float, float) -> Tensor r"""Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random values works best when :math:`a \leq \text{mean} \leq b`. Args: tensor: an n-dimensional `torch.Tensor` mean: the mean of the normal distribution std: the standard deviation of the normal distribution a: the minimum cutoff value b: the maximum cutoff value Examples: >>> w = torch.empty(3, 5) >>> nn.init.trunc_normal_(w) """ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
29,841
43.942771
192
py
CDTrans
CDTrans-master/model/backbones/se_resnet_ibn_a.py
from .se_module import SELayer import torch.nn as nn import torch import math from collections import OrderedDict import torch.utils.checkpoint as cp __all__ = ['se_resnet50_ibn_a', 'se_resnet101_ibn_a', 'se_resnet152_ibn_a'] def conv3x3(in_planes, out_planes, stride=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class IBN(nn.Module): def __init__(self, planes): super(IBN, self).__init__() half1 = int(planes/2) self.half = half1 half2 = planes - half1 self.IN = nn.InstanceNorm2d(half1, affine=True) self.BN = nn.BatchNorm2d(half2) def forward(self, x): split = torch.split(x, self.half, 1) out1 = self.IN(split[0].contiguous()) out2 = self.BN(split[1].contiguous()) out = torch.cat((out1, out2), 1) return out class SEBasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, reduction=16): super(SEBasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes, 1) self.bn2 = nn.BatchNorm2d(planes) self.se = SELayer(planes, reduction) 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.se(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class SEBottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, ibn=False, reduction=16): super(SEBottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) if ibn: self.bn1 = IBN(planes) else: self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.se = SELayer(planes * 4, reduction) 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) out = self.se(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, last_stride,block, layers, frozen_stages=-1, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.frozen_stages = frozen_stages self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=last_stride) self.avgpool = nn.AvgPool2d(7) self.fc = nn.Linear(512 * block.expansion, num_classes) self.conv1.weight.data.normal_(0, math.sqrt(2. / (7 * 7 * 64))) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.InstanceNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] ibn = True if planes == 512: ibn = False layers.append(block(self.inplanes, planes, stride, downsample, ibn=ibn)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes, 1, None, ibn=ibn)) return nn.Sequential(*layers) def _freeze_stages(self): if self.frozen_stages >= 0: self.bn1.eval() for m in [self.conv1, self.bn1]: for param in m.parameters(): param.requires_grad = False for i in range(1, self.frozen_stages + 1): m = getattr(self, 'layer{}'.format(i)) print('layer{}'.format(i)) m.eval() for param in m.parameters(): param.requires_grad = False def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) #x = self.avgpool(x) #x = x.view(x.size(0), -1) #x = self.fc(x) return x def load_param(self, model_path): param_dict = torch.load(model_path) if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for i in param_dict: if 'fc' in i: continue self.state_dict()[i.replace('module.','')].copy_(param_dict[i]) def se_resnet50_ibn_a(last_stride,num_classes=1000,**kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(last_stride,SEBottleneck, [3, 4, 6, 3], num_classes=num_classes,**kwargs) model.avgpool = nn.AdaptiveAvgPool2d(1) return model def se_resnet101_ibn_a(last_stride,num_classes=1000,**kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(last_stride,SEBottleneck, [3, 4, 23, 3], num_classes=num_classes,**kwargs) model.avgpool = nn.AdaptiveAvgPool2d(1) return model def se_resnet152_ibn_a(last_stride,num_classes): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(last_stride,SEBottleneck, [3, 8, 36, 3], num_classes=num_classes) model.avgpool = nn.AdaptiveAvgPool2d(1) return model
7,446
31.662281
96
py
CDTrans
CDTrans-master/model/backbones/resnet_ibn_a.py
import torch import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch.nn.functional as F __all__ = ['ResNet_IBN', 'resnet50_ibn_a', 'resnet101_ibn_a', 'resnet152_ibn_a'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', } class IBN(nn.Module): def __init__(self, planes): super(IBN, self).__init__() half1 = int(planes/2) self.half = half1 half2 = planes - half1 self.IN = nn.InstanceNorm2d(half1, affine=True) self.BN = nn.BatchNorm2d(half2) def forward(self, x): split = torch.split(x, self.half, 1) out1 = self.IN(split[0].contiguous()) out2 = self.BN(split[1].contiguous()) out = torch.cat((out1, out2), 1) return out class Bottleneck_IBN(nn.Module): expansion = 4 def __init__(self, inplanes, planes, ibn=False, stride=1, downsample=None): super(Bottleneck_IBN, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) if ibn: self.bn1 = IBN(planes) else: self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class ResNet_IBN(nn.Module): def __init__(self, last_stride, block, layers, frozen_stages=-1,num_classes=1000): scale = 64 self.inplanes = scale super(ResNet_IBN, self).__init__() self.conv1 = nn.Conv2d(3, scale, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(scale) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.frozen_stages = frozen_stages self.layer1 = self._make_layer(block, scale, layers[0]) self.layer2 = self._make_layer(block, scale*2, layers[1], stride=2) self.layer3 = self._make_layer(block, scale*4, layers[2], stride=2) self.layer4 = self._make_layer(block, scale*8, layers[3], stride=last_stride) self.avgpool = nn.AvgPool2d(7) self.fc = nn.Linear(scale * 8 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.InstanceNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] ibn = True if planes == 512: ibn = False layers.append(block(self.inplanes, planes, ibn, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes, ibn)) return nn.Sequential(*layers) def _freeze_stages(self): if self.frozen_stages >= 0: self.bn1.eval() for m in [self.conv1, self.bn1]: for param in m.parameters(): param.requires_grad = False for i in range(1, self.frozen_stages + 1): m = getattr(self, 'layer{}'.format(i)) print('layer{}'.format(i)) m.eval() for param in m.parameters(): param.requires_grad = False def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) # x = self.avgpool(x) # x = x.view(x.size(0), -1) # x = self.fc(x) return x def load_param(self, model_path): param_dict = torch.load(model_path) if 'state_dict' in param_dict: param_dict = param_dict['state_dict'] for i in param_dict: if 'fc' in i: continue self.state_dict()[i.replace('module.','')].copy_(param_dict[i]) def resnet50_ibn_a(last_stride, pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet_IBN(last_stride, Bottleneck_IBN, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model def resnet101_ibn_a(last_stride, pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet_IBN(last_stride, Bottleneck_IBN, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model def resnet152_ibn_a(last_stride, pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet_IBN(last_stride, Bottleneck_IBN, [3, 8, 36, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
6,681
32.747475
90
py
monotone_op_net
monotone_op_net-master/mon.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class MONSingleFc(nn.Module): """ Simple MON linear class, just a single full multiply. """ def __init__(self, in_dim, out_dim, m=1.0): super().__init__() self.U = nn.Linear(in_dim, out_dim) self.A = nn.Linear(out_dim, out_dim, bias=False) self.B = nn.Linear(out_dim, out_dim, bias=False) self.m = m def x_shape(self, n_batch): return (n_batch, self.U.in_features) def z_shape(self, n_batch): return ((n_batch, self.A.in_features),) def forward(self, x, *z): return (self.U(x) + self.multiply(*z)[0],) def bias(self, x): return (self.U(x),) def multiply(self, *z): ATAz = self.A(z[0]) @ self.A.weight z_out = (1 - self.m) * z[0] - ATAz + self.B(z[0]) - z[0] @ self.B.weight return (z_out,) def multiply_transpose(self, *g): ATAg = self.A(g[0]) @ self.A.weight g_out = (1 - self.m) * g[0] - ATAg - self.B(g[0]) + g[0] @ self.B.weight return (g_out,) def init_inverse(self, alpha, beta): I = torch.eye(self.A.weight.shape[0], dtype=self.A.weight.dtype, device=self.A.weight.device) W = (1 - self.m) * I - self.A.weight.T @ self.A.weight + self.B.weight - self.B.weight.T self.Winv = torch.inverse(alpha * I + beta * W) def inverse(self, *z): return (z[0] @ self.Winv.transpose(0, 1),) def inverse_transpose(self, *g): return (g[0] @ self.Winv,) class MONReLU(nn.Module): def forward(self, *z): return tuple(F.relu(z_) for z_ in z) def derivative(self, *z): return tuple((z_ > 0).type_as(z[0]) for z_ in z) # Convolutional layers w/ FFT-based inverses def fft_to_complex_matrix(x): """ Create matrix with [a -b; b a] entries for complex numbers. """ x_stacked = torch.stack((x, torch.flip(x, (4,))), dim=5).permute(2, 3, 0, 4, 1, 5) x_stacked[:, :, :, 0, :, 1] *= -1 return x_stacked.reshape(-1, 2 * x.shape[0], 2 * x.shape[1]) def fft_to_complex_vector(x): """ Create stacked vector with [a;b] entries for complex numbers""" return x.permute(2, 3, 0, 1, 4).reshape(-1, x.shape[0], x.shape[1] * 2) def init_fft_conv(weight, hw): """ Initialize fft-based convolution. Args: weight: Pytorch kernel hw: (height, width) tuple """ px, py = (weight.shape[2] - 1) // 2, (weight.shape[3] - 1) // 2 kernel = torch.flip(weight, (2, 3)) kernel = F.pad(F.pad(kernel, (0, hw[0] - weight.shape[2], 0, hw[1] - weight.shape[3])), (0, py, 0, px), mode="circular")[:, :, py:, px:] return fft_to_complex_matrix(torch.rfft(kernel, 2, onesided=False)) def fft_conv(x, w_fft, transpose=False): """ Perhaps FFT-based circular convolution. Args: x: (B, C, H, W) tensor w_fft: conv kernel processed by init_fft_conv transpose: flag of whether to transpose convolution """ x_fft = fft_to_complex_vector(torch.rfft(x, 2, onesided=False)) wx_fft = x_fft.bmm(w_fft.transpose(1, 2)) if not transpose else x_fft.bmm(w_fft) wx_fft = wx_fft.view(x.shape[2], x.shape[3], wx_fft.shape[1], -1, 2).permute(2, 3, 0, 1, 4) return torch.irfft(wx_fft, 2, onesided=False) class MONSingleConv(nn.Module): """ MON class with a single 3x3 (circular) convolution """ def __init__(self, in_channels, out_channels, shp, kernel_size=3, m=1.0): super().__init__() self.U = nn.Conv2d(in_channels, out_channels, kernel_size) self.A = nn.Conv2d(out_channels, out_channels, kernel_size, bias=False) self.g = nn.Parameter(torch.tensor(1.)) self.h = nn.Parameter(torch.tensor(1.)) self.B = nn.Conv2d(out_channels, out_channels, kernel_size, bias=False) self.pad = 4 * ((kernel_size - 1) // 2,) self.shp = shp self.m = m def cpad(self, x): return F.pad(x, self.pad, mode="circular") def uncpad(self, x): return x[:, :, 2 * self.pad[0]:-2 * self.pad[1], 2 * self.pad[2]:-2 * self.pad[3]] def x_shape(self, n_batch): return (n_batch, self.U.in_channels, self.shp[0], self.shp[1]) def z_shape(self, n_batch): return ((n_batch, self.A.in_channels, self.shp[0], self.shp[1]),) def forward(self, x, *z): # circular padding is broken in PyTorch return (F.conv2d(self.cpad(x), self.U.weight, self.U.bias) + self.multiply(*z)[0],) def bias(self, x): return (F.conv2d(self.cpad(x), self.U.weight, self.U.bias),) def multiply(self, *z): A = self.A.weight / self.A.weight.view(-1).norm() B = self.h * self.B.weight / self.B.weight.view(-1).norm() Az = F.conv2d(self.cpad(z[0]), A) ATAz = self.uncpad(F.conv_transpose2d(self.cpad(Az), A)) Bz = F.conv2d(self.cpad(z[0]), B) BTz = self.uncpad(F.conv_transpose2d(self.cpad(z[0]), B)) z_out = (1 - self.m) * z[0] - self.g * ATAz + Bz - BTz return (z_out,) def multiply_transpose(self, *g): A = self.A.weight / self.A.weight.view(-1).norm() B = self.h * self.B.weight / self.B.weight.view(-1).norm() Ag = F.conv2d(self.cpad(g[0]), A) ATAg = self.uncpad(F.conv_transpose2d(self.cpad(Ag), A)) Bg = F.conv2d(self.cpad(g[0]), B) BTg = self.uncpad(F.conv_transpose2d(self.cpad(g[0]), B)) g_out = (1 - self.m) * g[0] - self.g * ATAg - Bg + BTg return (g_out,) def init_inverse(self, alpha, beta): A = self.A.weight / self.A.weight.view(-1).norm() B = self.h * self.B.weight / self.B.weight.view(-1).norm() Afft = init_fft_conv(A, self.shp) Bfft = init_fft_conv(B, self.shp) I = torch.eye(Afft.shape[1], dtype=Afft.dtype, device=Afft.device)[None, :, :] self.Wfft = (1 - self.m) * I - self.g * Afft.transpose(1, 2) @ Afft + Bfft - Bfft.transpose(1, 2) self.Winv = torch.inverse(alpha * I + beta * self.Wfft) def inverse(self, *z): return (fft_conv(z[0], self.Winv),) def inverse_transpose(self, *g): return (fft_conv(g[0], self.Winv, transpose=True),) class MONBorderReLU(nn.Module): def __init__(self, border=1): super().__init__() self.border = border def forward(self, *z): zn = tuple(F.relu(z_) for z_ in z) for i in range(len(zn)): zn[i][:, :, :self.border, :] = 0 zn[i][:, :, -self.border:, :] = 0 zn[i][:, :, :, :self.border] = 0 zn[i][:, :, :, -self.border:] = 0 return zn def derivative(self, *z): return tuple((z_ > 0).type_as(z[0]) for z_ in z) class MONMultiConv(nn.Module): def __init__(self, in_channels, conv_channels, image_size, kernel_size=3, m=1.0): super().__init__() self.pad = 4 * ((kernel_size - 1) // 2,) self.conv_shp = tuple((image_size - 2 * self.pad[0]) // 2 ** i + 2 * self.pad[0] for i in range(len(conv_channels))) self.m = m # create convolutional layers self.U = nn.Conv2d(in_channels, conv_channels[0], kernel_size) self.A0 = nn.ModuleList([nn.Conv2d(c, c, kernel_size, bias=False) for c in conv_channels]) self.B0 = nn.ModuleList([nn.Conv2d(c, c, kernel_size, bias=False) for c in conv_channels]) self.A_n0 = nn.ModuleList([nn.Conv2d(c1, c2, kernel_size, bias=False, stride=2) for c1, c2 in zip(conv_channels[:-1], conv_channels[1:])]) self.g = nn.ParameterList([nn.Parameter(torch.tensor(1.)) for _ in range(len(conv_channels))]) self.gn = nn.ParameterList([nn.Parameter(torch.tensor(1.)) for _ in range(len(conv_channels) - 1)]) self.h = nn.ParameterList([nn.Parameter(torch.tensor(1.)) for _ in range(len(conv_channels))]) self.S_idx = list() self.S_idxT = list() for n in self.conv_shp: p = n // 2 q = n idxT = list() _idx = [[j + (i - 1) * p for i in range(1, q + 1)] for j in range(1, p + 1)] for i in _idx: for j in i: idxT.append(j - 1) _idx = [[j + (i - 1) * p + p * q for i in range(1, q + 1)] for j in range(1, p + 1)] for i in _idx: for j in i: idxT.append(j - 1) idx = list() _idx = [[j + (i - 1) * q for i in range(1, p + 1)] for j in range(1, q + 1)] for i in _idx: for j in i: idx.append(j - 1) _idx = [[j + (i - 1) * q + p * q for i in range(1, p + 1)] for j in range(1, q + 1)] for i in _idx: for j in i: idx.append(j - 1) self.S_idx.append(idx) self.S_idxT.append(idxT) def A(self, i): return torch.sqrt(self.g[i]) * self.A0[i].weight / self.A0[i].weight.view(-1).norm() def A_n(self, i): return torch.sqrt(self.gn[i]) * self.A_n0[i].weight / self.A_n0[i].weight.view(-1).norm() def B(self, i): return self.h[i] * self.B0[i].weight / self.B0[i].weight.view(-1).norm() def cpad(self, x): return F.pad(x, self.pad, mode="circular") def uncpad(self, x): return x[:, :, 2 * self.pad[0]:-2 * self.pad[1], 2 * self.pad[2]:-2 * self.pad[3]] def zpad(self, x): return F.pad(x, (0, 1, 0, 1)) def unzpad(self, x): return x[:, :, :-1, :-1] def unstride(self, x): x[:, :, :, -1] += x[:, :, :, 0] x[:, :, -1, :] += x[:, :, 0, :] return x[:, :, 1:, 1:] def x_shape(self, n_batch): return (n_batch, self.U.in_channels, self.conv_shp[0], self.conv_shp[0]) def z_shape(self, n_batch): return tuple((n_batch, self.A0[i].in_channels, self.conv_shp[i], self.conv_shp[i]) for i in range(len(self.A0))) def forward(self, x, *z): z_out = self.multiply(*z) bias = self.bias(x) return tuple([z_out[i] + bias[i] for i in range(len(self.A0))]) def bias(self, x): z_shape = self.z_shape(x.shape[0]) n = len(self.A0) b_out = [self.U(self.cpad(x))] for i in range(n - 1): b_out.append(torch.zeros(z_shape[i + 1], dtype=self.A0[0].weight.dtype, device=self.A0[0].weight.device)) return tuple(b_out) def multiply(self, *z): def multiply_zi(z1, A1, B1, A1_n=None, z0=None, A2_n=None): Az1 = F.conv2d(self.cpad(z1), A1) A1TA1z1 = self.uncpad(F.conv_transpose2d(self.cpad(Az1), A1)) B1z1 = F.conv2d(self.cpad(z1), B1) B1Tz1 = self.uncpad(F.conv_transpose2d(self.cpad(z1), B1)) out = (1 - self.m) * z1 - A1TA1z1 + B1z1 - B1Tz1 if A2_n is not None: A2_nz1 = F.conv2d(self.cpad(z1), A2_n, stride=2) A2_nTA2_nz1 = self.unstride(F.conv_transpose2d(A2_nz1, A2_n, stride=2)) out -= A2_nTA2_nz1 if A1_n is not None: A1_nz0 = self.zpad(F.conv2d(self.cpad(z0), A1_n, stride=2)) A1TA1_nz0 = self.uncpad(F.conv_transpose2d(self.cpad(A1_nz0), A1)) out -= 2 * A1TA1_nz0 return out n = len(self.A0) z_out = [multiply_zi(z[0], self.A(0), self.B(0), A2_n=self.A_n(0))] for i in range(1, n - 1): z_out.append(multiply_zi(z[i], self.A(i), self.B(i), A1_n=self.A_n(i - 1), z0=z[i - 1], A2_n=self.A_n(i))) z_out.append(multiply_zi(z[n - 1], self.A(n - 1), self.B(n - 1), A1_n=self.A_n(n - 2), z0=z[n - 2])) return tuple(z_out) def multiply_transpose(self, *g): def multiply_zi(z1, A1, B1, z2=None, A2_n=None, A2=None): Az1 = F.conv2d(self.cpad(z1), A1) A1TA1z1 = self.uncpad(F.conv_transpose2d(self.cpad(Az1), A1)) B1z1 = F.conv2d(self.cpad(z1), B1) B1Tz1 = self.uncpad(F.conv_transpose2d(self.cpad(z1), B1)) out = (1 - self.m) * z1 - A1TA1z1 - B1z1 + B1Tz1 if A2_n is not None: A2z2 = F.conv2d(self.cpad(z2), A2) A2_nTA2z2 = self.unstride(F.conv_transpose2d(self.unzpad(A2z2), A2_n, stride=2)) out -= 2 * A2_nTA2z2 A2_nz1 = F.conv2d(self.cpad(z1), A2_n, stride=2) A2_nTA2_nz1 = self.unstride(F.conv_transpose2d(A2_nz1, A2_n, stride=2)) out -= A2_nTA2_nz1 return out n = len(self.A0) g_out = [] for i in range(n - 1): g_out.append(multiply_zi(g[i], self.A(i), self.B(i), z2=g[i + 1], A2_n=self.A_n(i), A2=self.A(i + 1))) g_out.append(multiply_zi(g[n - 1], self.A(n - 1), self.B(n - 1))) return g_out def init_inverse(self, alpha, beta): n = len(self.A0) conv_fft_A = [init_fft_conv(self.A(i), (self.conv_shp[i], self.conv_shp[i])) for i in range(n)] conv_fft_B = [init_fft_conv(self.B(i), (self.conv_shp[i], self.conv_shp[i])) for i in range(n)] conv_fft_A_n = [init_fft_conv(self.A_n(i - 1), (self.conv_shp[i - 1], self.conv_shp[i - 1])) for i in range(1, n)] I = [torch.eye(2 * self.A0[i].weight.shape[1], dtype=self.A0[i].weight.dtype, device=self.A0[i].weight.device)[None, :, :] for i in range(n)] D1 = [(alpha + beta - beta * self.m) * I[i] \ - beta * conv_fft_A[i].transpose(1, 2) @ conv_fft_A[i] \ + beta * conv_fft_B[i] - beta * conv_fft_B[i].transpose(1, 2) for i in range(n - 1)] self.D1inv = [torch.inverse(D) for D in D1] self.D2 = [np.sqrt(-beta) * conv_fft_A_n[i] for i in range(n - 1)] G = [(self.D2[i] @ self.D1inv[i] @ self.D2[i].transpose(1, 2))[self.S_idx[i]] for i in range(n - 1)] S = [G[i][:self.conv_shp[i] ** 2 // 4] + G[i][self.conv_shp[i] ** 2 // 4:self.conv_shp[i] ** 2 // 2] + G[i][self.conv_shp[i] ** 2 // 2:3 * self.conv_shp[i] ** 2 // 4] + G[i][3 * self.conv_shp[i] ** 2 // 4:] for i in range(n - 1)] Hinv = [torch.eye(s.shape[1], device=s.device) + 0.25 * s for s in S] self.H = [torch.inverse(hinv).float() for hinv in Hinv] Wn = (1 - self.m) * I[n - 1] \ - conv_fft_A[n - 1].transpose(1, 2) @ conv_fft_A[n - 1] \ + conv_fft_B[n - 1] - conv_fft_B[n - 1].transpose(1, 2) self.Wn_inv = torch.inverse(alpha * I[n - 1] + beta * Wn) self.beta = beta def apply_inverse_conv(self, z, i): z0_fft = fft_to_complex_vector(torch.rfft(z, 2, onesided=False)) y0 = 0.5 * z0_fft.bmm((self.D2[i] @ self.D1inv[i]).transpose(1, 2))[self.S_idx[i]] n = self.conv_shp[i] y1 = y0[:n ** 2 // 4] + y0[n ** 2 // 4:n ** 2 // 2] + y0[n ** 2 // 2:3 * n ** 2 // 4] + y0[3 * n ** 2 // 4:] y2 = y1.bmm(self.H[i].transpose(1, 2)) y3 = y2.repeat(4, 1, 1) y4 = y3[self.S_idxT[i]] y5 = 0.5 * y4.bmm(self.D2[i] @ self.D1inv[i].transpose(1, 2)) x0 = z0_fft.bmm(self.D1inv[i].transpose(1, 2)) - y5 x0 = x0.view(n, n, x0.shape[1], -1, 2).permute(2, 3, 0, 1, 4) x0 = torch.irfft(x0, 2, onesided=False) return x0 def apply_inverse_conv_transpose(self, g, i): g0_fft = fft_to_complex_vector(torch.rfft(g, 2, onesided=False)) y0 = 0.5 * g0_fft.bmm(self.D1inv[i] @ self.D2[i].transpose(1, 2))[self.S_idx[i]] n = self.conv_shp[i] y1 = y0[:n ** 2 // 4] + y0[n ** 2 // 4:n ** 2 // 2] + y0[n ** 2 // 2:3 * n ** 2 // 4] + y0[3 * n ** 2 // 4:] y2 = y1.bmm(self.H[i]) y3 = y2.repeat(4, 1, 1) y4 = y3[self.S_idxT[i]] y5 = 0.5 * y4.bmm(self.D2[i] @ self.D1inv[i]) x0 = g0_fft.bmm(self.D1inv[i]) - y5 x0 = x0.view(n, n, x0.shape[1], -1, 2).permute(2, 3, 0, 1, 4) x0 = torch.irfft(x0, 2, onesided=False) return x0 def inverse(self, *z): n = len(self.A0) x = [self.apply_inverse_conv(z[0], 0)] for i in range(n - 1): A_nx0 = self.zpad(F.conv2d(self.cpad(x[-1]), self.A_n(i), stride=2)) ATA_nx0 = self.uncpad(F.conv_transpose2d(self.cpad(A_nx0), self.A(i + 1))) xn = -self.beta * 2 * ATA_nx0 if i < n - 2: x.append(self.apply_inverse_conv(z[i + 1] - xn, i + 1)) else: x.append(fft_conv(z[i + 1] - xn, self.Wn_inv)) return tuple(x) def inverse_transpose(self, *g): n = len(self.A0) x = [fft_conv(g[-1], self.Wn_inv, transpose=True)] for i in range(n - 2, -1, -1): A2x2 = F.conv2d(self.cpad(x[-1]), self.A(i + 1)) A2_NTA2x2 = self.unstride(F.conv_transpose2d(self.unzpad(A2x2), self.A_n(i), stride=2)) xp = -self.beta * 2 * A2_NTA2x2 x.append(self.apply_inverse_conv_transpose(g[i] - xp, i)) x.reverse() return tuple(x)
17,466
38.788155
116
py
monotone_op_net
monotone_op_net-master/splitting.py
import torch import torch.nn as nn from torch.autograd import Function import utils import time class MONForwardBackwardSplitting(nn.Module): def __init__(self, linear_module, nonlin_module, alpha=1.0, tol=1e-5, max_iter=50, verbose=False): super().__init__() self.linear_module = linear_module self.nonlin_module = nonlin_module self.alpha = alpha self.tol = tol self.max_iter = max_iter self.verbose = verbose self.stats = utils.SplittingMethodStats() self.save_abs_err = False def forward(self, x): """ Forward pass of the MON, find an equilibirum with forward-backward splitting""" start = time.time() # Run the forward pass _without_ tracking gradients with torch.no_grad(): z = tuple(torch.zeros(s, dtype=x.dtype, device=x.device) for s in self.linear_module.z_shape(x.shape[0])) n = len(z) bias = self.linear_module.bias(x) err = 1.0 it = 0 errs = [] while (err > self.tol and it < self.max_iter): zn = self.linear_module.multiply(*z) zn = tuple((1 - self.alpha) * z[i] + self.alpha * (zn[i] + bias[i]) for i in range(n)) zn = self.nonlin_module(*zn) if self.save_abs_err: fn = self.nonlin_module(*self.linear_module(x, *zn)) err = sum((zn[i] - fn[i]).norm().item() / (zn[i].norm().item()) for i in range(n)) errs.append(err) else: err = sum((zn[i] - z[i]).norm().item() / (1e-6 + zn[i].norm().item()) for i in range(n)) z = zn it = it + 1 if self.verbose: print("Forward: ", it, err) # Run the forward pass one more time, tracking gradients, then backward placeholder zn = self.linear_module(x, *z) zn = self.nonlin_module(*zn) zn = self.Backward.apply(self, *zn) self.stats.fwd_iters.update(it) self.stats.fwd_time.update(time.time() - start) self.errs = errs return zn class Backward(Function): @staticmethod def forward(ctx, splitter, *z): ctx.splitter = splitter ctx.save_for_backward(*z) return z @staticmethod def backward(ctx, *g): start = time.time() sp = ctx.splitter n = len(g) z = ctx.saved_tensors j = sp.nonlin_module.derivative(*z) I = [j[i] == 0 for i in range(n)] d = [(1 - j[i]) / j[i] for i in range(n)] v = tuple(j[i] * g[i] for i in range(n)) u = tuple(torch.zeros(s, dtype=g[0].dtype, device=g[0].device) for s in sp.linear_module.z_shape(g[0].shape[0])) err = 1.0 it = 0 errs = [] while (err > sp.tol and it < sp.max_iter): un = sp.linear_module.multiply_transpose(*u) un = tuple((1 - sp.alpha) * u[i] + sp.alpha * un[i] for i in range(n)) un = tuple((un[i] + sp.alpha * (1 + d[i]) * v[i]) / (1 + sp.alpha * d[i]) for i in range(n)) for i in range(n): un[i][I[i]] = v[i][I[i]] err = sum((un[i] - u[i]).norm().item() / (1e-6 + un[i].norm().item()) for i in range(n)) errs.append(err) u = un it = it + 1 if sp.verbose: print("Backward: ", it, err) dg = sp.linear_module.multiply_transpose(*u) dg = tuple(g[i] + dg[i] for i in range(n)) sp.stats.bkwd_iters.update(it) sp.stats.bkwd_time.update(time.time() - start) sp.errs = errs return (None,) + dg class MONPeacemanRachford(nn.Module): def __init__(self, linear_module, nonlin_module, alpha=1.0, tol=1e-5, max_iter=50, verbose=False): super().__init__() self.linear_module = linear_module self.nonlin_module = nonlin_module self.alpha = alpha self.tol = tol self.max_iter = max_iter self.verbose = verbose self.stats = utils.SplittingMethodStats() self.save_abs_err = False def forward(self, x): """ Forward pass of the MON, find an equilibirum with forward-backward splitting""" start = time.time() # Run the forward pass _without_ tracking gradients self.linear_module.init_inverse(1 + self.alpha, -self.alpha) with torch.no_grad(): z = tuple(torch.zeros(s, dtype=x.dtype, device=x.device) for s in self.linear_module.z_shape(x.shape[0])) u = tuple(torch.zeros(s, dtype=x.dtype, device=x.device) for s in self.linear_module.z_shape(x.shape[0])) n = len(z) bias = self.linear_module.bias(x) err = 1.0 it = 0 errs = [] while (err > self.tol and it < self.max_iter): u_12 = tuple(2 * z[i] - u[i] for i in range(n)) z_12 = self.linear_module.inverse(*tuple(u_12[i] + self.alpha * bias[i] for i in range(n))) u = tuple(2 * z_12[i] - u_12[i] for i in range(n)) zn = self.nonlin_module(*u) if self.save_abs_err: fn = self.nonlin_module(*self.linear_module(x, *zn)) err = sum((zn[i] - fn[i]).norm().item() / (zn[i].norm().item()) for i in range(n)) errs.append(err) else: err = sum((zn[i] - z[i]).norm().item() / (1e-6 + zn[i].norm().item()) for i in range(n)) z = zn it = it + 1 if self.verbose: print("Forward: ", it, err) # Run the forward pass one more time, tracking gradients, then backward placeholder zn = self.linear_module(x, *z) zn = self.nonlin_module(*zn) zn = self.Backward.apply(self, *zn) self.stats.fwd_iters.update(it) self.stats.fwd_time.update(time.time() - start) self.errs = errs return zn class Backward(Function): @staticmethod def forward(ctx, splitter, *z): ctx.splitter = splitter ctx.save_for_backward(*z) return z @staticmethod def backward(ctx, *g): start = time.time() sp = ctx.splitter n = len(g) z = ctx.saved_tensors j = sp.nonlin_module.derivative(*z) I = [j[i] == 0 for i in range(n)] d = [(1 - j[i]) / j[i] for i in range(n)] v = tuple(j[i] * g[i] for i in range(n)) z = tuple(torch.zeros(s, dtype=g[0].dtype, device=g[0].device) for s in sp.linear_module.z_shape(g[0].shape[0])) u = tuple(torch.zeros(s, dtype=g[0].dtype, device=g[0].device) for s in sp.linear_module.z_shape(g[0].shape[0])) err = 1.0 errs=[] it = 0 while (err >sp.tol and it < sp.max_iter): u_12 = tuple(2 * z[i] - u[i] for i in range(n)) z_12 = sp.linear_module.inverse_transpose(*u_12) u = tuple(2 * z_12[i] - u_12[i] for i in range(n)) zn = tuple((u[i] + sp.alpha * (1 + d[i]) * v[i]) / (1 + sp.alpha * d[i]) for i in range(n)) for i in range(n): zn[i][I[i]] = v[i][I[i]] err = sum((zn[i] - z[i]).norm().item() / (1e-6 + zn[i].norm().item()) for i in range(n)) errs.append(err) z = zn it = it + 1 if sp.verbose: print("Backward: ", it, err) dg = sp.linear_module.multiply_transpose(*zn) dg = tuple(g[i] + dg[i] for i in range(n)) sp.stats.bkwd_iters.update(it) sp.stats.bkwd_time.update(time.time() - start) sp.errs = errs return (None,) + dg
8,149
37.262911
108
py
monotone_op_net
monotone_op_net-master/utils.py
import torch import numpy as np from train import cuda class Meter(object): """Computes and stores the min, max, avg, and current values""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 self.max = -float("inf") self.min = float("inf") def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count self.max = max(self.max, val) self.min = min(self.min, val) class SplittingMethodStats(object): def __init__(self): self.fwd_iters = Meter() self.bkwd_iters = Meter() self.fwd_time = Meter() self.bkwd_time = Meter() def reset(self): self.fwd_iters.reset() self.fwd_time.reset() self.bkwd_iters.reset() self.bkwd_time.reset() def report(self): print('Fwd iters: {:.2f}\tFwd Time: {:.4f}\tBkwd Iters: {:.2f}\tBkwd Time: {:.4f}\n'.format( self.fwd_iters.avg, self.fwd_time.avg, self.bkwd_iters.avg, self.bkwd_time.avg)) def compute_eigval(lin_module, method="power", compute_smallest=False, largest=None): with torch.no_grad(): if method == "direct": W = lin_module.W.weight eigvals = torch.symeig(W + W.T)[0] return eigvals.detach().cpu().numpy()[-1] / 2 elif method == "power": z0 = tuple(torch.randn(*shp).to(lin_module.U.weight.device) for shp in lin_module.z_shape(1)) lam = power_iteration(lin_module, z0, 100, compute_smallest=compute_smallest, largest=largest) return lam def power_iteration(linear_module, z, T, compute_smallest=False, largest=None): n = len(z) for i in range(T): za = linear_module.multiply(*z) zb = linear_module.multiply_transpose(*z) if compute_smallest: zn = tuple(-2*largest*a + 0.5*b + 0.5*c for a,b,c in zip(z, za, zb)) else: zn = tuple(0.5*a + 0.5*b for a,b in zip(za, zb)) x = sum((zn[i]*z[i]).sum().item() for i in range(n)) y = sum((z[i]*z[i]).sum().item() for i in range(n)) lam = x/y z = tuple(zn[i]/np.sqrt(y) for i in range(n)) return lam +2*largest if compute_smallest else lam def get_splitting_stats(dataLoader, model): model = cuda(model) model.train() model.mon.save_abs_err = True for batch in dataLoader: data, target = cuda(batch[0]), cuda(batch[1]) model(data) return model.mon.errs
2,684
31.743902
105
py
monotone_op_net
monotone_op_net-master/train.py
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.datasets as dset import torchvision.transforms as transforms from torch.utils.data import DataLoader import torch.optim as optim import mon import numpy as np import time def cuda(tensor): if torch.cuda.is_available(): return tensor.cuda() else: return tensor def train(trainLoader, testLoader, model, epochs=15, max_lr=1e-3, print_freq=10, change_mo=True, model_path=None, lr_mode='step', step=10,tune_alpha=False,max_alpha=1.): optimizer = optim.Adam(model.parameters(), lr=max_lr) if lr_mode == '1cycle': lr_schedule = lambda t: np.interp([t], [0, (epochs-5)//2, epochs-5, epochs], [1e-3, max_lr, 1e-3, 1e-3])[0] elif lr_mode == 'step': lr_scheduler =optim.lr_scheduler.StepLR(optimizer, step, gamma=0.1, last_epoch=-1) elif lr_mode != 'constant': raise Exception('lr mode one of constant, step, 1cycle') if change_mo: max_mo = 0.85 momentum_schedule = lambda t: np.interp([t], [0, (epochs - 5) // 2, epochs - 5, epochs], [0.95, max_mo, 0.95, 0.95])[0] model = cuda(model) for epoch in range(1, 1 + epochs): nProcessed = 0 nTrain = len(trainLoader.dataset) model.train() start = time.time() for batch_idx, batch in enumerate(trainLoader): if (batch_idx == 30 or batch_idx == int(len(trainLoader)/2)) and tune_alpha: run_tune_alpha(model, cuda(batch[0]), max_alpha) if lr_mode == '1cycle': lr = lr_schedule(epoch - 1 + batch_idx/ len(trainLoader)) for param_group in optimizer.param_groups: param_group['lr'] = lr if change_mo: beta1 = momentum_schedule(epoch - 1 + batch_idx / len(trainLoader)) for param_group in optimizer.param_groups: param_group['betas'] = (beta1, optimizer.param_groups[0]['betas'][1]) data, target = cuda(batch[0]), cuda(batch[1]) optimizer.zero_grad() preds = model(data) ce_loss = nn.CrossEntropyLoss()(preds, target) ce_loss.backward() nProcessed += len(data) if batch_idx % print_freq == 0 and batch_idx > 0: incorrect = preds.float().argmax(1).ne(target.data).sum() err = 100. * incorrect.float() / float(len(data)) partialEpoch = epoch + batch_idx / len(trainLoader) - 1 print('Train Epoch: {:.2f} [{}/{} ({:.0f}%)]\tLoss: {:.4f}\tError: {:.2f}'.format( partialEpoch, nProcessed, nTrain, 100. * batch_idx / len(trainLoader), ce_loss.item(), err)) model.mon.stats.report() model.mon.stats.reset() optimizer.step() if lr_mode == 'step': lr_scheduler.step() if model_path is not None: torch.save(model.state_dict(), model_path) print("Tot train time: {}".format(time.time() - start)) start = time.time() test_loss = 0 incorrect = 0 model.eval() with torch.no_grad(): for batch in testLoader: data, target = cuda(batch[0]), cuda(batch[1]) preds = model(data) ce_loss = nn.CrossEntropyLoss(reduction='sum')(preds, target) test_loss += ce_loss incorrect += preds.float().argmax(1).ne(target.data).sum() test_loss /= len(testLoader.dataset) nTotal = len(testLoader.dataset) err = 100. * incorrect.float() / float(nTotal) print('\n\nTest set: Average loss: {:.4f}, Error: {}/{} ({:.2f}%)'.format( test_loss, incorrect, nTotal, err)) print("Tot test time: {}\n\n\n\n".format(time.time() - start)) def run_tune_alpha(model, x, max_alpha): print("----tuning alpha----") print("current: ", model.mon.alpha) orig_alpha = model.mon.alpha model.mon.stats.reset() model.mon.alpha = max_alpha with torch.no_grad(): model(x) iters = model.mon.stats.fwd_iters.val model.mon.stats.reset() iters_n = iters print('alpha: {}\t iters: {}'.format(model.mon.alpha, iters_n)) while model.mon.alpha > 1e-4 and iters_n <= iters: model.mon.alpha = model.mon.alpha/2 with torch.no_grad(): model(x) iters = iters_n iters_n = model.mon.stats.fwd_iters.val print('alpha: {}\t iters: {}'.format(model.mon.alpha, iters_n)) model.mon.stats.reset() if iters==model.mon.max_iter: print("none converged, resetting to current") model.mon.alpha=orig_alpha else: model.mon.alpha = model.mon.alpha * 2 print("setting to: ", model.mon.alpha) print("--------------\n") def mnist_loaders(train_batch_size, test_batch_size=None): if test_batch_size is None: test_batch_size = train_batch_size trainLoader = torch.utils.data.DataLoader( dset.MNIST('data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=train_batch_size, shuffle=True) testLoader = torch.utils.data.DataLoader( dset.MNIST('data', train=False, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=test_batch_size, shuffle=False) return trainLoader, testLoader def cifar_loaders(train_batch_size, test_batch_size=None, augment=True): if test_batch_size is None: test_batch_size = train_batch_size normalize = transforms.Normalize(mean=[0.4914, 0.4822, 0.4465], std=[0.2470, 0.2435, 0.2616]) if augment: transforms_list = [transforms.RandomHorizontalFlip(), transforms.RandomCrop(32, 4), transforms.ToTensor(), normalize] else: transforms_list = [transforms.ToTensor(), normalize] train_dset = dset.CIFAR10('data', train=True, download=True, transform=transforms.Compose(transforms_list)) test_dset = dset.CIFAR10('data', train=False, transform=transforms.Compose([ transforms.ToTensor(), normalize ])) trainLoader = torch.utils.data.DataLoader(train_dset, batch_size=train_batch_size, shuffle=True, pin_memory=True) testLoader = torch.utils.data.DataLoader(test_dset, batch_size=test_batch_size, shuffle=False, pin_memory=True) return trainLoader, testLoader def svhn_loaders(train_batch_size, test_batch_size=None): if test_batch_size is None: test_batch_size = train_batch_size normalize = transforms.Normalize(mean=[0.4377, 0.4438, 0.4728], std=[0.1980, 0.2010, 0.1970]) train_loader = torch.utils.data.DataLoader( dset.SVHN( root='data', split='train', download=True, transform=transforms.Compose([ transforms.ToTensor(), normalize ]), ), batch_size=train_batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader( dset.SVHN( root='data', split='test', download=True, transform=transforms.Compose([ transforms.ToTensor(), normalize ])), batch_size=test_batch_size, shuffle=False) return train_loader, test_loader def expand_args(defaults, kwargs): d = defaults.copy() for k, v in kwargs.items(): d[k] = v return d MON_DEFAULTS = { 'alpha': 1.0, 'tol': 1e-5, 'max_iter': 50 } class SingleFcNet(nn.Module): def __init__(self, splittingMethod, in_dim=784, out_dim=100, m=0.1, **kwargs): super().__init__() linear_module = mon.MONSingleFc(in_dim, out_dim, m=m) nonlin_module = mon.MONReLU() self.mon = splittingMethod(linear_module, nonlin_module, **expand_args(MON_DEFAULTS, kwargs)) self.Wout = nn.Linear(out_dim, 10) def forward(self, x): x = x.view(x.shape[0], -1) z = self.mon(x) return self.Wout(z[-1]) class SingleConvNet(nn.Module): def __init__(self, splittingMethod, in_dim=28, in_channels=1, out_channels=32, m=0.1, **kwargs): super().__init__() n = in_dim + 2 shp = (n, n) self.pool = 4 self.out_dim = out_channels * (n // self.pool) ** 2 linear_module = mon.MONSingleConv(in_channels, out_channels, shp, m=m) nonlin_module = mon.MONBorderReLU(linear_module.pad[0]) self.mon = splittingMethod(linear_module, nonlin_module, **expand_args(MON_DEFAULTS, kwargs)) self.Wout = nn.Linear(self.out_dim, 10) def forward(self, x): x = F.pad(x, (1, 1, 1, 1)) z = self.mon(x) z = F.avg_pool2d(z[-1], self.pool) return self.Wout(z.view(z.shape[0], -1)) class MultiConvNet(nn.Module): def __init__(self, splittingMethod, in_dim=28, in_channels=1, conv_sizes=(16, 32, 64), m=1.0, **kwargs): super().__init__() linear_module = mon.MONMultiConv(in_channels, conv_sizes, in_dim+2, kernel_size=3, m=m) nonlin_module = mon.MONBorderReLU(linear_module.pad[0]) self.mon = splittingMethod(linear_module, nonlin_module, **expand_args(MON_DEFAULTS, kwargs)) out_shape = linear_module.z_shape(1)[-1] dim = out_shape[1]*out_shape[2]*out_shape[3] self.Wout = nn.Linear(dim, 10) def forward(self, x): x = F.pad(x, (1,1,1,1)) zs = self.mon(x) z = zs[-1] z = z.view(z.shape[0],-1) return self.Wout(z)
10,630
36.041812
101
py
teacher-perception
teacher-perception-master/code/utils.py
import numpy as np import pandas as pd import xgboost as xgb from sklearn.datasets import load_svmlight_files np.random.seed(1) from collections import defaultdict from copy import deepcopy from scipy.stats import chisquare import os from sklearn.preprocessing import LabelEncoder from sklearn.feature_selection import VarianceThreshold from collections import Counter import pyconll import random from indictrans import Transliterator def convertStringToset(data): feats = {} if data == "_": return {} for f in data.split("|"): k = f.split("=")[0] v = f.split("=")[1] feats[k]=v return feats def find_agreement(feats1, feats2): shared = set() agreed = set() for feat in feats1: if feat in feats2: shared.add(feat) if feats1[feat] == feats2[feat]: agreed.add(feat) return shared, agreed def get_vocab_from_set(input): word_to_id = {} if "NA" in input: word_to_id['NA'] = 0 for i in input: if i == "NA": continue word_to_id[i] = len(word_to_id) id_to_word = {v:k for k,v in word_to_id.items()} return word_to_id, id_to_word def transformRulesIntoReadable(feature, task, rel, relation_map, folder_name, pos_examples={}, source='eng'): global trn if source: trn = Transliterator(source=source, target='eng', build_lookup=True) else: trn = None task = task.lower() if task == 'wordorder': dependent = rel.split("-")[0] head = rel.split("-")[1] if rel in ['adjective-noun', 'numeral-noun']: head = 'nominal' if rel in ['noun-adposition']: dependent = 'nominal' elif task == 'agreement': if "-" in rel: dependent = rel.split("-")[1] else: dependent = "current word" head = 'head' elif task == "assignment": dependent = rel head = 'head' else: dependent = '' head = '' new_features = feature info = feature.split("_") def get_relation(info): lang_link = f'https://universaldependencies.org/' lang = folder_name.split('/')[3] if info in relation_map: lang_link = f'https://aditi138.github.io/auto-lex-learn-general-info/{lang}/helper/{info.lower()}_relations.html' (value, link) = relation_map[info] #if not os.path.exists(f'{folder_name}/helper/{info.lower()}_relations.html'): # lang_link = link elif info.lower() in relation_map: lang_link = f'https://aditi138.github.io/auto-lex-learn-general-info/{lang}/helper/{info.lower()}_relations.html' (value, link) = relation_map[info.lower()] #if not os.path.exists(f'{folder_name}/helper/{info.lower()}_relations.html'): # lang_link = link #hovertext= f'<a href=" " title="for e.g. words like ..." style="background-color:#FFFFFF;color:#000000;text-decoration:none">{value}</a>' #value = hovertext elif info.split("@")[0] in relation_map or info.split("@")[0].lower() in relation_map: lang_link = f'https://aditi138.github.io/auto-lex-learn-general-info/{lang}/helper/{info.lower()}_relations.html' (value, link) = relation_map.get(info.split("@")[0].lower(), info.lower()) #if not os.path.exists(f'{folder_name}/helper/{info.lower()}_relations.html'): # lang_link = link #hovertext= f'<a href=" " title="for e.g. words like ..." style="background-color:#FFFFFF;color:#000000;text-decoration:none">{value}</a>' #value = hovertext else: value = info return value, lang_link if feature.startswith("spinehead"): return f'{head} is a word like= {info[1]}' elif feature.startswith('spine'): return f'{dependent} is a word like= {info[1]}' if len(info) == 2: #f'dep_{relation}_' if feature.startswith('wiki'): new_features = f'{dependent}\'s semantic class is= {info[1]}' elif feature == 'headmatch_True': new_features = f'the head agrees with its head on= {rel}' elif feature.startswith('lemma'): if trn: eng = trn.transform(info[1]) new_features = f'{dependent} has lemma= {info[1]} ({eng})' else: new_features = f'{dependent} has lemma= {info[1]}' elif feature.startswith('headlemma'): if trn: eng = trn.transform(info[1]) new_features = f'{dependent} is governed by= {info[1]} ({eng})' else: new_features = f'{dependent} is governed by= {info[1]}' elif feature.startswith('depdeplemma'): if trn: eng = trn.transform(info[1]) new_features = f'{dependent} is governing= {info[1]} ({eng})' else: new_features = f'{dependent} is governing= {info[1]}' elif feature.startswith('headheadlemma'): if trn: eng = trn.transform(info[1]) new_features = f'{head} is governed by= {info[1]} ({eng})' else: new_features = f'{head} is governed by= {info[1]}' elif feature.startswith('depheadlemma'): if trn: eng = trn.transform(info[1]) new_features = f'{head} is also governing= {info[1]} ({eng})' else: new_features = f'{head} is also governing= {info[1]}' elif feature.startswith('neighborhood'): if trn: eng = trn.transform(info[1]) new_features = f'{dependent} is nearby= {info[1]} ({eng})' else: new_features = f'{dependent} is nearby= {info[1]}' elif feature.startswith('left'): if trn: eng = trn.transform(info[1]) new_features = f'before the {dependent} is= {info[1]} ({eng})' else: new_features = f'before the {dependent} is= {info[1]}' elif feature.startswith('right'): if trn: eng = trn.transform(info[1]) new_features = f'after the {dependent} is= {info[1]} ({eng})' else: new_features = f'after the {dependent} is= {info[1]}' elif feature.startswith('lang'): new_features = f'lang is= {info[1]}' elif feature.startswith('srclem'): new_features = f'in English is= {info[1]}' elif feature.startswith('srcpos'): info_, link = get_relation(info[1]) title = '' if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{link}" title="{title}"> {info_} </a>' new_features = f'in English is= {info[1]}' else: #f'deppos_{pos}' info_, link = get_relation(info[1]) if feature.startswith('deppos'): title = '' if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{link}" title="{title}"> {info_} </a>' new_features = f'{dependent} is a= {info[1]}' elif feature.startswith('headpos'): title = '' if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{link}" title="{title}"> {info_} </a>' new_features = f'{dependent} is governed by a= {info[1]}' elif feature.startswith('deprel'): info[1] = f'<a href="{link}" title=""> {info_} </a>' new_features = f'{dependent} is the= {info[1]}' elif feature.startswith('headrelrel'): info[1] = f'<a href="{link}" title=""> {info_} </a>' new_features= f'{dependent} is governed by= {info[1]}' elif feature.startswith('depdeppos'): title = '' if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{link}" title="{title}"> {info_} </a>' new_features = f'{dependent} is governing= {info[1]}' elif feature.startswith('depdeprel'): info[1] = f'<a href="{link}" title=""> {info_} </a>' new_features = f'{dependent} is governing= {info[1]}' elif feature.startswith('depheadrel') or feature.startswith('depheadpos'): title = '' if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{link}" title="{title}"> {info_} </a>' head_phrase = head if head_phrase == 'head': new_features = f'{dependent} is nearby= {info[1]}' else: new_features = f'{dependent} is nearby= {info[1]}' elif feature.startswith('svo'): new_features = f'anaphora= True' elif feature.startswith('agreepos'): title = '' if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{link}" title="{title}"> {info_} </a>' new_features = f'{dependent} agrees with its head= {info[1]}' elif feature.startswith('agreerel'): info[1] = f'<a href="{link}" title=""> {info_} </a>' new_features = f'{dependent} agrees with its head when {dependent} is a= {info[1]}' elif feature.startswith('agree'): title = '' if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{link}" title="{title}"> {info_} </a>' new_features = f'{dependent} agrees with its head when the head is a= {info[1]}' if len(info) == 3: #f'depposrel_{pos}_{relation}' info_, link = get_relation(info[-1]) if feature.startswith("depposrel"): info_pos, pos_link = get_relation(info[1]) title = '' if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' info[2] = f'<a href="{link}" title=""> {info_} </a>' new_features = f'{info[1]} is the dependent and is the= {info[2]}' elif feature.startswith('headrelrel'): #f'headrelrel_{head_pos}_{headrelation.lower()}' title = '' if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{link}" title="{title}"> {info[1]} </a>' new_features = f'{dependent} has head-{info[1]} is a= {info_}' elif feature.startswith('headfeat'): feats_link = 'https://universaldependencies.org/u/feat/index.html' info[1] = f'<a href="{feats_link}" title=""> {info[1]} </a>' new_features = f'{dependent} is governed by a word with {info[1]}= {info[2]}' elif feature.startswith('depfeat'): feats_link = 'https://universaldependencies.org/u/feat/index.html' info[1] = f'<a href="{feats_link}" title=""> {info[1]} </a>' new_features = f'{dependent} with {info[1]}= {info[2]}' elif feature.startswith('wiki'): new_features = f'the head of the {dependent} has semantic class= {info[-1]}' elif feature.startswith("head") :#f'head_{head_pos}_{relation}' title = '' info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info[1]} </a>' info[-1] = f'<a href="{link}" title=""> {info_} </a>' new_features = f'{info[-1]} of head= {info[1]}' elif feature.startswith('agree'): # f'agree_{head_pos}_{headrelation.lower()}' title = '' info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info[1]} </a>' info[-1] = f'<a href="{link}" title=""> {info_} </a>' new_features = f'{dependent} agrees with its {info[1]}-head which is a= {info[-1]}' if len(info) == 4: if feature.startswith('wiki'): new_features = f'the head has semantic class= {info[-1]}' elif feature.startswith('depfeat'): info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' new_features = f'{info[1]} is the dependent with {info[2]}= {info[3]}' #f'depfeat_{pos}_{feat}_{value}' elif feature.startswith('headfeatrel'):#f'headfeatrel_{rel}_{feat}_{value}' info_rel, rel_link = get_relation(info[1]) info[1] = f'<a href="{rel_link}" title=""> {info_rel} </a>' feats_link = 'https://universaldependencies.org/u/feat/index.html' info[2] = f'<a href="{feats_link}" title=""> {info} </a>' new_features = f'{dependent} has head is a {info[1]} with {info[2]}= {info[3]}' elif feature.startswith('headfeat'): #f'headfeat_{head_pos}_{feat}_' title = '' info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' feats_link = 'https://universaldependencies.org/u/feat/index.html' info[2] = f'<a href="{feats_link}" title=""> {info[2]} </a>' new_features = f'{dependent} is governed by {info[1]} with {info[2]}= {info[3]}' elif feature.startswith('headrelrel'):#f'headrelrel_{head_pos}_{relation}_{headrelation.lower()}' info_rel, rel_link = get_relation(info[-1]) info[-1] = f'<a href="{rel_link}" title=""> {info_rel} </a>' title = '' info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' info_rel, rel_link = get_relation(info[2]) info[2] = f'<a href="{rel_link}" title=""> {info_rel} </a>' new_features = f'{dependent} is a {info[2]} of {info[1]} where the head-{info[1]} is a= {info[-1]}' elif feature.startswith('head'): #f'head_{pos}_{relation}_{head}' info_rel, rel_link = get_relation(info[-1]) info[-1] = f'<a href="{rel_link}" title=""> {info_rel} </a>' info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' info_pos, pos_link = get_relation(info[2]) info[2] = f'<a href="{pos_link}" title=""> {info_pos} </a>' new_features = f'{dependent} is a {info[1]} is a {info[2]} of head= {info[-1]}' elif feature.startswith('agree'): # f'agree_{relation}_{head_pos}_{headrelation.lower()}' info_rel, rel_link = get_relation(info[-1]) info[-1] = f'<a href="{rel_link}" title=""> {info_rel} </a>' title = '' info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' info_rel, rel_link = get_relation(info[2]) info[2] = f'<a href="{rel_link}" title=""> {info_rel} </a>' new_features = f'{dependent} is a {info[1]} and agrees with {info[2]}-head which is a= {info[-1]}' if len(info) == 5: if feature.startswith('headrelrel'):#f'headrelrel_{pos}_{relation}_{head}_{headrelation.lower()}' info_rel, rel_link = get_relation(info[-1]) info[-1] = f'<a href="{rel_link}" title=""> {info_rel} </a>' title = '' info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' title = '' info_pos, pos_link = get_relation(info[2]) if len(pos_examples) > 0 and info[2] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[2]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' info_rel, rel_link = get_relation(info[3]) info[3] = f'<a href="{rel_link}" title=""> {info_rel} </a>' new_features = f'{info[1]} is a {info[2]} of head {info[3]} where that {info[3]} is the= {info[-1]}' elif feature.startswith('headfeat'): #f'headfeat_{head_pos}_{relation}_{feat}_{value}' info_rel, rel_link = get_relation(info[2]) info[2] = f'<a href="{rel_link}" title=""> {info_rel} </a>' title = '' info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' feats_link = 'https://universaldependencies.org/u/feat/index.html' info[3] = f'<a href="{feats_link}" title=""> {info[3]} </a>' new_features = f'{dependent} is a {info[2]} of {info[1]} with {info[3]}= {info[4]}' elif feature.startswith('depfeat'): # f'dpefeat_{pos}_{relation}_{feat}_{value}' info_rel, rel_link = get_relation(info[2]) info[2] = f'<a href="{rel_link}" title=""> {info_rel} </a>' title = '' info_pos, pos_link = get_relation(info[1]) if len(pos_examples) > 0 and info[1] in pos_examples: title = f'For eg. words like {", ".join(pos_examples[info[1]])}' info[1] = f'<a href="{pos_link}" title="{title}"> {info_pos} </a>' feats_link = 'https://universaldependencies.org/u/feat/index.html' info[3] = f'<a href="{feats_link}" title=""> {info[3]} </a>' new_features = f'{info[1]} is a {info[2]} with {info[3]}= {info[4]}' return new_features def getHeader(cols, important_features, model, task, relation_map, folder_name, source_lang): cols = np.array(cols) feats = np.array(important_features)[cols] header, subheaders = "", [] if len(feats) == 1: header = "" info = transformRulesIntoReadable(feats[0], task, model, relation_map, folder_name, source=source_lang) header = info.split("= ")[0] subheader = info.split("= ")[-1] if "spine" in feats[0]: subheader = subheader.split(",") subheader = ",".join(subheader[:5]) + "<br>" + ",".join(subheader[5:]) subheaders.append(subheader) return header, subheaders for feat in feats: info = transformRulesIntoReadable(feat, task, model, relation_map, folder_name, source=source_lang) header = info.split("= ")[0] subheader = info.split("= ")[-1] if "spine" in feat: subheader = subheader.split(",") subheader = ",".join(subheader[:5]) + "<br>" + ",".join(subheader[5:]) subheaders.append(subheader) return header, subheaders def iterateTreesFromXGBoost(rules_df_t0, task, model, relation_map, tree_features, folder_name, source_lang): topnodes,leafnodes = [],[] tree_dictionary = {} edge_mapping = {} leafedges = defaultdict(list) idmap = {} for index, row in rules_df_t0.iterrows(): ID, feature_id, split, yes_id, no_id = row['ID'], row['Feature'], row['Split'], row['Yes'], row['No'] idmap[ID] = index for index, row in rules_df_t0.iterrows(): ID, feature_id, split, yes_id, no_id = row['ID'], row['Feature'], row['Split'], row['Yes'], row['No'] split = max(split, 0.0) id = idmap[ID] if not pd.isna(yes_id): yes_id = idmap[yes_id] if not pd.isna(no_id): no_id = idmap[no_id] if id not in tree_dictionary: tree_dictionary[id] = {"children": [], "label_distribution": "", "info": "", "id": ID, 'top': -1, "class": "", "leaf": False, "active": [], "non_active": []} if feature_id == 'Leaf': tree_dictionary[id]['leaf'] = True leafnodes.append(id) # Leaf node number else: feature_name = tree_features[int(feature_id.replace('f', ''))] feature_label = transformRulesIntoReadable(feature_name, task, model, relation_map, folder_name, source=source_lang) tree_dictionary[id]['edge'] = (feature_name, split) edge_mapping[feature_name] = feature_label topnodes.append(id) tree_dictionary[id]['info'] = (feature_name, split) if not pd.isna(yes_id): tree_dictionary[id]['children'].append(yes_id) #tree_dictionary[id]['yes'] = yes_id if yes_id not in tree_dictionary: tree_dictionary[yes_id] = {"children": [], "label_distribution": "", "info": "", "class": "", "leaf": False, "active": [], "non_active": []} tree_dictionary[yes_id]['top'] = id tree_dictionary[yes_id]['non_active'].append((feature_name, split)) #if feature < split leafedges[yes_id] = feature_name if not pd.isna(no_id): tree_dictionary[id]['children'].append(no_id) #tree_dictionary[id]['no'] = no_id if no_id not in tree_dictionary: tree_dictionary[no_id] = {"children": [], "label_distribution": "", "info": "", "class": "", "leaf": False, "active": [], "non_active": []} tree_dictionary[no_id]['top'] = id tree_dictionary[no_id]['active'].append((feature_name, split)) #if feature > split leafedges[no_id] = 'Not ' + feature_name return topnodes, tree_dictionary, leafnodes, leafedges, edge_mapping def FixLabelTree(dot_data, tree_dictionary, leafmap, labels, datalabels, threshold=0.01, task='agreement'): collatedGraph = dot_data.getvalue().split("\n") newGraph, relabeled_leaves = [], {} newGraph.append(collatedGraph[0]) newGraph.append(collatedGraph[1]) newGraph.append(collatedGraph[2]) #Get expected distribution expected_prob = [] total = 0 for label in labels: total += datalabels[label] for label in labels: expected_prob.append(datalabels[label]) if len(tree_dictionary) == 1 and len(leafmap) == 1: #There are no root nodes, possibly one one leaf return collatedGraph, leafmap updated = {} for new_num, leaf in enumerate(leafmap): leafinfo = tree_dictionary[leaf]['label_distribution'] if not isLabel(expected_prob, leafinfo, threshold, task): class_ = tree_dictionary[leaf]['class'] tree_dictionary[leaf]['class'] = 'NA' tree_dictionary[leaf]['info'] = tree_dictionary[leaf]['info'].replace(class_, 'NA') updated[leaf]=str(new_num) #print('Updated', len(updated)) for d in collatedGraph[3:]: if " ->" in d or '}' in d: newGraph.append(d) else: leafnode=int(d.split(" [")[0].lstrip().rstrip()) if leafnode in updated: new_leaf_info = "{0} [label=\"Leaf- {1}\\n{2}\\lvalue = [{3}]\\lclass = {4}\\l\", fillcolor={5} " color = tree_dictionary[leafnode]["info"].split("fillcolor=")[-1] label_distribution = [str(l) for l in tree_dictionary[leafnode]['label_distribution']] leafinfo = new_leaf_info.format(str(leafnode), str(updated[leafnode]), "", ", ".join(label_distribution), tree_dictionary[leafnode]['class'], color) newGraph.append(leafinfo) else: newGraph.append(d) return newGraph def FixLabelTreeFromXGBoost(rules_df_t0, tree_dictionary, leafmap, labels, datalabels, rel, train_df, train_data, threshold=0.01, task='agreement'): if len(tree_dictionary) == 1 and len(leafmap) == 1: #There are no root nodes, possibly one one leaf return rules_df_t0, leafmap # Get expected distribution expected_prob = [] total = 0 for label in labels: total += datalabels[label] for label in labels: expected_prob.append(datalabels[label]) if task == 'agreement': class_map = {'0': 'NA', '1': 'req-agree'} labels = ['NA', 'req-agree'] #TODO identify and extract all examples which satisfy the rule and store them [agree, disgaree] #If the distrbution of agree-disagree under that leaf is valid then assign the leaf with the class with the label which has larger number of examples #first extract active and not active features for each leaf updated = {} leaf_examples = {} leaf_sent_examples = {} for new_num, leaf in enumerate(leafmap): #sent_examples for each label, examples are not usefule examples = {} sent_examples = defaultdict(list) getExamplesPerLeaf(leaf, tree_dictionary, rel, train_df, train_data, task, examples, sent_examples) leaf_examples[leaf] = examples leaf_sent_examples[leaf] = sent_examples leafinfo, leaflabel, label_distribution = [], {}, [] for label in labels: leafinfo.append(len(sent_examples[label])) leaflabel[label] = len(sent_examples[label]) label_distribution.append(str(len(sent_examples[label]))) tree_dictionary[leaf]['label_distribution'] = [int(label) for label in label_distribution] new_leaf_info = "{0} [label=\"Leaf- {1}\\n{2}\\lvalue = [{3}]\\lclass = {4}\\l\", fillcolor={5} " if not isLabel(expected_prob, leafinfo, threshold, task): tree_dictionary[leaf]['class'] = 'NA' updated[leaf]=str(new_num) class_ = "NA" else: sorted_leaflabels = sorted(leaflabel.items(), key=lambda kv:kv[1], reverse=True)[0] class_ = sorted_leaflabels[0] tree_dictionary[leaf]['class'] = class_ color = colorRetrival(leaflabel, class_) tree_dictionary[leaf]['info'] = new_leaf_info.format(str(new_num), str(new_num), "", ", ".join(label_distribution), tree_dictionary[leaf]['class'], color) return leaf_examples, leaf_sent_examples def FixLabelTreeFromXGBoostWithFeatures(rules_df_t0, tree_dictionary, leafmap, labels, datalabels, rel, train_df, train_data, tree_features, dataloader, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim, threshold=0.01, task='agreement'): if len(tree_dictionary) == 1 and len(leafmap) == 1: #There are no root nodes, possibly one one leaf return rules_df_t0, leafmap # Get expected distribution expected_prob = [] total = 0 for label in labels: total += datalabels[label] for label in labels: expected_prob.append(datalabels[label]) if task == 'agreement': labels = ['chance-agree', 'req-agree'] elif task == 'wordorder': labels = ['before', 'after'] #TODO identify and extract all examples which satisfy the rule and store them [agree, disgaree] #If the distrbution of agree-disagree under that leaf is valid then assign the leaf with the class with the label which has larger number of examples #first extract active and not active features for each leaf updated = {} leaf_examples = {} leaf_sent_examples = {} leafmapcopy = deepcopy(leafmap) #train_data = pyconll.load_from_file(train_data_path) for new_num, leaf in enumerate(leafmapcopy): #sent_examples for each label, examples are not usefule examples = {} sent_examples = defaultdict(list) getExamplesPerLeafWithFeatures(leaf, tree_dictionary, rel, train_df, train_data, task, examples, sent_examples, tree_features, dataloader, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim) # getExamplesPerLeaf(leaf, tree_dictionary, rel, train_df, train_data, task, # examples, sent_examples) leafinfo, leaflabel, label_distribution = [], {}, [] all_examples_agaree, total = 0, 0 for label in labels: leafinfo.append(len(sent_examples[label])) leaflabel[label] = len(sent_examples[label]) label_distribution.append(str(len(sent_examples[label]))) total += len(sent_examples[label]) if total == 0: leafmap.remove(leaf) continue if task == 'agreement': all_examples_agaree = leaflabel.get('req-agree') leaf_examples[leaf] = examples leaf_sent_examples[leaf] = sent_examples tree_dictionary[leaf]['label_distribution'] = [int(label) for label in label_distribution] new_leaf_info = "{0} [label=\"Leaf- {1}\\n{2}\\lvalue = [{3}]\\lclass = {4}\\l\", fillcolor={5} " if not isLabel(expected_prob, leafinfo, threshold, task): if task == 'agreement' and all_examples_agaree > 0: tree_dictionary[leaf]['class'] = 'chance-agree' updated[leaf] = str(new_num) class_ = "chance-agree" else: #there are no agreeing examples or class is not significant tree_dictionary[leaf]['class'] = 'NA' updated[leaf]=str(new_num) class_ = "NA" else: sorted_leaflabels = sorted(leaflabel.items(), key=lambda kv:kv[1], reverse=True)[0] class_ = sorted_leaflabels[0] tree_dictionary[leaf]['class'] = class_ color = colorRetrival(leaflabel, class_) tree_dictionary[leaf]['info'] = new_leaf_info.format(str(new_num), str(new_num), "", ", ".join(label_distribution), tree_dictionary[leaf]['class'], color) #del train_data return leaf_examples, leaf_sent_examples def FixLabelTreeFromXGBoostWithFeaturesDistributed(rules_df_t0, tree_dictionary, leafmap, labels, datalabels, rel, train_df_path, train_data_path, tree_features, dataloader, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim, threshold=0.01, task='agreement'): if len(tree_dictionary) == 1 and len(leafmap) == 1: #There are no root nodes, possibly one one leaf return rules_df_t0, leafmap # Get expected distribution expected_prob = [] total = 0 for label in labels: total += datalabels[label] for label in labels: expected_prob.append(datalabels[label]) if task == 'agreement': labels = ['chance-agree', 'req-agree'] elif task == 'wordorder': labels = ['before', 'after'] #TODO identify and extract all examples which satisfy the rule and store them [agree, disgaree] #If the distrbution of agree-disagree under that leaf is valid then assign the leaf with the class with the label which has larger number of examples #first extract active and not active features for each leaf filenames = getSmallerFiles(train_data_path) updated = {} leaf_examples = {} leaf_sent_examples = {} leafmapcopy = deepcopy(leafmap) for new_num, leaf in enumerate(leafmapcopy): #For each leaf, iterate each file #sent_examples for each label, examples are not usefule examples = {} sent_examples = defaultdict(list) for file in filenames: #training_data_path is the path to the intermediate path created to hold each file's extracted features train_df_path_sub = f'{train_df_path}/{os.path.basename(file)}.train.feats.' getExamplesPerLeafWithFeaturesDistributed(leaf, tree_dictionary, rel, train_df_path_sub, file, task, examples, sent_examples, tree_features, dataloader, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim) leafinfo, leaflabel, label_distribution = [], {}, [] all_examples_agaree, total = 0, 0 for label in labels: leafinfo.append(len(sent_examples[label])) leaflabel[label] = len(sent_examples[label]) label_distribution.append(str(len(sent_examples[label]))) total += len(sent_examples[label]) if total == 0: leafmap.remove(leaf) continue if task == 'agreement': all_examples_agaree = leaflabel.get('req-agree') leaf_examples[leaf] = examples leaf_sent_examples[leaf] = sent_examples tree_dictionary[leaf]['label_distribution'] = [int(label) for label in label_distribution] new_leaf_info = "{0} [label=\"Leaf- {1}\\n{2}\\lvalue = [{3}]\\lclass = {4}\\l\", fillcolor={5} " if not isLabel(expected_prob, leafinfo, threshold, task): if task == 'agreement' and all_examples_agaree > 0: tree_dictionary[leaf]['class'] = 'chance-agree' updated[leaf] = str(new_num) class_ = "chance-agree" else: #there are no agreeing examples or class is not significant tree_dictionary[leaf]['class'] = 'NA' updated[leaf]=str(new_num) class_ = "NA" else: sorted_leaflabels = sorted(leaflabel.items(), key=lambda kv:kv[1], reverse=True)[0] class_ = sorted_leaflabels[0] tree_dictionary[leaf]['class'] = class_ color = colorRetrival(leaflabel, class_) tree_dictionary[leaf]['info'] = new_leaf_info.format(str(new_num), str(new_num), "", ", ".join(label_distribution), tree_dictionary[leaf]['class'], color) return leaf_examples, leaf_sent_examples def plot_coefficients_label(classifier, feature_names, label_list, top_features=20): coef = classifier.coef_ num_classes = coef.shape[0] important_features = {} if num_classes > 2: for class_ in range(num_classes): label = label_list[class_].split("/")[0] print(label) coefficients = coef[class_,:] top_positive_coefficients = np.argsort(coefficients)[-top_features:] top_negative_coefficients = np.argsort(coefficients)[:top_features] top_coefficients = np.hstack([top_negative_coefficients, top_positive_coefficients]) # # create plot # plt.figure(figsize=(15, 5)) # colors = ['red' if c < 0 else 'blue' for c in coefficients[top_coefficients]] # plt.bar(np.arange(2 * top_features), coefficients[top_coefficients], color=colors) feature_names = np.array(feature_names) required_features = feature_names[top_coefficients][-top_features:] print("\n".join([str(r) for r in required_features])) # plt.xticks(np.arange(1, 1 + 2 * top_features), feature_names[top_coefficients], rotation=60, ha='right') #plt.show() print() # plt.savefig(f'./{label}.pdf') important_features[class_] = required_features else: coef = coef.ravel() top_positive_coefficients = np.argsort(coef)[-top_features:] top_negative_coefficients = np.argsort(coef)[:top_features] top_coefficients = np.hstack([top_negative_coefficients, top_positive_coefficients]) # create plot # plt.figure(figsize=(15, 5)) # colors = ['red' if c < 0 else 'blue' for c in coef[top_coefficients]] # plt.bar(np.arange(2 * top_features), coef[top_coefficients], color=colors) # feature_names = np.array(feature_names) # plt.xticks(np.arange(1, 1 + 2 * top_features), feature_names[top_coefficients], rotation=60, ha='right') #plt.show() #plt.savefig(f'./{word}.pdf') #Class = 0 label = label_list[0].split("/")[0] print(label) required_features = list(feature_names[top_negative_coefficients]) required_features.reverse() print("\n".join([str(r) for r in required_features]) + "\n") important_features[0] = required_features # Class = 1 label = label_list[1].split("/")[0] print(label) required_features = list(feature_names[top_positive_coefficients]) required_features.reverse() print("\n".join([str(r) for r in required_features])) important_features[1] = required_features return important_features def collateTree(editedgraph, tree_dictionary,topnodes, leafnodes, leafedges): collatedGraph, relabeled_leaves = [], {} if len(tree_dictionary) == 1 and len(leafnodes) == 1: # There are no root nodes, possibly one one leaf for leafnum, leaf in enumerate(leafnodes): relabeled_leaves[leafnum] = leaf return editedgraph, tree_dictionary, relabeled_leaves collatedGraph.append(editedgraph[0]) collatedGraph.append(editedgraph[1]) collatedGraph.append(editedgraph[2]) lableindexmap = {} i=0 removed_leaves = set() removednodes = set() classm_leaf = {} topleafnodes = set() for leaf in leafnodes: topleafnodes.add(tree_dictionary[leaf]['top']) topleafnodes = list(topleafnodes) topleafnodes.sort() revisedleafnodes = [] while True: #print(i) i += 1 num_changes = 0 revisedtopleafnodes = defaultdict(set) for topnode in topleafnodes: #Traversing only tops of leaves if topnode in revisedtopleafnodes: continue classes = defaultdict(list) children = tree_dictionary[topnode]["children"] for child_index in children: child = tree_dictionary[child_index] if child["leaf"]: class_ = child['class'] classes[class_].append(child_index) num_labels = len(child['label_distribution']) for class_, children in classes.items(): if len(children) > 1: # Merge the children num_changes += 1 labels = [] label_distributions = np.zeros((num_labels), ) leaf_indices = [] for child_index in children: labels.append(tree_dictionary[child_index]["class"]) label_distribution = np.array(tree_dictionary[child_index]["label_distribution"]) label_distributions += label_distribution leaf_indices.append(child_index) #update the tree_dictionary leaf_label, leaf_index = labels[0], leaf_indices[0] tree_dictionary[leaf_index]["class"] = leaf_label tree_dictionary[leaf_index]["label_distribution"] = label_distributions topedge = tree_dictionary[topnode]['edge'] if topedge in tree_dictionary[leaf_index]['active']: tree_dictionary[leaf_index]['active'].remove(topedge) if topedge in tree_dictionary[leaf_index]['non_active']: tree_dictionary[leaf_index]['non_active'].remove(topedge) classm_leaf[leaf_label] = class_ for llind in leaf_indices[1:]: tree_dictionary[topnode]['children'].remove(llind) removed_leaves.add(llind) del tree_dictionary[llind] if len(tree_dictionary[topnode]['children']) == 1: child = tree_dictionary[topnode]["children"][0] if topnode == 0: del tree_dictionary[topnode]["children"][0] removednodes.add(child) break else: toptopnode = tree_dictionary[topnode]['top'] for active in tree_dictionary[topnode]['active']: tree_dictionary[child]['active'].append(active) for non_active in tree_dictionary[topnode]['non_active']: tree_dictionary[child]['non_active'].append(non_active) tree_dictionary[toptopnode]['children'].append(child) tree_dictionary[child]['top'] = toptopnode del tree_dictionary[topnode] tree_dictionary[toptopnode]['children'].remove(topnode) removednodes.add(topnode) leafedges[child] = leafedges.get(topnode, '') revisedtopleafnodes[toptopnode].add(child) else: revisedtopleafnodes[topnode].add(leaf_index) elif len(children) == 1: revisedtopleafnodes[topnode].add(children[0]) topleafnodes = deepcopy(revisedtopleafnodes) if num_changes == 0 or i > 5: break # for node in topnodes: # #Check if the subtree labeltext = "[label=\"{0}\",labelfontsize=10,labelangle={1}];" topnodes = set(topnodes) - removednodes rules_for_each_leaf = {} rule = "" root_label = tree_dictionary[0]['class'] rule_stack = {} nonodes = [] yesnodes= [] for node in topnodes: #if node not in removednodes: info = tree_dictionary[node]["info"] #new_info = info[0] + "\\n" + "\\n".join(info[2:]) collatedGraph.append(info) if node == 0: rule_stack[node] = "" else: rule_stack[node] = leafedges[node] for num, children in enumerate(tree_dictionary[node]["children"]): rule_stack[children] = "" textinfo = str(node) + " -> " + str(children) angle = 50 if num > len(tree_dictionary[node]["children"]) / 2: angle *= -1 if "Not" in leafedges[children]: edge = "No" if tree_dictionary[node]['class'] != tree_dictionary[children]['class']: if node not in rule_stack: print() rule_stack[children] = rule_stack[node] + leafedges[children] + "\n " else: rule_stack[children] = rule_stack[node] textinfo += " " + labeltext.format(edge, angle) nonodes.append(textinfo) else: edge = "Yes" if node not in rule_stack: print() rule_stack[children] = rule_stack[node] + leafedges[children] + "\n " textinfo += " " + labeltext.format(edge, angle) yesnodes.append(textinfo) if children in leafnodes and children not in removed_leaves: # reached a leaf rules_for_each_leaf[children] = rule_stack[children] collatedGraph += nonodes + yesnodes new_leaf_info = "{0} [label=\"Leaf- {1}\\n{2}\\lvalue = [{3}]\\lclass = {4}\\l\", fillcolor={5} " new_leaves, new_leaf_num = {}, 0 for leaf, leafnode in enumerate(leafnodes): if leafnode in removed_leaves: continue label_distribution = tree_dictionary[leafnode]['label_distribution'] nsamples = sum(label_distribution) label_distribution = [str(l) for l in label_distribution] color = tree_dictionary[leafnode]["info"].split("fillcolor=")[-1] leafinfo = new_leaf_info.format(leafnode, new_leaf_num, "", ", ".join(label_distribution),tree_dictionary[leafnode]['class'], color) collatedGraph.append(leafinfo) new_leaves[new_leaf_num] = leafnode new_leaf_num += 1 # if tree_dictionary[leafnode]['class'] != root_label: # print(tree_dictionary[leafnode]['class'] + "\n" + rules_for_each_leaf[leafnode]) collatedGraph.append(editedgraph[-1]) #print("\n".join(collatedGraph)) #exit(-1) return collatedGraph, tree_dictionary, new_leaves def collateTreeFromXGBoost(tree_dictionary,topnodes, leafnodes, leafedges): collatedGraph, relabeled_leaves = [], {} if len(tree_dictionary) == 1 and len(leafnodes) == 1: # There are no root nodes, possibly one one leaf for leafnum, leaf in enumerate(leafnodes): relabeled_leaves[leafnum] = leaf return tree_dictionary, relabeled_leaves lableindexmap = {} i=0 removed_leaves = set() removednodes = set() classm_leaf = {} topleafnodes = set() for leaf in leafnodes: top = tree_dictionary[leaf]['top'] if top == -1: continue topleafnodes.add(tree_dictionary[leaf]['top']) topleafnodes = list(topleafnodes) topleafnodes.sort() revisedleafnodes = [] while True: #print(i) i += 1 num_changes = 0 revisedtopleafnodes = defaultdict(set) for topnode in topleafnodes: #Traversing only tops of leaves if topnode in revisedtopleafnodes: continue classes = defaultdict(list) children = tree_dictionary[topnode]["children"] for child_index in children: child = tree_dictionary[child_index] if child["leaf"]: class_ = child['class'] classes[class_].append(child_index) num_labels = len(child['label_distribution']) for class_, children in classes.items(): if len(children) > 1: # Merge the children num_changes += 1 labels = [] label_distributions = np.zeros((num_labels), ) leaf_indices = [] for child_index in children: labels.append(tree_dictionary[child_index]["class"]) label_distribution = np.array(tree_dictionary[child_index]["label_distribution"]) label_distributions += label_distribution leaf_indices.append(child_index) #update the tree_dictionary leaf_label, leaf_index = labels[0], leaf_indices[0] tree_dictionary[leaf_index]["class"] = leaf_label tree_dictionary[leaf_index]["label_distribution"] = label_distributions topedge = tree_dictionary[topnode]['edge'] if topedge in tree_dictionary[leaf_index]['active']: tree_dictionary[leaf_index]['active'].remove(topedge) if topedge in tree_dictionary[leaf_index]['non_active']: tree_dictionary[leaf_index]['non_active'].remove(topedge) classm_leaf[leaf_label] = class_ for llind in leaf_indices[1:]: tree_dictionary[topnode]['children'].remove(llind) removed_leaves.add(llind) del tree_dictionary[llind] if len(tree_dictionary[topnode]['children']) == 1: child = tree_dictionary[topnode]["children"][0] if topnode == 0 or topnode == -1: del tree_dictionary[topnode]["children"][0] removednodes.add(child) break else: toptopnode = tree_dictionary[topnode]['top'] if toptopnode != -1: #Separate tree with only one leaf tree_dictionary[toptopnode]['children'].append(child) tree_dictionary[child]['top'] = toptopnode del tree_dictionary[topnode] else: del tree_dictionary[topnode]["children"][0] removednodes.add(child) del tree_dictionary[topnode] removednodes.add(topnode) break tree_dictionary[toptopnode]['children'].remove(topnode) removednodes.add(topnode) leafedges[child] = leafedges.get(topnode, '') revisedtopleafnodes[toptopnode].add(child) else: revisedtopleafnodes[topnode].add(leaf_index) elif len(children) == 1: revisedtopleafnodes[topnode].add(children[0]) topleafnodes = deepcopy(revisedtopleafnodes) if num_changes == 0 or i > 5: break # for node in topnodes: # #Check if the subtree labeltext = "[label=\"{0}\",labelfontsize=10,labelangle={1}];" topnodes = set(topnodes) - removednodes rules_for_each_leaf = {} rule_stack = {} nonodes = [] yesnodes= [] for node in topnodes: #if node not in removednodes: info = tree_dictionary[node]["info"] #new_info = info[0] + "\\n" + "\\n".join(info[2:]) #collatedGraph.append(info) if node not in leafedges: rule_stack[node] = "" else: rule_stack[node] = leafedges[node] for num, children in enumerate(tree_dictionary[node]["children"]): rule_stack[children] = "" textinfo = str(node) + " -> " + str(children) angle = 50 if num > len(tree_dictionary[node]["children"]) / 2: angle *= -1 if "Not" in leafedges[children]: edge = "No" if tree_dictionary[node]['class'] != tree_dictionary[children]['class']: if node not in rule_stack: print() rule_stack[children] = rule_stack[node] + leafedges[children] + "\n " else: rule_stack[children] = rule_stack[node] textinfo += " " + labeltext.format(edge, angle) nonodes.append(textinfo) else: edge = "Yes" if node not in rule_stack: print() rule_stack[children] = rule_stack[node] + leafedges[children] + "\n " textinfo += " " + labeltext.format(edge, angle) yesnodes.append(textinfo) if children in leafnodes and children not in removed_leaves: # reached a leaf rules_for_each_leaf[children] = rule_stack[children] #collatedGraph += nonodes + yesnodes new_leaf_info = "{0} [label=\"Leaf- {1}\\n{2}\\lvalue = [{3}]\\lclass = {4}\\l\", fillcolor={5} " new_leaves, new_leaf_num = {}, 0 for leaf, leafnode in enumerate(leafnodes): if leafnode in removed_leaves: continue label_distribution = tree_dictionary[leafnode]['label_distribution'] nsamples = sum(label_distribution) label_distribution = [str(l) for l in label_distribution] #color = tree_dictionary[leafnode]["info"].split("fillcolor=")[-1] #leafinfo = new_leaf_info.format(leafnode, new_leaf_num, "", ", ".join(label_distribution),tree_dictionary[leafnode]['class'], color) #collatedGraph.append(leafinfo) new_leaves[new_leaf_num] = leafnode new_leaf_num += 1 # if tree_dictionary[leafnode]['class'] != root_label: # print(tree_dictionary[leafnode]['class'] + "\n" + rules_for_each_leaf[leafnode]) return tree_dictionary, new_leaves def collateTreeRemoveNA(editedgraph, tree_dictionary,topnodes, leafnodes, leafedges): tree_dictionary_removeNA = deepcopy(tree_dictionary) collatedGraph, relabeled_leaves = [], {} if len(tree_dictionary_removeNA) == 1 and len(leafnodes) == 1: # There are no root nodes, possibly one one leaf for leafnum, leaf in enumerate(leafnodes): relabeled_leaves[leafnum] = leaf return editedgraph, tree_dictionary_removeNA, relabeled_leaves collatedGraph.append(editedgraph[0]) collatedGraph.append(editedgraph[1]) collatedGraph.append(editedgraph[2]) i=0 removed_leaves = set() removednodes = set() classm_leaf = {} topleafnodes = set() for leaf in leafnodes: topleafnodes.add(tree_dictionary_removeNA[leaf]['top']) topleafnodes = list(topleafnodes) topleafnodes.sort() while True: i += 1 num_changes = 0 revisedtopleafnodes = defaultdict(set) for topnode in topleafnodes: #Traversing only tops of leaves if topnode in revisedtopleafnodes: continue classes = defaultdict(list) children = tree_dictionary_removeNA[topnode]["children"] for child_index in children: child = tree_dictionary_removeNA[child_index] if child["leaf"]: class_ = child['class'] if class_ == 'NA': #Skipping NA class for collating continue classes[class_].append(child_index) num_labels = len(child['label_distribution']) for class_, children in classes.items(): if len(children) > 1: # Merge the children num_changes += 1 labels = [] label_distributions = np.zeros((num_labels), ) leaf_indices = [] for child_index in children: labels.append(tree_dictionary_removeNA[child_index]["class"]) label_distribution = np.array(tree_dictionary_removeNA[child_index]["label_distribution"]) label_distributions += label_distribution leaf_indices.append(child_index) #update the tree_dictionary leaf_label, leaf_index = labels[0], leaf_indices[0] tree_dictionary_removeNA[leaf_index]["class"] = leaf_label tree_dictionary_removeNA[leaf_index]["label_distribution"] = label_distributions topedge = tree_dictionary_removeNA[topnode]['edge'] if topedge in tree_dictionary_removeNA[leaf_index]['active']: tree_dictionary_removeNA[leaf_index]['active'].remove(topedge) if topedge in tree_dictionary_removeNA[leaf_index]['non_active']: tree_dictionary_removeNA[leaf_index]['non_active'].remove(topedge) classm_leaf[leaf_label] = class_ for llind in leaf_indices[1:]: tree_dictionary_removeNA[topnode]['children'].remove(llind) removed_leaves.add(llind) del tree_dictionary_removeNA[llind] if len(tree_dictionary_removeNA[topnode]['children']) == 1: child = tree_dictionary_removeNA[topnode]["children"][0] if topnode == 0: del tree_dictionary_removeNA[topnode]["children"][0] removednodes.add(child) break else: toptopnode = tree_dictionary_removeNA[topnode]['top'] for active in tree_dictionary_removeNA[topnode]['active']: tree_dictionary_removeNA[child]['active'].append(active) for non_active in tree_dictionary_removeNA[topnode]['non_active']: tree_dictionary_removeNA[child]['non_active'].append(non_active) tree_dictionary_removeNA[toptopnode]['children'].append(child) tree_dictionary_removeNA[child]['top'] = toptopnode del tree_dictionary_removeNA[topnode] tree_dictionary_removeNA[toptopnode]['children'].remove(topnode) removednodes.add(topnode) leafedges[child] = leafedges.get(topnode, '') revisedtopleafnodes[toptopnode].add(child) else: revisedtopleafnodes[topnode].add(leaf_index) elif len(children) == 1: revisedtopleafnodes[topnode].add(children[0]) topleafnodes = deepcopy(revisedtopleafnodes) if num_changes == 0 or i > 5: break # for node in topnodes: # #Check if the subtree labeltext = "[label=\"{0}\",labelfontsize=10,labelangle={1}];" topnodes_ = set(topnodes) - removednodes rules_for_each_leaf = {} rule = "" root_label = tree_dictionary_removeNA[0]['class'] rule_stack = {} nonodes = [] yesnodes= [] for node in topnodes_: #if node not in removednodes: info = tree_dictionary_removeNA[node]["info"] #new_info = info[0] + "\\n" + "\\n".join(info[2:]) collatedGraph.append(info) if node == 0: rule_stack[node] = "" else: rule_stack[node] = leafedges[node] for num, children in enumerate(tree_dictionary_removeNA[node]["children"]): rule_stack[children] = "" textinfo = str(node) + " -> " + str(children) angle = 50 if num > len(tree_dictionary_removeNA[node]["children"]) / 2: angle *= -1 if "Not" in leafedges[children]: edge = "No" if tree_dictionary_removeNA[node]['class'] != tree_dictionary_removeNA[children]['class']: if node not in rule_stack: print() rule_stack[children] = rule_stack[node] + leafedges[children] + "\n " else: rule_stack[children] = rule_stack[node] textinfo += " " + labeltext.format(edge, angle) nonodes.append(textinfo) else: edge = "Yes" if node not in rule_stack: print() rule_stack[children] = rule_stack[node] + leafedges[children] + "\n " textinfo += " " + labeltext.format(edge, angle) yesnodes.append(textinfo) if children in leafnodes and children not in removed_leaves: # reached a leaf rules_for_each_leaf[children] = rule_stack[children] collatedGraph += nonodes + yesnodes new_leaf_info = "{0} [label=\"Leaf- {1}\\n{2}\\lvalue = [{3}]\\lclass = {4}\\l\", fillcolor={5} " new_leaves, new_leaf_num = {}, 0 for leaf, leafnode in enumerate(leafnodes): if leafnode in removed_leaves: continue label_distribution = tree_dictionary_removeNA[leafnode]['label_distribution'] label_distribution = [str(l) for l in label_distribution] color = tree_dictionary_removeNA[leafnode]["info"].split("fillcolor=")[-1] leafinfo = new_leaf_info.format(leafnode, new_leaf_num, "", ", ".join(label_distribution),tree_dictionary_removeNA[leafnode]['class'], color) collatedGraph.append(leafinfo) new_leaves[new_leaf_num] = leafnode new_leaf_num += 1 collatedGraph.append(editedgraph[-1]) return collatedGraph, tree_dictionary_removeNA, new_leaves def pruneTree(collatedGraph, tree_dictionary,topnodes, leafnodes): newGraph, relabeled_leaves = [], {} newGraph.append(collatedGraph[0]) newGraph.append(collatedGraph[1]) newGraph.append(collatedGraph[2]) lableindexmap = {} i=0 removednodes = set() if len(tree_dictionary) == 1 and len(leafnodes) == 1: #There are no root nodes, possibly one one leaf return collatedGraph, relabeled_leaves classm_leaf = {} topleafnodes = set() for new_leaf_num, leaf in leafnodes.items(): top = tree_dictionary[leaf]['top'] if top == -1: continue topleafnodes.add(tree_dictionary[leaf]['top']) topleafnodes = list(topleafnodes) topleafnodes.sort() while True: #print(i) i += 1 num_changes = 0 for topnode in topleafnodes: #Traversing only tops of leaves if topnode in removednodes: continue classes = defaultdict(list) children = tree_dictionary[topnode]["children"] num_children = len(children) for child_index in children: child = tree_dictionary[child_index] if child["leaf"]: class_ = child['class'] if class_ == 'NA': #To remove leaf: classes[class_].append(child_index) removed_leaves = set() for class_, children in classes.items(): num_changes += 1 for child_index in children: removed_leaves.add(child_index) del tree_dictionary[child_index] tree_dictionary[topnode]['children'].remove(child_index) removednodes.add(child_index) if num_children == len(removed_leaves): #all leaves are 'NA' toptopnode = tree_dictionary[topnode]['top'] del tree_dictionary[topnode] tree_dictionary[toptopnode]['children'].remove(topnode) removednodes.add(topnode) revisedtopleafnodes = set(topleafnodes) - removednodes topleafnodes = deepcopy(revisedtopleafnodes) if num_changes == 0 or i > 5: break leafnum = 0 new_leaves = {} for new_leaf_num, leaf in leafnodes.items(): if leaf in removednodes: continue new_leaves[leafnum] = leaf leafnum += 1 return new_leaves def collateTreePrune(collatedGraph, tree_dictionary,topnodes, leafnodes): newGraph, relabeled_leaves = [], {} newGraph.append(collatedGraph[0]) newGraph.append(collatedGraph[1]) newGraph.append(collatedGraph[2]) lableindexmap = {} i=0 removed_leaves = set() removednodes = set() if len(tree_dictionary) == 1 and len(leafnodes) == 1: #There are no root nodes, possibly one one leaf return collatedGraph, tree_dictionary, leafnodes classm_leaf = {} topleafnodes = set() for _,leaf in enumerate(leafnodes): topleafnodes.add(tree_dictionary[leaf]['top']) topleafnodes = list(topleafnodes) topleafnodes.sort() revisedleafnodes = [] while True: #print(i) i += 1 num_changes = 0 revisedtopleafnodes = defaultdict(set) for topnode in topleafnodes: #Traversing only tops of leaves if topnode in revisedtopleafnodes: continue classes = defaultdict(list) children = tree_dictionary[topnode]["children"] for child_index in children: child = tree_dictionary[child_index] if child["leaf"]: class_ = child['class'] classes[class_].append(child_index) num_labels = len(child['label_distribution']) for class_, children in classes.items(): if len(children) > 1: # Merge the children num_changes += 1 labels = [] label_distributions = np.zeros((num_labels), ) leaf_indices = [] for child_index in children: labels.append(tree_dictionary[child_index]["class"]) label_distribution = np.array(tree_dictionary[child_index]["label_distribution"]) label_distributions += label_distribution leaf_indices.append(child_index) #update the tree_dictionary leaf_label, leaf_index = labels[0], leaf_indices[0] tree_dictionary[leaf_index]["class"] = leaf_label tree_dictionary[leaf_index]["label_distribution"] = label_distributions topedge = tree_dictionary[topnode]['edge'] if topedge in tree_dictionary[leaf_index]['active']: tree_dictionary[leaf_index]['active'].remove(topedge) if topedge in tree_dictionary[leaf_index]['non_active']: tree_dictionary[leaf_index]['non_active'].remove(topedge) classm_leaf[leaf_label] = class_ for llind in leaf_indices[1:]: tree_dictionary[topnode]['children'].remove(llind) removed_leaves.add(llind) removednodes.add(llind) del tree_dictionary[llind] if len(tree_dictionary[topnode]['children']) == 1: child = tree_dictionary[topnode]["children"][0] if topnode == 0: del tree_dictionary[topnode]["children"][0] removednodes.add(child) break else: toptopnode = tree_dictionary[topnode]['top'] for active in tree_dictionary[topnode]['active']: tree_dictionary[child]['active'].append(active) for non_active in tree_dictionary[topnode]['non_active']: tree_dictionary[child]['non_active'].append(non_active) tree_dictionary[toptopnode]['children'].append(child) tree_dictionary[child]['top'] = toptopnode del tree_dictionary[topnode] tree_dictionary[toptopnode]['children'].remove(topnode) removednodes.add(topnode) revisedtopleafnodes[toptopnode].add(child) else: revisedtopleafnodes[topnode].add(leaf_index) elif len(children) == 1: revisedtopleafnodes[topnode].add(children[0]) topleafnodes = deepcopy(revisedtopleafnodes) if num_changes == 0: #or i > 5: break # for node in topnodes: # #Check if the subtree labeltext = "[label=\"{0}\",labelfontsize=10,labelangle={1}];" topnodes = set(topnodes) - removednodes rule = "" root_label = tree_dictionary[0]['class'] rule_stack = {} # nonodes = [] # yesnodes= [] # for node in topnodes: # #if node not in removednodes: # info = tree_dictionary[node]["info"] # #new_info = info[0] + "\\n" + "\\n".join(info[2:]) # collatedGraph.append(info) # # if node == 0: # rule_stack[node] = "" # else: # rule_stack[node] = leafedges[node] # for num, children in enumerate(tree_dictionary[node]["children"]): # rule_stack[children] = "" # textinfo = str(node) + " -> " + str(children) # angle = 50 # if num > len(tree_dictionary[node]["children"]) / 2: # angle *= -1 # # # if "Not" in leafedges[children]: # edge = "No" # if tree_dictionary[node]['class'] != tree_dictionary[children]['class']: # if node not in rule_stack: # print() # rule_stack[children] = rule_stack[node] + leafedges[children] + "\n " # else: # rule_stack[children] = rule_stack[node] # textinfo += " " + labeltext.format(edge, angle) # nonodes.append(textinfo) # else: # edge = "Yes" # if node not in rule_stack: # print() # rule_stack[children] = rule_stack[node] + leafedges[children] + "\n " # # textinfo += " " + labeltext.format(edge, angle) # yesnodes.append(textinfo) # # # if children in leafnodes and children not in removed_leaves: # reached a leaf # rules_for_each_leaf[children] = rule_stack[children] # # collatedGraph += nonodes + yesnodes new_leaf_info = "{0} [label=\"Leaf- {1}\\n{2}\\lvalue = [{3}]\\lclass = {4}\\l\", fillcolor={5} " new_leaves, new_leaf_num = {}, 0 for leaf, leafnode in enumerate(leafnodes): if leafnode in removed_leaves: continue label_distribution = tree_dictionary[leafnode]['label_distribution'] nsamples = sum(label_distribution) label_distribution = [str(l) for l in label_distribution] color = tree_dictionary[leafnode]["info"].split("fillcolor=")[-1] leafinfo = new_leaf_info.format(leafnode, new_leaf_num, "", ", ".join(label_distribution),tree_dictionary[leafnode]['class'], color) collatedGraph.append(leafinfo) new_leaves[new_leaf_num] = leafnode new_leaf_num += 1 # if tree_dictionary[leafnode]['class'] != root_label: # print(tree_dictionary[leafnode]['class'] + "\n" + rules_for_each_leaf[leafnode]) collatedGraph.append(collatedGraph[-1]) #print("\n".join(collatedGraph)) #exit(-1) return collatedGraph, tree_dictionary, new_leaves def isLabel(expected_prob, leafinfo, threshold, task): leafinfo = np.array(leafinfo) new_leaf_index, new_leaf_info , max_value, max_index= [],[], 0, -1 for index, val in enumerate(leafinfo): new_leaf_info.append(val) new_leaf_index.append(index) if val > max_value: max_value = val max_index = index if len(new_leaf_info) < 2: return True new_leaf_info = np.array(new_leaf_info) sumtotal = np.sum(new_leaf_info) p_value = max_value / sumtotal #Hard threshold expected_prob = np.array(expected_prob) total_values = np.sum(expected_prob) if task == 'agreement': expected_prob_per_feature = 0 for num in expected_prob: p = num / total_values expected_prob_per_feature += p * p empirical_distr = [1 - expected_prob_per_feature, expected_prob_per_feature] expected_agree = empirical_distr[1] * sumtotal expected_disagree = empirical_distr[0] * sumtotal expected_values = [expected_disagree, expected_agree] p_value = new_leaf_info[1] / sumtotal k = 1 else: p = 1/ len(expected_prob) expected_prob = [p] * len(expected_prob) expected_prob = np.array(expected_prob) expected_values = expected_prob * sumtotal k = len(expected_values) -1 min_value = 0 for value in expected_values: if value < 5: min_value += 1 if min_value >= (k+1) : #Not apply stastical test return False T,p = chisquare(new_leaf_info, expected_values) w = np.sqrt(T * 1.0 /(k * sumtotal)) if p_value > 0.5 and p < threshold and w > 0.5 : #for majority class label and p-value and effect size and reject the null return True else: return False def computeAccuracy(tree_dictionary, leafmap, featuresdata, data, prop, labels, task='agreement', threshold=[0.85, 0.90]): correct, total, na = 0, 0, 0 all_data = 0 leaf_samples = [] leaf_correct = [] gold_labels_per_threshold = defaultdict(list) leaf_labels = [] for _,leaf in leafmap.items(): gold_distribution_leaf = defaultdict(lambda: 0) leaf = tree_dictionary[leaf] leaf_label = leaf['class'] top = leaf['top'] active = leaf['active'] non_active = leaf['non_active'] while top > 0: # Not root active += tree_dictionary[top]['active'] non_active += tree_dictionary[top]['non_active'] top = tree_dictionary[top]['top'] active = list(set(active)) non_active = list(set(non_active)) features = [] for index in range(len(featuresdata)): datapoint = featuresdata.iloc[index] sent_num = int(datapoint['sent_num']) token_num = str(datapoint['token_num']) sent = data[sent_num] for id, token in enumerate(sent): if token.id == token_num: feats = token.feats break valid = True for active_feature in active: value = datapoint[active_feature] if value != 1: valid = False break if not valid: break features.append(active_feature) if not valid: continue for non_active_feature in non_active: value = datapoint[non_active_feature] if value != 0: valid = False break if not valid: break features.append(non_active_feature) if not valid: continue if prop not in feats: continue label = list(feats[prop]) label.sort() label = "/".join(label) if task == 'agreement': headtoken = sent[token.head] headfeats = headtoken.feats if prop not in headfeats: continue headlabel = list(feats[prop]) headlabel.sort() headlabel = '/'.join(headlabel) if label == headlabel: gold_distribution_leaf[1] += 1 else: gold_distribution_leaf[0] += 1 elif task == 'assignment': gold_distribution_leaf[label] += 1 all_data += 1 #Gold label as having required agreement > 95% leaftotal = 0 for label in labels: leaftotal += gold_distribution_leaf[label] if leaftotal == 0: continue leaf_samples.append(leaftotal) total += 1 leaf_labels.append(leaf_label) for t in threshold: if task == 'agreement': gold_value = gold_distribution_leaf[1] / leaftotal if gold_value > t: gold_label = 'req-agree' else: gold_label = 'NA' elif task == 'assignment': majority_label, majorityValue = None, 0 for label, value in gold_distribution_leaf.items(): if value > majorityValue: majorityValue = value majority_label = label gold_value = majorityValue / leaftotal if gold_value > t: gold_label = majority_label else: gold_label = 'NA' gold_labels_per_threshold[t].append(gold_label) max_score = 0.0 best_t = 0.0 leaf_samples = np.array(leaf_samples) leaf_distribution = leaf_samples / np.sum(leaf_samples) for t, gold_labels in gold_labels_per_threshold.items(): assert len(leaf_labels) == len(gold_labels) leaf_correct = [] for gold_label, leaf_label in zip(gold_labels, leaf_labels): if gold_label == leaf_label: correct += 1 leaf_correct.append(1.0) elif leaf_label == 'NA' and gold_label == 'chance-agree': correct += 1 leaf_correct.append(1.0) else: leaf_correct.append(0.0) leaf_distribution = leaf_distribution * np.array(leaf_correct) score = np.sum(leaf_distribution) if score > max_score: max_score = score best_t = t print(max_score, best_t) return best_t # acc = correct / total # print(acc, correct, total, np.sum(leaf_distribution)) def computeAutomatedMetric(leaves, tree_dictionary, test_df, testdata, feature_pos, tree_features, dataloader, task, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim, foldername, lang, isbaseline=False): automated_evaluation_score = {} if '-' in feature_pos: feature = feature_pos.split("-")[0] rel = feature_pos.split("-")[1] else: feature = feature_pos rel = feature_pos test_agree_tuple, test_freq_tuple = getTestData(testdata, feature, task) examples = {} sent_examples = defaultdict(list) for leaf_num, leaf in leaves.items(): #test samples fitted on the tree getExamplesPerLeafWithFeatures(leaf, tree_dictionary, feature_pos, test_df, testdata, task, examples, sent_examples, tree_features, dataloader, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim) with open(f"{foldername}/{rel}/learnt_rules_{lang}.txt", 'w') as fout: fout.write('rel,head-pos,child-pos\ttree-label\tgold-label\n') for tuple, total in test_freq_tuple.items(): agree_examples = test_agree_tuple.get(tuple, 0) test_percent = agree_examples * 1.0 / total if test_percent >= 0.95: gold_label = 'req-agree' else: gold_label = 'NA' #tree-label if tuple in examples: (rel, head_pos, dep_pos) = tuple data_distribution = examples[tuple] agree = data_distribution.get('req-agree', 0) disagree = data_distribution.get('NA', 0) if agree > disagree: tree_label = 'req-agree' else: tree_label = 'NA' if isbaseline: #all leaves are chance-baseline tree_label = 'NA' fout.write(f'{rel},{head_pos},{dep_pos}\t{tree_label}\t{gold_label}\n') if tree_label == gold_label: automated_evaluation_score[tuple] = 1 else: automated_evaluation_score[tuple] = 0 total = 0 correct = 0 for tuple, count in automated_evaluation_score.items(): correct += count total += 1 metric = correct * 1.0 / total return metric, sent_examples def readWikiData(input): wikidata = {} with open(input, 'r') as fin: lines = fin.readlines() for line in lines: info = line.strip().split("\t") babel_id, relation, value = info[0], info[1], int(info[-1]) if babel_id not in wikidata: wikidata[babel_id] = {} wikidata[babel_id][relation] = value return wikidata def readWikiParsedInput(input): sentence_token_map =defaultdict(list) with open(input, 'r') as fin: start_token = defaultdict(list) for line in fin.readlines(): if line == "" or line == "\n": sentence_token_map[sentence] = deepcopy(start_token) start_token = defaultdict(list) continue elif "bn:" in line: info = line.strip().split("\t") if "all" in input: token_start, token_end, char_start, char_end, babel_id = info[0], info[1], info[2], info[3], info[4] else: token_start, token_end, char_start, char_end, babel_id = int(info[0]), int(info[1]), int( info[2]), int(info[3]), info[4] start_token[token_start].append(babel_id) #Add babelids per each token else: info = line.strip().split("\t") if len(info) == 1: sentence = line.strip() elif len(info) == 3: linenum, sentence, tokenid = info[0].lstrip().rstrip(), info[1].lstrip().rstrip(), info[2].lstrip().rstrip() return sentence_token_map def readWSDPath(input): word_pos_wsd = {} with open(input, 'r') as fin: for line in fin.readlines(): info = line.strip().split("\t") word_pos = info[0].split(",") features = info[-1].split(";") word_pos_wsd[(word_pos[0], word_pos[1])] = features return word_pos_wsd def readWikiGenreInput(input): sentence_token_map = {} with open(input, 'r') as fin: lines = fin.readlines() for line in lines: info = line.strip().split("\t") text, tokenids, qids = info[0].lstrip().rstrip(), info[1], info[2] tokenids = tokenids.split(",") if text not in sentence_token_map: sentence_token_map[text] = defaultdict(list) sentence_token_map[text][tokenids[0]].append(qids) return sentence_token_map def getTestData(data, feature, task): freq_tuple = defaultdict(lambda: 0) tuple_agree_information = defaultdict(lambda: 0) #In case of word order agree == right for sentence in data: id2index = sentence._ids_to_indexes for token in sentence: token_id = token.id if "-" in token_id or "." in token_id: continue if token.deprel is None: continue relation = token.deprel.lower() pos = token.upos feats = token.feats if token.head and token.head != "0": head_pos = sentence[token.head].upos head_feats = sentence[token.head].feats if task == 'agreement': shared, agreed = find_agreement(feats, head_feats) if feature in shared:# and pos == req_pos: tuple = (relation, head_pos, pos) freq_tuple[(relation, head_pos, pos)] += 1 if feats[feature] == head_feats[feature]: tuple_agree_information[tuple] += 1 if task == 'wordorder': feature_info = feature.split("_") if relation == feature_info[0] and head_pos == feature_info[0]: token_position = id2index[token.id] head_position = id2index[token.head] if token_position < head_position: label = 'before' else: label = 'after' tuple_agree_information[feature] += 1 freq_tuple[feature] += 1 return tuple_agree_information, freq_tuple def getFeaturesForLeaf(leaf, tree_dictionary): top = leaf.get('top', -1) active = leaf['active'] non_active = leaf['non_active'] while top > 0: # Not root active += tree_dictionary[top]['active'] non_active += tree_dictionary[top]['non_active'] top = tree_dictionary[top]['top'] return active, non_active def filterSents(examples, data, spine_features, isTrain=False, agree_examples=False): #each examples (sent_num, token_id, active, non_active) sentences_per_unique_token = defaultdict(list) filteredExamples = [] prev_data_path = None for (sent_id, token_id, active, non_active) in examples: token = data[sent_id][token_id].lemma head_id = data[sent_id][token_id].head if head_id != '0': head = data[sent_id][head_id].lemma else: head = "" sentences_per_unique_token[(token, head)].append((sent_id, token_id, active, non_active)) for tokenhead, examples in sentences_per_unique_token.items(): (token, head) = tokenhead sent_lengths = {} sent_info = {} for (sent_id, token_id, active, non_active) in examples: sent_lengths[sent_id] = len(data[sent_id]) #Sent length sent_info[sent_id] = (token_id, active, non_active) #sort sent lenghts sorted_sents = sorted(sent_lengths.items(), key=lambda kv:kv[1])[:2] #Get at least three examples per each token-head pair for (sent_id, length) in sorted_sents: token_id, active, non_active = sent_info[sent_id] filteredExamples.append((sent_id, token_id, active, non_active)) active = list(active) if agree_examples and len(active) > 0 and len(active[0]) == 2: #len(filteredExamples) < 10: for (active_feature, active_value) in active: if isTrain and "spine_" in active_feature: if active_feature not in spine_features: spine_features[active_feature] = defaultdict(lambda: 0) spine_features[active_feature][token.lower()] += active_value if isTrain and "spinehead_" in active_feature: if active_feature not in spine_features: spine_features[active_feature] = defaultdict(lambda: 0) spine_features[active_feature][head.lower()] += active_value return filteredExamples def getExamples(sent_examples, leaf, data, isTrain=False): leaf_label = leaf['class'] found_agree = [] found_disagree = [] total_agree, total_disagree = 0,0 spine_features = {} #filter sentences by length and uniqueness of the dependent if leaf_label == 'NA': all_examples = [] for task_label, examples in sent_examples.items(): agree_examples = leaf_label == task_label if leaf_label == 'NA': agree_examples = True examples = examples[:1000] filterExamples = filterSents(examples, data, spine_features, isTrain, agree_examples) if leaf_label == 'NA': all_examples += filterExamples[:10] #10 examples from each label total_disagree += len(filterExamples) else: if leaf_label == task_label: found_agree = filterExamples[:10] #examples[:10] total_agree += len(filterExamples) else: found_disagree = filterExamples[:10] #examples[:10] total_disagree += len(filterExamples) if leaf_label == 'NA': found_disagree = all_examples return found_agree, found_disagree, total_agree, total_disagree, spine_features def getExamplesPerLeaf(leaf, tree_dictionary, prop, train_df, data, task, examples, sent_examples, isTrain=False): leaf = tree_dictionary[leaf] leaf_label = leaf['class'] active, non_active = getFeaturesForLeaf(leaf, tree_dictionary) #spine_features = {} for index in range(len(train_df)): #try: datapoint = train_df.iloc[index] sent_num = int(datapoint['sent_num']) #print(sent_num) token_num = str(datapoint['token_num']) sent = data[sent_num] for id, token in enumerate(sent): if token.id == token_num: token_id = token.id head_token_id = token.head head_token = sent[head_token_id] feats = token.feats relation = token.deprel.lower() id_to_indexes = sent._ids_to_indexes tuple = (relation, head_token.upos, token.upos) break if task == 'agreement': if prop not in feats or prop not in head_token.feats: continue valid = True for (active_feature, active_value) in active: value = float(datapoint[active_feature]) if value <= active_value: valid = False break if not valid: break # if isTrain and "spine_" in active_feature: # if active_feature not in spine_features: # spine_features[active_feature] = defaultdict(lambda:0) # spine_features[active_feature][token.form.lower()] += value # # if isTrain and "spinehead_" in active_feature: # if active_feature not in spine_features: # spine_features[active_feature] = defaultdict(lambda: 0) # spine_features[active_feature][head_token.form.lower()] += value if not valid: continue for (non_active_feature, non_active_value) in non_active: value = float(datapoint[non_active_feature]) if value > non_active_value: valid = False break if not valid: break # if isTrain and "spine_" in non_active_feature: # if non_active_feature not in spine_features: # spine_features[non_active_feature] = defaultdict(lambda:0) # spine_features[non_active_feature][token.form.lower()] += value # # if isTrain and "spinehead_" in non_active_feature: # if non_active_feature not in spine_features: # spine_features[non_active_feature] = defaultdict(lambda: 0) # spine_features[non_active_feature][head_token.form.lower()] += value if not valid: continue #Update the spine features, if spine_ then the feature is for dep, if spinehead_ then the feature is for head, #collect all tokens which have a high positive value and is frequent in the example if task == 'agreement': if prop not in feats: continue label = list(feats[prop]) label.sort() label = "/".join(label) task_label = label if head_token_id == '0': continue headlabel = list(head_token.feats[prop]) headlabel.sort() headlabel = "/".join(headlabel) if label == headlabel: task_label = 'req-agree' else: task_label = 'chance-agree' elif task == 'wordorder': if head_token_id == '0': continue token_position = id_to_indexes[token.id] head_position = id_to_indexes[head_token_id] if token_position < head_position: label ='before' else: label = 'after' task_label = label # if label == leaf_label: # task_label = label # else: # task_label = 'NA' elif task == 'assignment': if token.upos != prop: continue model = 'Case' if model not in feats: continue label = list(feats[model]) label.sort() label = "/".join(label) task_label = label elif task.lower() == 'suffix': task_label = list(token.misc['affix'])[0] if tuple not in examples: examples[tuple] = defaultdict(lambda : 0) examples[tuple][leaf_label] += 1 sent_examples[task_label].append((sent_num, token_id, active, non_active)) #except Exception as e: # print(e, sent_num) #return spine_features def getExamplesPerLeafWithFeatures(leaf, tree_dictionary, prop, train_df, data, task, examples, sent_examples, tree_features, dataloader, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim): leaf = tree_dictionary[leaf] leaf_label = leaf['class'] active, non_active = getFeaturesForLeaf(leaf, tree_dictionary) #data = pyconll.load_from_file(data_path) #spine_features = {} if task == 'agreement': if "-" in prop: feature_pos = prop.split("-") prop = feature_pos[0] prop_pos = feature_pos[1] else: prop_pos = None for index in range(len(train_df)): #try: datapoint = train_df.iloc[index] sent_num = int(datapoint['sent_num']) #print(sent_num) token_num = str(datapoint['token_num']) sent = data[sent_num] token = sent[token_num] token_id = token.id head_token_id = token.head relation = token.deprel.lower() feats = token.feats id_to_indexes = sent._ids_to_indexes if head_token_id == '0': tuple = (relation, token.upos) head_token = None else: head_token = sent[head_token_id] tuple = (relation, head_token.upos, token.upos) if task == 'agreement': if prop not in feats or prop not in head_token.feats: continue if prop_pos and token.upos != prop_pos: continue if task.lower() == 'suffix': if prop != token.upos: continue # ensent = endata[sent_num] # alignmentsent = alignmentdata[sent_num] # alignments_src, alignments_tgt = parseAlignment(alignmentsent.strip().replace("p", "-").split()) feature_array = dataloader.getFeaturesForToken(sent, token, tree_features, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim, prop) valid = True for (active_feature, active_value) in active: value = float(feature_array.get(active_feature, 0)) if value <= active_value: valid = False break if not valid: break if not valid: continue for (non_active_feature, non_active_value) in non_active: value = float(feature_array.get(non_active_feature, 0)) if value > non_active_value: valid = False break if not valid: break if not valid: continue #Update the spine features, if spine_ then the feature is for dep, if spinehead_ then the feature is for head, #collect all tokens which have a high positive value and is frequent in the example if task == 'agreement': if prop not in feats: continue label = list(feats[prop]) label.sort() label = "/".join(label) task_label = label if head_token_id == '0': continue headlabel = list(head_token.feats[prop]) headlabel.sort() headlabel = "/".join(headlabel) if label == headlabel: task_label = 'req-agree' else: task_label = 'chance-agree' elif task == 'wordorder': if head_token_id == '0': continue token_position = id_to_indexes[token.id] head_position = id_to_indexes[head_token_id] if token_position < head_position: label ='before' else: label = 'after' task_label = label elif task == 'assignment': if token.upos != prop: continue model = 'Case' if model not in feats: continue label = list(feats[model]) label.sort() label = "/".join(label) task_label = label elif task.lower() == 'suffix': task_label = list(token.misc['affix'])[0] if tuple not in examples: examples[tuple] = defaultdict(lambda : 0) examples[tuple][leaf_label] += 1 sent_examples[task_label].append((sent_num, token_id, active, non_active)) # except Exception as e: # print(e, sent_num) def getExamplesPerLeafWithFeaturesDistributed(leaf, tree_dictionary, prop, train_df_path, data_path, task, examples, sent_examples, tree_features, dataloader, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim): leaf = tree_dictionary[leaf] leaf_label = leaf['class'] active, non_active = getFeaturesForLeaf(leaf, tree_dictionary) train_df = pd.read_csv(train_df_path, sep=',') data = pyconll.load_from_file(data_path) #spine_features = {} for index in range(len(train_df)): try: datapoint = train_df.iloc[index] sent_num = int(datapoint['sent_num']) #print(sent_num) token_num = str(datapoint['token_num']) sent = data[sent_num] token = sent[token_num] token_id = token.id head_token_id = token.head if head_token_id == '0': print() head_token = sent[head_token_id] feats = token.feats relation = token.deprel.lower() id_to_indexes = sent._ids_to_indexes tuple = (relation, head_token.upos, token.upos) if task == 'agreement': if prop not in feats or prop not in head_token.feats: continue feature_array = dataloader.getFeaturesForToken(sent, token, tree_features, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim, prop=prop) valid = True for (active_feature, active_value) in active: value = float(feature_array.get(active_feature, 0)) if value <= active_value: valid = False break if not valid: break if not valid: continue for (non_active_feature, non_active_value) in non_active: value = float(feature_array.get(non_active_feature, 0)) if value > non_active_value: valid = False break if not valid: break if not valid: continue #Update the spine features, if spine_ then the feature is for dep, if spinehead_ then the feature is for head, #collect all tokens which have a high positive value and is frequent in the example if task == 'agreement': if prop not in feats: continue label = list(feats[prop]) label.sort() label = "/".join(label) task_label = label if head_token_id == '0': continue headlabel = list(head_token.feats[prop]) headlabel.sort() headlabel = "/".join(headlabel) if label == headlabel: task_label = 'req-agree' else: task_label = 'chance-agree' elif task == 'wordorder': if head_token_id == '0': continue token_position = id_to_indexes[token.id] head_position = id_to_indexes[head_token_id] if token_position < head_position: label ='before' else: label = 'after' task_label = label elif task == 'assignment': if token.upos != prop: continue model = 'Case' if model not in feats: continue label = list(feats[model]) label.sort() label = "/".join(label) task_label = label if tuple not in examples: examples[tuple] = defaultdict(lambda : 0) examples[tuple][leaf_label] += 1 sent_examples[task_label].append((data_path, sent_num, token_id, active, non_active)) except Exception as e: print(e, sent_num) def example_web_print( ex, outp2, data, task='agreement'): try: # print('\t\t',data[ex[0]].text) sentid = int(ex[0]) tokid = str(ex[1]) active = ex[2] # data_path = ex[4] # data = pyconll.load_from_file(data_path) req_head_head, req_head_dep, req_dep_dep = False, False, False for (feature, value) in active: if feature.startswith("headrelrel") or feature.startswith('headmatch') or feature.startswith('headhead'): req_head_head = True break if feature.startswith("dephead"): req_head_dep = True if feature.startswith("depdep"): req_dep_dep = True info = feature.split("_") if len(info) > 2: if feature.startswith("agree"): req_head_head = True headid = data[sentid][tokid].head outp2.write('<pre><code class="language-conllu">\n') for token in data[sentid]: if token.id == tokid: temp = token.conll().split('\t') temp[1] = "***" + temp[1] + "***" temp2 = '\t'.join(temp) outp2.write(temp2 + "\n") elif token.id == headid: if req_head_head: temp = token.conll().split('\t') if task == 'agreement' or task == 'wordorder': temp[1] = "***" + temp[1] + "***" temp2 = '\t'.join(temp) outp2.write(temp2 + "\n") else: temp = token.conll().split('\t') if task == 'agreement' or task == 'wordorder': temp[1] = "***" + temp[1] + "***" temp2 = '\t'.join(temp[:6]) outp2.write(f"{temp2}\t0\t_\t_\t_\n") elif token.id == data[sentid][headid].head and req_head_head: temp = token.conll().split('\t') temp2 = '\t'.join(temp[:6]) outp2.write(f"{temp2}\t0\t_\t_\t_\n") elif token.head == headid and req_head_dep: #Getting other dep of the head outp2.write(token.conll() + "\n") elif tokid == token.head and req_dep_dep: # Getting other dep of token outp2.write(token.conll() + "\n") elif '-' not in token.id: outp2.write(f"{token.id}\t{token.form}\t_\t_\t_\t_\t0\t_\t_\t_\n") outp2.write('\n</code></pre>\n\n') # print(f"\t\t\tID: {tokid} token: {data[sentid][tokid].form}\t{data[sentid][tokid].upos}\t{data[sentid][tokid].feats}") # print(data[sentid][tokid].conll()) # headid = data[sentid][tokid].head # print(f"\t\t\tID: {headid} token: {data[sentid][headid].form}\t{data[sentid][headid].upos}\t{data[sentid][headid].feats}") # print(data[sentid][headid].conll()) except: pass def example_web_print_with_english(ex, outp2, data, en_data): #try: # print('\t\t',data[ex[0]].text) sentid = int(ex[0]) tokid = str(ex[1]) eng_sent = en_data[sentid] active = ex[2] alignment_sent = ex[3] #active = ex[2] #active features in that examples req_head_head, req_head_dep, req_dep_dep = False, False, False headid = data[sentid][tokid].head for feature in active: if feature.startswith("headrelrel") or feature.startswith('headmatch') or feature.startswith('headhead'): req_head_head = True break if feature.startswith("dephead"): req_head_dep = True if feature.startswith("depdep"): req_dep_dep = True info = feature.split("_") if len(info) > 2: if feature.startswith("agree"): req_head_head = True outp2.write('<pre><code class="language-conllu">\n') for token in data[sentid]: if token.id == tokid: temp = token.conll().split('\t') temp[1] = "***" + temp[1] + "*** (" + trn.transform(temp[1]) + " )" temp2 = '\t'.join(temp) outp2.write(temp2 + "\n") elif token.id == headid: if req_head_head: temp = token.conll().split('\t') temp[1] = f'{temp[1]} ({trn.transform(temp[1])})' outp2.write("\t".join(temp) + "\n") else: temp = token.conll().split('\t') temp[1] = f'{temp[1]} ({trn.transform(temp[1])})' temp2 = '\t'.join(temp[:6]) outp2.write(f"{temp2}\t0\t_\t_\t_\n") elif headid != '0' and token.id == data[sentid][headid].head and req_head_head: temp = token.conll().split('\t') temp[1] = f'{temp[1]} ({trn.transform(temp[1])})' temp2 = '\t'.join(temp[:6]) outp2.write(f"{temp2}\t0\t_\t_\t_\n") elif token.head == headid and req_head_dep: #Getting other dep of the head temp = token.conll().split('\t') temp[1] = f'{temp[1]} ({trn.transform(temp[1])})' outp2.write("\t".join(temp) + "\n") elif tokid == token.head and req_dep_dep: # Getting other dep of token temp = token.conll().split('\t') temp[1] = f'{temp[1]} ({trn.transform(temp[1])})' outp2.write("\t".join(temp) + "\n") elif '-' not in token.id: temp = token.form temp = f'{temp} ({trn.transform(temp)})' outp2.write(f"{token.id}\t{temp}\t_\t_\t_\t_\t0\t_\t_\t_\n") outp2.write('\n</code></pre>\n\n') #Get the English translation s2t, t2s = parseAlignment(alignment_sent.strip().replace("p", "-").split()) outp2.write('<pre><code class="language-conllu">\n') tokid = data[sentid]._ids_to_indexes[tokid] for token_num, token in enumerate(eng_sent): if token_num in t2s[tokid]: #If the english token is aligned to the main word, mark theb by *** in the english sentence too temp = token.conll().split('\t') temp[1] = "<b>***" + temp[1] + "***</b>" temp2 = '\t'.join(temp) outp2.write(temp2 + "\n") else: outp2.write(f"{token.id}\t{token.form}\t_\t_\t_\t_\t0\t_\t_\t_\n") outp2.write('\n</code></pre>\n\n') #make a table of all word alignments outp2.write(f'<div> <button type="button" class="collapsible" style=\"text-align:center\">Word by word translations </button>\n<div class="content-hover">\n') outp2.write( f'<table><col><colgroup span="2"></colgroup>' f'<th rowspan=\"2\" style=\"text-align:center\">English</th>' f'<th rowspan=\"2\" style=\"text-align:center\">Marathi</th></tr><tr>\n') for target_id, source_ids in t2s.items(): target_form = data[sentid][target_id].form target_form = target_form + ' (' + trn.transform(target_form) + ')' source_forms = [] for source_id in source_ids: source_forms.append(eng_sent[source_id].form) source_form = " ".join(source_forms) outp2.write(f'<tr><td> {source_form} </td> <td> {target_form} </td></tr>\n') outp2.write('</table></div></div>\n<br>\n') # except: # pass def example_web_print_with_transliteration(ex, outp2, data, task='agreement', trn=None): #try: sentid = int(ex[0]) tokid = str(ex[1]) active = ex[2] req_head_head, req_head_dep, req_dep_dep = False, False, False for (feature, value) in active: if feature.startswith("headrelrel") or feature.startswith('headmatch') or feature.startswith('headhead'): req_head_head = True break if feature.startswith("dephead"): req_head_dep = True if feature.startswith("depdep"): req_dep_dep = True info = feature.split("_") if len(info) > 2: if feature.startswith("agree"): req_head_head = True headid = data[sentid][tokid].head outp2.write('<pre><code class="language-conllu">\n') for token in data[sentid]: if token.id == tokid: temp = token.conll().split('\t') temp[1] = "***" + temp[1] + "***" temp2 = '\t'.join(temp) outp2.write(temp2 + "\n") elif token.id == headid: if req_head_head: temp = token.conll().split('\t') if task == 'agreement' or task == 'wordorder': temp[1] = "***" + temp[1] + "***" temp2 = '\t'.join(temp) outp2.write(temp2 + "\n") else: temp = token.conll().split('\t') if task == 'agreement' or task == 'wordorder': temp[1] = "***" + temp[1] + "***" temp2 = '\t'.join(temp[:6]) outp2.write(f"{temp2}\t0\t_\t_\t_\n") elif token.id == data[sentid][headid].head and req_head_head: temp = token.conll().split('\t') temp2 = '\t'.join(temp[:6]) outp2.write(f"{temp2}\t0\t_\t_\t_\n") elif token.head == headid and req_head_dep: # Getting other dep of the head outp2.write(token.conll() + "\n") elif tokid == token.head and req_dep_dep: # Getting other dep of token outp2.write(token.conll() + "\n") elif '-' not in token.id: outp2.write(f"{token.id}\t{token.form}\t_\t_\t_\t_\t0\t_\t_\t_\n") outp2.write('\n</code></pre>\n\n') outp2.write('<pre><code class="language-conllu">\n') for token in data[sentid]: transliteration = trn.transform(token.form) if token.id == tokid: temp = token.conll().split('\t') temp[1] = "***" + transliteration + "***" temp2 = '\t'.join(temp) outp2.write(temp2 + "\n") elif token.id == headid: if req_head_head: temp = token.conll().split('\t') if task == 'agreement': temp[1] = "***" + transliteration + "***" else: temp[1] = transliteration temp2 = '\t'.join(temp) outp2.write(temp2 + "\n") else: temp = token.conll().split('\t') if task == 'agreement': temp[1] = "***" + transliteration + "***" else: temp[1] = transliteration temp2 = '\t'.join(temp[:6]) outp2.write(f"{temp2}\t0\t_\t_\t_\n") elif token.id == data[sentid][headid].head and req_head_head: temp = token.conll().split('\t') temp[1] = transliteration temp2 = '\t'.join(temp[:6]) outp2.write(f"{temp2}\t0\t_\t_\t_\n") elif token.head == headid and req_head_dep: # Getting other dep of the head temp = token.conll().split('\t') temp[1] = transliteration outp2.write("\t".join(temp) + "\n") elif tokid == token.head and req_dep_dep: # Getting other dep of token temp = token.conll().split('\t') temp[1] = transliteration outp2.write("\t".join(temp) + "\n") elif '-' not in token.id: outp2.write(f"{token.id}\t{transliteration}\t_\t_\t_\t_\t0\t_\t_\t_\n") outp2.write('\n</code></pre>\n\n<br>') # except: # pass def isValidFeature(pos, relation, head_pos,features): model_features = [] for feature_type in features: info = feature_type.split("_") if info[0] in relation and info[1] == head_pos: model_features.append(feature_type) if info[0] == pos and info[1] == head_pos: model_features.append(feature_type) return model_features def getImportantFeatures(tree_dictionary, leafmap, obs_label, retainNA=False): features_involved_labels = [] for leaf_num in range(len(leafmap)): leaf_index = leafmap[leaf_num] leaf_label = tree_dictionary[leaf_index]['class'] if leaf_label != obs_label: if not retainNA and leaf_label == 'NA': continue active = tree_dictionary[leaf_index]['active'] # features which are active for this leaf non_active = tree_dictionary[leaf_index]['non_active'] # features which are not active for this leaf top = tree_dictionary[leaf_index].get('top', -1) if len(active) > 0: features_involved_labels += active if len(non_active) > 0: features_involved_labels += non_active while top > 0: # Not root if top not in tree_dictionary: break active += tree_dictionary[top]['active'] non_active += tree_dictionary[top]['non_active'] top = tree_dictionary[top]['top'] if len(active) > 0: features_involved_labels += active if len(non_active) > 0: features_involved_labels += non_active features_involved_labels_only = [] for (feat, _) in features_involved_labels: features_involved_labels_only.append(feat) return list(set(features_involved_labels_only)), [] ''' while len(queue) > 0: topid = queue.pop() top = tree_dictionary[topid] if 'edge' in top: important_features.append(top['edge'][0]) for children in tree_dictionary[topid]['children']: queue.append(children) prev_num = -1 to_combine = [0] cols = [to_combine] new_important_features = [] feat_num = 0 for feat in important_features: if feat not in features_involved_labels_only:#Feature is not part of the leaf to be retained continue if feat in new_important_features:#Avoding repeat columns continue new_important_features.append(feat) if feat_num == 0: prev_num = feat_num feat_num += 1 continue prev = new_important_features[prev_num] prev = prev.split("_") feat = feat.split("_") if len(prev) == len(feat): if "_".join(prev[:-1]) == "_".join(feat[:-1]) and prev[-1] != feat[-1]: cols[-1].append(feat_num) else: to_combine = [feat_num] cols.append(to_combine) else: to_combine = [feat_num] cols.append(to_combine) prev_num = feat_num feat_num += 1 return new_important_features, cols ''' def getColsToCombine(individual_columns): prev_num = -1 to_combine = [0] cols = [to_combine] new_important_features = [] feat_num = 0 individual_columns.sort() for feat in individual_columns: new_important_features.append(feat) if feat_num == 0: prev_num = feat_num feat_num += 1 continue prev = new_important_features[prev_num] prev = prev.split("_") feat = feat.split("_") if len(prev) == len(feat): if "_".join(prev[:-1]) == "_".join(feat[:-1]) and prev[-1] != feat[-1]: cols[-1].append(feat_num) else: to_combine = [feat_num] cols.append(to_combine) else: to_combine = [feat_num] cols.append(to_combine) prev_num = feat_num feat_num += 1 return cols def getTreebankPaths(treebank, args): train_path, dev_path, test_path, lang = None, None, None, None for [path, dir, inputfiles] in os.walk(treebank): for file in inputfiles: if args.auto: if "-auto-ud-train.conllu" in file or "-auto-oscar-train.conllu" in file or "-oscar-auto" in file: train_path = treebank + "/" + file lang = train_path.strip().split('/')[-1].split("-")[0] if "-sud-dev.conllu" in file: dev_path = treebank + "/" + file if "-sud-test.conllu" in file: test_path = treebank + "/" + file else: if args.sud: if "-sud-train.conllu" in file and "auto" not in file and "noise" not in file: train_path = treebank + "/" + file lang = train_path.strip().split('/')[-1].split("-")[0] if "-sud-dev.conllu" in file: dev_path = treebank + "/" + file if "-sud-test.conllu" in file: test_path = treebank + "/" + file elif args.noise: if "-noise-sud-train.conllu" in file and "auto" not in file: train_path = treebank + "/" + file lang = train_path.strip().split('/')[-1].split("-")[0] if "-sud-dev.conllu" in file: dev_path = treebank + "/" + file if "-sud-test.conllu" in file: test_path = treebank + "/" + file else: if "-ud-train.conllu" in file and "auto" not in file: train_path = treebank + "/" + file lang = train_path.strip().split('/')[-1].split("-")[0] if "-ud-dev.conllu" in file: dev_path = treebank + "/" + file if "-ud-test.conllu" in file: test_path = treebank + "/" + file break print(f'Reading from {train_path}, {dev_path}, {test_path}') return train_path, dev_path, test_path, lang def getTreebankPathsMulti(treebanks, args): train_paths, dev_paths, test_paths, langs = [], [], [], [] treebanks = treebanks.split(",") for treebank in treebanks: for [path, dir, inputfiles] in os.walk(treebank): for file in inputfiles: if args.auto: if "-auto-ud-train.conllu" in file or "-auto-oscar-train.conllu" in file or "-oscar-auto" in file: train_path = treebank + "/" + file lang = train_path.strip().split('/')[-1].split("-")[0] if "-sud-dev.conllu" in file: dev_path = treebank + "/" + file if "-sud-test.conllu" in file: test_path = treebank + "/" + file else: if "-sud-train.conllu" in file and "auto" not in file: train_path = treebank + "/" + file lang = train_path.strip().split('/')[-1].split("-")[0] train_paths.append(train_path) langs.append(lang) if "-sud-dev.conllu" in file: dev_path = treebank + "/" + file dev_paths.append(dev_path) if "-sud-test.conllu" in file: test_path = treebank + "/" + file test_paths.append(test_path) #print(f'Reading from {train_path}, {dev_path}, {test_path}') return train_paths, dev_paths, test_paths, langs def colorRetrival(labeldistribution, class_): agreement_color_schemes = {0.1: '#eff3ff', 0.5: '#bdd7e7', 0.9: '#2171b5'} chanceagreement_color_schemes = {0.1: '#fee8c8', 0.5: '#fdbb84', 0.9: '#e34a33'} total = 0 max_value, max_label = 0, '' for label, value in labeldistribution.items(): if value > max_value: max_label = label max_value = value total += value t = max_value / total if class_ != 'NA':#t >= threshold: if t >= 0.9: color = agreement_color_schemes[0.9] elif t >= 0.5: color = agreement_color_schemes[0.5] else: color = agreement_color_schemes[0.1] else: if (1 - t) >= 0.9: color = chanceagreement_color_schemes[0.9] elif (1 - t) >= 0.5: color = chanceagreement_color_schemes[0.5] else: color = chanceagreement_color_schemes[0.1] return color def getWikiFeatures(args, lang, test=False): genre_train_data, genre_dev_data, genre_test_data, wikiData = None, None, None, None if args.use_wikid: # Get the wikiparsed data wikiData = readWikiData(args.wikidata) if not test: genre_train_file = args.wiki_path + f'{lang}_train_genre_output_formatted.txt' genre_dev_file = args.wiki_path + f'{lang}_dev_genre_output_formatted.txt' genre_test_file = args.wiki_path + f'{lang}_test_genre_output_formatted.txt' if os.path.exists(genre_train_file) and os.path.exists(genre_test_file): genre_train_data = readWikiGenreInput(genre_train_file) if os.path.exists(genre_dev_file): genre_dev_data = readWikiGenreInput(genre_dev_file) genre_test_data = readWikiGenreInput(genre_test_file) else: genre_test_file = args.wiki_path + f'{lang}_test_genre_output_formatted.txt' if os.path.exists(genre_test_file): genre_test_data = readWikiGenreInput(genre_test_file) return genre_train_data, genre_dev_data, genre_test_data, wikiData def getBabelNetFeatures(args, lang, treebank): # Working with BabelNet annotated wiki_train_sentence_token_map, wiki_dev_sentence_token_map, wiki_test_sentence_token_map = None, None, None word_pos_wsd, lemma_pos_wsd = None, None use_prefix_all = False if False: #args.use_animate: wiki_train_file = args.wiki_path + f'{lang}_train.txt' wiki_test_file = args.wiki_path + f'{lang}_test.txt' wiki_dev_file = args.wiki_path + f'{lang}_dev.txt' wiki_wsd = treebank + f'/{lang}-wsd.txt' wiki_wsd_lem = treebank + f'/{lang}-wsd-l.txt' wiki_train_sentence_token_map = readWikiParsedInput(wiki_train_file) wiki_test_sentence_token_map = readWikiParsedInput(wiki_test_file) if "_all" in wiki_train_file: use_prefix_all = True if os.path.exists(wiki_dev_file): wiki_dev_sentence_token_map = readWikiParsedInput(wiki_dev_file) if args.lp and os.path.exists(wiki_wsd): word_pos_wsd =readWSDPath(wiki_wsd) if args.lp and os.path.exists(wiki_wsd_lem): lemma_pos_wsd =readWSDPath(wiki_wsd_lem) return wiki_train_sentence_token_map, wiki_dev_sentence_token_map, wiki_test_sentence_token_map, word_pos_wsd, lemma_pos_wsd , use_prefix_all def reloadData(train_file, dev_file, test_file): train_df = pd.read_csv(train_file, sep=',') dev_df = None if os.path.exists(dev_file): dev_df = pd.read_csv(dev_file, sep=',') test_df = pd.read_csv(test_file, sep=',') columns = train_df.columns.to_list() return train_df, dev_df, test_df, columns def reloadDataLibsvm(train_file, dev_file, test_file): dtrain = xgb.DMatrix(train_file) dev_df = None if os.path.exists(dev_file): ddev = xgb.DMatrix(dev_file) dtest = xgb.DMatrix(test_file) columns = dtrain.feature_names return dtrain, ddev, dtest, columns def getModelTrainingData(train_df, dev_df, test_df): label_encoder = LabelEncoder() label_encoder = label_encoder.fit(train_df[["label"]]) label2id = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_))) id2label = {v: k for k, v in label2id.items()} label_list = [] for i in range(len(id2label)): label_list.append(id2label[i]) train_features, train_label = train_df.drop(columns=['label', 'sent_num', 'token_num'], axis=1), label_encoder.transform(train_df[["label"]]) dev_features, dev_label = None, None if dev_df is not None and not dev_df.empty: dev_features, dev_label = dev_df.drop(columns=['label', 'sent_num', 'token_num'], axis=1), label_encoder.transform( dev_df[["label"]]) test_features, test_label = test_df.drop(columns=['label', 'sent_num', 'token_num'], axis=1), label_encoder.transform( test_df[["label"]]) most_fre_label = train_df['label'].value_counts().max() trainlabels = train_df['label'].value_counts().index.to_list() trainvalues = train_df['label'].value_counts().to_list() minority, majority = 1000000, 0 for label, value in zip(trainlabels, trainvalues): if value == most_fre_label: baseline_label = label majority = value if value < minority: minority = value return train_features, train_label, dev_features, dev_label, test_features, test_label, baseline_label, id2label, label_list, label_encoder, minority, majority def getModelTrainingDataLibsvm(train_file, dev_file, test_file, label2id, datalabels): if os.path.exists(dev_file): all_data = load_svmlight_files([train_file, dev_file, test_file], zero_based=True) train_features, train_labels = all_data[0], all_data[1] dev_features, dev_labels = all_data[2], all_data[3] test_features, test_labels = all_data[4], all_data[5] else: all_data = load_svmlight_files([train_file, test_file], zero_based=True) train_features, train_labels = all_data[0], all_data[1] dev_features, dev_labels = None, None test_features, test_labels = all_data[2], all_data[3] counter = Counter(train_labels) minority, majority = 1000000, 0 baseline_label = -1 id2label = {v: k for k, v in label2id.items()} values = [] for class_ in range(len(counter)): value = counter[class_] datalabels[id2label[class_]] = value values.append(f'{id2label[class_]}: {value}') if value < minority: minority = value if value > majority: majority = value baseline_label = id2label[class_] print(",".join(values)) return train_features, train_labels , dev_features, dev_labels, test_features, test_labels, baseline_label, id2label, minority, majority def removeFeatures(train_df, t=0): valid = True train_features, train_label_info = train_df.drop(columns=['label', 'sent_num', 'token_num'], axis=1), train_df[['label', 'sent_num', 'token_num']] sel = VarianceThreshold(threshold=(t * (1-t))) columns = np.array(train_features.columns.to_list()) orig_features = np.array(train_features.columns.to_list()) train_features = sel.fit_transform(train_features) columns = columns[sel.get_support()] print('Before', len(orig_features), 'After', len(columns)) if len(columns) == 0: valid = False updated_columns = np.concatenate((columns, ['label', 'sent_num', 'token_num'])) #updated_columns = np.concatenate((orig_features, ['label', 'sent_num', 'token_num'])) return updated_columns, valid def loadSpine(spine_outputs, lang, is_continuous=False): word_vectors = {} feats = [] spine_emb = f'{spine_outputs}/{lang}_spine.txt' spine_feats = f'{spine_outputs}/{lang}_spine_feats_ud_freqtop.txt' spine_feats = f'{spine_outputs}/{lang}_spine_feats_knen.txt' with open(spine_emb, 'r') as fin: lines = fin.readlines() for line in lines: info = line.strip().split() word = info[0].lower() embs = [abs(float(e)) for e in info[1:]] if is_continuous: word_vectors[word] = np.array(embs) else: new_embs = [] for e in embs: if e < 0.9: new_embs.append(0) else: new_embs.append(1) word_vectors[word] = np.array(new_embs) with open(spine_feats, 'r') as fin: for line in fin.readlines(): info = line.strip().split("\t") if len(info) > 2: if info[1] != 'NA': feats.append(info[1]) else: feats.append((info[-1])) else: feats.append(info[-1]) assert len(embs) == len(feats) return word_vectors, np.array(feats), len(embs) def transformSpine(tree_rules, spine_features, spine_word_vectors, train_data, dot_data): dot_data = dot_data.getvalue().split("\n") spine_features = list(spine_features) feature_value = {} for feature in tree_rules: if "<=" in feature: feature_info = feature.split("--- ")[-1] feature, value = feature_info.split("<=")[0].lstrip().rstrip(), float(feature_info.split("<=")[1].lstrip().rstrip()) feature_value[feature] = value dim_indices, spine_features_of_interest, values = [], [], [] for feature, value in feature_value.items(): if feature.startswith('spine'): feature = feature.replace("spinehead_", "").replace("spine_", "") dim_indices.append(spine_features.index(feature)) spine_features_of_interest.append(feature) values.append(value) dim_indices, values = np.array(dim_indices), np.array(values) new_features = {} new_feature_names = {} if len(dim_indices) > 0: for sent in train_data: for token in sent: if token: form = token.form.lower() if token.upos not in ['ADJ', 'NOUN', 'PROPN', 'INTJ', 'ADV', 'VERB']: continue if form in spine_word_vectors: vector = spine_word_vectors[form] dim_values = vector[dim_indices] #Get the spine values for the spine index of interest for dim_value, threshold_value, old_feature in zip(dim_values, values, spine_features_of_interest): if old_feature not in new_features: new_features[old_feature] = defaultdict(lambda : 0) if dim_value >= threshold_value: # new_features[old_feature][form] = max(dim_value, new_features[old_feature].get(form, 0.0)) for old_feature, new_feature_info in new_features.items(): sorted_features = sorted(new_feature_info.items(), key=lambda kv: kv[1], reverse=True)[:5] header = [] for (f, _) in sorted_features: header.append(f) if len(header) > 0: new_feature_names[old_feature] = ",".join(header) else: new_feature_names[old_feature] = old_feature if len(new_feature_names) > 0: new_dot_data = [] for d in dot_data: if 'spine' in d: for old, new in new_feature_names.items(): if old in d: d = d.replace(old, new) new_dot_data.append(d) break else: new_dot_data.append(d) #print(d) return new_feature_names, new_dot_data def getActiveNotActive(active, non_active, columns_to_retain, task, rel, relation_map, folder_name, source_lang): active_text, nonactive_text = "Active:", "Not Active:" if len(active) > 0: covered_act = set() for a in active: if a in covered_act or a not in columns_to_retain: continue active_human = a #transformRulesIntoReadable(a, task, rel, relation_map, folder_name, source=source_lang) covered_act.add(a) active_text += active_human + ";" if len(non_active) > 0: covered_na = set() for n in non_active: if n in covered_na or n not in columns_to_retain: continue nonactive_human = n #transformRulesIntoReadable(n, task, rel, relation_map, folder_name, source=source_lang) covered_na.add(n) nonactive_text += nonactive_human + ";" return active_text, nonactive_text def createRuleTable(outp2, active, non_active, task, rel, relation_map, columns_to_retain, folder_name, source_lang): # Print features active/inactive in the rule active_text, nonactive_text = "Active:", "Not Active:" outp2.write("<div id=\"rules\">") outp2.write( f'<table><col><colgroup span=\"2\"></colgroup>' f'<tr><th colspan=\"2\" scope=\"colgroup\" style=\"text-align:center\">Features that make up this rule</th></tr>' f'<th rowspan=\"1\" style=\"text-align:center\">Active Features</th>' f'<th rowspan=\"1\" style=\"text-align:center\">Inactive Features</th>' f'</tr><tr>\n') if len(active) > 0: outp2.write(f'<td style=\"text-align:center\">') covered_act = set() for a in active: if a in covered_act or a not in columns_to_retain: continue active_human = transformRulesIntoReadable(a, task, rel, relation_map, folder_name, source=source_lang) outp2.write(f'{active_human} <br>\n') covered_act.add(a) active_text += a + ";" outp2.write(f'</td>') else: outp2.write(f'<td style=\"text-align:center\"> - </td>\n') if len(non_active) > 0: outp2.write(f'<td style=\"text-align:center\">') covered_na = set() for n in non_active: if n in covered_na or n not in columns_to_retain: continue nonactive_human = transformRulesIntoReadable(n, task, rel, relation_map, folder_name, source=source_lang) covered_na.add(n) nonactive_text += n + ";" outp2.write(f'{nonactive_human} <br>\n') outp2.write(f'</td>') else: outp2.write(f'<td style=\"text-align:center\"> - </td>\n') outp2.write(f'</tr></table></div>\n') outp2.write(f'<input type="hidden" id="rules_text" name="rules_text" value="{active_text + " " + nonactive_text}">') def createRuleTableSuffix(outp2, active, active_features, task, rel, relation_map, folder_name, label, pos_examples, source='eng'): # Print features active/inactive in the rule active_text, nonactive_text = "Active:", "Not Active:" outp2.write("<div id=\"rules\">") outp2.write( f'<table><col><colgroup span=\"2\"></colgroup>' f'<tr><th colspan=\"2\" scope=\"colgroup\" style=\"text-align:center\">Features that make up this rule</th></tr>' #f'<th rowspan=\"1\" style=\"text-align:center\">Active Features</th>' #f'<th rowspan=\"1\" style=\"text-align:center\">Inactive Features</th>' f'</tr><tr>\n') if len(active) > 0: outp2.write(f'<td style=\"text-align:center\">') covered_act = set() for a in active: if a in covered_act and a not in active_features: continue active_human = transformRulesIntoReadable(a, task, rel, relation_map, folder_name, pos_examples, source) outp2.write(f'{active_human} <br>\n') covered_act.add(a) active_text += active_human + ";" outp2.write(f'</td>') else: outp2.write(f'<td style=\"text-align:center\"> - </td>\n') outp2.write(f'</tr></table></div>\n') outp2.write(f'<input type="hidden" id="rules_text_{label}" name="rules_text">') def printExamples(outp2, data, agree, disagree, dep, leaf_label, task, source_lang): outp2.write(f'<div id=\"examples\">\n') if len(agree) > 0: if leaf_label == 'NA': outp2.write(f'<h4> Examples: The words of interest are denoted by *** </h4>') elif leaf_label == 'chance-agree': outp2.write(f'<h4> Examples that do not agree: The words of interest are marked by ***, hover over those tokens to see more information. </h4>') else: outp2.write(f'<h4> Examples that agree with label: <b>{leaf_label}</b>: The tokens of interest are denoted by ***, hover over those tokens to see more information. </h4>') for eg in agree: if source_lang and source_lang != 'eng': trn = Transliterator(source=source_lang, target='eng', build_lookup=True) example_web_print_with_transliteration(eg, outp2, data, task, trn) else: example_web_print(eg, outp2, data, task) else: if leaf_label != 'NA' and leaf_label != 'chance-agree': outp2.write(f'<h5> No examples found </h5>\n') if len(disagree) > 0: if leaf_label == 'NA': outp2.write(f'<h4> Examples: The words of interest are denoted by *** </h4>') elif leaf_label == 'chance-agree': outp2.write(f'<h4> Examples that agree: The words of interest are denoted by *** </h4>') else: outp2.write(f'<h4> Examples that disagree with the label: <b>{leaf_label}</b> </h4>\n') for eg in disagree: if source_lang and source_lang != 'eng': trn = Transliterator(source=source_lang, target='eng', build_lookup=True) example_web_print_with_transliteration(eg, outp2, data, task, trn) else: example_web_print(eg, outp2, data, task) else: outp2.write(f'<h5> No examples found </h5>\n') outp2.write(f'</div>\n') def populateLeaf(data, leaf_examples_file, leaf_label, agree, disagree, active, non_active, default_leaf, rel, task, language_full_name, relation_map, columns_to_retain, ORIG_HEADER, HEADER, FOOTER, folder_name, source_lang): # Populate the leaf with examples with open(leaf_examples_file, 'w') as outp2: if task == 'agreement': HEADER = ORIG_HEADER.replace("main.css", "../../../../main.css") else: HEADER = ORIG_HEADER.replace("main.css", "../../../main.css") outp2.write(HEADER + '\n') if task == 'agreement': outp2.write( f'<ul class="nav"><li class="nav"><a class="active" href=\"../../../../index.html\">Home</a>' f'</li><li class="nav"><a href=\"../../../../introduction.html\">Usage</a></li>' f'<li class="nav"><a href="../../../../about.html\">About Us</a></li></ul>') else: outp2.write( f'<ul class="nav"><li class="nav"><a class="active" href=\"../../../index.html\">Home</a>' f'</li><li class="nav"><a href=\"../../../introduction.html\">Usage</a></li>' f'<li class="nav"><a href="../../../about.html\">About Us</a></li></ul>') outp2.write( f"<br><li><a href=\"{rel}.html\">Back to {language_full_name} page</a></li>\n") if task == 'wordorder': modelinfo = rel.split("-") if leaf_label == 'NA': outp2.write( f'<h3> Cannot decide the relative order of <b>{modelinfo[0]}</b> with its head <b>{modelinfo[1]}</b> </h3>') else: outp2.write( f'<h3> <b>{modelinfo[0]}</b> is <b>{leaf_label}</b> its head <b>{modelinfo[1]}</b> </h3>') dep = modelinfo[0] elif task == 'assignment': modelinfo = rel if leaf_label == 'NA': outp2.write( f'<h3> Cannot decide the case of <b>{modelinfo}</b> </h3>') else: outp2.write( f'<h3> <b>{modelinfo}</b> has Case <b>{leaf_label}</b> </h3>') dep = rel elif task == 'agreement': if "-" in rel: feature = rel.split("-")[0] pos = rel.split("-")[1] else: feature = rel pos = "dependent" if leaf_label == 'chance-agree': outp2.write( f'<h3> There is <b> NO required-agreement </b> between the head and its {pos} for <b>{feature}</b> </h3>') elif leaf_label == 'req-agree': outp2.write( f'<h3> The {rel} values <b> should match </b> between the head and its {pos} </h3>') dep = "dependent" elif task.lower() == 'suffix': dep = "current word" # output the rule in each leaf if default_leaf: active_text, nonactive_text = getActiveNotActive(active, non_active, columns_to_retain, task, rel, relation_map, folder_name, source_lang) outp2.write( f'<input type="hidden" id="rules_text" name="rules_text" value="{active_text + " " + nonactive_text}">') #outp2.write("<h2> Examples for the default label </h3> ") else: createRuleTable(outp2, active, non_active, task, rel, relation_map, columns_to_retain, folder_name, source_lang) # print examples in each leaf printExamples(outp2, data, agree, disagree,dep, leaf_label, task, source_lang) outp2.write("</ul><br><br><br>\n" + FOOTER + "\n") def getSmallerFiles(one_file): dir = os.path.dirname(one_file) filenames = [] for [path, _, files] in os.walk(dir): for file in files: if file.endswith("conllu"): filenames.append(dir + "/" + file) print(f'Loading smaller files from {dir}: {len(filenames)}') return filenames def parseAlignment(info): src_tgt_alignments = defaultdict(list) tgt_src_alignments = defaultdict(list) for align in info: s = int(align.split('-')[0]) t = int(align.split('-')[1]) src_tgt_alignments[s].append(t) tgt_src_alignments[t].append(s) return src_tgt_alignments, tgt_src_alignments
144,353
40.067994
234
py
teacher-perception
teacher-perception-master/code/word_order.py
import os, pyconll import dataloader_word_order as dataloader import argparse import numpy as np np.random.seed(1) import sklearn import sklearn.tree from collections import defaultdict import pandas as pd from sklearn.metrics import accuracy_score from sklearn.model_selection import GridSearchCV import utils from scipy.stats import entropy from scipy.sparse import vstack import xgboost as xgb DTREE_DEPTH = [3, 4, 5, 6, 7, 8, 9, 10, 15, 20] DTREE_IMPURITY = [5e-4, 1e-3, 2e-3, 5e-3, 1e-2, 5e-2, 1e-1, 5e-1] XGBOOST_GAMMA = [0.005, 0.01, 1, 2, 5, 10] def printTreeFromXGBoost(model, rel, folder_name, train_data_path, train_path , lang, tree_features, relation_map, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim): best_model = model.best_estimator_ rules_df = best_model.get_booster().trees_to_dataframe() rules_df_t0 = rules_df.loc[rules_df['Tree'] == 0] # Iterate the tree to get information about the tree features topnodes, tree_dictionary, leafnodes, leafedges, edge_mapping = utils.iterateTreesFromXGBoost(rules_df_t0, args.task, rel, relation_map, tree_features, folder_name, args.transliterate) #Assign statistical threshold to each leaf train_df = pd.read_csv(train_data_path, sep=',') train_data = pyconll.load_from_file(train_path) leaf_examples, leaf_sent_examples = utils.FixLabelTreeFromXGBoostWithFeatures(rules_df_t0, tree_dictionary, leafnodes, label_list, data_loader.model_data_case[rel], rel, train_df, train_data, tree_features, data_loader, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim, task=args.task) tree_dictionary, leafmap = utils.collateTreeFromXGBoost(tree_dictionary, topnodes, leafnodes, leafedges) print("Num of leaves : ", len(leafmap)) if args.no_print: return tree_dictionary, leafmap, {}, {}, {} retainNA = args.retainNA # Get the features in breadth first order of the class which deviates from the dominant order important_features, cols = utils.getImportantFeatures(tree_dictionary, leafmap, '', retainNA) if len(important_features) == 0: # If there is no sig other label return tree_dictionary, leafmap, {}, {}, {} leaf_examples_features = {} #Iterate each leaf of the tree to populate the table total_num_examples = 0 num_examples_label = defaultdict(lambda: 0) num_leaf_examples = {} leaf_values_per_columns, columns_per_leaf, update_spine_features = {}, {}, {} with open(f'{folder_name}/{lang}_{rel}_rules.txt', 'w') as fleaf: for leaf_num in range(len(leafmap)): leaf_examples_features[leaf_num] = {} columns_per_leaf[leaf_num] = defaultdict(list) leaf_index = leafmap[leaf_num] leaf_label = tree_dictionary[leaf_index]['class'] leaf_examples_features[leaf_num]['leaf_label'] = leaf_label # Get examples which agree and disagree with the leaf-label sent_examples = leaf_sent_examples[leaf_index] agree, disagree, total_agree, total_disagree, spine_features = utils.getExamples(sent_examples, tree_dictionary[leaf_index], train_data, isTrain=True) for keyspine, valuespines in spine_features.items(): key = keyspine.split("_")[0] sorted_spine = sorted(valuespines.items(), key=lambda kv:kv[1], reverse=True)[:10] values = [v for (v,_) in sorted_spine] update_spine_features[keyspine] = f'{key}_{",".join(values)}' leaf_examples_features[leaf_num]['agree'] = agree leaf_examples_features[leaf_num]['disagree'] = disagree row = f'<tr>' active_all = tree_dictionary[leaf_index]['active'] #features which are active for this leaf non_active_all = tree_dictionary[leaf_index]['non_active'] #features which are not active for this leaf top = tree_dictionary[leaf_index].get('top', -1) while top > 0: # Not root active_all += tree_dictionary[top]['active'] non_active_all += tree_dictionary[top]['non_active'] top = tree_dictionary[top]['top'] active, non_active = [],[] for (feat, _) in active_all: feat = update_spine_features.get(feat, feat) active.append(feat) for (feat, _) in non_active_all: feat = update_spine_features.get(feat, feat) non_active.append(feat) active, non_active = list(set(active)), list(set(non_active)) leaf_examples_features[leaf_num]['active'] = active leaf_examples_features[leaf_num]['non_active'] = non_active fleaf.write(leaf_label + "\n") fleaf.write('active: ' + " ### ".join(active) + "\n") fleaf.write('non_active: ' + " ### ".join(non_active) + "\n") fleaf.write( f'agree:{total_agree}, disagree: {total_disagree}, total: {total_agree + total_disagree}\n') fleaf.write("\n") # populating only rules which deviate from the dominant label as observed from the training data if not retainNA and leaf_label == 'NA': continue for feat in important_features: feat = update_spine_features.get(feat, feat) if feat in active: columns_per_leaf[leaf_num]['Y'].append(feat) row += f'<td style=\"text-align:center\"> Y </td>' elif feat in non_active: columns_per_leaf[leaf_num]['N'].append(feat) row += f'<td style=\"text-align:center\"> N </td>' else: columns_per_leaf[leaf_num]['-'].append(feat) row += f'<td style=\"text-align:center\"> - </td>' row += f'<td> {leaf_label} </td> <td> <a href=\"Leaf-{leaf_num}.html\"> Examples</a> </td>\n' leaf_examples_features[leaf_num]['row'] = row #get the number of examples predicted for each label for _, num_example_per_leaf in sent_examples.items(): num_examples_label[leaf_label] += len(num_example_per_leaf) total_num_examples += len(num_example_per_leaf) num_leaf_examples[leaf_num] = total_agree + total_disagree #Get the dominant order for printing print_leaf = [] max_label = None max_value = 0 prob = [] for leaf_label, num_examples in num_examples_label.items(): print_leaf.append(f'{leaf_label}: {num_examples}, {num_examples / total_num_examples}') prob.append(num_examples / total_num_examples) if num_examples > max_value: max_value = num_examples max_label = leaf_label print_leaf.append(f'Word order: {max_label}') #fleaf.write(f'Total Examples: {total_num_examples}\n\n') H = entropy(prob, base=2) print_leaf.append(f'Entropy in training data: {H}') print("\n".join(print_leaf)) print() return tree_dictionary, leafmap, leaf_examples_features, num_leaf_examples, columns_per_leaf def xgboostModel(rel, x,y, x_test, y_test, depth,cv): criterion = ['gini', 'entropy'] parameters = {'criterion': criterion, 'max_depth': depth, 'min_child_weight': [20]} if args.use_forest: xgb_model = xgb.XGBClassifier(learning_rate=0.1, n_estimators=1, subsample=0.8, num_parallel_tree=100, colsample_bytree=0.8, objective='multi:softprob', num_class=len(label_list), silent=True, nthread=args.n_thread, scale_pos_weight=majority / minority, seed=1001) else: xgb_model = xgb.XGBClassifier(learning_rate=0.1, n_estimators=1, subsample=0.8, colsample_bytree=0.8, objective='multi:softprob', num_class=len(label_list), silent=True, nthread=args.n_thread, scale_pos_weight=majority / minority, seed=1001) model = GridSearchCV(xgb_model, parameters, cv=cv, n_jobs=args.n_jobs) #sparse_x = csr_matrix(x) model.fit(x, y) best_model = model.best_estimator_ #dense_x = csc_matrix(sparse_x) dtrainPredictions = best_model.predict(x) #x_test = x_test.to_numpy() dtestPredictions = best_model.predict(x_test) train_acc = accuracy_score(y, dtrainPredictions) * 100.0 test_acc = accuracy_score(y_test, dtestPredictions) * 100.0 print( "Model: %s, Lang: %s, Train Accuracy : %.4g, Test Accuracy : %.4g, Baseline Test Accuracy: %.4g, Baseline Label: %s" % ( rel, lang_full, train_acc, test_acc, baseline_acc, baseline_label)) print("Hyperparameter tuning: ", model.best_params_) return model def train(train_features, train_labels, train_path, train_data_path, dev_features, dev_labels, test_features, test_labels, rel, outp, folder_name, baseline_label, lang_full, tree_features_ , relation_map, best_depths, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim, test_datasets): x_train, y_train, x_test, y_test = train_features, train_labels, test_features, test_labels tree_features = [] for f in range(len(tree_features_)): tree_features.append(tree_features_[f]) tree_features = np.array(tree_features) if dev_features is not None: x_dev, y_dev = dev_features, dev_labels #x_dev = csc_matrix(x_dev) x = vstack((x_train, x_dev)) #x = np.concatenate([x_train, x_dev]) y = np.concatenate([y_train, y_dev]) test_fold = np.concatenate([ # The training data. np.full(x_train.shape[0], -1, dtype=np.int8), # The development data. np.zeros(x_dev.shape[0], dtype=np.int8) ]) cv = sklearn.model_selection.PredefinedSplit(test_fold) else: x, y = x_train, y_train cv = 5 if args.use_xgboost: x = x.to_numpy() #Print acc/leaves for diff settings if args.no_print: for depth in DTREE_DEPTH: #: setting = f'-depth-{depth}' model = xgboostModel(rel, x, y, x_test, y_test, [depth], cv) best_model = model.best_estimator_ best_model.get_booster().dump_model(f'{folder_name}/{rel}/xgb_model-{setting}.txt', with_stats=True) printTreeFromXGBoost(model, rel, folder_name, train_data_path, train_path, lang, tree_features, relation_map, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim ) print() return if rel in best_depths and best_depths[rel] != -1: model = xgboostModel(rel, x, y, x_test, y_test, [int(best_depths[rel])], cv) best_model = model.best_estimator_ best_model.get_booster().dump_model(f'{folder_name}/{rel}/xgb_model.txt', with_stats=True) tree_dictionary, leafmap, leaf_examples_features, num_leaf_examples, columns_per_leaf = printTreeFromXGBoost(model, rel, folder_name, train_data_path, train_path, lang, tree_features, relation_map, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim) else: model = xgboostModel(rel, x, y, x_test, y_test, DTREE_DEPTH, cv) best_model = model.best_estimator_ best_model.get_booster().dump_model(f'{folder_name}/{rel}/xgb_model.txt', with_stats=True) tree_dictionary, leafmap, leaf_examples_features, num_leaf_examples, columns_per_leaf = printTreeFromXGBoost(model, rel, folder_name, train_data_path, train_path, lang, tree_features, relation_map, genreparseddata, wikidata, spine_word_vectors, spine_features, spine_dim) best_model = model.best_estimator_ outp.write(f'<h4> <a href=\"{rel}/{rel}.html\">{rel}</a></h4>\n') retainNA = args.retainNA with open(f"{folder_name}/{rel}/{rel}.html", 'w') as output: HEADER = ORIG_HEADER.replace("main.css", "../../../main.css") output.write(HEADER + '\n') output.write(f'<ul class="nav"><li class="nav"><a class="active" href=\"../../../index.html\">Home</a>' f'</li><li class="nav"><a href=\"../../../introduction.html\">Usage</a></li>' f'<li class="nav"><a href="../../../about.html\">About Us</a></li></ul>\n') output.write(f"<br><li><a href=\"../WordOrder.html\">Back to {language_fullname} page</a></li>\n") model_info = rel.split("-") output.write( f'<h3> Order of <b>{model_info[0]}s</b> with respect to the syntactic head <b>{model_info[1]}</b> </h3>\n') if baseline_label == '0': baseline_label = 'before' else: baseline_label = 'after' output.write(f'<div id="\label\"> <h3> The dominant order in the corpus is <b>{baseline_label}</b></div>\n') # Sort leaves by number of examples, and remove the col from first general leaf sorted_leaves = sorted(num_leaf_examples.items(), key=lambda kv: kv[1], reverse=True) first_leaf, columns_to_remove, columns_to_retain = True, set(), set() first_leaf = True for (leaf_num, _) in sorted_leaves: leaf_label = leaf_examples_features[leaf_num]['leaf_label'] if not retainNA and leaf_label == 'NA': continue if first_leaf: # This is the leaf which says the general word-order active_columns_in_leaf = columns_per_leaf[leaf_num].get('Y', []) nonactive_columns_in_leaf = columns_per_leaf[leaf_num].get('N', []) + columns_per_leaf[ leaf_num].get("-", []) all_cols = active_columns_in_leaf + nonactive_columns_in_leaf all_cols = set(all_cols) if len(active_columns_in_leaf) == 0: # If no active column in this leaf then remove it leaf_examples_features[leaf_num]['cols'] = ['general word order is '] leaf_examples_features[leaf_num]['default'] = True else: leaf_examples_features[leaf_num]['cols'] = list(all_cols) for c in all_cols: # the column is active for at least one leaf if c in active_columns_in_leaf: columns_to_retain.add(c) leaf_examples_features[leaf_num]['default'] = False first_leaf = False else: active_columns_in_leaf = columns_per_leaf[leaf_num].get('Y', []) nonactive_columns_in_leaf = columns_per_leaf[leaf_num].get('N', []) + columns_per_leaf[ leaf_num].get("-", []) all_cols = active_columns_in_leaf + nonactive_columns_in_leaf all_cols = set(all_cols) leaf_examples_features[leaf_num]['cols'] = list(all_cols) for c in all_cols: #the column is active for at least one leaf if c in active_columns_in_leaf: columns_to_retain.add(c) # Create the table of features columns_to_retain = list(columns_to_retain) if len(columns_to_retain) == 0: #all NA leaves: return output.write( f'<table>' f'<tr><th colspan=\"rowspan=\"3\" scope=\"colgroup\" \" style=\"text-align:center\"> Word Order </th>' #f'<th colspan=\"rowspan=\"2\" scope=\"colgroup\" \" style=\"text-align:center\"><b> </th>' '</tr><tr>\n') col_names = ["" for _ in range(len(columns_to_retain))] cols = utils.getColsToCombine(columns_to_retain) for combined in cols: header, subheader = utils.getHeader(combined, columns_to_retain, rel, args.task, relation_map, folder_name, args.transliterate) for col, header in zip(combined, subheader): col_names[col] = header first_leaf = True words = rel.split("-") non_dominant_leaves = defaultdict(list) for (leaf_num, _) in sorted_leaves: leaf_label = leaf_examples_features[leaf_num]['leaf_label'] if not retainNA and leaf_label == 'NA': continue yes_cols_text, no_cols_text = [], [] if first_leaf: leaf_examples_file = f'{folder_name}/{rel}/Leaf-{leaf_num}.html' active, non_active = leaf_examples_features[leaf_num]['active'], leaf_examples_features[leaf_num][ 'non_active'] agree, disagree = leaf_examples_features[leaf_num]['agree'], leaf_examples_features[leaf_num][ 'disagree'] if leaf_examples_features[leaf_num]['default']: row = f'<tr> <th colspan=\"{len(columns_to_retain)} scope=\"colgroup\" \" style=\"text-align:center;width:130px\">Generally the word order is </th>\n' row += f'<td> {leaf_label} </td> <td> <a href=\"Leaf-{leaf_num}.html\"> Examples</a> </td>' utils.populateLeaf(train_data, leaf_examples_file, leaf_label, agree, disagree, active, non_active, first_leaf, rel, args.task, lang_full, relation_map, columns_to_retain, ORIG_HEADER, HEADER, FOOTER, folder_name, args.transliterate) output.write( f'<tr> <td style=\"text-align:center\"> Generally the word order for <b>{rel} is {leaf_label}</b> i.e. <b> {words[0]} {leaf_label} {words[1]} </b> </td> </tr>') output.write( f'<tr><td style=\"text-align:center\"> Some examples are: <a href="Leaf-{leaf_num}.html"> Examples </a> </td></tr>') else: yes_cols, no_cols, missin_cols = columns_per_leaf[leaf_num].get('Y', []), columns_per_leaf[ leaf_num].get('N', []), columns_per_leaf[leaf_num].get('-', []) row = '<tr>' for column in columns_to_retain: # Iterate all columns if column in yes_cols: row += f'<td style=\"text-align:center\"> Y </td>' yes_cols_text.append(column) elif column in no_cols: row += f'<td style=\"text-align:center\"> N </td>' else: row += f'<td style=\"text-align:center\"> - </td>' row += f'<td> {leaf_label} </td> <td> <a href=\"Leaf-{leaf_num}.html\"> Examples</a> </td>' utils.populateLeaf(train_data, leaf_examples_file, leaf_label, agree, disagree, active, non_active, False, rel, args.task, lang_full, relation_map, columns_to_retain, ORIG_HEADER, HEADER, FOOTER, folder_name, args.transliterate) feature_def = "" for feat_name in yes_cols_text: feature_def += utils.transformRulesIntoReadable(feat_name, args.task, rel, relation_map, f'{args.folder_name}/{lang}', source = args.transliterate) + '\n<br>' non_dominant_leaves[leaf_label].append((leaf_num, feature_def)) leaf_examples_features[leaf_num]['row'] = row first_leaf = False else: yes_cols, no_cols, missin_cols = columns_per_leaf[leaf_num].get('Y', []), columns_per_leaf[leaf_num].get('N', []), columns_per_leaf[leaf_num].get('-', []) row = '<tr>' for column in columns_to_retain: #Iterate all columns if column in yes_cols: row += f'<td style=\"text-align:center\"> Y </td>' yes_cols_text.append(column) elif column in no_cols: row += f'<td style=\"text-align:center\"> N </td>' else: row += f'<td style=\"text-align:center\"> - </td>' row += f'<td> {leaf_label} </td> <td> <a href=\"Leaf-{leaf_num}.html\"> Examples</a> </td>\n' leaf_examples_features[leaf_num]['row'] = row leaf_examples_file = f'{folder_name}/{rel}/Leaf-{leaf_num}.html' active, non_active = leaf_examples_features[leaf_num]['active'], leaf_examples_features[leaf_num]['non_active'] agree, disagree = leaf_examples_features[leaf_num]['agree'], leaf_examples_features[leaf_num][ 'disagree'] utils.populateLeaf(train_data, leaf_examples_file, leaf_label, agree, disagree, active, non_active, first_leaf, rel, args.task, lang_full, relation_map, columns_to_retain, ORIG_HEADER, HEADER, FOOTER, folder_name, args.transliterate) feature_def = "" for feat_name in yes_cols_text: feature_def += utils.transformRulesIntoReadable(feat_name, args.task, rel, relation_map, f'{args.folder_name}/{lang}', source=args.transliterate) + '\n<br>' non_dominant_leaves[leaf_label].append((leaf_num, feature_def)) for leaf_label, leaf_info in non_dominant_leaves.items(): if leaf_label == baseline_label: continue if leaf_label != 'NA': output.write( f'<tr> <td style=\"text-align:center\"> {words[0]} is <b> {leaf_label} </b> {words[1]} when: </td> </tr>') else: output.write( f'<tr> <td style=\"text-align:center\"> {words[0]} could be <b> either before or after </b> {words[1]} when: </td> </tr>') output.write(f'<tr> <td style=\"text-align:center\">') num = 0 for (leaf_num, feature_def) in leaf_info: output.write(f'{feature_def} (<a href="Leaf-{leaf_num}.html"> Examples </a>)\n<br>\n') if num < len(leaf_info) - 1: output.write(f'<b>OR </b> <br><br>\n') num += 1 output.write(f'</tr></td>') output.write(f'</table></div>') print() def createPage(foldername): filename = foldername + "/" + "WordOrder.html" with open(filename, 'w') as outp: HEADER = ORIG_HEADER.replace("main.css", "../../main.css") outp.write(HEADER + '\n') outp.write(f'<ul class="nav"><li class="nav"><a class="active" href=\"../../index.html\">Home</a>' f'</li><li class="nav"><a href=\"../../introduction.html\">Usage</a></li>' f'<li class="nav"><a href=\"../../about.html\">About Us</a></li></ul>') outp.write(f'<h1>Rules for the following WordOrder relations:</h1>') def loadDataLoader(vocab_file, data_loader): data_loader.feature_map_id2model, label2id,label_list = {}, {}, [] with open(vocab_file, 'r') as fin: for line in fin.readlines(): if line == "" or line == '\n': continue elif line.startswith("Model:"): rel = line.strip().split("Model:")[-1] data_loader.feature_map[rel] = {} data_loader.model_data_case[rel] = {} elif line.startswith("Data:"): info = line.strip().split("\t") num = int(info[0].split("Data:")[-1]) data_loader.model_data[rel] = int(info[0].split("Data:")[-1]) if num == 0: continue labels_values = info[2].split(";") for label in labels_values: lv = label.split(",") data_loader.model_data_case[rel][lv[0]] = int(lv[1]) elif line.startswith("Feature"): info = line.strip().split("\t") feature_id, feature_name = info[0].lstrip().rstrip(), info[1].lstrip().rstrip() data_loader.feature_map[rel][feature_name] = int(feature_id.split("Feature:")[1]) elif line.startswith("Labels"): info = line.strip().split("Labels:")[1].split(",") label_list = [] for l in info: label_id, label_name = l.split("-")[0], l.split("-")[1] label_list.append(label_id) label2id[label_id] = int(label_id) #0-0, 1-1 for rel, _ in data_loader.feature_map.items(): data_loader.feature_map_id2model[rel] = {v: k for k, v in data_loader.feature_map[rel].items()} print(f'Loaded the vocab from {vocab_file}') data_loader.lang_full = train_path.strip().split('/')[-2].split('-')[0][3:] return label2id, label_list def filterData(data_loader): """ Only train models for those relations/POS which have at least 50 examples for every label""" classes = {} for model, count in data_loader.model_data.items(): if count < 100: #Overall number of examples for that model is less than 100 continue labels = data_loader.model_data_case[model] if len(labels) == 1: print(f'{model} always has {labels[0]} syntactic head') continue to_retain_labels = [] max_label = 0 max_dir = '' for label, value in labels.items(): if value < 50: continue to_retain_labels.append((label, value)) if len(to_retain_labels) == 1: print(f'{model} majority of the is {to_retain_labels[0]} syntactic head') continue if len(to_retain_labels) == 0: continue classes[model] = to_retain_labels #print( model, to_retain_labels) #print() return classes def createHomePage(): with open(f"{folder_name}/index.html", 'a') as op: lang_id = lang.split("_")[0] language_name = language_fullname.split("-")[0] treebank_name = language_fullname.split("-")[1] op.write(f'<tr><td>{lang_id}</td> ' f'<td>{language_name}</td> ' f'<td> {treebank_name} </td>' f' <td> <li> <a href=\"{lang}/Agreement/Agreement.html\">Agreement</a></li>' f'<li> <a href=\"{lang}/WordOrder/WordOrder.html\">WordOrder</a></li>' f'<li> <a href=\"{lang}/CaseMarking/CaseMarking.html\">CaseMarking</a></li> </td></tr>\n') try: os.mkdir(f"{folder_name}/{lang}/") except OSError: i = 0 try: os.mkdir(f"{folder_name}/{lang}/WordOrder") except OSError: i = 0 with open(f"{folder_name}/{lang}/index_wordorder.html", 'w') as outp: HEADER = ORIG_HEADER.replace("main.css", "../main.css") outp.write(HEADER + "\n") outp.write(f'<ul class="nav"><li class="nav"><a class="active" href=\"../index.html\">Home</a>' f'</li><li class="nav"><a href=\"../introduction.html\">Usage</a></li>' f'<li class="nav"><a href=\"../about.html\">About Us</a></li></ul>') outp.write(f"<br><a href=\"../index.html\">Back to language list</a><br>") outp.write(f"<h1> {language_fullname} </h1> <br>\n") outp.write( f'<h3> We present a framework that automatically creates a first-pass specification of word order rules for various WALs features (82A, 83A, 85A, 87A, 89A and 90A.) from raw text for the language in question.</h3>') outp.write( "<h3> We parsed the <a href=\"https://universaldependencies.org\">Universal Dependencies</a> (UD) data in order to extract these rules.</h3>\n") outp.write(f"<br><strong>{language_fullname}</strong> exhibits the following assignment:<br><ul>") outp.write( f"<li> <a href=\"Agreement/Agreement.html\">Agreement</a></li>\n") outp.write( f"<li> <a href=\"CaseMarking/CaseMarking.html\">Case Assignment</a></li>\n") outp.write( f"<li> <a href=\"WordOrder/WordOrder.html\">Word Order</a></li>\n") outp.write("</ul><br><br><br>\n" + FOOTER + "\n") filename = f"{folder_name}/{lang}/WordOrder/" createPage(filename) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--input", type=str, default='/Users/aditichaudhary/Documents/CMU/teacher-perception/data') parser.add_argument("--file", type=str, default="./input_files.txt") parser.add_argument("--relation_map", type=str, default="./relation_map") parser.add_argument("--seed", type=int, default=1) parser.add_argument("--folder_name", type=str, default='./website/', help="Folder to hold the rules, need to add header.html, footer.html always") parser.add_argument("--features", type=str, default="WordOrder") parser.add_argument("--task", type=str, default="wordorder") parser.add_argument("--sud", action="store_true", default=True, help="Enable to read from SUD treebanks") parser.add_argument("--auto", action="store_true", default=False, help="Enable to read from automatically parsed data") parser.add_argument("--noise", action="store_true", default=False, help="Enable to read from automatically parsed data") parser.add_argument("--prune", action="store_true", default=True) parser.add_argument("--binary", action="store_true", default=True) parser.add_argument("--retainNA", action="store_true", default=False) parser.add_argument("--no_print", action="store_true", default=False, help="To not print the website pages") parser.add_argument("--lang", type=str, default=None) # Different features to experiment with parser.add_argument("--only_triples", action="store_true", default=False, help="Only use relaton, head-pos, dep-pos, disable to use other features") parser.add_argument("--use_wikid", action="store_true", default=False, help="Add features from WikiData, requires args.wiki_path and args.wikidata") parser.add_argument("--wiki_path", type=str, default="/Users/aditichaudhary/Documents/CMU/WSD-MT/babelnet_outputs/outputs/", help="Contains entity identification for nominals") parser.add_argument("--wikidata", type=str, default="./wikidata_processed.txt", help="Contains the WikiData property for each Qfeature") parser.add_argument("--lexical", action="store_true", default=True, help="Add lexicalized features for head and dep") parser.add_argument("--use_spine", action="store_true", default=False, help="Add features from spine embeddings, read from args.spine_outputs path.") parser.add_argument("--spine_outputs", type=str, default="./spine_outputs/") parser.add_argument("--continuous", action="store_true", default=True, help="Add features from spine embeddings, read from args.spine_outputs path.") parser.add_argument("--best_depth", type=int, nargs='+', default=[-1, -1, -1, -1, -1], help="Set an integer betwen [3,10] to print the website," "order ['subj-verb', 'obj-verb' ,'adj-noun', 'num-noun', 'noun-adp']") parser.add_argument("--skip_models", type=str, nargs='+', default=[]) parser.add_argument("--use_xgboost", action="store_true", default=True) parser.add_argument("--use_forest", action="store_true", default=False) parser.add_argument("--n_jobs", type=int, default=1) parser.add_argument("--n_thread", type=int,default=1) parser.add_argument("--transliterate", type=str, default=None) args = parser.parse_args() folder_name = f'{args.folder_name}' with open(f"{folder_name}/header.html") as inp: ORIG_HEADER = inp.readlines() ORIG_HEADER = ''.join(ORIG_HEADER) with open(f"{folder_name}/footer.html") as inp: FOOTER = inp.readlines() FOOTER = ''.join(FOOTER) #populate the best-depth to print the rules for treebank mentioned in args.file #If all values are -1 then it will search for the best performing depth by accuracy best_depths = {'subject-verb': args.best_depth[0], 'object-verb': args.best_depth[1], 'adjective-noun': args.best_depth[2], 'numeral-noun': args.best_depth[3], 'noun-adposition': args.best_depth[4], } with open(args.file, "r") as inp: files = [] test_files = defaultdict(set) for file in inp.readlines(): if file.startswith("#"): continue file_info = file.strip().split() files.append(f'{args.input}/{file_info[0]}') if len(file_info) > 1: #there are test files mentioned for test_file in file_info[1:]: test_file = f'{args.input}/{test_file}' test_files[f'{args.input}/{file_info[0]}'].add(test_file.lstrip().rstrip()) d = {} relation_map = {} with open(args.relation_map, "r") as inp: for line in inp.readlines(): info = line.strip().split(";") key = info[0] value = info[1] relation_map[key] = (value, info[-1]) if '@x' in key: relation_map[key.split("@x")[0]] = (value, info[-1]) index_file = f"{folder_name}/index.html" if not os.path.exists(index_file): with open(index_file, 'w') as op: op.write(ORIG_HEADER + '\n') op.write(f'<ul class="nav"><li class="nav"><a class="active" href=\"index.html\">Home</a>' f'</li><li class="nav"><a href=\"introduction.html\">Usage</a></li>' f'<li class="nav"><a href=\"about.html\">About Us</a></li></ul>') op.write(f'<h2>AutoLEX: Language Structure Explorer</h2>') op.write( f'<h3> Most of the world\'s languages have an adherence to grammars — sets of morpho-syntactic rules specifying how to create sentences in the language. ' f'Hence, an important step in the understanding and documentation of languages is the creation of a grammar sketch, a concise and human-readabled escription of the unique characteristics of that particular language. </h3>') op.write(f'<h3> AutoLEX is a tool for exploring language structure and provides an automated framework for ' f'extracting a first-pass grammatical specification from raw text in a concise, human-and machine-readable format.' f'</h3>') op.write( "<h3> We apply our framework to all languages of the <a href=\"https://universaldependencies.org/\"> Universal Dependencies project </a>. </h3><h3> Here are the languages (and treebanks) we currently support.</h3><br><ul>") op.write(f'<h3> Linguistic analysis based on automatically parsed syntactic analysis </h3>') op.write(f'<table><tr><th>ISO</th><th>Language</th><th>Treebank</th><th>Linguistic Analysis </th></tr>') # Read train/dev/test from UD/SUD/auto-parsed for fnum, treebank in enumerate(files): train_path, dev_path, test_path, lang = utils.getTreebankPaths(treebank.strip(), args) test_files[treebank].add(test_path) if train_path is None: print(f'Skipping the treebank as no training data!') continue language_fullname = "_".join(os.path.basename(treebank).split("_")[1:]) lang_full = lang lang_id = lang.split("_")[0] if args.auto: lang = f'{lang}_auto' elif args.noise: lang = f'{lang}_noise' #creating the website home page; it requires to have all html files present in that args.folder_name createHomePage() #Get wiki-data features as obtained from GENRE entity-linking tool genre_train_data, genre_dev_data, genre_test_data, wikiData = utils.getWikiFeatures(args, lang) #Get spine embedding spine_word_vectors, spine_features, spine_dim = None, [], 0 if args.use_spine: spine_word_vectors, spine_features, spine_dim = utils.loadSpine(args.spine_outputs, lang_id, args.continuous) # Decision Tree code f = train_path.strip() train_data = pyconll.load_from_file(f"{f}") data_loader = dataloader.DataLoader(args, relation_map) # Creating the vocabulary input_dir = f"{folder_name}/{lang}" vocab_file = input_dir + f'/WordOrder/vocab.txt' inputFiles = [train_path, dev_path, test_path] data_loader.readData(inputFiles,[genre_train_data, genre_dev_data, genre_test_data], wikiData, vocab_file, spine_word_vectors, spine_features, spine_dim) # Get the model info i.e. which models do we have to train e.g. subject-verb, object-verb and so on. modelsData = filterData(data_loader) filename = f"{folder_name}/{lang}/WordOrder/" baseline_acc = 0.0 with open(filename + '/' + 'WordOrder.html', 'a') as outp: outp.write(f"<br><a href=\"../../index.html\">Back to language list</a><br>") for model, to_retain_labels in modelsData.items(): if args.skip_models and model in args.skip_models: continue try: #Create the model dir if not already present os.mkdir(f"{folder_name}/{lang}/WordOrder/{model}/") except OSError: i = 0 train_file = f'{filename}/{model}/train.feats.libsvm' #Stores the features dev_file = f'{filename}/{model}/dev.feats.libsvm' test_file = f'{filename}/{model}/test.feats.libsvm' columns_file = f'{filename}/{model}/column.feats' freq_file = f'{filename}/{model}/feats.freq' #Stores the freq of the features in the training data labels = [] for (label, _) in to_retain_labels: labels.append(label) if not (os.path.exists(train_file) and os.path.exists(test_file)): # creating the features for training train_features, columns, output_labels = data_loader.getFeatures(train_path, model, labels, genre_train_data, wikiData, spine_word_vectors, spine_features, spine_dim, train_file) dev_df = None if dev_path: dev_features, _, output_labels = data_loader.getFeatures(dev_path, model, labels, genre_dev_data, wikiData, spine_word_vectors, spine_features, spine_dim, dev_file) test_features, _, output_labels = data_loader.getFeatures(test_path, model, labels, genre_test_data, wikiData, spine_word_vectors, spine_features, spine_dim, test_file) #Reload the df again, as some issue with first loading, print(f'Reading train/dev/test from {lang}/{pos}') print(f'Loading train/dev/test...') label2id, label_list = loadDataLoader(vocab_file, data_loader) train_features, train_labels, \ dev_features, dev_labels, \ test_features, test_labels, \ baseline_label, \ id2label, minority, majority = utils.getModelTrainingDataLibsvm(train_file, dev_file, test_file, label2id, data_loader.model_data_case[model]) y_baseline = [label2id[baseline_label]] * len(test_labels) baseline_acc = accuracy_score(test_labels, y_baseline) * 100.0 tree_features = data_loader.feature_map_id2model[model] #feature_name: feature_id print('Training Started...') train_data_path = train_file.replace("libsvm", "") test_data_path = test_file.replace("libsvm", "") test_datasets = [(test_features, test_labels, lang_full, test_data_path, test_path)] #try: train(train_features, train_labels, train_path, train_data_path, dev_features, dev_labels, test_features, test_labels, model, outp, filename, baseline_label, lang_full, tree_features , relation_map, best_depths, genre_train_data, wikiData, spine_word_vectors, spine_features, spine_dim, test_datasets) # except Exception as e: # print(f'ERROR: Skipping {lang_full} - {model}') # continue outp.write("</ul><br><br><br>\n" + FOOTER + "\n")
42,613
51.609877
279
py