repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
mmyolo
mmyolo-main/mmyolo/datasets/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from .transforms import * # noqa: F401,F403 from .utils import BatchShapePolicy, yolov5_collate from .yolov5_coco import YOLOv5CocoDataset from .yolov5_crowdhuman import YOLOv5CrowdHumanDataset from .yolov5_dota import YOLOv5DOTADataset from .yolov5_voc import YOLOv5VOCDataset __all__ = [ 'YOLOv5CocoDataset', 'YOLOv5VOCDataset', 'BatchShapePolicy', 'yolov5_collate', 'YOLOv5CrowdHumanDataset', 'YOLOv5DOTADataset' ]
476
35.692308
68
py
mmyolo
mmyolo-main/mmyolo/datasets/yolov5_voc.py
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.datasets import VOCDataset from mmyolo.datasets.yolov5_coco import BatchShapePolicyDataset from ..registry import DATASETS @DATASETS.register_module() class YOLOv5VOCDataset(BatchShapePolicyDataset, VOCDataset): """Dataset for YOLOv5 VOC Dataset. We only add `BatchShapePolicy` function compared with VOCDataset. See `mmyolo/datasets/utils.py#BatchShapePolicy` for details """ pass
465
28.125
73
py
mmyolo
mmyolo-main/mmyolo/datasets/yolov5_dota.py
# Copyright (c) OpenMMLab. All rights reserved. from mmyolo.datasets.yolov5_coco import BatchShapePolicyDataset from ..registry import DATASETS try: from mmrotate.datasets import DOTADataset MMROTATE_AVAILABLE = True except ImportError: from mmengine.dataset import BaseDataset DOTADataset = BaseDataset MMROTATE_AVAILABLE = False @DATASETS.register_module() class YOLOv5DOTADataset(BatchShapePolicyDataset, DOTADataset): """Dataset for YOLOv5 DOTA Dataset. We only add `BatchShapePolicy` function compared with DOTADataset. See `mmyolo/datasets/utils.py#BatchShapePolicy` for details """ def __init__(self, *args, **kwargs): if not MMROTATE_AVAILABLE: raise ImportError( 'Please run "mim install -r requirements/mmrotate.txt" ' 'to install mmrotate first for rotated detection.') super().__init__(*args, **kwargs)
922
29.766667
74
py
mmyolo
mmyolo-main/mmyolo/datasets/transforms/mix_img_transforms.py
# Copyright (c) OpenMMLab. All rights reserved. import collections import copy from abc import ABCMeta, abstractmethod from typing import Optional, Sequence, Tuple, Union import mmcv import numpy as np from mmcv.transforms import BaseTransform from mmdet.structures.bbox import autocast_box_type from mmengine.dataset import BaseDataset from mmengine.dataset.base_dataset import Compose from numpy import random from mmyolo.registry import TRANSFORMS class BaseMixImageTransform(BaseTransform, metaclass=ABCMeta): """A Base Transform of multiple images mixed. Suitable for training on multiple images mixed data augmentation like mosaic and mixup. Cached mosaic transform will random select images from the cache and combine them into one output image if use_cached is True. Args: pre_transform(Sequence[str]): Sequence of transform object or config dict to be composed. Defaults to None. prob(float): The transformation probability. Defaults to 1.0. use_cached (bool): Whether to use cache. Defaults to False. max_cached_images (int): The maximum length of the cache. The larger the cache, the stronger the randomness of this transform. As a rule of thumb, providing 10 caches for each image suffices for randomness. Defaults to 40. random_pop (bool): Whether to randomly pop a result from the cache when the cache is full. If set to False, use FIFO popping method. Defaults to True. max_refetch (int): The maximum number of retry iterations for getting valid results from the pipeline. If the number of iterations is greater than `max_refetch`, but results is still None, then the iteration is terminated and raise the error. Defaults to 15. """ def __init__(self, pre_transform: Optional[Sequence[str]] = None, prob: float = 1.0, use_cached: bool = False, max_cached_images: int = 40, random_pop: bool = True, max_refetch: int = 15): self.max_refetch = max_refetch self.prob = prob self.use_cached = use_cached self.max_cached_images = max_cached_images self.random_pop = random_pop self.results_cache = [] if pre_transform is None: self.pre_transform = None else: self.pre_transform = Compose(pre_transform) @abstractmethod def get_indexes(self, dataset: Union[BaseDataset, list]) -> Union[list, int]: """Call function to collect indexes. Args: dataset (:obj:`Dataset` or list): The dataset or cached list. Returns: list or int: indexes. """ pass @abstractmethod def mix_img_transform(self, results: dict) -> dict: """Mixed image data transformation. Args: results (dict): Result dict. Returns: results (dict): Updated result dict. """ pass @autocast_box_type() def transform(self, results: dict) -> dict: """Data augmentation function. The transform steps are as follows: 1. Randomly generate index list of other images. 2. Before Mosaic or MixUp need to go through the necessary pre_transform, such as MixUp' pre_transform pipeline include: 'LoadImageFromFile','LoadAnnotations', 'Mosaic' and 'RandomAffine'. 3. Use mix_img_transform function to implement specific mix operations. Args: results (dict): Result dict. Returns: results (dict): Updated result dict. """ if random.uniform(0, 1) > self.prob: return results if self.use_cached: # Be careful: deep copying can be very time-consuming # if results includes dataset. dataset = results.pop('dataset', None) self.results_cache.append(copy.deepcopy(results)) if len(self.results_cache) > self.max_cached_images: if self.random_pop: index = random.randint(0, len(self.results_cache) - 1) else: index = 0 self.results_cache.pop(index) if len(self.results_cache) <= 4: return results else: assert 'dataset' in results # Be careful: deep copying can be very time-consuming # if results includes dataset. dataset = results.pop('dataset', None) for _ in range(self.max_refetch): # get index of one or three other images if self.use_cached: indexes = self.get_indexes(self.results_cache) else: indexes = self.get_indexes(dataset) if not isinstance(indexes, collections.abc.Sequence): indexes = [indexes] if self.use_cached: mix_results = [ copy.deepcopy(self.results_cache[i]) for i in indexes ] else: # get images information will be used for Mosaic or MixUp mix_results = [ copy.deepcopy(dataset.get_data_info(index)) for index in indexes ] if self.pre_transform is not None: for i, data in enumerate(mix_results): # pre_transform may also require dataset data.update({'dataset': dataset}) # before Mosaic or MixUp need to go through # the necessary pre_transform _results = self.pre_transform(data) _results.pop('dataset') mix_results[i] = _results if None not in mix_results: results['mix_results'] = mix_results break print('Repeated calculation') else: raise RuntimeError( 'The loading pipeline of the original dataset' ' always return None. Please check the correctness ' 'of the dataset and its pipeline.') # Mosaic or MixUp results = self.mix_img_transform(results) if 'mix_results' in results: results.pop('mix_results') results['dataset'] = dataset return results @TRANSFORMS.register_module() class Mosaic(BaseMixImageTransform): """Mosaic augmentation. Given 4 images, mosaic transform combines them into one output image. The output image is composed of the parts from each sub- image. .. code:: text mosaic transform center_x +------------------------------+ | pad | | | +-----------+ pad | | | | | | | image1 +-----------+ | | | | | | | image2 | center_y |----+-+-----------+-----------+ | | cropped | | |pad | image3 | image4 | | | | | +----|-------------+-----------+ | | +-------------+ The mosaic transform steps are as follows: 1. Choose the mosaic center as the intersections of 4 images 2. Get the left top image according to the index, and randomly sample another 3 images from the custom dataset. 3. Sub image will be cropped if image is larger than mosaic patch Required Keys: - img - gt_bboxes (BaseBoxes[torch.float32]) (optional) - gt_bboxes_labels (np.int64) (optional) - gt_ignore_flags (bool) (optional) - mix_results (List[dict]) Modified Keys: - img - img_shape - gt_bboxes (optional) - gt_bboxes_labels (optional) - gt_ignore_flags (optional) Args: img_scale (Sequence[int]): Image size after mosaic pipeline of single image. The shape order should be (width, height). Defaults to (640, 640). center_ratio_range (Sequence[float]): Center ratio range of mosaic output. Defaults to (0.5, 1.5). bbox_clip_border (bool, optional): Whether to clip the objects outside the border of the image. In some dataset like MOT17, the gt bboxes are allowed to cross the border of images. Therefore, we don't need to clip the gt bboxes in these cases. Defaults to True. pad_val (int): Pad value. Defaults to 114. pre_transform(Sequence[dict]): Sequence of transform object or config dict to be composed. prob (float): Probability of applying this transformation. Defaults to 1.0. use_cached (bool): Whether to use cache. Defaults to False. max_cached_images (int): The maximum length of the cache. The larger the cache, the stronger the randomness of this transform. As a rule of thumb, providing 10 caches for each image suffices for randomness. Defaults to 40. random_pop (bool): Whether to randomly pop a result from the cache when the cache is full. If set to False, use FIFO popping method. Defaults to True. max_refetch (int): The maximum number of retry iterations for getting valid results from the pipeline. If the number of iterations is greater than `max_refetch`, but results is still None, then the iteration is terminated and raise the error. Defaults to 15. """ def __init__(self, img_scale: Tuple[int, int] = (640, 640), center_ratio_range: Tuple[float, float] = (0.5, 1.5), bbox_clip_border: bool = True, pad_val: float = 114.0, pre_transform: Sequence[dict] = None, prob: float = 1.0, use_cached: bool = False, max_cached_images: int = 40, random_pop: bool = True, max_refetch: int = 15): assert isinstance(img_scale, tuple) assert 0 <= prob <= 1.0, 'The probability should be in range [0,1]. ' \ f'got {prob}.' if use_cached: assert max_cached_images >= 4, 'The length of cache must >= 4, ' \ f'but got {max_cached_images}.' super().__init__( pre_transform=pre_transform, prob=prob, use_cached=use_cached, max_cached_images=max_cached_images, random_pop=random_pop, max_refetch=max_refetch) self.img_scale = img_scale self.center_ratio_range = center_ratio_range self.bbox_clip_border = bbox_clip_border self.pad_val = pad_val def get_indexes(self, dataset: Union[BaseDataset, list]) -> list: """Call function to collect indexes. Args: dataset (:obj:`Dataset` or list): The dataset or cached list. Returns: list: indexes. """ indexes = [random.randint(0, len(dataset)) for _ in range(3)] return indexes def mix_img_transform(self, results: dict) -> dict: """Mixed image data transformation. Args: results (dict): Result dict. Returns: results (dict): Updated result dict. """ assert 'mix_results' in results mosaic_bboxes = [] mosaic_bboxes_labels = [] mosaic_ignore_flags = [] mosaic_masks = [] with_mask = True if 'gt_masks' in results else False # self.img_scale is wh format img_scale_w, img_scale_h = self.img_scale if len(results['img'].shape) == 3: mosaic_img = np.full( (int(img_scale_h * 2), int(img_scale_w * 2), 3), self.pad_val, dtype=results['img'].dtype) else: mosaic_img = np.full((int(img_scale_h * 2), int(img_scale_w * 2)), self.pad_val, dtype=results['img'].dtype) # mosaic center x, y center_x = int(random.uniform(*self.center_ratio_range) * img_scale_w) center_y = int(random.uniform(*self.center_ratio_range) * img_scale_h) center_position = (center_x, center_y) loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right') for i, loc in enumerate(loc_strs): if loc == 'top_left': results_patch = results else: results_patch = results['mix_results'][i - 1] img_i = results_patch['img'] h_i, w_i = img_i.shape[:2] # keep_ratio resize scale_ratio_i = min(img_scale_h / h_i, img_scale_w / w_i) img_i = mmcv.imresize( img_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i))) # compute the combine parameters paste_coord, crop_coord = self._mosaic_combine( loc, center_position, img_i.shape[:2][::-1]) x1_p, y1_p, x2_p, y2_p = paste_coord x1_c, y1_c, x2_c, y2_c = crop_coord # crop and paste image mosaic_img[y1_p:y2_p, x1_p:x2_p] = img_i[y1_c:y2_c, x1_c:x2_c] # adjust coordinate gt_bboxes_i = results_patch['gt_bboxes'] gt_bboxes_labels_i = results_patch['gt_bboxes_labels'] gt_ignore_flags_i = results_patch['gt_ignore_flags'] padw = x1_p - x1_c padh = y1_p - y1_c gt_bboxes_i.rescale_([scale_ratio_i, scale_ratio_i]) gt_bboxes_i.translate_([padw, padh]) mosaic_bboxes.append(gt_bboxes_i) mosaic_bboxes_labels.append(gt_bboxes_labels_i) mosaic_ignore_flags.append(gt_ignore_flags_i) if with_mask and results_patch.get('gt_masks', None) is not None: gt_masks_i = results_patch['gt_masks'] gt_masks_i = gt_masks_i.rescale(float(scale_ratio_i)) gt_masks_i = gt_masks_i.translate( out_shape=(int(self.img_scale[0] * 2), int(self.img_scale[1] * 2)), offset=padw, direction='horizontal') gt_masks_i = gt_masks_i.translate( out_shape=(int(self.img_scale[0] * 2), int(self.img_scale[1] * 2)), offset=padh, direction='vertical') mosaic_masks.append(gt_masks_i) mosaic_bboxes = mosaic_bboxes[0].cat(mosaic_bboxes, 0) mosaic_bboxes_labels = np.concatenate(mosaic_bboxes_labels, 0) mosaic_ignore_flags = np.concatenate(mosaic_ignore_flags, 0) if self.bbox_clip_border: mosaic_bboxes.clip_([2 * img_scale_h, 2 * img_scale_w]) if with_mask: mosaic_masks = mosaic_masks[0].cat(mosaic_masks) results['gt_masks'] = mosaic_masks else: # remove outside bboxes inside_inds = mosaic_bboxes.is_inside( [2 * img_scale_h, 2 * img_scale_w]).numpy() mosaic_bboxes = mosaic_bboxes[inside_inds] mosaic_bboxes_labels = mosaic_bboxes_labels[inside_inds] mosaic_ignore_flags = mosaic_ignore_flags[inside_inds] if with_mask: mosaic_masks = mosaic_masks[0].cat(mosaic_masks)[inside_inds] results['gt_masks'] = mosaic_masks results['img'] = mosaic_img results['img_shape'] = mosaic_img.shape results['gt_bboxes'] = mosaic_bboxes results['gt_bboxes_labels'] = mosaic_bboxes_labels results['gt_ignore_flags'] = mosaic_ignore_flags return results def _mosaic_combine( self, loc: str, center_position_xy: Sequence[float], img_shape_wh: Sequence[int]) -> Tuple[Tuple[int], Tuple[int]]: """Calculate global coordinate of mosaic image and local coordinate of cropped sub-image. Args: loc (str): Index for the sub-image, loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right'). center_position_xy (Sequence[float]): Mixing center for 4 images, (x, y). img_shape_wh (Sequence[int]): Width and height of sub-image Returns: tuple[tuple[float]]: Corresponding coordinate of pasting and cropping - paste_coord (tuple): paste corner coordinate in mosaic image. - crop_coord (tuple): crop corner coordinate in mosaic image. """ assert loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right') if loc == 'top_left': # index0 to top left part of image x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ max(center_position_xy[1] - img_shape_wh[1], 0), \ center_position_xy[0], \ center_position_xy[1] crop_coord = img_shape_wh[0] - (x2 - x1), img_shape_wh[1] - ( y2 - y1), img_shape_wh[0], img_shape_wh[1] elif loc == 'top_right': # index1 to top right part of image x1, y1, x2, y2 = center_position_xy[0], \ max(center_position_xy[1] - img_shape_wh[1], 0), \ min(center_position_xy[0] + img_shape_wh[0], self.img_scale[0] * 2), \ center_position_xy[1] crop_coord = 0, img_shape_wh[1] - (y2 - y1), min( img_shape_wh[0], x2 - x1), img_shape_wh[1] elif loc == 'bottom_left': # index2 to bottom left part of image x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ center_position_xy[1], \ center_position_xy[0], \ min(self.img_scale[1] * 2, center_position_xy[1] + img_shape_wh[1]) crop_coord = img_shape_wh[0] - (x2 - x1), 0, img_shape_wh[0], min( y2 - y1, img_shape_wh[1]) else: # index3 to bottom right part of image x1, y1, x2, y2 = center_position_xy[0], \ center_position_xy[1], \ min(center_position_xy[0] + img_shape_wh[0], self.img_scale[0] * 2), \ min(self.img_scale[1] * 2, center_position_xy[1] + img_shape_wh[1]) crop_coord = 0, 0, min(img_shape_wh[0], x2 - x1), min(y2 - y1, img_shape_wh[1]) paste_coord = x1, y1, x2, y2 return paste_coord, crop_coord def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(img_scale={self.img_scale}, ' repr_str += f'center_ratio_range={self.center_ratio_range}, ' repr_str += f'pad_val={self.pad_val}, ' repr_str += f'prob={self.prob})' return repr_str @TRANSFORMS.register_module() class Mosaic9(BaseMixImageTransform): """Mosaic9 augmentation. Given 9 images, mosaic transform combines them into one output image. The output image is composed of the parts from each sub- image. .. code:: text +-------------------------------+------------+ | pad | pad | | | +----------+ | | | | +---------------+ top_right | | | | top | image2 | | | top_left | image1 | | | | image8 o--------+------+--------+---+ | | | | | | +----+----------+ | right |pad| | | center | image3 | | | left | image0 +---------------+---| | image7 | | | | +---+-----------+---+--------+ | | | | cropped | | bottom_right |pad| | |bottom_left| | image4 | | | | image6 | bottom | | | +---|-----------+ image5 +---------------+---| | pad | | pad | +-----------+------------+-------------------+ The mosaic transform steps are as follows: 1. Get the center image according to the index, and randomly sample another 8 images from the custom dataset. 2. Randomly offset the image after Mosaic Required Keys: - img - gt_bboxes (BaseBoxes[torch.float32]) (optional) - gt_bboxes_labels (np.int64) (optional) - gt_ignore_flags (bool) (optional) - mix_results (List[dict]) Modified Keys: - img - img_shape - gt_bboxes (optional) - gt_bboxes_labels (optional) - gt_ignore_flags (optional) Args: img_scale (Sequence[int]): Image size after mosaic pipeline of single image. The shape order should be (width, height). Defaults to (640, 640). bbox_clip_border (bool, optional): Whether to clip the objects outside the border of the image. In some dataset like MOT17, the gt bboxes are allowed to cross the border of images. Therefore, we don't need to clip the gt bboxes in these cases. Defaults to True. pad_val (int): Pad value. Defaults to 114. pre_transform(Sequence[dict]): Sequence of transform object or config dict to be composed. prob (float): Probability of applying this transformation. Defaults to 1.0. use_cached (bool): Whether to use cache. Defaults to False. max_cached_images (int): The maximum length of the cache. The larger the cache, the stronger the randomness of this transform. As a rule of thumb, providing 5 caches for each image suffices for randomness. Defaults to 50. random_pop (bool): Whether to randomly pop a result from the cache when the cache is full. If set to False, use FIFO popping method. Defaults to True. max_refetch (int): The maximum number of retry iterations for getting valid results from the pipeline. If the number of iterations is greater than `max_refetch`, but results is still None, then the iteration is terminated and raise the error. Defaults to 15. """ def __init__(self, img_scale: Tuple[int, int] = (640, 640), bbox_clip_border: bool = True, pad_val: Union[float, int] = 114.0, pre_transform: Sequence[dict] = None, prob: float = 1.0, use_cached: bool = False, max_cached_images: int = 50, random_pop: bool = True, max_refetch: int = 15): assert isinstance(img_scale, tuple) assert 0 <= prob <= 1.0, 'The probability should be in range [0,1]. ' \ f'got {prob}.' if use_cached: assert max_cached_images >= 9, 'The length of cache must >= 9, ' \ f'but got {max_cached_images}.' super().__init__( pre_transform=pre_transform, prob=prob, use_cached=use_cached, max_cached_images=max_cached_images, random_pop=random_pop, max_refetch=max_refetch) self.img_scale = img_scale self.bbox_clip_border = bbox_clip_border self.pad_val = pad_val # intermediate variables self._current_img_shape = [0, 0] self._center_img_shape = [0, 0] self._previous_img_shape = [0, 0] def get_indexes(self, dataset: Union[BaseDataset, list]) -> list: """Call function to collect indexes. Args: dataset (:obj:`Dataset` or list): The dataset or cached list. Returns: list: indexes. """ indexes = [random.randint(0, len(dataset)) for _ in range(8)] return indexes def mix_img_transform(self, results: dict) -> dict: """Mixed image data transformation. Args: results (dict): Result dict. Returns: results (dict): Updated result dict. """ assert 'mix_results' in results mosaic_bboxes = [] mosaic_bboxes_labels = [] mosaic_ignore_flags = [] img_scale_w, img_scale_h = self.img_scale if len(results['img'].shape) == 3: mosaic_img = np.full( (int(img_scale_h * 3), int(img_scale_w * 3), 3), self.pad_val, dtype=results['img'].dtype) else: mosaic_img = np.full((int(img_scale_h * 3), int(img_scale_w * 3)), self.pad_val, dtype=results['img'].dtype) # index = 0 is mean original image # len(results['mix_results']) = 8 loc_strs = ('center', 'top', 'top_right', 'right', 'bottom_right', 'bottom', 'bottom_left', 'left', 'top_left') results_all = [results, *results['mix_results']] for index, results_patch in enumerate(results_all): img_i = results_patch['img'] # keep_ratio resize img_i_h, img_i_w = img_i.shape[:2] scale_ratio_i = min(img_scale_h / img_i_h, img_scale_w / img_i_w) img_i = mmcv.imresize( img_i, (int(img_i_w * scale_ratio_i), int(img_i_h * scale_ratio_i))) paste_coord = self._mosaic_combine(loc_strs[index], img_i.shape[:2]) padw, padh = paste_coord[:2] x1, y1, x2, y2 = (max(x, 0) for x in paste_coord) mosaic_img[y1:y2, x1:x2] = img_i[y1 - padh:, x1 - padw:] gt_bboxes_i = results_patch['gt_bboxes'] gt_bboxes_labels_i = results_patch['gt_bboxes_labels'] gt_ignore_flags_i = results_patch['gt_ignore_flags'] gt_bboxes_i.rescale_([scale_ratio_i, scale_ratio_i]) gt_bboxes_i.translate_([padw, padh]) mosaic_bboxes.append(gt_bboxes_i) mosaic_bboxes_labels.append(gt_bboxes_labels_i) mosaic_ignore_flags.append(gt_ignore_flags_i) # Offset offset_x = int(random.uniform(0, img_scale_w)) offset_y = int(random.uniform(0, img_scale_h)) mosaic_img = mosaic_img[offset_y:offset_y + 2 * img_scale_h, offset_x:offset_x + 2 * img_scale_w] mosaic_bboxes = mosaic_bboxes[0].cat(mosaic_bboxes, 0) mosaic_bboxes.translate_([-offset_x, -offset_y]) mosaic_bboxes_labels = np.concatenate(mosaic_bboxes_labels, 0) mosaic_ignore_flags = np.concatenate(mosaic_ignore_flags, 0) if self.bbox_clip_border: mosaic_bboxes.clip_([2 * img_scale_h, 2 * img_scale_w]) else: # remove outside bboxes inside_inds = mosaic_bboxes.is_inside( [2 * img_scale_h, 2 * img_scale_w]).numpy() mosaic_bboxes = mosaic_bboxes[inside_inds] mosaic_bboxes_labels = mosaic_bboxes_labels[inside_inds] mosaic_ignore_flags = mosaic_ignore_flags[inside_inds] results['img'] = mosaic_img results['img_shape'] = mosaic_img.shape results['gt_bboxes'] = mosaic_bboxes results['gt_bboxes_labels'] = mosaic_bboxes_labels results['gt_ignore_flags'] = mosaic_ignore_flags return results def _mosaic_combine(self, loc: str, img_shape_hw: Tuple[int, int]) -> Tuple[int, ...]: """Calculate global coordinate of mosaic image. Args: loc (str): Index for the sub-image. img_shape_hw (Sequence[int]): Height and width of sub-image Returns: paste_coord (tuple): paste corner coordinate in mosaic image. """ assert loc in ('center', 'top', 'top_right', 'right', 'bottom_right', 'bottom', 'bottom_left', 'left', 'top_left') img_scale_w, img_scale_h = self.img_scale self._current_img_shape = img_shape_hw current_img_h, current_img_w = self._current_img_shape previous_img_h, previous_img_w = self._previous_img_shape center_img_h, center_img_w = self._center_img_shape if loc == 'center': self._center_img_shape = self._current_img_shape # xmin, ymin, xmax, ymax paste_coord = img_scale_w, \ img_scale_h, \ img_scale_w + current_img_w, \ img_scale_h + current_img_h elif loc == 'top': paste_coord = img_scale_w, \ img_scale_h - current_img_h, \ img_scale_w + current_img_w, \ img_scale_h elif loc == 'top_right': paste_coord = img_scale_w + previous_img_w, \ img_scale_h - current_img_h, \ img_scale_w + previous_img_w + current_img_w, \ img_scale_h elif loc == 'right': paste_coord = img_scale_w + center_img_w, \ img_scale_h, \ img_scale_w + center_img_w + current_img_w, \ img_scale_h + current_img_h elif loc == 'bottom_right': paste_coord = img_scale_w + center_img_w, \ img_scale_h + previous_img_h, \ img_scale_w + center_img_w + current_img_w, \ img_scale_h + previous_img_h + current_img_h elif loc == 'bottom': paste_coord = img_scale_w + center_img_w - current_img_w, \ img_scale_h + center_img_h, \ img_scale_w + center_img_w, \ img_scale_h + center_img_h + current_img_h elif loc == 'bottom_left': paste_coord = img_scale_w + center_img_w - \ previous_img_w - current_img_w, \ img_scale_h + center_img_h, \ img_scale_w + center_img_w - previous_img_w, \ img_scale_h + center_img_h + current_img_h elif loc == 'left': paste_coord = img_scale_w - current_img_w, \ img_scale_h + center_img_h - current_img_h, \ img_scale_w, \ img_scale_h + center_img_h elif loc == 'top_left': paste_coord = img_scale_w - current_img_w, \ img_scale_h + center_img_h - \ previous_img_h - current_img_h, \ img_scale_w, \ img_scale_h + center_img_h - previous_img_h self._previous_img_shape = self._current_img_shape # xmin, ymin, xmax, ymax return paste_coord def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(img_scale={self.img_scale}, ' repr_str += f'pad_val={self.pad_val}, ' repr_str += f'prob={self.prob})' return repr_str @TRANSFORMS.register_module() class YOLOv5MixUp(BaseMixImageTransform): """MixUp data augmentation for YOLOv5. .. code:: text The mixup transform steps are as follows: 1. Another random image is picked by dataset. 2. Randomly obtain the fusion ratio from the beta distribution, then fuse the target of the original image and mixup image through this ratio. Required Keys: - img - gt_bboxes (BaseBoxes[torch.float32]) (optional) - gt_bboxes_labels (np.int64) (optional) - gt_ignore_flags (bool) (optional) - mix_results (List[dict]) Modified Keys: - img - img_shape - gt_bboxes (optional) - gt_bboxes_labels (optional) - gt_ignore_flags (optional) Args: alpha (float): parameter of beta distribution to get mixup ratio. Defaults to 32. beta (float): parameter of beta distribution to get mixup ratio. Defaults to 32. pre_transform (Sequence[dict]): Sequence of transform object or config dict to be composed. prob (float): Probability of applying this transformation. Defaults to 1.0. use_cached (bool): Whether to use cache. Defaults to False. max_cached_images (int): The maximum length of the cache. The larger the cache, the stronger the randomness of this transform. As a rule of thumb, providing 10 caches for each image suffices for randomness. Defaults to 20. random_pop (bool): Whether to randomly pop a result from the cache when the cache is full. If set to False, use FIFO popping method. Defaults to True. max_refetch (int): The maximum number of iterations. If the number of iterations is greater than `max_refetch`, but gt_bbox is still empty, then the iteration is terminated. Defaults to 15. """ def __init__(self, alpha: float = 32.0, beta: float = 32.0, pre_transform: Sequence[dict] = None, prob: float = 1.0, use_cached: bool = False, max_cached_images: int = 20, random_pop: bool = True, max_refetch: int = 15): if use_cached: assert max_cached_images >= 2, 'The length of cache must >= 2, ' \ f'but got {max_cached_images}.' super().__init__( pre_transform=pre_transform, prob=prob, use_cached=use_cached, max_cached_images=max_cached_images, random_pop=random_pop, max_refetch=max_refetch) self.alpha = alpha self.beta = beta def get_indexes(self, dataset: Union[BaseDataset, list]) -> int: """Call function to collect indexes. Args: dataset (:obj:`Dataset` or list): The dataset or cached list. Returns: int: indexes. """ return random.randint(0, len(dataset)) def mix_img_transform(self, results: dict) -> dict: """YOLOv5 MixUp transform function. Args: results (dict): Result dict Returns: results (dict): Updated result dict. """ assert 'mix_results' in results retrieve_results = results['mix_results'][0] retrieve_img = retrieve_results['img'] ori_img = results['img'] assert ori_img.shape == retrieve_img.shape # Randomly obtain the fusion ratio from the beta distribution, # which is around 0.5 ratio = np.random.beta(self.alpha, self.beta) mixup_img = (ori_img * ratio + retrieve_img * (1 - ratio)) retrieve_gt_bboxes = retrieve_results['gt_bboxes'] retrieve_gt_bboxes_labels = retrieve_results['gt_bboxes_labels'] retrieve_gt_ignore_flags = retrieve_results['gt_ignore_flags'] mixup_gt_bboxes = retrieve_gt_bboxes.cat( (results['gt_bboxes'], retrieve_gt_bboxes), dim=0) mixup_gt_bboxes_labels = np.concatenate( (results['gt_bboxes_labels'], retrieve_gt_bboxes_labels), axis=0) mixup_gt_ignore_flags = np.concatenate( (results['gt_ignore_flags'], retrieve_gt_ignore_flags), axis=0) if 'gt_masks' in results: assert 'gt_masks' in retrieve_results mixup_gt_masks = results['gt_masks'].cat( [results['gt_masks'], retrieve_results['gt_masks']]) results['gt_masks'] = mixup_gt_masks results['img'] = mixup_img.astype(np.uint8) results['img_shape'] = mixup_img.shape results['gt_bboxes'] = mixup_gt_bboxes results['gt_bboxes_labels'] = mixup_gt_bboxes_labels results['gt_ignore_flags'] = mixup_gt_ignore_flags return results @TRANSFORMS.register_module() class YOLOXMixUp(BaseMixImageTransform): """MixUp data augmentation for YOLOX. .. code:: text mixup transform +---------------+--------------+ | mixup image | | | +--------|--------+ | | | | | | +---------------+ | | | | | | | | image | | | | | | | | | | | +-----------------+ | | pad | +------------------------------+ The mixup transform steps are as follows: 1. Another random image is picked by dataset and embedded in the top left patch(after padding and resizing) 2. The target of mixup transform is the weighted average of mixup image and origin image. Required Keys: - img - gt_bboxes (BaseBoxes[torch.float32]) (optional) - gt_bboxes_labels (np.int64) (optional) - gt_ignore_flags (bool) (optional) - mix_results (List[dict]) Modified Keys: - img - img_shape - gt_bboxes (optional) - gt_bboxes_labels (optional) - gt_ignore_flags (optional) Args: img_scale (Sequence[int]): Image output size after mixup pipeline. The shape order should be (width, height). Defaults to (640, 640). ratio_range (Sequence[float]): Scale ratio of mixup image. Defaults to (0.5, 1.5). flip_ratio (float): Horizontal flip ratio of mixup image. Defaults to 0.5. pad_val (int): Pad value. Defaults to 114. bbox_clip_border (bool, optional): Whether to clip the objects outside the border of the image. In some dataset like MOT17, the gt bboxes are allowed to cross the border of images. Therefore, we don't need to clip the gt bboxes in these cases. Defaults to True. pre_transform(Sequence[dict]): Sequence of transform object or config dict to be composed. prob (float): Probability of applying this transformation. Defaults to 1.0. use_cached (bool): Whether to use cache. Defaults to False. max_cached_images (int): The maximum length of the cache. The larger the cache, the stronger the randomness of this transform. As a rule of thumb, providing 10 caches for each image suffices for randomness. Defaults to 20. random_pop (bool): Whether to randomly pop a result from the cache when the cache is full. If set to False, use FIFO popping method. Defaults to True. max_refetch (int): The maximum number of iterations. If the number of iterations is greater than `max_refetch`, but gt_bbox is still empty, then the iteration is terminated. Defaults to 15. """ def __init__(self, img_scale: Tuple[int, int] = (640, 640), ratio_range: Tuple[float, float] = (0.5, 1.5), flip_ratio: float = 0.5, pad_val: float = 114.0, bbox_clip_border: bool = True, pre_transform: Sequence[dict] = None, prob: float = 1.0, use_cached: bool = False, max_cached_images: int = 20, random_pop: bool = True, max_refetch: int = 15): assert isinstance(img_scale, tuple) if use_cached: assert max_cached_images >= 2, 'The length of cache must >= 2, ' \ f'but got {max_cached_images}.' super().__init__( pre_transform=pre_transform, prob=prob, use_cached=use_cached, max_cached_images=max_cached_images, random_pop=random_pop, max_refetch=max_refetch) self.img_scale = img_scale self.ratio_range = ratio_range self.flip_ratio = flip_ratio self.pad_val = pad_val self.bbox_clip_border = bbox_clip_border def get_indexes(self, dataset: Union[BaseDataset, list]) -> int: """Call function to collect indexes. Args: dataset (:obj:`Dataset` or list): The dataset or cached list. Returns: int: indexes. """ return random.randint(0, len(dataset)) def mix_img_transform(self, results: dict) -> dict: """YOLOX MixUp transform function. Args: results (dict): Result dict. Returns: results (dict): Updated result dict. """ assert 'mix_results' in results assert len( results['mix_results']) == 1, 'MixUp only support 2 images now !' if results['mix_results'][0]['gt_bboxes'].shape[0] == 0: # empty bbox return results retrieve_results = results['mix_results'][0] retrieve_img = retrieve_results['img'] jit_factor = random.uniform(*self.ratio_range) is_filp = random.uniform(0, 1) > self.flip_ratio if len(retrieve_img.shape) == 3: out_img = np.ones((self.img_scale[1], self.img_scale[0], 3), dtype=retrieve_img.dtype) * self.pad_val else: out_img = np.ones( self.img_scale[::-1], dtype=retrieve_img.dtype) * self.pad_val # 1. keep_ratio resize scale_ratio = min(self.img_scale[1] / retrieve_img.shape[0], self.img_scale[0] / retrieve_img.shape[1]) retrieve_img = mmcv.imresize( retrieve_img, (int(retrieve_img.shape[1] * scale_ratio), int(retrieve_img.shape[0] * scale_ratio))) # 2. paste out_img[:retrieve_img.shape[0], :retrieve_img.shape[1]] = retrieve_img # 3. scale jit scale_ratio *= jit_factor out_img = mmcv.imresize(out_img, (int(out_img.shape[1] * jit_factor), int(out_img.shape[0] * jit_factor))) # 4. flip if is_filp: out_img = out_img[:, ::-1, :] # 5. random crop ori_img = results['img'] origin_h, origin_w = out_img.shape[:2] target_h, target_w = ori_img.shape[:2] padded_img = np.ones((max(origin_h, target_h), max( origin_w, target_w), 3)) * self.pad_val padded_img = padded_img.astype(np.uint8) padded_img[:origin_h, :origin_w] = out_img x_offset, y_offset = 0, 0 if padded_img.shape[0] > target_h: y_offset = random.randint(0, padded_img.shape[0] - target_h) if padded_img.shape[1] > target_w: x_offset = random.randint(0, padded_img.shape[1] - target_w) padded_cropped_img = padded_img[y_offset:y_offset + target_h, x_offset:x_offset + target_w] # 6. adjust bbox retrieve_gt_bboxes = retrieve_results['gt_bboxes'] retrieve_gt_bboxes.rescale_([scale_ratio, scale_ratio]) if self.bbox_clip_border: retrieve_gt_bboxes.clip_([origin_h, origin_w]) if is_filp: retrieve_gt_bboxes.flip_([origin_h, origin_w], direction='horizontal') # 7. filter cp_retrieve_gt_bboxes = retrieve_gt_bboxes.clone() cp_retrieve_gt_bboxes.translate_([-x_offset, -y_offset]) if self.bbox_clip_border: cp_retrieve_gt_bboxes.clip_([target_h, target_w]) # 8. mix up mixup_img = 0.5 * ori_img + 0.5 * padded_cropped_img retrieve_gt_bboxes_labels = retrieve_results['gt_bboxes_labels'] retrieve_gt_ignore_flags = retrieve_results['gt_ignore_flags'] mixup_gt_bboxes = cp_retrieve_gt_bboxes.cat( (results['gt_bboxes'], cp_retrieve_gt_bboxes), dim=0) mixup_gt_bboxes_labels = np.concatenate( (results['gt_bboxes_labels'], retrieve_gt_bboxes_labels), axis=0) mixup_gt_ignore_flags = np.concatenate( (results['gt_ignore_flags'], retrieve_gt_ignore_flags), axis=0) if not self.bbox_clip_border: # remove outside bbox inside_inds = mixup_gt_bboxes.is_inside([target_h, target_w]).numpy() mixup_gt_bboxes = mixup_gt_bboxes[inside_inds] mixup_gt_bboxes_labels = mixup_gt_bboxes_labels[inside_inds] mixup_gt_ignore_flags = mixup_gt_ignore_flags[inside_inds] results['img'] = mixup_img.astype(np.uint8) results['img_shape'] = mixup_img.shape results['gt_bboxes'] = mixup_gt_bboxes results['gt_bboxes_labels'] = mixup_gt_bboxes_labels results['gt_ignore_flags'] = mixup_gt_ignore_flags return results def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(img_scale={self.img_scale}, ' repr_str += f'ratio_range={self.ratio_range}, ' repr_str += f'flip_ratio={self.flip_ratio}, ' repr_str += f'pad_val={self.pad_val}, ' repr_str += f'max_refetch={self.max_refetch}, ' repr_str += f'bbox_clip_border={self.bbox_clip_border})' return repr_str
46,505
39.404865
79
py
mmyolo
mmyolo-main/mmyolo/datasets/transforms/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from .mix_img_transforms import Mosaic, Mosaic9, YOLOv5MixUp, YOLOXMixUp from .transforms import (LetterResize, LoadAnnotations, PPYOLOERandomCrop, PPYOLOERandomDistort, RegularizeRotatedBox, RemoveDataElement, YOLOv5CopyPaste, YOLOv5HSVRandomAug, YOLOv5KeepRatioResize, YOLOv5RandomAffine) __all__ = [ 'YOLOv5KeepRatioResize', 'LetterResize', 'Mosaic', 'YOLOXMixUp', 'YOLOv5MixUp', 'YOLOv5HSVRandomAug', 'LoadAnnotations', 'YOLOv5RandomAffine', 'PPYOLOERandomDistort', 'PPYOLOERandomCrop', 'Mosaic9', 'YOLOv5CopyPaste', 'RemoveDataElement', 'RegularizeRotatedBox' ]
732
47.866667
77
py
mmyolo
mmyolo-main/mmyolo/datasets/transforms/transforms.py
# Copyright (c) OpenMMLab. All rights reserved. import math from copy import deepcopy from typing import List, Sequence, Tuple, Union import cv2 import mmcv import numpy as np import torch from mmcv.transforms import BaseTransform, Compose from mmcv.transforms.utils import cache_randomness from mmdet.datasets.transforms import LoadAnnotations as MMDET_LoadAnnotations from mmdet.datasets.transforms import Resize as MMDET_Resize from mmdet.structures.bbox import (HorizontalBoxes, autocast_box_type, get_box_type) from mmdet.structures.mask import PolygonMasks from numpy import random from mmyolo.registry import TRANSFORMS # TODO: Waiting for MMCV support TRANSFORMS.register_module(module=Compose, force=True) @TRANSFORMS.register_module() class YOLOv5KeepRatioResize(MMDET_Resize): """Resize images & bbox(if existed). This transform resizes the input image according to ``scale``. Bboxes (if existed) are then resized with the same scale factor. Required Keys: - img (np.uint8) - gt_bboxes (BaseBoxes[torch.float32]) (optional) Modified Keys: - img (np.uint8) - img_shape (tuple) - gt_bboxes (optional) - scale (float) Added Keys: - scale_factor (np.float32) Args: scale (Union[int, Tuple[int, int]]): Images scales for resizing. """ def __init__(self, scale: Union[int, Tuple[int, int]], keep_ratio: bool = True, **kwargs): assert keep_ratio is True super().__init__(scale=scale, keep_ratio=True, **kwargs) @staticmethod def _get_rescale_ratio(old_size: Tuple[int, int], scale: Union[float, Tuple[int]]) -> float: """Calculate the ratio for rescaling. Args: old_size (tuple[int]): The old size (w, h) of image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. Returns: float: The resize ratio. """ w, h = old_size if isinstance(scale, (float, int)): if scale <= 0: raise ValueError(f'Invalid scale {scale}, must be positive.') scale_factor = scale elif isinstance(scale, tuple): max_long_edge = max(scale) max_short_edge = min(scale) scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w)) else: raise TypeError('Scale must be a number or tuple of int, ' f'but got {type(scale)}') return scale_factor def _resize_img(self, results: dict): """Resize images with ``results['scale']``.""" assert self.keep_ratio is True if results.get('img', None) is not None: image = results['img'] original_h, original_w = image.shape[:2] ratio = self._get_rescale_ratio((original_h, original_w), self.scale) if ratio != 1: # resize image according to the ratio image = mmcv.imrescale( img=image, scale=ratio, interpolation='area' if ratio < 1 else 'bilinear', backend=self.backend) resized_h, resized_w = image.shape[:2] scale_ratio = resized_h / original_h scale_factor = (scale_ratio, scale_ratio) results['img'] = image results['img_shape'] = image.shape[:2] results['scale_factor'] = scale_factor @TRANSFORMS.register_module() class LetterResize(MMDET_Resize): """Resize and pad image while meeting stride-multiple constraints. Required Keys: - img (np.uint8) - batch_shape (np.int64) (optional) Modified Keys: - img (np.uint8) - img_shape (tuple) - gt_bboxes (optional) Added Keys: - pad_param (np.float32) Args: scale (Union[int, Tuple[int, int]]): Images scales for resizing. pad_val (dict): Padding value. Defaults to dict(img=0, seg=255). use_mini_pad (bool): Whether using minimum rectangle padding. Defaults to True stretch_only (bool): Whether stretch to the specified size directly. Defaults to False allow_scale_up (bool): Allow scale up when ratio > 1. Defaults to True """ def __init__(self, scale: Union[int, Tuple[int, int]], pad_val: dict = dict(img=0, mask=0, seg=255), use_mini_pad: bool = False, stretch_only: bool = False, allow_scale_up: bool = True, **kwargs): super().__init__(scale=scale, keep_ratio=True, **kwargs) self.pad_val = pad_val if isinstance(pad_val, (int, float)): pad_val = dict(img=pad_val, seg=255) assert isinstance( pad_val, dict), f'pad_val must be dict, but got {type(pad_val)}' self.use_mini_pad = use_mini_pad self.stretch_only = stretch_only self.allow_scale_up = allow_scale_up def _resize_img(self, results: dict): """Resize images with ``results['scale']``.""" image = results.get('img', None) if image is None: return # Use batch_shape if a batch_shape policy is configured if 'batch_shape' in results: scale = tuple(results['batch_shape']) # hw else: scale = self.scale[::-1] # wh -> hw image_shape = image.shape[:2] # height, width # Scale ratio (new / old) ratio = min(scale[0] / image_shape[0], scale[1] / image_shape[1]) # only scale down, do not scale up (for better test mAP) if not self.allow_scale_up: ratio = min(ratio, 1.0) ratio = [ratio, ratio] # float -> (float, float) for (height, width) # compute the best size of the image no_pad_shape = (int(round(image_shape[0] * ratio[0])), int(round(image_shape[1] * ratio[1]))) # padding height & width padding_h, padding_w = [ scale[0] - no_pad_shape[0], scale[1] - no_pad_shape[1] ] if self.use_mini_pad: # minimum rectangle padding padding_w, padding_h = np.mod(padding_w, 32), np.mod(padding_h, 32) elif self.stretch_only: # stretch to the specified size directly padding_h, padding_w = 0.0, 0.0 no_pad_shape = (scale[0], scale[1]) ratio = [scale[0] / image_shape[0], scale[1] / image_shape[1]] # height, width ratios if image_shape != no_pad_shape: # compare with no resize and padding size image = mmcv.imresize( image, (no_pad_shape[1], no_pad_shape[0]), interpolation=self.interpolation, backend=self.backend) scale_factor = (ratio[1], ratio[0]) # mmcv scale factor is (w, h) if 'scale_factor' in results: results['scale_factor_origin'] = results['scale_factor'] results['scale_factor'] = scale_factor # padding top_padding, left_padding = int(round(padding_h // 2 - 0.1)), int( round(padding_w // 2 - 0.1)) bottom_padding = padding_h - top_padding right_padding = padding_w - left_padding padding_list = [ top_padding, bottom_padding, left_padding, right_padding ] if top_padding != 0 or bottom_padding != 0 or \ left_padding != 0 or right_padding != 0: pad_val = self.pad_val.get('img', 0) if isinstance(pad_val, int) and image.ndim == 3: pad_val = tuple(pad_val for _ in range(image.shape[2])) image = mmcv.impad( img=image, padding=(padding_list[2], padding_list[0], padding_list[3], padding_list[1]), pad_val=pad_val, padding_mode='constant') results['img'] = image results['img_shape'] = image.shape if 'pad_param' in results: results['pad_param_origin'] = results['pad_param'] * \ np.repeat(ratio, 2) results['pad_param'] = np.array(padding_list, dtype=np.float32) def _resize_masks(self, results: dict): """Resize masks with ``results['scale']``""" if results.get('gt_masks', None) is None: return gt_masks = results['gt_masks'] assert isinstance( gt_masks, PolygonMasks ), f'Only supports PolygonMasks, but got {type(gt_masks)}' # resize the gt_masks gt_mask_h = results['gt_masks'].height * results['scale_factor'][1] gt_mask_w = results['gt_masks'].width * results['scale_factor'][0] gt_masks = results['gt_masks'].resize( (int(round(gt_mask_h)), int(round(gt_mask_w)))) top_padding, _, left_padding, _ = results['pad_param'] if int(left_padding) != 0: gt_masks = gt_masks.translate( out_shape=results['img_shape'][:2], offset=int(left_padding), direction='horizontal') if int(top_padding) != 0: gt_masks = gt_masks.translate( out_shape=results['img_shape'][:2], offset=int(top_padding), direction='vertical') results['gt_masks'] = gt_masks def _resize_bboxes(self, results: dict): """Resize bounding boxes with ``results['scale_factor']``.""" if results.get('gt_bboxes', None) is None: return results['gt_bboxes'].rescale_(results['scale_factor']) if len(results['pad_param']) != 4: return results['gt_bboxes'].translate_( (results['pad_param'][2], results['pad_param'][0])) if self.clip_object_border: results['gt_bboxes'].clip_(results['img_shape']) def transform(self, results: dict) -> dict: results = super().transform(results) if 'scale_factor_origin' in results: scale_factor_origin = results.pop('scale_factor_origin') results['scale_factor'] = (results['scale_factor'][0] * scale_factor_origin[0], results['scale_factor'][1] * scale_factor_origin[1]) if 'pad_param_origin' in results: pad_param_origin = results.pop('pad_param_origin') results['pad_param'] += pad_param_origin return results # TODO: Check if it can be merged with mmdet.YOLOXHSVRandomAug @TRANSFORMS.register_module() class YOLOv5HSVRandomAug(BaseTransform): """Apply HSV augmentation to image sequentially. Required Keys: - img Modified Keys: - img Args: hue_delta ([int, float]): delta of hue. Defaults to 0.015. saturation_delta ([int, float]): delta of saturation. Defaults to 0.7. value_delta ([int, float]): delta of value. Defaults to 0.4. """ def __init__(self, hue_delta: Union[int, float] = 0.015, saturation_delta: Union[int, float] = 0.7, value_delta: Union[int, float] = 0.4): self.hue_delta = hue_delta self.saturation_delta = saturation_delta self.value_delta = value_delta def transform(self, results: dict) -> dict: """The HSV augmentation transform function. Args: results (dict): The result dict. Returns: dict: The result dict. """ hsv_gains = \ random.uniform(-1, 1, 3) * \ [self.hue_delta, self.saturation_delta, self.value_delta] + 1 hue, sat, val = cv2.split( cv2.cvtColor(results['img'], cv2.COLOR_BGR2HSV)) table_list = np.arange(0, 256, dtype=hsv_gains.dtype) lut_hue = ((table_list * hsv_gains[0]) % 180).astype(np.uint8) lut_sat = np.clip(table_list * hsv_gains[1], 0, 255).astype(np.uint8) lut_val = np.clip(table_list * hsv_gains[2], 0, 255).astype(np.uint8) im_hsv = cv2.merge( (cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) results['img'] = cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR) return results def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(hue_delta={self.hue_delta}, ' repr_str += f'saturation_delta={self.saturation_delta}, ' repr_str += f'value_delta={self.value_delta})' return repr_str @TRANSFORMS.register_module() class LoadAnnotations(MMDET_LoadAnnotations): """Because the yolo series does not need to consider ignore bboxes for the time being, in order to speed up the pipeline, it can be excluded in advance.""" def __init__(self, mask2bbox: bool = False, poly2mask: bool = False, **kwargs) -> None: self.mask2bbox = mask2bbox assert not poly2mask, 'Does not support BitmapMasks considering ' \ 'that bitmap consumes more memory.' super().__init__(poly2mask=poly2mask, **kwargs) if self.mask2bbox: assert self.with_mask, 'Using mask2bbox requires ' \ 'with_mask is True.' self._mask_ignore_flag = None def transform(self, results: dict) -> dict: """Function to load multiple types annotations. Args: results (dict): Result dict from :obj:``mmengine.BaseDataset``. Returns: dict: The dict contains loaded bounding box, label and semantic segmentation. """ if self.mask2bbox: self._load_masks(results) if self.with_label: self._load_labels(results) self._update_mask_ignore_data(results) gt_bboxes = results['gt_masks'].get_bboxes(dst_type='hbox') results['gt_bboxes'] = gt_bboxes else: results = super().transform(results) self._update_mask_ignore_data(results) return results def _update_mask_ignore_data(self, results: dict) -> None: if 'gt_masks' not in results: return if 'gt_bboxes_labels' in results and len( results['gt_bboxes_labels']) != len(results['gt_masks']): assert len(results['gt_bboxes_labels']) == len( self._mask_ignore_flag) results['gt_bboxes_labels'] = results['gt_bboxes_labels'][ self._mask_ignore_flag] if 'gt_bboxes' in results and len(results['gt_bboxes']) != len( results['gt_masks']): assert len(results['gt_bboxes']) == len(self._mask_ignore_flag) results['gt_bboxes'] = results['gt_bboxes'][self._mask_ignore_flag] def _load_bboxes(self, results: dict): """Private function to load bounding box annotations. Note: BBoxes with ignore_flag of 1 is not considered. Args: results (dict): Result dict from :obj:``mmengine.BaseDataset``. Returns: dict: The dict contains loaded bounding box annotations. """ gt_bboxes = [] gt_ignore_flags = [] for instance in results.get('instances', []): if instance['ignore_flag'] == 0: gt_bboxes.append(instance['bbox']) gt_ignore_flags.append(instance['ignore_flag']) results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool) if self.box_type is None: results['gt_bboxes'] = np.array( gt_bboxes, dtype=np.float32).reshape((-1, 4)) else: _, box_type_cls = get_box_type(self.box_type) results['gt_bboxes'] = box_type_cls(gt_bboxes, dtype=torch.float32) def _load_labels(self, results: dict): """Private function to load label annotations. Note: BBoxes with ignore_flag of 1 is not considered. Args: results (dict): Result dict from :obj:``mmengine.BaseDataset``. Returns: dict: The dict contains loaded label annotations. """ gt_bboxes_labels = [] for instance in results.get('instances', []): if instance['ignore_flag'] == 0: gt_bboxes_labels.append(instance['bbox_label']) results['gt_bboxes_labels'] = np.array( gt_bboxes_labels, dtype=np.int64) def _load_masks(self, results: dict) -> None: """Private function to load mask annotations. Args: results (dict): Result dict from :obj:``mmengine.BaseDataset``. """ gt_masks = [] gt_ignore_flags = [] self._mask_ignore_flag = [] for instance in results.get('instances', []): if instance['ignore_flag'] == 0: if 'mask' in instance: gt_mask = instance['mask'] if isinstance(gt_mask, list): gt_mask = [ np.array(polygon) for polygon in gt_mask if len(polygon) % 2 == 0 and len(polygon) >= 6 ] if len(gt_mask) == 0: # ignore self._mask_ignore_flag.append(0) else: gt_masks.append(gt_mask) gt_ignore_flags.append(instance['ignore_flag']) self._mask_ignore_flag.append(1) else: raise NotImplementedError( 'Only supports mask annotations in polygon ' 'format currently') else: # TODO: Actually, gt with bbox and without mask needs # to be retained self._mask_ignore_flag.append(0) self._mask_ignore_flag = np.array(self._mask_ignore_flag, dtype=bool) results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool) h, w = results['ori_shape'] gt_masks = PolygonMasks([mask for mask in gt_masks], h, w) results['gt_masks'] = gt_masks def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(with_bbox={self.with_bbox}, ' repr_str += f'with_label={self.with_label}, ' repr_str += f'with_mask={self.with_mask}, ' repr_str += f'with_seg={self.with_seg}, ' repr_str += f'mask2bbox={self.mask2bbox}, ' repr_str += f'poly2mask={self.poly2mask}, ' repr_str += f"imdecode_backend='{self.imdecode_backend}', " repr_str += f'file_client_args={self.file_client_args})' return repr_str @TRANSFORMS.register_module() class YOLOv5RandomAffine(BaseTransform): """Random affine transform data augmentation in YOLOv5 and YOLOv8. It is different from the implementation in YOLOX. This operation randomly generates affine transform matrix which including rotation, translation, shear and scaling transforms. If you set use_mask_refine == True, the code will use the masks annotation to refine the bbox. Our implementation is slightly different from the official. In COCO dataset, a gt may have multiple mask tags. The official YOLOv5 annotation file already combines the masks that an object has, but our code takes into account the fact that an object has multiple masks. Required Keys: - img - gt_bboxes (BaseBoxes[torch.float32]) (optional) - gt_bboxes_labels (np.int64) (optional) - gt_ignore_flags (bool) (optional) - gt_masks (PolygonMasks) (optional) Modified Keys: - img - img_shape - gt_bboxes (optional) - gt_bboxes_labels (optional) - gt_ignore_flags (optional) - gt_masks (PolygonMasks) (optional) Args: max_rotate_degree (float): Maximum degrees of rotation transform. Defaults to 10. max_translate_ratio (float): Maximum ratio of translation. Defaults to 0.1. scaling_ratio_range (tuple[float]): Min and max ratio of scaling transform. Defaults to (0.5, 1.5). max_shear_degree (float): Maximum degrees of shear transform. Defaults to 2. border (tuple[int]): Distance from width and height sides of input image to adjust output shape. Only used in mosaic dataset. Defaults to (0, 0). border_val (tuple[int]): Border padding values of 3 channels. Defaults to (114, 114, 114). bbox_clip_border (bool, optional): Whether to clip the objects outside the border of the image. In some dataset like MOT17, the gt bboxes are allowed to cross the border of images. Therefore, we don't need to clip the gt bboxes in these cases. Defaults to True. min_bbox_size (float): Width and height threshold to filter bboxes. If the height or width of a box is smaller than this value, it will be removed. Defaults to 2. min_area_ratio (float): Threshold of area ratio between original bboxes and wrapped bboxes. If smaller than this value, the box will be removed. Defaults to 0.1. use_mask_refine (bool): Whether to refine bbox by mask. max_aspect_ratio (float): Aspect ratio of width and height threshold to filter bboxes. If max(h/w, w/h) larger than this value, the box will be removed. Defaults to 20. resample_num (int): Number of poly to resample to. """ def __init__(self, max_rotate_degree: float = 10.0, max_translate_ratio: float = 0.1, scaling_ratio_range: Tuple[float, float] = (0.5, 1.5), max_shear_degree: float = 2.0, border: Tuple[int, int] = (0, 0), border_val: Tuple[int, int, int] = (114, 114, 114), bbox_clip_border: bool = True, min_bbox_size: int = 2, min_area_ratio: float = 0.1, use_mask_refine: bool = False, max_aspect_ratio: float = 20., resample_num: int = 1000): assert 0 <= max_translate_ratio <= 1 assert scaling_ratio_range[0] <= scaling_ratio_range[1] assert scaling_ratio_range[0] > 0 self.max_rotate_degree = max_rotate_degree self.max_translate_ratio = max_translate_ratio self.scaling_ratio_range = scaling_ratio_range self.max_shear_degree = max_shear_degree self.border = border self.border_val = border_val self.bbox_clip_border = bbox_clip_border self.min_bbox_size = min_bbox_size self.min_area_ratio = min_area_ratio self.use_mask_refine = use_mask_refine self.max_aspect_ratio = max_aspect_ratio self.resample_num = resample_num @autocast_box_type() def transform(self, results: dict) -> dict: """The YOLOv5 random affine transform function. Args: results (dict): The result dict. Returns: dict: The result dict. """ img = results['img'] # self.border is wh format height = img.shape[0] + self.border[1] * 2 width = img.shape[1] + self.border[0] * 2 # Note: Different from YOLOX center_matrix = np.eye(3, dtype=np.float32) center_matrix[0, 2] = -img.shape[1] / 2 center_matrix[1, 2] = -img.shape[0] / 2 warp_matrix, scaling_ratio = self._get_random_homography_matrix( height, width) warp_matrix = warp_matrix @ center_matrix img = cv2.warpPerspective( img, warp_matrix, dsize=(width, height), borderValue=self.border_val) results['img'] = img results['img_shape'] = img.shape img_h, img_w = img.shape[:2] bboxes = results['gt_bboxes'] num_bboxes = len(bboxes) if num_bboxes: orig_bboxes = bboxes.clone() if self.use_mask_refine and 'gt_masks' in results: # If the dataset has annotations of mask, # the mask will be used to refine bbox. gt_masks = results['gt_masks'] gt_masks_resample = self.resample_masks(gt_masks) gt_masks = self.warp_mask(gt_masks_resample, warp_matrix, img_h, img_w) # refine bboxes by masks bboxes = gt_masks.get_bboxes(dst_type='hbox') # filter bboxes outside image valid_index = self.filter_gt_bboxes(orig_bboxes, bboxes).numpy() results['gt_masks'] = gt_masks[valid_index] else: bboxes.project_(warp_matrix) if self.bbox_clip_border: bboxes.clip_([height, width]) # filter bboxes orig_bboxes.rescale_([scaling_ratio, scaling_ratio]) # Be careful: valid_index must convert to numpy, # otherwise it will raise out of bounds when len(valid_index)=1 valid_index = self.filter_gt_bboxes(orig_bboxes, bboxes).numpy() if 'gt_masks' in results: results['gt_masks'] = PolygonMasks( results['gt_masks'].masks, img_h, img_w) results['gt_bboxes'] = bboxes[valid_index] results['gt_bboxes_labels'] = results['gt_bboxes_labels'][ valid_index] results['gt_ignore_flags'] = results['gt_ignore_flags'][ valid_index] return results @staticmethod def warp_poly(poly: np.ndarray, warp_matrix: np.ndarray, img_w: int, img_h: int) -> np.ndarray: """Function to warp one mask and filter points outside image. Args: poly (np.ndarray): Segmentation annotation with shape (n, ) and with format (x1, y1, x2, y2, ...). warp_matrix (np.ndarray): Affine transformation matrix. Shape: (3, 3). img_w (int): Width of output image. img_h (int): Height of output image. """ # TODO: Current logic may cause retained masks unusable for # semantic segmentation training, which is same as official # implementation. poly = poly.reshape((-1, 2)) poly = np.concatenate((poly, np.ones( (len(poly), 1), dtype=poly.dtype)), axis=-1) # transform poly poly = poly @ warp_matrix.T poly = poly[:, :2] / poly[:, 2:3] # filter point outside image x, y = poly.T valid_ind_point = (x >= 0) & (y >= 0) & (x <= img_w) & (y <= img_h) return poly[valid_ind_point].reshape(-1) def warp_mask(self, gt_masks: PolygonMasks, warp_matrix: np.ndarray, img_w: int, img_h: int) -> PolygonMasks: """Warp masks by warp_matrix and retain masks inside image after warping. Args: gt_masks (PolygonMasks): Annotations of semantic segmentation. warp_matrix (np.ndarray): Affine transformation matrix. Shape: (3, 3). img_w (int): Width of output image. img_h (int): Height of output image. Returns: PolygonMasks: Masks after warping. """ masks = gt_masks.masks new_masks = [] for poly_per_obj in masks: warpped_poly_per_obj = [] # One gt may have multiple masks. for poly in poly_per_obj: valid_poly = self.warp_poly(poly, warp_matrix, img_w, img_h) if len(valid_poly): warpped_poly_per_obj.append(valid_poly.reshape(-1)) # If all the masks are invalid, # add [0, 0, 0, 0, 0, 0,] here. if not warpped_poly_per_obj: # This will be filtered in function `filter_gt_bboxes`. warpped_poly_per_obj = [ np.zeros(6, dtype=poly_per_obj[0].dtype) ] new_masks.append(warpped_poly_per_obj) gt_masks = PolygonMasks(new_masks, img_h, img_w) return gt_masks def resample_masks(self, gt_masks: PolygonMasks) -> PolygonMasks: """Function to resample each mask annotation with shape (2 * n, ) to shape (resample_num * 2, ). Args: gt_masks (PolygonMasks): Annotations of semantic segmentation. """ masks = gt_masks.masks new_masks = [] for poly_per_obj in masks: resample_poly_per_obj = [] for poly in poly_per_obj: poly = poly.reshape((-1, 2)) # xy poly = np.concatenate((poly, poly[0:1, :]), axis=0) x = np.linspace(0, len(poly) - 1, self.resample_num) xp = np.arange(len(poly)) poly = np.concatenate([ np.interp(x, xp, poly[:, i]) for i in range(2) ]).reshape(2, -1).T.reshape(-1) resample_poly_per_obj.append(poly) new_masks.append(resample_poly_per_obj) return PolygonMasks(new_masks, gt_masks.height, gt_masks.width) def filter_gt_bboxes(self, origin_bboxes: HorizontalBoxes, wrapped_bboxes: HorizontalBoxes) -> torch.Tensor: """Filter gt bboxes. Args: origin_bboxes (HorizontalBoxes): Origin bboxes. wrapped_bboxes (HorizontalBoxes): Wrapped bboxes Returns: dict: The result dict. """ origin_w = origin_bboxes.widths origin_h = origin_bboxes.heights wrapped_w = wrapped_bboxes.widths wrapped_h = wrapped_bboxes.heights aspect_ratio = np.maximum(wrapped_w / (wrapped_h + 1e-16), wrapped_h / (wrapped_w + 1e-16)) wh_valid_idx = (wrapped_w > self.min_bbox_size) & \ (wrapped_h > self.min_bbox_size) area_valid_idx = wrapped_w * wrapped_h / (origin_w * origin_h + 1e-16) > self.min_area_ratio aspect_ratio_valid_idx = aspect_ratio < self.max_aspect_ratio return wh_valid_idx & area_valid_idx & aspect_ratio_valid_idx @cache_randomness def _get_random_homography_matrix(self, height: int, width: int) -> Tuple[np.ndarray, float]: """Get random homography matrix. Args: height (int): Image height. width (int): Image width. Returns: Tuple[np.ndarray, float]: The result of warp_matrix and scaling_ratio. """ # Rotation rotation_degree = random.uniform(-self.max_rotate_degree, self.max_rotate_degree) rotation_matrix = self._get_rotation_matrix(rotation_degree) # Scaling scaling_ratio = random.uniform(self.scaling_ratio_range[0], self.scaling_ratio_range[1]) scaling_matrix = self._get_scaling_matrix(scaling_ratio) # Shear x_degree = random.uniform(-self.max_shear_degree, self.max_shear_degree) y_degree = random.uniform(-self.max_shear_degree, self.max_shear_degree) shear_matrix = self._get_shear_matrix(x_degree, y_degree) # Translation trans_x = random.uniform(0.5 - self.max_translate_ratio, 0.5 + self.max_translate_ratio) * width trans_y = random.uniform(0.5 - self.max_translate_ratio, 0.5 + self.max_translate_ratio) * height translate_matrix = self._get_translation_matrix(trans_x, trans_y) warp_matrix = ( translate_matrix @ shear_matrix @ rotation_matrix @ scaling_matrix) return warp_matrix, scaling_ratio @staticmethod def _get_rotation_matrix(rotate_degrees: float) -> np.ndarray: """Get rotation matrix. Args: rotate_degrees (float): Rotate degrees. Returns: np.ndarray: The rotation matrix. """ radian = math.radians(rotate_degrees) rotation_matrix = np.array( [[np.cos(radian), -np.sin(radian), 0.], [np.sin(radian), np.cos(radian), 0.], [0., 0., 1.]], dtype=np.float32) return rotation_matrix @staticmethod def _get_scaling_matrix(scale_ratio: float) -> np.ndarray: """Get scaling matrix. Args: scale_ratio (float): Scale ratio. Returns: np.ndarray: The scaling matrix. """ scaling_matrix = np.array( [[scale_ratio, 0., 0.], [0., scale_ratio, 0.], [0., 0., 1.]], dtype=np.float32) return scaling_matrix @staticmethod def _get_shear_matrix(x_shear_degrees: float, y_shear_degrees: float) -> np.ndarray: """Get shear matrix. Args: x_shear_degrees (float): X shear degrees. y_shear_degrees (float): Y shear degrees. Returns: np.ndarray: The shear matrix. """ x_radian = math.radians(x_shear_degrees) y_radian = math.radians(y_shear_degrees) shear_matrix = np.array([[1, np.tan(x_radian), 0.], [np.tan(y_radian), 1, 0.], [0., 0., 1.]], dtype=np.float32) return shear_matrix @staticmethod def _get_translation_matrix(x: float, y: float) -> np.ndarray: """Get translation matrix. Args: x (float): X translation. y (float): Y translation. Returns: np.ndarray: The translation matrix. """ translation_matrix = np.array([[1, 0., x], [0., 1, y], [0., 0., 1.]], dtype=np.float32) return translation_matrix def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(max_rotate_degree={self.max_rotate_degree}, ' repr_str += f'max_translate_ratio={self.max_translate_ratio}, ' repr_str += f'scaling_ratio_range={self.scaling_ratio_range}, ' repr_str += f'max_shear_degree={self.max_shear_degree}, ' repr_str += f'border={self.border}, ' repr_str += f'border_val={self.border_val}, ' repr_str += f'bbox_clip_border={self.bbox_clip_border})' return repr_str @TRANSFORMS.register_module() class PPYOLOERandomDistort(BaseTransform): """Random hue, saturation, contrast and brightness distortion. Required Keys: - img Modified Keys: - img (np.float32) Args: hue_cfg (dict): Hue settings. Defaults to dict(min=-18, max=18, prob=0.5). saturation_cfg (dict): Saturation settings. Defaults to dict( min=0.5, max=1.5, prob=0.5). contrast_cfg (dict): Contrast settings. Defaults to dict( min=0.5, max=1.5, prob=0.5). brightness_cfg (dict): Brightness settings. Defaults to dict( min=0.5, max=1.5, prob=0.5). num_distort_func (int): The number of distort function. Defaults to 4. """ def __init__(self, hue_cfg: dict = dict(min=-18, max=18, prob=0.5), saturation_cfg: dict = dict(min=0.5, max=1.5, prob=0.5), contrast_cfg: dict = dict(min=0.5, max=1.5, prob=0.5), brightness_cfg: dict = dict(min=0.5, max=1.5, prob=0.5), num_distort_func: int = 4): self.hue_cfg = hue_cfg self.saturation_cfg = saturation_cfg self.contrast_cfg = contrast_cfg self.brightness_cfg = brightness_cfg self.num_distort_func = num_distort_func assert 0 < self.num_distort_func <= 4, \ 'num_distort_func must > 0 and <= 4' for cfg in [ self.hue_cfg, self.saturation_cfg, self.contrast_cfg, self.brightness_cfg ]: assert 0. <= cfg['prob'] <= 1., 'prob must >=0 and <=1' def transform_hue(self, results): """Transform hue randomly.""" if random.uniform(0., 1.) >= self.hue_cfg['prob']: return results img = results['img'] delta = random.uniform(self.hue_cfg['min'], self.hue_cfg['max']) u = np.cos(delta * np.pi) w = np.sin(delta * np.pi) delta_iq = np.array([[1.0, 0.0, 0.0], [0.0, u, -w], [0.0, w, u]]) rgb2yiq_matrix = np.array([[0.114, 0.587, 0.299], [-0.321, -0.274, 0.596], [0.311, -0.523, 0.211]]) yiq2rgb_matric = np.array([[1.0, -1.107, 1.705], [1.0, -0.272, -0.647], [1.0, 0.956, 0.621]]) t = np.dot(np.dot(yiq2rgb_matric, delta_iq), rgb2yiq_matrix).T img = np.dot(img, t) results['img'] = img return results def transform_saturation(self, results): """Transform saturation randomly.""" if random.uniform(0., 1.) >= self.saturation_cfg['prob']: return results img = results['img'] delta = random.uniform(self.saturation_cfg['min'], self.saturation_cfg['max']) # convert bgr img to gray img gray = img * np.array([[[0.114, 0.587, 0.299]]], dtype=np.float32) gray = gray.sum(axis=2, keepdims=True) gray *= (1.0 - delta) img *= delta img += gray results['img'] = img return results def transform_contrast(self, results): """Transform contrast randomly.""" if random.uniform(0., 1.) >= self.contrast_cfg['prob']: return results img = results['img'] delta = random.uniform(self.contrast_cfg['min'], self.contrast_cfg['max']) img *= delta results['img'] = img return results def transform_brightness(self, results): """Transform brightness randomly.""" if random.uniform(0., 1.) >= self.brightness_cfg['prob']: return results img = results['img'] delta = random.uniform(self.brightness_cfg['min'], self.brightness_cfg['max']) img += delta results['img'] = img return results def transform(self, results: dict) -> dict: """The hue, saturation, contrast and brightness distortion function. Args: results (dict): The result dict. Returns: dict: The result dict. """ results['img'] = results['img'].astype(np.float32) functions = [ self.transform_brightness, self.transform_contrast, self.transform_saturation, self.transform_hue ] distortions = random.permutation(functions)[:self.num_distort_func] for func in distortions: results = func(results) return results def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(hue_cfg={self.hue_cfg}, ' repr_str += f'saturation_cfg={self.saturation_cfg}, ' repr_str += f'contrast_cfg={self.contrast_cfg}, ' repr_str += f'brightness_cfg={self.brightness_cfg}, ' repr_str += f'num_distort_func={self.num_distort_func})' return repr_str @TRANSFORMS.register_module() class PPYOLOERandomCrop(BaseTransform): """Random crop the img and bboxes. Different thresholds are used in PPYOLOE to judge whether the clipped image meets the requirements. This implementation is different from the implementation of RandomCrop in mmdet. Required Keys: - img - gt_bboxes (BaseBoxes[torch.float32]) (optional) - gt_bboxes_labels (np.int64) (optional) - gt_ignore_flags (bool) (optional) Modified Keys: - img - img_shape - gt_bboxes (optional) - gt_bboxes_labels (optional) - gt_ignore_flags (optional) Added Keys: - pad_param (np.float32) Args: aspect_ratio (List[float]): Aspect ratio of cropped region. Default to [.5, 2]. thresholds (List[float]): Iou thresholds for deciding a valid bbox crop in [min, max] format. Defaults to [.0, .1, .3, .5, .7, .9]. scaling (List[float]): Ratio between a cropped region and the original image in [min, max] format. Default to [.3, 1.]. num_attempts (int): Number of tries for each threshold before giving up. Default to 50. allow_no_crop (bool): Allow return without actually cropping them. Default to True. cover_all_box (bool): Ensure all bboxes are covered in the final crop. Default to False. """ def __init__(self, aspect_ratio: List[float] = [.5, 2.], thresholds: List[float] = [.0, .1, .3, .5, .7, .9], scaling: List[float] = [.3, 1.], num_attempts: int = 50, allow_no_crop: bool = True, cover_all_box: bool = False): self.aspect_ratio = aspect_ratio self.thresholds = thresholds self.scaling = scaling self.num_attempts = num_attempts self.allow_no_crop = allow_no_crop self.cover_all_box = cover_all_box def _crop_data(self, results: dict, crop_box: Tuple[int, int, int, int], valid_inds: np.ndarray) -> Union[dict, None]: """Function to randomly crop images, bounding boxes, masks, semantic segmentation maps. Args: results (dict): Result dict from loading pipeline. crop_box (Tuple[int, int, int, int]): Expected absolute coordinates for cropping, (x1, y1, x2, y2). valid_inds (np.ndarray): The indexes of gt that needs to be retained. Returns: results (Union[dict, None]): Randomly cropped results, 'img_shape' key in result dict is updated according to crop size. None will be returned when there is no valid bbox after cropping. """ # crop the image img = results['img'] crop_x1, crop_y1, crop_x2, crop_y2 = crop_box img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...] results['img'] = img img_shape = img.shape results['img_shape'] = img.shape # crop bboxes accordingly and clip to the image boundary if results.get('gt_bboxes', None) is not None: bboxes = results['gt_bboxes'] bboxes.translate_([-crop_x1, -crop_y1]) bboxes.clip_(img_shape[:2]) results['gt_bboxes'] = bboxes[valid_inds] if results.get('gt_ignore_flags', None) is not None: results['gt_ignore_flags'] = \ results['gt_ignore_flags'][valid_inds] if results.get('gt_bboxes_labels', None) is not None: results['gt_bboxes_labels'] = \ results['gt_bboxes_labels'][valid_inds] if results.get('gt_masks', None) is not None: results['gt_masks'] = results['gt_masks'][ valid_inds.nonzero()[0]].crop( np.asarray([crop_x1, crop_y1, crop_x2, crop_y2])) # crop semantic seg if results.get('gt_seg_map', None) is not None: results['gt_seg_map'] = results['gt_seg_map'][crop_y1:crop_y2, crop_x1:crop_x2] return results @autocast_box_type() def transform(self, results: dict) -> Union[dict, None]: """The random crop transform function. Args: results (dict): The result dict. Returns: dict: The result dict. """ if results.get('gt_bboxes', None) is None or len( results['gt_bboxes']) == 0: return results orig_img_h, orig_img_w = results['img'].shape[:2] gt_bboxes = results['gt_bboxes'] thresholds = list(self.thresholds) if self.allow_no_crop: thresholds.append('no_crop') random.shuffle(thresholds) for thresh in thresholds: # Determine the coordinates for cropping if thresh == 'no_crop': return results found = False for i in range(self.num_attempts): crop_h, crop_w = self._get_crop_size((orig_img_h, orig_img_w)) if self.aspect_ratio is None: if crop_h / crop_w < 0.5 or crop_h / crop_w > 2.0: continue # get image crop_box margin_h = max(orig_img_h - crop_h, 0) margin_w = max(orig_img_w - crop_w, 0) offset_h, offset_w = self._rand_offset((margin_h, margin_w)) crop_y1, crop_y2 = offset_h, offset_h + crop_h crop_x1, crop_x2 = offset_w, offset_w + crop_w crop_box = [crop_x1, crop_y1, crop_x2, crop_y2] # Calculate the iou between gt_bboxes and crop_boxes iou = self._iou_matrix(gt_bboxes, np.array([crop_box], dtype=np.float32)) # If the maximum value of the iou is less than thresh, # the current crop_box is considered invalid. if iou.max() < thresh: continue # If cover_all_box == True and the minimum value of # the iou is less than thresh, the current crop_box # is considered invalid. if self.cover_all_box and iou.min() < thresh: continue # Get which gt_bboxes to keep after cropping. valid_inds = self._get_valid_inds( gt_bboxes, np.array(crop_box, dtype=np.float32)) if valid_inds.size > 0: found = True break if found: results = self._crop_data(results, crop_box, valid_inds) return results return results @cache_randomness def _rand_offset(self, margin: Tuple[int, int]) -> Tuple[int, int]: """Randomly generate crop offset. Args: margin (Tuple[int, int]): The upper bound for the offset generated randomly. Returns: Tuple[int, int]: The random offset for the crop. """ margin_h, margin_w = margin offset_h = np.random.randint(0, margin_h + 1) offset_w = np.random.randint(0, margin_w + 1) return (offset_h, offset_w) @cache_randomness def _get_crop_size(self, image_size: Tuple[int, int]) -> Tuple[int, int]: """Randomly generates the crop size based on `image_size`. Args: image_size (Tuple[int, int]): (h, w). Returns: crop_size (Tuple[int, int]): (crop_h, crop_w) in absolute pixels. """ h, w = image_size scale = random.uniform(*self.scaling) if self.aspect_ratio is not None: min_ar, max_ar = self.aspect_ratio aspect_ratio = random.uniform( max(min_ar, scale**2), min(max_ar, scale**-2)) h_scale = scale / np.sqrt(aspect_ratio) w_scale = scale * np.sqrt(aspect_ratio) else: h_scale = random.uniform(*self.scaling) w_scale = random.uniform(*self.scaling) crop_h = h * h_scale crop_w = w * w_scale return int(crop_h), int(crop_w) def _iou_matrix(self, gt_bbox: HorizontalBoxes, crop_bbox: np.ndarray, eps: float = 1e-10) -> np.ndarray: """Calculate iou between gt and image crop box. Args: gt_bbox (HorizontalBoxes): Ground truth bounding boxes. crop_bbox (np.ndarray): Image crop coordinates in [x1, y1, x2, y2] format. eps (float): Default to 1e-10. Return: (np.ndarray): IoU. """ gt_bbox = gt_bbox.tensor.numpy() lefttop = np.maximum(gt_bbox[:, np.newaxis, :2], crop_bbox[:, :2]) rightbottom = np.minimum(gt_bbox[:, np.newaxis, 2:], crop_bbox[:, 2:]) overlap = np.prod( rightbottom - lefttop, axis=2) * (lefttop < rightbottom).all(axis=2) area_gt_bbox = np.prod(gt_bbox[:, 2:] - crop_bbox[:, :2], axis=1) area_crop_bbox = np.prod(gt_bbox[:, 2:] - crop_bbox[:, :2], axis=1) area_o = (area_gt_bbox[:, np.newaxis] + area_crop_bbox - overlap) return overlap / (area_o + eps) def _get_valid_inds(self, gt_bbox: HorizontalBoxes, img_crop_bbox: np.ndarray) -> np.ndarray: """Get which Bboxes to keep at the current cropping coordinates. Args: gt_bbox (HorizontalBoxes): Ground truth bounding boxes. img_crop_bbox (np.ndarray): Image crop coordinates in [x1, y1, x2, y2] format. Returns: (np.ndarray): Valid indexes. """ cropped_box = gt_bbox.tensor.numpy().copy() gt_bbox = gt_bbox.tensor.numpy().copy() cropped_box[:, :2] = np.maximum(gt_bbox[:, :2], img_crop_bbox[:2]) cropped_box[:, 2:] = np.minimum(gt_bbox[:, 2:], img_crop_bbox[2:]) cropped_box[:, :2] -= img_crop_bbox[:2] cropped_box[:, 2:] -= img_crop_bbox[:2] centers = (gt_bbox[:, :2] + gt_bbox[:, 2:]) / 2 valid = np.logical_and(img_crop_bbox[:2] <= centers, centers < img_crop_bbox[2:]).all(axis=1) valid = np.logical_and( valid, (cropped_box[:, :2] < cropped_box[:, 2:]).all(axis=1)) return np.where(valid)[0] def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(aspect_ratio={self.aspect_ratio}, ' repr_str += f'thresholds={self.thresholds}, ' repr_str += f'scaling={self.scaling}, ' repr_str += f'num_attempts={self.num_attempts}, ' repr_str += f'allow_no_crop={self.allow_no_crop}, ' repr_str += f'cover_all_box={self.cover_all_box})' return repr_str @TRANSFORMS.register_module() class YOLOv5CopyPaste(BaseTransform): """Copy-Paste used in YOLOv5 and YOLOv8. This transform randomly copy some objects in the image to the mirror position of the image.It is different from the `CopyPaste` in mmdet. Required Keys: - img (np.uint8) - gt_bboxes (BaseBoxes[torch.float32]) - gt_bboxes_labels (np.int64) (optional) - gt_ignore_flags (bool) (optional) - gt_masks (PolygonMasks) (optional) Modified Keys: - img - gt_bboxes - gt_bboxes_labels (np.int64) (optional) - gt_ignore_flags (optional) - gt_masks (optional) Args: ioa_thresh (float): Ioa thresholds for deciding valid bbox. prob (float): Probability of choosing objects. Defaults to 0.5. """ def __init__(self, ioa_thresh: float = 0.3, prob: float = 0.5): self.ioa_thresh = ioa_thresh self.prob = prob @autocast_box_type() def transform(self, results: dict) -> Union[dict, None]: """The YOLOv5 and YOLOv8 Copy-Paste transform function. Args: results (dict): The result dict. Returns: dict: The result dict. """ if len(results.get('gt_masks', [])) == 0: return results gt_masks = results['gt_masks'] assert isinstance(gt_masks, PolygonMasks),\ 'only support type of PolygonMasks,' \ ' but get type: %s' % type(gt_masks) gt_bboxes = results['gt_bboxes'] gt_bboxes_labels = results.get('gt_bboxes_labels', None) img = results['img'] img_h, img_w = img.shape[:2] # calculate ioa gt_bboxes_flip = deepcopy(gt_bboxes) gt_bboxes_flip.flip_(img.shape) ioa = self.bbox_ioa(gt_bboxes_flip, gt_bboxes) indexes = torch.nonzero((ioa < self.ioa_thresh).all(1))[:, 0] n = len(indexes) valid_inds = random.choice( indexes, size=round(self.prob * n), replace=False) if len(valid_inds) == 0: return results if gt_bboxes_labels is not None: # prepare labels gt_bboxes_labels = np.concatenate( (gt_bboxes_labels, gt_bboxes_labels[valid_inds]), axis=0) # prepare bboxes copypaste_bboxes = gt_bboxes_flip[valid_inds] gt_bboxes = gt_bboxes.cat([gt_bboxes, copypaste_bboxes]) # prepare images copypaste_gt_masks = gt_masks[valid_inds] copypaste_gt_masks_flip = copypaste_gt_masks.flip() # convert poly format to bitmap format # example: poly: [[array(0.0, 0.0, 10.0, 0.0, 10.0, 10.0, 0.0, 10.0]] # -> bitmap: a mask with shape equal to (1, img_h, img_w) # # type1 low speed # copypaste_gt_masks_bitmap = copypaste_gt_masks.to_ndarray() # copypaste_mask = np.sum(copypaste_gt_masks_bitmap, axis=0) > 0 # type2 copypaste_mask = np.zeros((img_h, img_w), dtype=np.uint8) for poly in copypaste_gt_masks.masks: poly = [i.reshape((-1, 1, 2)).astype(np.int32) for i in poly] cv2.drawContours(copypaste_mask, poly, -1, (1, ), cv2.FILLED) copypaste_mask = copypaste_mask.astype(bool) # copy objects, and paste to the mirror position of the image copypaste_mask_flip = mmcv.imflip( copypaste_mask, direction='horizontal') copypaste_img = mmcv.imflip(img, direction='horizontal') img[copypaste_mask_flip] = copypaste_img[copypaste_mask_flip] # prepare masks gt_masks = copypaste_gt_masks.cat([gt_masks, copypaste_gt_masks_flip]) if 'gt_ignore_flags' in results: # prepare gt_ignore_flags gt_ignore_flags = results['gt_ignore_flags'] gt_ignore_flags = np.concatenate( [gt_ignore_flags, gt_ignore_flags[valid_inds]], axis=0) results['gt_ignore_flags'] = gt_ignore_flags results['img'] = img results['gt_bboxes'] = gt_bboxes if gt_bboxes_labels is not None: results['gt_bboxes_labels'] = gt_bboxes_labels results['gt_masks'] = gt_masks return results @staticmethod def bbox_ioa(gt_bboxes_flip: HorizontalBoxes, gt_bboxes: HorizontalBoxes, eps: float = 1e-7) -> np.ndarray: """Calculate ioa between gt_bboxes_flip and gt_bboxes. Args: gt_bboxes_flip (HorizontalBoxes): Flipped ground truth bounding boxes. gt_bboxes (HorizontalBoxes): Ground truth bounding boxes. eps (float): Default to 1e-10. Return: (Tensor): Ioa. """ gt_bboxes_flip = gt_bboxes_flip.tensor gt_bboxes = gt_bboxes.tensor # Get the coordinates of bounding boxes b1_x1, b1_y1, b1_x2, b1_y2 = gt_bboxes_flip.T b2_x1, b2_y1, b2_x2, b2_y2 = gt_bboxes.T # Intersection area inter_area = (torch.minimum(b1_x2[:, None], b2_x2) - torch.maximum(b1_x1[:, None], b2_x1)).clip(0) * \ (torch.minimum(b1_y2[:, None], b2_y2) - torch.maximum(b1_y1[:, None], b2_y1)).clip(0) # box2 area box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps # Intersection over box2 area return inter_area / box2_area def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(ioa_thresh={self.ioa_thresh},' repr_str += f'prob={self.prob})' return repr_str @TRANSFORMS.register_module() class RemoveDataElement(BaseTransform): """Remove unnecessary data element in results. Args: keys (Union[str, Sequence[str]]): Keys need to be removed. """ def __init__(self, keys: Union[str, Sequence[str]]): self.keys = [keys] if isinstance(keys, str) else keys def transform(self, results: dict) -> dict: for key in self.keys: results.pop(key, None) return results def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(keys={self.keys})' return repr_str @TRANSFORMS.register_module() class RegularizeRotatedBox(BaseTransform): """Regularize rotated boxes. Due to the angle periodicity, one rotated box can be represented in many different (x, y, w, h, t). To make each rotated box unique, ``regularize_boxes`` will take the remainder of the angle divided by 180 degrees. For convenience, three angle_version can be used here: - 'oc': OpenCV Definition. Has the same box representation as ``cv2.minAreaRect`` the angle ranges in [-90, 0). - 'le90': Long Edge Definition (90). the angle ranges in [-90, 90). The width is always longer than the height. - 'le135': Long Edge Definition (135). the angle ranges in [-45, 135). The width is always longer than the height. Required Keys: - gt_bboxes (RotatedBoxes[torch.float32]) Modified Keys: - gt_bboxes Args: angle_version (str): Angle version. Can only be 'oc', 'le90', or 'le135'. Defaults to 'le90. """ def __init__(self, angle_version='le90') -> None: self.angle_version = angle_version try: from mmrotate.structures.bbox import RotatedBoxes self.box_type = RotatedBoxes except ImportError: raise ImportError( 'Please run "mim install -r requirements/mmrotate.txt" ' 'to install mmrotate first for rotated detection.') def transform(self, results: dict) -> dict: assert isinstance(results['gt_bboxes'], self.box_type) results['gt_bboxes'] = self.box_type( results['gt_bboxes'].regularize_boxes(self.angle_version)) return results
59,261
37.037227
79
py
mmyolo
mmyolo-main/mmyolo/deploy/object_detection.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Callable, Dict, Optional import torch from mmdeploy.codebase.base import CODEBASE, MMCodebase from mmdeploy.codebase.mmdet.deploy import ObjectDetection from mmdeploy.utils import Codebase, Task from mmengine import Config from mmengine.registry import Registry MMYOLO_TASK = Registry('mmyolo_tasks') @CODEBASE.register_module(Codebase.MMYOLO.value) class MMYOLO(MMCodebase): """MMYOLO codebase class.""" task_registry = MMYOLO_TASK @classmethod def register_deploy_modules(cls): """register all rewriters for mmdet.""" import mmdeploy.codebase.mmdet.models # noqa: F401 import mmdeploy.codebase.mmdet.ops # noqa: F401 import mmdeploy.codebase.mmdet.structures # noqa: F401 @classmethod def register_all_modules(cls): """register all modules.""" from mmdet.utils.setup_env import \ register_all_modules as register_all_modules_mmdet from mmyolo.utils.setup_env import \ register_all_modules as register_all_modules_mmyolo cls.register_deploy_modules() register_all_modules_mmyolo(True) register_all_modules_mmdet(False) def _get_dataset_metainfo(model_cfg: Config): """Get metainfo of dataset. Args: model_cfg Config: Input model Config object. Returns: list[str]: A list of string specifying names of different class. """ from mmyolo import datasets # noqa from mmyolo.registry import DATASETS module_dict = DATASETS.module_dict for dataloader_name in [ 'test_dataloader', 'val_dataloader', 'train_dataloader' ]: if dataloader_name not in model_cfg: continue dataloader_cfg = model_cfg[dataloader_name] dataset_cfg = dataloader_cfg.dataset dataset_cls = module_dict.get(dataset_cfg.type, None) if dataset_cls is None: continue if hasattr(dataset_cls, '_load_metainfo') and isinstance( dataset_cls._load_metainfo, Callable): meta = dataset_cls._load_metainfo( dataset_cfg.get('metainfo', None)) if meta is not None: return meta if hasattr(dataset_cls, 'METAINFO'): return dataset_cls.METAINFO return None @MMYOLO_TASK.register_module(Task.OBJECT_DETECTION.value) class YOLOObjectDetection(ObjectDetection): """YOLO Object Detection task.""" def get_visualizer(self, name: str, save_dir: str): """Get visualizer. Args: name (str): Name of visualizer. save_dir (str): Directory to save visualization results. Returns: Visualizer: A visualizer instance. """ from mmdet.visualization import DetLocalVisualizer # noqa: F401,F403 metainfo = _get_dataset_metainfo(self.model_cfg) visualizer = super().get_visualizer(name, save_dir) if metainfo is not None: visualizer.dataset_meta = metainfo return visualizer def build_pytorch_model(self, model_checkpoint: Optional[str] = None, cfg_options: Optional[Dict] = None, **kwargs) -> torch.nn.Module: """Initialize torch model. Args: model_checkpoint (str): The checkpoint file of torch model, defaults to `None`. cfg_options (dict): Optional config key-pair parameters. Returns: nn.Module: An initialized torch model generated by other OpenMMLab codebases. """ from copy import deepcopy from mmengine.model import revert_sync_batchnorm from mmengine.registry import MODELS from mmyolo.utils import switch_to_deploy model = deepcopy(self.model_cfg.model) preprocess_cfg = deepcopy(self.model_cfg.get('preprocess_cfg', {})) preprocess_cfg.update( deepcopy(self.model_cfg.get('data_preprocessor', {}))) model.setdefault('data_preprocessor', preprocess_cfg) model = MODELS.build(model) if model_checkpoint is not None: from mmengine.runner.checkpoint import load_checkpoint load_checkpoint(model, model_checkpoint, map_location=self.device) model = revert_sync_batchnorm(model) switch_to_deploy(model) model = model.to(self.device) model.eval() return model
4,523
33.015038
78
py
mmyolo
mmyolo-main/mmyolo/deploy/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from mmdeploy.codebase.base import MMCodebase from .models import * # noqa: F401,F403 from .object_detection import MMYOLO, YOLOObjectDetection __all__ = ['MMCodebase', 'MMYOLO', 'YOLOObjectDetection']
253
30.75
57
py
mmyolo
mmyolo-main/mmyolo/deploy/models/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from . import dense_heads # noqa: F401,F403
93
30.333333
47
py
mmyolo
mmyolo-main/mmyolo/deploy/models/layers/bbox_nms.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmdeploy.core import mark from torch import Tensor def _efficient_nms( boxes: Tensor, scores: Tensor, max_output_boxes_per_class: int = 1000, iou_threshold: float = 0.5, score_threshold: float = 0.05, pre_top_k: int = -1, keep_top_k: int = 100, box_coding: int = 0, ): """Wrapper for `efficient_nms` with TensorRT. Args: boxes (Tensor): The bounding boxes of shape [N, num_boxes, 4]. scores (Tensor): The detection scores of shape [N, num_boxes, num_classes]. max_output_boxes_per_class (int): Maximum number of output boxes per class of nms. Defaults to 1000. iou_threshold (float): IOU threshold of nms. Defaults to 0.5. score_threshold (float): score threshold of nms. Defaults to 0.05. pre_top_k (int): Number of top K boxes to keep before nms. Defaults to -1. keep_top_k (int): Number of top K boxes to keep after nms. Defaults to -1. box_coding (int): Bounding boxes format for nms. Defaults to 0 means [x, y, w, h]. Set to 1 means [x1, y1 ,x2, y2]. Returns: tuple[Tensor, Tensor]: (dets, labels), `dets` of shape [N, num_det, 5] and `labels` of shape [N, num_det]. """ boxes = boxes if boxes.dim() == 4 else boxes.unsqueeze(2) _, det_boxes, det_scores, labels = TRTEfficientNMSop.apply( boxes, scores, -1, box_coding, iou_threshold, keep_top_k, '1', 0, score_threshold) dets = torch.cat([det_boxes, det_scores.unsqueeze(2)], -1) # retain shape info batch_size = boxes.size(0) dets_shape = dets.shape label_shape = labels.shape dets = dets.reshape([batch_size, *dets_shape[1:]]) labels = labels.reshape([batch_size, *label_shape[1:]]) return dets, labels @mark('efficient_nms', inputs=['boxes', 'scores'], outputs=['dets', 'labels']) def efficient_nms(*args, **kwargs): """Wrapper function for `_efficient_nms`.""" return _efficient_nms(*args, **kwargs) class TRTEfficientNMSop(torch.autograd.Function): """Efficient NMS op for TensorRT.""" @staticmethod def forward( ctx, boxes, scores, background_class=-1, box_coding=0, iou_threshold=0.45, max_output_boxes=100, plugin_version='1', score_activation=0, score_threshold=0.25, ): """Forward function of TRTEfficientNMSop.""" batch_size, num_boxes, num_classes = scores.shape num_det = torch.randint( 0, max_output_boxes, (batch_size, 1), dtype=torch.int32) det_boxes = torch.randn(batch_size, max_output_boxes, 4) det_scores = torch.randn(batch_size, max_output_boxes) det_classes = torch.randint( 0, num_classes, (batch_size, max_output_boxes), dtype=torch.int32) return num_det, det_boxes, det_scores, det_classes @staticmethod def symbolic(g, boxes, scores, background_class=-1, box_coding=0, iou_threshold=0.45, max_output_boxes=100, plugin_version='1', score_activation=0, score_threshold=0.25): """Symbolic function of TRTEfficientNMSop.""" out = g.op( 'TRT::EfficientNMS_TRT', boxes, scores, background_class_i=background_class, box_coding_i=box_coding, iou_threshold_f=iou_threshold, max_output_boxes_i=max_output_boxes, plugin_version_s=plugin_version, score_activation_i=score_activation, score_threshold_f=score_threshold, outputs=4) nums, boxes, scores, classes = out return nums, boxes, scores, classes
3,931
33.491228
78
py
mmyolo
mmyolo-main/mmyolo/deploy/models/layers/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from .bbox_nms import efficient_nms __all__ = ['efficient_nms']
113
21.8
47
py
mmyolo
mmyolo-main/mmyolo/deploy/models/dense_heads/yolov5_head.py
# Copyright (c) OpenMMLab. All rights reserved. import copy from functools import partial from typing import List, Optional, Tuple import torch from mmdeploy.codebase.mmdet import get_post_processing_params from mmdeploy.codebase.mmdet.models.layers import multiclass_nms from mmdeploy.core import FUNCTION_REWRITER from mmengine.config import ConfigDict from mmengine.structures import InstanceData from torch import Tensor from mmyolo.deploy.models.layers import efficient_nms from mmyolo.models.dense_heads import YOLOv5Head def yolov5_bbox_decoder(priors: Tensor, bbox_preds: Tensor, stride: int) -> Tensor: """Decode YOLOv5 bounding boxes. Args: priors (Tensor): Prior boxes in center-offset form. bbox_preds (Tensor): Predicted bounding boxes. stride (int): Stride of the feature map. Returns: Tensor: Decoded bounding boxes. """ bbox_preds = bbox_preds.sigmoid() x_center = (priors[..., 0] + priors[..., 2]) * 0.5 y_center = (priors[..., 1] + priors[..., 3]) * 0.5 w = priors[..., 2] - priors[..., 0] h = priors[..., 3] - priors[..., 1] x_center_pred = (bbox_preds[..., 0] - 0.5) * 2 * stride + x_center y_center_pred = (bbox_preds[..., 1] - 0.5) * 2 * stride + y_center w_pred = (bbox_preds[..., 2] * 2)**2 * w h_pred = (bbox_preds[..., 3] * 2)**2 * h decoded_bboxes = torch.stack( [x_center_pred, y_center_pred, w_pred, h_pred], dim=-1) return decoded_bboxes @FUNCTION_REWRITER.register_rewriter( func_name='mmyolo.models.dense_heads.yolov5_head.' 'YOLOv5Head.predict_by_feat') def yolov5_head__predict_by_feat(self, cls_scores: List[Tensor], bbox_preds: List[Tensor], objectnesses: Optional[List[Tensor]] = None, batch_img_metas: Optional[List[dict]] = None, cfg: Optional[ConfigDict] = None, rescale: bool = False, with_nms: bool = True) -> Tuple[InstanceData]: """Transform a batch of output features extracted by the head into bbox results. Args: cls_scores (list[Tensor]): Classification scores for all scale levels, each is a 4D-tensor, has shape (batch_size, num_priors * num_classes, H, W). bbox_preds (list[Tensor]): Box energies / deltas for all scale levels, each is a 4D-tensor, has shape (batch_size, num_priors * 4, H, W). objectnesses (list[Tensor], Optional): Score factor for all scale level, each is a 4D-tensor, has shape (batch_size, 1, H, W). batch_img_metas (list[dict], Optional): Batch image meta info. Defaults to None. cfg (ConfigDict, optional): Test / postprocessing configuration, if None, test_cfg would be used. Defaults to None. rescale (bool): If True, return boxes in original image space. Defaults to False. with_nms (bool): If True, do nms before return boxes. Defaults to True. Returns: tuple[Tensor, Tensor]: The first item is an (N, num_box, 5) tensor, where 5 represent (tl_x, tl_y, br_x, br_y, score), N is batch size and the score between 0 and 1. The shape of the second tensor in the tuple is (N, num_box), and each element represents the class label of the corresponding box. """ ctx = FUNCTION_REWRITER.get_context() detector_type = type(self) deploy_cfg = ctx.cfg use_efficientnms = deploy_cfg.get('use_efficientnms', False) dtype = cls_scores[0].dtype device = cls_scores[0].device bbox_decoder = self.bbox_coder.decode nms_func = multiclass_nms if use_efficientnms: if detector_type is YOLOv5Head: nms_func = partial(efficient_nms, box_coding=0) bbox_decoder = yolov5_bbox_decoder else: nms_func = efficient_nms assert len(cls_scores) == len(bbox_preds) cfg = self.test_cfg if cfg is None else cfg cfg = copy.deepcopy(cfg) num_imgs = cls_scores[0].shape[0] featmap_sizes = [cls_score.shape[2:] for cls_score in cls_scores] mlvl_priors = self.prior_generator.grid_priors( featmap_sizes, dtype=dtype, device=device) flatten_priors = torch.cat(mlvl_priors) mlvl_strides = [ flatten_priors.new_full( (featmap_size[0] * featmap_size[1] * self.num_base_priors, ), stride) for featmap_size, stride in zip(featmap_sizes, self.featmap_strides) ] flatten_stride = torch.cat(mlvl_strides) # flatten cls_scores, bbox_preds and objectness flatten_cls_scores = [ cls_score.permute(0, 2, 3, 1).reshape(num_imgs, -1, self.num_classes) for cls_score in cls_scores ] cls_scores = torch.cat(flatten_cls_scores, dim=1).sigmoid() flatten_bbox_preds = [ bbox_pred.permute(0, 2, 3, 1).reshape(num_imgs, -1, 4) for bbox_pred in bbox_preds ] flatten_bbox_preds = torch.cat(flatten_bbox_preds, dim=1) if objectnesses is not None: flatten_objectness = [ objectness.permute(0, 2, 3, 1).reshape(num_imgs, -1) for objectness in objectnesses ] flatten_objectness = torch.cat(flatten_objectness, dim=1).sigmoid() cls_scores = cls_scores * (flatten_objectness.unsqueeze(-1)) scores = cls_scores bboxes = bbox_decoder(flatten_priors[None], flatten_bbox_preds, flatten_stride) if not with_nms: return bboxes, scores post_params = get_post_processing_params(deploy_cfg) max_output_boxes_per_class = post_params.max_output_boxes_per_class iou_threshold = cfg.nms.get('iou_threshold', post_params.iou_threshold) score_threshold = cfg.get('score_thr', post_params.score_threshold) pre_top_k = post_params.pre_top_k keep_top_k = cfg.get('max_per_img', post_params.keep_top_k) return nms_func(bboxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, pre_top_k, keep_top_k) @FUNCTION_REWRITER.register_rewriter( func_name='mmyolo.models.dense_heads.yolov5_head.' 'YOLOv5Head.predict', backend='rknn') def yolov5_head__predict__rknn(self, x: Tuple[Tensor], *args, **kwargs) -> Tuple[Tensor, Tensor, Tensor]: """Perform forward propagation of the detection head and predict detection results on the features of the upstream network. Args: x (tuple[Tensor]): Multi-level features from the upstream network, each is a 4D-tensor. """ outs = self(x) return outs @FUNCTION_REWRITER.register_rewriter( func_name='mmyolo.models.dense_heads.yolov5_head.' 'YOLOv5HeadModule.forward', backend='rknn') def yolov5_head_module__forward__rknn( self, x: Tensor, *args, **kwargs) -> Tuple[Tensor, Tensor, Tensor]: """Forward feature of a single scale level.""" out = [] for i, feat in enumerate(x): out.append(self.convs_pred[i](feat)) return out
7,242
37.121053
79
py
mmyolo
mmyolo-main/mmyolo/deploy/models/dense_heads/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from . import yolov5_head # noqa: F401,F403 __all__ = ['yolov5_head']
120
23.2
47
py
mmyolo
mmyolo-main/mmyolo/engine/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from .hooks import * # noqa: F401,F403 from .optimizers import * # noqa: F401,F403
133
32.5
47
py
mmyolo
mmyolo-main/mmyolo/engine/hooks/yolov5_param_scheduler_hook.py
# Copyright (c) OpenMMLab. All rights reserved. import math from typing import Optional import numpy as np from mmengine.hooks import ParamSchedulerHook from mmengine.runner import Runner from mmyolo.registry import HOOKS def linear_fn(lr_factor: float, max_epochs: int): """Generate linear function.""" return lambda x: (1 - x / max_epochs) * (1.0 - lr_factor) + lr_factor def cosine_fn(lr_factor: float, max_epochs: int): """Generate cosine function.""" return lambda x: ( (1 - math.cos(x * math.pi / max_epochs)) / 2) * (lr_factor - 1) + 1 @HOOKS.register_module() class YOLOv5ParamSchedulerHook(ParamSchedulerHook): """A hook to update learning rate and momentum in optimizer of YOLOv5.""" priority = 9 scheduler_maps = {'linear': linear_fn, 'cosine': cosine_fn} def __init__(self, scheduler_type: str = 'linear', lr_factor: float = 0.01, max_epochs: int = 300, warmup_epochs: int = 3, warmup_bias_lr: float = 0.1, warmup_momentum: float = 0.8, warmup_mim_iter: int = 1000, **kwargs): assert scheduler_type in self.scheduler_maps self.warmup_epochs = warmup_epochs self.warmup_bias_lr = warmup_bias_lr self.warmup_momentum = warmup_momentum self.warmup_mim_iter = warmup_mim_iter kwargs.update({'lr_factor': lr_factor, 'max_epochs': max_epochs}) self.scheduler_fn = self.scheduler_maps[scheduler_type](**kwargs) self._warmup_end = False self._base_lr = None self._base_momentum = None def before_train(self, runner: Runner): """Operations before train. Args: runner (Runner): The runner of the training process. """ optimizer = runner.optim_wrapper.optimizer for group in optimizer.param_groups: # If the param is never be scheduled, record the current value # as the initial value. group.setdefault('initial_lr', group['lr']) group.setdefault('initial_momentum', group.get('momentum', -1)) self._base_lr = [ group['initial_lr'] for group in optimizer.param_groups ] self._base_momentum = [ group['initial_momentum'] for group in optimizer.param_groups ] def before_train_iter(self, runner: Runner, batch_idx: int, data_batch: Optional[dict] = None): """Operations before each training iteration. Args: runner (Runner): The runner of the training process. batch_idx (int): The index of the current batch in the train loop. data_batch (dict or tuple or list, optional): Data from dataloader. """ cur_iters = runner.iter cur_epoch = runner.epoch optimizer = runner.optim_wrapper.optimizer # The minimum warmup is self.warmup_mim_iter warmup_total_iters = max( round(self.warmup_epochs * len(runner.train_dataloader)), self.warmup_mim_iter) if cur_iters <= warmup_total_iters: xp = [0, warmup_total_iters] for group_idx, param in enumerate(optimizer.param_groups): if group_idx == 2: # bias learning rate will be handled specially yp = [ self.warmup_bias_lr, self._base_lr[group_idx] * self.scheduler_fn(cur_epoch) ] else: yp = [ 0.0, self._base_lr[group_idx] * self.scheduler_fn(cur_epoch) ] param['lr'] = np.interp(cur_iters, xp, yp) if 'momentum' in param: param['momentum'] = np.interp( cur_iters, xp, [self.warmup_momentum, self._base_momentum[group_idx]]) else: self._warmup_end = True def after_train_epoch(self, runner: Runner): """Operations after each training epoch. Args: runner (Runner): The runner of the training process. """ if not self._warmup_end: return cur_epoch = runner.epoch optimizer = runner.optim_wrapper.optimizer for group_idx, param in enumerate(optimizer.param_groups): param['lr'] = self._base_lr[group_idx] * self.scheduler_fn( cur_epoch)
4,611
34.206107
79
py
mmyolo
mmyolo-main/mmyolo/engine/hooks/ppyoloe_param_scheduler_hook.py
# Copyright (c) OpenMMLab. All rights reserved. import math from typing import Optional from mmengine.hooks import ParamSchedulerHook from mmengine.runner import Runner from mmyolo.registry import HOOKS @HOOKS.register_module() class PPYOLOEParamSchedulerHook(ParamSchedulerHook): """A hook to update learning rate and momentum in optimizer of PPYOLOE. We use this hook to implement adaptive computation for `warmup_total_iters`, which is not possible with the built-in ParamScheduler in mmyolo. Args: warmup_min_iter (int): Minimum warmup iters. Defaults to 1000. start_factor (float): The number we multiply learning rate in the first epoch. The multiplication factor changes towards end_factor in the following epochs. Defaults to 0. warmup_epochs (int): Epochs for warmup. Defaults to 5. min_lr_ratio (float): Minimum learning rate ratio. total_epochs (int): In PPYOLOE, `total_epochs` is set to training_epochs x 1.2. Defaults to 360. """ priority = 9 def __init__(self, warmup_min_iter: int = 1000, start_factor: float = 0., warmup_epochs: int = 5, min_lr_ratio: float = 0.0, total_epochs: int = 360): self.warmup_min_iter = warmup_min_iter self.start_factor = start_factor self.warmup_epochs = warmup_epochs self.min_lr_ratio = min_lr_ratio self.total_epochs = total_epochs self._warmup_end = False self._base_lr = None def before_train(self, runner: Runner): """Operations before train. Args: runner (Runner): The runner of the training process. """ optimizer = runner.optim_wrapper.optimizer for group in optimizer.param_groups: # If the param is never be scheduled, record the current value # as the initial value. group.setdefault('initial_lr', group['lr']) self._base_lr = [ group['initial_lr'] for group in optimizer.param_groups ] self._min_lr = [i * self.min_lr_ratio for i in self._base_lr] def before_train_iter(self, runner: Runner, batch_idx: int, data_batch: Optional[dict] = None): """Operations before each training iteration. Args: runner (Runner): The runner of the training process. batch_idx (int): The index of the current batch in the train loop. data_batch (dict or tuple or list, optional): Data from dataloader. """ cur_iters = runner.iter optimizer = runner.optim_wrapper.optimizer dataloader_len = len(runner.train_dataloader) # The minimum warmup is self.warmup_min_iter warmup_total_iters = max( round(self.warmup_epochs * dataloader_len), self.warmup_min_iter) if cur_iters <= warmup_total_iters: # warm up alpha = cur_iters / warmup_total_iters factor = self.start_factor * (1 - alpha) + alpha for group_idx, param in enumerate(optimizer.param_groups): param['lr'] = self._base_lr[group_idx] * factor else: for group_idx, param in enumerate(optimizer.param_groups): total_iters = self.total_epochs * dataloader_len lr = self._min_lr[group_idx] + ( self._base_lr[group_idx] - self._min_lr[group_idx]) * 0.5 * ( math.cos((cur_iters - warmup_total_iters) * math.pi / (total_iters - warmup_total_iters)) + 1.0) param['lr'] = lr
3,781
37.989691
79
py
mmyolo
mmyolo-main/mmyolo/engine/hooks/yolox_mode_switch_hook.py
# Copyright (c) OpenMMLab. All rights reserved. import copy from typing import Sequence from mmengine.hooks import Hook from mmengine.model import is_model_wrapper from mmengine.runner import Runner from mmyolo.registry import HOOKS @HOOKS.register_module() class YOLOXModeSwitchHook(Hook): """Switch the mode of YOLOX during training. This hook turns off the mosaic and mixup data augmentation and switches to use L1 loss in bbox_head. Args: num_last_epochs (int): The number of latter epochs in the end of the training to close the data augmentation and switch to L1 loss. Defaults to 15. """ def __init__(self, num_last_epochs: int = 15, new_train_pipeline: Sequence[dict] = None): self.num_last_epochs = num_last_epochs self.new_train_pipeline_cfg = new_train_pipeline def before_train_epoch(self, runner: Runner): """Close mosaic and mixup augmentation and switches to use L1 loss.""" epoch = runner.epoch model = runner.model if is_model_wrapper(model): model = model.module if (epoch + 1) == runner.max_epochs - self.num_last_epochs: runner.logger.info(f'New Pipeline: {self.new_train_pipeline_cfg}') train_dataloader_cfg = copy.deepcopy(runner.cfg.train_dataloader) train_dataloader_cfg.dataset.pipeline = self.new_train_pipeline_cfg # Note: Why rebuild the dataset? # When build_dataloader will make a deep copy of the dataset, # it will lead to potential risks, such as the global instance # object FileClient data is disordered. # This problem needs to be solved in the future. new_train_dataloader = Runner.build_dataloader( train_dataloader_cfg) runner.train_loop.dataloader = new_train_dataloader runner.logger.info('recreate the dataloader!') runner.logger.info('Add additional bbox reg loss now!') model.bbox_head.use_bbox_aux = True
2,095
37.109091
79
py
mmyolo
mmyolo-main/mmyolo/engine/hooks/switch_to_deploy_hook.py
# Copyright (c) OpenMMLab. All rights reserved. from mmengine.hooks import Hook from mmengine.runner import Runner from mmyolo.registry import HOOKS from mmyolo.utils import switch_to_deploy @HOOKS.register_module() class SwitchToDeployHook(Hook): """Switch to deploy mode before testing. This hook converts the multi-channel structure of the training network (high performance) to the one-way structure of the testing network (fast speed and memory saving). """ def before_test_epoch(self, runner: Runner): """Switch to deploy mode before testing.""" switch_to_deploy(runner.model)
630
27.681818
76
py
mmyolo
mmyolo-main/mmyolo/engine/hooks/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from .ppyoloe_param_scheduler_hook import PPYOLOEParamSchedulerHook from .switch_to_deploy_hook import SwitchToDeployHook from .yolov5_param_scheduler_hook import YOLOv5ParamSchedulerHook from .yolox_mode_switch_hook import YOLOXModeSwitchHook __all__ = [ 'YOLOv5ParamSchedulerHook', 'YOLOXModeSwitchHook', 'SwitchToDeployHook', 'PPYOLOEParamSchedulerHook' ]
416
36.909091
76
py
mmyolo
mmyolo-main/mmyolo/engine/optimizers/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from .yolov5_optim_constructor import YOLOv5OptimizerConstructor from .yolov7_optim_wrapper_constructor import YOLOv7OptimWrapperConstructor __all__ = ['YOLOv5OptimizerConstructor', 'YOLOv7OptimWrapperConstructor']
264
43.166667
75
py
mmyolo
mmyolo-main/mmyolo/engine/optimizers/yolov5_optim_constructor.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional import torch.nn as nn from mmengine.dist import get_world_size from mmengine.logging import print_log from mmengine.model import is_model_wrapper from mmengine.optim import OptimWrapper from mmyolo.registry import (OPTIM_WRAPPER_CONSTRUCTORS, OPTIM_WRAPPERS, OPTIMIZERS) @OPTIM_WRAPPER_CONSTRUCTORS.register_module() class YOLOv5OptimizerConstructor: """YOLOv5 constructor for optimizers. It has the following functions: - divides the optimizer parameters into 3 groups: Conv, Bias and BN - support `weight_decay` parameter adaption based on `batch_size_per_gpu` Args: optim_wrapper_cfg (dict): The config dict of the optimizer wrapper. Positional fields are - ``type``: class name of the OptimizerWrapper - ``optimizer``: The configuration of optimizer. Optional fields are - any arguments of the corresponding optimizer wrapper type, e.g., accumulative_counts, clip_grad, etc. The positional fields of ``optimizer`` are - `type`: class name of the optimizer. Optional fields are - any arguments of the corresponding optimizer type, e.g., lr, weight_decay, momentum, etc. paramwise_cfg (dict, optional): Parameter-wise options. Must include `base_total_batch_size` if not None. If the total input batch is smaller than `base_total_batch_size`, the `weight_decay` parameter will be kept unchanged, otherwise linear scaling. Example: >>> model = torch.nn.modules.Conv1d(1, 1, 1) >>> optim_wrapper_cfg = dict( >>> dict(type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01, >>> momentum=0.9, weight_decay=0.0001, batch_size_per_gpu=16)) >>> paramwise_cfg = dict(base_total_batch_size=64) >>> optim_wrapper_builder = YOLOv5OptimizerConstructor( >>> optim_wrapper_cfg, paramwise_cfg) >>> optim_wrapper = optim_wrapper_builder(model) """ def __init__(self, optim_wrapper_cfg: dict, paramwise_cfg: Optional[dict] = None): if paramwise_cfg is None: paramwise_cfg = {'base_total_batch_size': 64} assert 'base_total_batch_size' in paramwise_cfg if not isinstance(optim_wrapper_cfg, dict): raise TypeError('optimizer_cfg should be a dict', f'but got {type(optim_wrapper_cfg)}') assert 'optimizer' in optim_wrapper_cfg, ( '`optim_wrapper_cfg` must contain "optimizer" config') self.optim_wrapper_cfg = optim_wrapper_cfg self.optimizer_cfg = self.optim_wrapper_cfg.pop('optimizer') self.base_total_batch_size = paramwise_cfg['base_total_batch_size'] def __call__(self, model: nn.Module) -> OptimWrapper: if is_model_wrapper(model): model = model.module optimizer_cfg = self.optimizer_cfg.copy() weight_decay = optimizer_cfg.pop('weight_decay', 0) if 'batch_size_per_gpu' in optimizer_cfg: batch_size_per_gpu = optimizer_cfg.pop('batch_size_per_gpu') # No scaling if total_batch_size is less than # base_total_batch_size, otherwise linear scaling. total_batch_size = get_world_size() * batch_size_per_gpu accumulate = max( round(self.base_total_batch_size / total_batch_size), 1) scale_factor = total_batch_size * \ accumulate / self.base_total_batch_size if scale_factor != 1: weight_decay *= scale_factor print_log(f'Scaled weight_decay to {weight_decay}', 'current') params_groups = [], [], [] for v in model.modules(): if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): params_groups[2].append(v.bias) # Includes SyncBatchNorm if isinstance(v, nn.modules.batchnorm._NormBase): params_groups[1].append(v.weight) elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): params_groups[0].append(v.weight) # Note: Make sure bias is in the last parameter group optimizer_cfg['params'] = [] # conv optimizer_cfg['params'].append({ 'params': params_groups[0], 'weight_decay': weight_decay }) # bn optimizer_cfg['params'].append({'params': params_groups[1]}) # bias optimizer_cfg['params'].append({'params': params_groups[2]}) print_log( 'Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(params_groups[2]), len(params_groups[0]), len( params_groups[1])), 'current') del params_groups optimizer = OPTIMIZERS.build(optimizer_cfg) optim_wrapper = OPTIM_WRAPPERS.build( self.optim_wrapper_cfg, default_args=dict(optimizer=optimizer)) return optim_wrapper
5,201
38.112782
78
py
mmyolo
mmyolo-main/mmyolo/engine/optimizers/yolov7_optim_wrapper_constructor.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional import torch.nn as nn from mmengine.dist import get_world_size from mmengine.logging import print_log from mmengine.model import is_model_wrapper from mmengine.optim import OptimWrapper from mmyolo.models.dense_heads.yolov7_head import ImplicitA, ImplicitM from mmyolo.registry import (OPTIM_WRAPPER_CONSTRUCTORS, OPTIM_WRAPPERS, OPTIMIZERS) # TODO: Consider merging into YOLOv5OptimizerConstructor @OPTIM_WRAPPER_CONSTRUCTORS.register_module() class YOLOv7OptimWrapperConstructor: """YOLOv7 constructor for optimizer wrappers. It has the following functions: - divides the optimizer parameters into 3 groups: Conv, Bias and BN/ImplicitA/ImplicitM - support `weight_decay` parameter adaption based on `batch_size_per_gpu` Args: optim_wrapper_cfg (dict): The config dict of the optimizer wrapper. Positional fields are - ``type``: class name of the OptimizerWrapper - ``optimizer``: The configuration of optimizer. Optional fields are - any arguments of the corresponding optimizer wrapper type, e.g., accumulative_counts, clip_grad, etc. The positional fields of ``optimizer`` are - `type`: class name of the optimizer. Optional fields are - any arguments of the corresponding optimizer type, e.g., lr, weight_decay, momentum, etc. paramwise_cfg (dict, optional): Parameter-wise options. Must include `base_total_batch_size` if not None. If the total input batch is smaller than `base_total_batch_size`, the `weight_decay` parameter will be kept unchanged, otherwise linear scaling. Example: >>> model = torch.nn.modules.Conv1d(1, 1, 1) >>> optim_wrapper_cfg = dict( >>> dict(type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01, >>> momentum=0.9, weight_decay=0.0001, batch_size_per_gpu=16)) >>> paramwise_cfg = dict(base_total_batch_size=64) >>> optim_wrapper_builder = YOLOv7OptimWrapperConstructor( >>> optim_wrapper_cfg, paramwise_cfg) >>> optim_wrapper = optim_wrapper_builder(model) """ def __init__(self, optim_wrapper_cfg: dict, paramwise_cfg: Optional[dict] = None): if paramwise_cfg is None: paramwise_cfg = {'base_total_batch_size': 64} assert 'base_total_batch_size' in paramwise_cfg if not isinstance(optim_wrapper_cfg, dict): raise TypeError('optimizer_cfg should be a dict', f'but got {type(optim_wrapper_cfg)}') assert 'optimizer' in optim_wrapper_cfg, ( '`optim_wrapper_cfg` must contain "optimizer" config') self.optim_wrapper_cfg = optim_wrapper_cfg self.optimizer_cfg = self.optim_wrapper_cfg.pop('optimizer') self.base_total_batch_size = paramwise_cfg['base_total_batch_size'] def __call__(self, model: nn.Module) -> OptimWrapper: if is_model_wrapper(model): model = model.module optimizer_cfg = self.optimizer_cfg.copy() weight_decay = optimizer_cfg.pop('weight_decay', 0) if 'batch_size_per_gpu' in optimizer_cfg: batch_size_per_gpu = optimizer_cfg.pop('batch_size_per_gpu') # No scaling if total_batch_size is less than # base_total_batch_size, otherwise linear scaling. total_batch_size = get_world_size() * batch_size_per_gpu accumulate = max( round(self.base_total_batch_size / total_batch_size), 1) scale_factor = total_batch_size * \ accumulate / self.base_total_batch_size if scale_factor != 1: weight_decay *= scale_factor print_log(f'Scaled weight_decay to {weight_decay}', 'current') params_groups = [], [], [] for v in model.modules(): # no decay # Caution: Coupling with model if isinstance(v, (ImplicitA, ImplicitM)): params_groups[0].append(v.implicit) elif isinstance(v, nn.modules.batchnorm._NormBase): params_groups[0].append(v.weight) # apply decay elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): params_groups[1].append(v.weight) # apply decay # biases, no decay if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): params_groups[2].append(v.bias) # Note: Make sure bias is in the last parameter group optimizer_cfg['params'] = [] # conv optimizer_cfg['params'].append({ 'params': params_groups[1], 'weight_decay': weight_decay }) # bn ... optimizer_cfg['params'].append({'params': params_groups[0]}) # bias optimizer_cfg['params'].append({'params': params_groups[2]}) print_log( 'Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(params_groups[2]), len(params_groups[1]), len( params_groups[0])), 'current') del params_groups optimizer = OPTIMIZERS.build(optimizer_cfg) optim_wrapper = OPTIM_WRAPPERS.build( self.optim_wrapper_cfg, default_args=dict(optimizer=optimizer)) return optim_wrapper
5,576
38.835714
78
py
mmyolo
mmyolo-main/mmyolo/utils/labelme_utils.py
# Copyright (c) OpenMMLab. All rights reserved. import json import os.path from mmengine.structures import InstanceData class LabelmeFormat: """Predict results save into labelme file. Base on https://github.com/wkentaro/labelme/blob/main/labelme/label_file.py Args: classes (tuple): Model classes name. """ def __init__(self, classes: tuple): super().__init__() self.classes = classes def __call__(self, pred_instances: InstanceData, metainfo: dict, output_path: str, selected_classes: list): """Get image data field for labelme. Args: pred_instances (InstanceData): Candidate prediction info. metainfo (dict): Meta info of prediction. output_path (str): Image file path. selected_classes (list): Selected class name. Labelme file eg. { "version": "5.1.1", "flags": {}, "imagePath": "/data/cat/1.jpg", "imageData": null, "imageHeight": 3000, "imageWidth": 4000, "shapes": [ { "label": "cat", "points": [ [ 1148.076923076923, 1188.4615384615383 ], [ 2471.1538461538457, 2176.923076923077 ] ], "group_id": null, "shape_type": "rectangle", "flags": {} }, {...} ] } """ image_path = os.path.abspath(metainfo['img_path']) json_info = { 'version': '5.1.1', 'flags': {}, 'imagePath': image_path, 'imageData': None, 'imageHeight': metainfo['ori_shape'][0], 'imageWidth': metainfo['ori_shape'][1], 'shapes': [] } for pred_instance in pred_instances: pred_bbox = pred_instance.bboxes.cpu().numpy().tolist()[0] pred_label = self.classes[pred_instance.labels] if selected_classes is not None and \ pred_label not in selected_classes: # filter class name continue sub_dict = { 'label': pred_label, 'points': [pred_bbox[:2], pred_bbox[2:]], 'group_id': None, 'shape_type': 'rectangle', 'flags': {} } json_info['shapes'].append(sub_dict) with open(output_path, 'w', encoding='utf-8') as f_json: json.dump(json_info, f_json, ensure_ascii=False, indent=2)
2,799
29.107527
79
py
mmyolo
mmyolo-main/mmyolo/utils/large_image.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Sequence, Tuple import torch from mmcv.ops import batched_nms from mmdet.structures import DetDataSample, SampleList from mmengine.structures import InstanceData def shift_rbboxes(bboxes: torch.Tensor, offset: Sequence[int]): """Shift rotated bboxes with offset. Args: bboxes (Tensor): The rotated bboxes need to be translated. With shape (n, 5), which means (x, y, w, h, a). offset (Sequence[int]): The translation offsets with shape of (2, ). Returns: Tensor: Shifted rotated bboxes. """ offset_tensor = bboxes.new_tensor(offset) shifted_bboxes = bboxes.clone() shifted_bboxes[:, 0:2] = shifted_bboxes[:, 0:2] + offset_tensor return shifted_bboxes def shift_predictions(det_data_samples: SampleList, offsets: Sequence[Tuple[int, int]], src_image_shape: Tuple[int, int]) -> SampleList: """Shift predictions to the original image. Args: det_data_samples (List[:obj:`DetDataSample`]): A list of patch results. offsets (Sequence[Tuple[int, int]]): Positions of the left top points of patches. src_image_shape (Tuple[int, int]): A (height, width) tuple of the large image's width and height. Returns: (List[:obj:`DetDataSample`]): shifted results. """ try: from sahi.slicing import shift_bboxes, shift_masks except ImportError: raise ImportError('Please run "pip install -U sahi" ' 'to install sahi first for large image inference.') assert len(det_data_samples) == len( offsets), 'The `results` should has the ' 'same length with `offsets`.' shifted_predictions = [] for det_data_sample, offset in zip(det_data_samples, offsets): pred_inst = det_data_sample.pred_instances.clone() # Check bbox type if pred_inst.bboxes.size(-1) == 4: # Horizontal bboxes shifted_bboxes = shift_bboxes(pred_inst.bboxes, offset) elif pred_inst.bboxes.size(-1) == 5: # Rotated bboxes shifted_bboxes = shift_rbboxes(pred_inst.bboxes, offset) else: raise NotImplementedError # shift bboxes and masks pred_inst.bboxes = shifted_bboxes if 'masks' in det_data_sample: pred_inst.masks = shift_masks(pred_inst.masks, offset, src_image_shape) shifted_predictions.append(pred_inst.clone()) shifted_predictions = InstanceData.cat(shifted_predictions) return shifted_predictions def merge_results_by_nms(results: SampleList, offsets: Sequence[Tuple[int, int]], src_image_shape: Tuple[int, int], nms_cfg: dict) -> DetDataSample: """Merge patch results by nms. Args: results (List[:obj:`DetDataSample`]): A list of patch results. offsets (Sequence[Tuple[int, int]]): Positions of the left top points of patches. src_image_shape (Tuple[int, int]): A (height, width) tuple of the large image's width and height. nms_cfg (dict): it should specify nms type and other parameters like `iou_threshold`. Returns: :obj:`DetDataSample`: merged results. """ shifted_instances = shift_predictions(results, offsets, src_image_shape) _, keeps = batched_nms( boxes=shifted_instances.bboxes, scores=shifted_instances.scores, idxs=shifted_instances.labels, nms_cfg=nms_cfg) merged_instances = shifted_instances[keeps] merged_result = results[0].clone() merged_result.pred_instances = merged_instances return merged_result
3,871
36.230769
79
py
mmyolo
mmyolo-main/mmyolo/utils/misc.py
# Copyright (c) OpenMMLab. All rights reserved. import os import urllib import numpy as np import torch from mmengine.utils import scandir from prettytable import PrettyTable from mmyolo.models import RepVGGBlock IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp') def switch_to_deploy(model): """Model switch to deploy status.""" for layer in model.modules(): if isinstance(layer, RepVGGBlock): layer.switch_to_deploy() print('Switch model to deploy modality.') def auto_arrange_images(image_list: list, image_column: int = 2) -> np.ndarray: """Auto arrange image to image_column x N row. Args: image_list (list): cv2 image list. image_column (int): Arrange to N column. Default: 2. Return: (np.ndarray): image_column x N row merge image """ img_count = len(image_list) if img_count <= image_column: # no need to arrange image_show = np.concatenate(image_list, axis=1) else: # arrange image according to image_column image_row = round(img_count / image_column) fill_img_list = [np.ones(image_list[0].shape, dtype=np.uint8) * 255 ] * ( image_row * image_column - img_count) image_list.extend(fill_img_list) merge_imgs_col = [] for i in range(image_row): start_col = image_column * i end_col = image_column * (i + 1) merge_col = np.hstack(image_list[start_col:end_col]) merge_imgs_col.append(merge_col) # merge to one image image_show = np.vstack(merge_imgs_col) return image_show def get_file_list(source_root: str) -> [list, dict]: """Get file list. Args: source_root (str): image or video source path Return: source_file_path_list (list): A list for all source file. source_type (dict): Source type: file or url or dir. """ is_dir = os.path.isdir(source_root) is_url = source_root.startswith(('http:/', 'https:/')) is_file = os.path.splitext(source_root)[-1].lower() in IMG_EXTENSIONS source_file_path_list = [] if is_dir: # when input source is dir for file in scandir(source_root, IMG_EXTENSIONS, recursive=True): source_file_path_list.append(os.path.join(source_root, file)) elif is_url: # when input source is url filename = os.path.basename( urllib.parse.unquote(source_root).split('?')[0]) file_save_path = os.path.join(os.getcwd(), filename) print(f'Downloading source file to {file_save_path}') torch.hub.download_url_to_file(source_root, file_save_path) source_file_path_list = [file_save_path] elif is_file: # when input source is single image source_file_path_list = [source_root] else: print('Cannot find image file.') source_type = dict(is_dir=is_dir, is_url=is_url, is_file=is_file) return source_file_path_list, source_type def show_data_classes(data_classes): """When printing an error, all class names of the dataset.""" print('\n\nThe name of the class contained in the dataset:') data_classes_info = PrettyTable() data_classes_info.title = 'Information of dataset class' # List Print Settings # If the quantity is too large, 25 rows will be displayed in each column if len(data_classes) < 25: data_classes_info.add_column('Class name', data_classes) elif len(data_classes) % 25 != 0 and len(data_classes) > 25: col_num = int(len(data_classes) / 25) + 1 data_name_list = list(data_classes) for i in range(0, (col_num * 25) - len(data_classes)): data_name_list.append('') for i in range(0, len(data_name_list), 25): data_classes_info.add_column('Class name', data_name_list[i:i + 25]) # Align display data to the left data_classes_info.align['Class name'] = 'l' print(data_classes_info) def is_metainfo_lower(cfg): """Determine whether the custom metainfo fields are all lowercase.""" def judge_keys(dataloader_cfg): while 'dataset' in dataloader_cfg: dataloader_cfg = dataloader_cfg['dataset'] if 'metainfo' in dataloader_cfg: all_keys = dataloader_cfg['metainfo'].keys() all_is_lower = all([str(k).islower() for k in all_keys]) assert all_is_lower, f'The keys in dataset metainfo must be all lowercase, but got {all_keys}. ' \ f'Please refer to https://github.com/open-mmlab/mmyolo/blob/e62c8c4593/configs/yolov5/yolov5_s-v61_syncbn_fast_1xb4-300e_balloon.py#L8' # noqa judge_keys(cfg.get('train_dataloader', {})) judge_keys(cfg.get('val_dataloader', {})) judge_keys(cfg.get('test_dataloader', {}))
4,932
35.813433
175
py
mmyolo
mmyolo-main/mmyolo/utils/setup_env.py
# Copyright (c) OpenMMLab. All rights reserved. import datetime import warnings from mmengine import DefaultScope def register_all_modules(init_default_scope: bool = True): """Register all modules in mmdet into the registries. Args: init_default_scope (bool): Whether initialize the mmdet default scope. When `init_default_scope=True`, the global default scope will be set to `mmyolo`, and all registries will build modules from mmdet's registry node. To understand more about the registry, please refer to https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/registry.md Defaults to True. """ # noqa import mmdet.engine # noqa: F401,F403 import mmdet.visualization # noqa: F401,F403 import mmyolo.datasets # noqa: F401,F403 import mmyolo.engine # noqa: F401,F403 import mmyolo.models # noqa: F401,F403 if init_default_scope: never_created = DefaultScope.get_current_instance() is None \ or not DefaultScope.check_instance_created('mmyolo') if never_created: DefaultScope.get_instance('mmyolo', scope_name='mmyolo') return current_scope = DefaultScope.get_current_instance() if current_scope.scope_name != 'mmyolo': warnings.warn('The current default scope ' f'"{current_scope.scope_name}" is not "mmyolo", ' '`register_all_modules` will force the current' 'default scope to be "mmyolo". If this is not ' 'expected, please set `init_default_scope=False`.') # avoid name conflict new_instance_name = f'mmyolo-{datetime.datetime.now()}' DefaultScope.get_instance(new_instance_name, scope_name='mmyolo')
1,863
43.380952
93
py
mmyolo
mmyolo-main/mmyolo/utils/collect_env.py
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import mmdet from mmengine.utils import get_git_hash from mmengine.utils.dl_utils import collect_env as collect_base_env import mmyolo def collect_env() -> dict: """Collect the information of the running environments.""" env_info = collect_base_env() env_info['MMCV'] = mmcv.__version__ env_info['MMDetection'] = mmdet.__version__ env_info['MMYOLO'] = mmyolo.__version__ + '+' + get_git_hash()[:7] return env_info if __name__ == '__main__': for name, val in collect_env().items(): print(f'{name}: {val}')
606
26.590909
70
py
mmyolo
mmyolo-main/mmyolo/utils/__init__.py
# Copyright (c) OpenMMLab. All rights reserved. from .collect_env import collect_env from .misc import is_metainfo_lower, switch_to_deploy from .setup_env import register_all_modules __all__ = [ 'register_all_modules', 'collect_env', 'switch_to_deploy', 'is_metainfo_lower' ]
285
27.6
62
py
mmyolo
mmyolo-main/mmyolo/utils/boxam_utils.py
# Copyright (c) OpenMMLab. All rights reserved. import bisect import copy import warnings from pathlib import Path from typing import Callable, List, Optional, Tuple, Union import cv2 import numpy as np import torch import torch.nn as nn import torchvision from mmcv.transforms import Compose from mmdet.evaluation import get_classes from mmdet.utils import ConfigType from mmengine.config import Config from mmengine.registry import init_default_scope from mmengine.runner import load_checkpoint from mmengine.structures import InstanceData from torch import Tensor from mmyolo.registry import MODELS try: from pytorch_grad_cam import (AblationCAM, AblationLayer, ActivationsAndGradients) from pytorch_grad_cam import GradCAM as Base_GradCAM from pytorch_grad_cam import GradCAMPlusPlus as Base_GradCAMPlusPlus from pytorch_grad_cam.base_cam import BaseCAM from pytorch_grad_cam.utils.image import scale_cam_image, show_cam_on_image from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection except ImportError: pass def init_detector( config: Union[str, Path, Config], checkpoint: Optional[str] = None, palette: str = 'coco', device: str = 'cuda:0', cfg_options: Optional[dict] = None, ) -> nn.Module: """Initialize a detector from config file. Args: config (str, :obj:`Path`, or :obj:`mmengine.Config`): Config file path, :obj:`Path`, or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model will not load any weights. palette (str): Color palette used for visualization. If palette is stored in checkpoint, use checkpoint's palette first, otherwise use externally passed palette. Currently, supports 'coco', 'voc', 'citys' and 'random'. Defaults to coco. device (str): The device where the anchors will be put on. Defaults to cuda:0. cfg_options (dict, optional): Options to override some settings in the used config. Returns: nn.Module: The constructed detector. """ if isinstance(config, (str, Path)): config = Config.fromfile(config) elif not isinstance(config, Config): raise TypeError('config must be a filename or Config object, ' f'but got {type(config)}') if cfg_options is not None: config.merge_from_dict(cfg_options) elif 'init_cfg' in config.model.backbone: config.model.backbone.init_cfg = None # only change this # grad based method requires train_cfg # config.model.train_cfg = None init_default_scope(config.get('default_scope', 'mmyolo')) model = MODELS.build(config.model) if checkpoint is not None: checkpoint = load_checkpoint(model, checkpoint, map_location='cpu') # Weights converted from elsewhere may not have meta fields. checkpoint_meta = checkpoint.get('meta', {}) # save the dataset_meta in the model for convenience if 'dataset_meta' in checkpoint_meta: # mmdet 3.x, all keys should be lowercase model.dataset_meta = { k.lower(): v for k, v in checkpoint_meta['dataset_meta'].items() } elif 'CLASSES' in checkpoint_meta: # < mmdet 3.x classes = checkpoint_meta['CLASSES'] model.dataset_meta = {'classes': classes, 'palette': palette} else: warnings.simplefilter('once') warnings.warn( 'dataset_meta or class names are not saved in the ' 'checkpoint\'s meta data, use COCO classes by default.') model.dataset_meta = { 'classes': get_classes('coco'), 'palette': palette } model.cfg = config # save the config in the model for convenience model.to(device) model.eval() return model def reshape_transform(feats: Union[Tensor, List[Tensor]], max_shape: Tuple[int, int] = (20, 20), is_need_grad: bool = False): """Reshape and aggregate feature maps when the input is a multi-layer feature map. Takes these tensors with different sizes, resizes them to a common shape, and concatenates them. """ if len(max_shape) == 1: max_shape = max_shape * 2 if isinstance(feats, torch.Tensor): feats = [feats] else: if is_need_grad: raise NotImplementedError('The `grad_base` method does not ' 'support output multi-activation layers') max_h = max([im.shape[-2] for im in feats]) max_w = max([im.shape[-1] for im in feats]) if -1 in max_shape: max_shape = (max_h, max_w) else: max_shape = (min(max_h, max_shape[0]), min(max_w, max_shape[1])) activations = [] for feat in feats: activations.append( torch.nn.functional.interpolate( torch.abs(feat), max_shape, mode='bilinear')) activations = torch.cat(activations, axis=1) return activations class BoxAMDetectorWrapper(nn.Module): """Wrap the mmdet model class to facilitate handling of non-tensor situations during inference.""" def __init__(self, cfg: ConfigType, checkpoint: str, score_thr: float, device: str = 'cuda:0'): super().__init__() self.cfg = cfg self.device = device self.score_thr = score_thr self.checkpoint = checkpoint self.detector = init_detector(self.cfg, self.checkpoint, device=device) pipeline_cfg = copy.deepcopy(self.cfg.test_dataloader.dataset.pipeline) pipeline_cfg[0].type = 'mmdet.LoadImageFromNDArray' new_test_pipeline = [] for pipeline in pipeline_cfg: if not pipeline['type'].endswith('LoadAnnotations'): new_test_pipeline.append(pipeline) self.test_pipeline = Compose(new_test_pipeline) self.is_need_loss = False self.input_data = None self.image = None def need_loss(self, is_need_loss: bool): """Grad-based methods require loss.""" self.is_need_loss = is_need_loss def set_input_data(self, image: np.ndarray, pred_instances: Optional[InstanceData] = None): """Set the input data to be used in the next step.""" self.image = image if self.is_need_loss: assert pred_instances is not None pred_instances = pred_instances.numpy() data = dict( img=self.image, img_id=0, gt_bboxes=pred_instances.bboxes, gt_bboxes_labels=pred_instances.labels) data = self.test_pipeline(data) else: data = dict(img=self.image, img_id=0) data = self.test_pipeline(data) data['inputs'] = [data['inputs']] data['data_samples'] = [data['data_samples']] self.input_data = data def __call__(self, *args, **kwargs): assert self.input_data is not None if self.is_need_loss: # Maybe this is a direction that can be optimized # self.detector.init_weights() self.detector.bbox_head.head_module.training = True if hasattr(self.detector.bbox_head, 'featmap_sizes'): # Prevent the model algorithm error when calculating loss self.detector.bbox_head.featmap_sizes = None data_ = {} data_['inputs'] = [self.input_data['inputs']] data_['data_samples'] = [self.input_data['data_samples']] data = self.detector.data_preprocessor(data_, training=False) loss = self.detector._run_forward(data, mode='loss') if hasattr(self.detector.bbox_head, 'featmap_sizes'): self.detector.bbox_head.featmap_sizes = None return [loss] else: self.detector.bbox_head.head_module.training = False with torch.no_grad(): results = self.detector.test_step(self.input_data) return results class BoxAMDetectorVisualizer: """Box AM visualization class.""" def __init__(self, method_class, model: nn.Module, target_layers: List, reshape_transform: Optional[Callable] = None, is_need_grad: bool = False, extra_params: Optional[dict] = None): self.target_layers = target_layers self.reshape_transform = reshape_transform self.is_need_grad = is_need_grad if method_class.__name__ == 'AblationCAM': batch_size = extra_params.get('batch_size', 1) ratio_channels_to_ablate = extra_params.get( 'ratio_channels_to_ablate', 1.) self.cam = AblationCAM( model, target_layers, use_cuda=True if 'cuda' in model.device else False, reshape_transform=reshape_transform, batch_size=batch_size, ablation_layer=extra_params['ablation_layer'], ratio_channels_to_ablate=ratio_channels_to_ablate) else: self.cam = method_class( model, target_layers, use_cuda=True if 'cuda' in model.device else False, reshape_transform=reshape_transform, ) if self.is_need_grad: self.cam.activations_and_grads.release() self.classes = model.detector.dataset_meta['classes'] self.COLORS = np.random.uniform(0, 255, size=(len(self.classes), 3)) def switch_activations_and_grads(self, model) -> None: """In the grad-based method, we need to switch ``ActivationsAndGradients`` layer, otherwise an error will occur.""" self.cam.model = model if self.is_need_grad is True: self.cam.activations_and_grads = ActivationsAndGradients( model, self.target_layers, self.reshape_transform) self.is_need_grad = False else: self.cam.activations_and_grads.release() self.is_need_grad = True def __call__(self, img, targets, aug_smooth=False, eigen_smooth=False): img = torch.from_numpy(img)[None].permute(0, 3, 1, 2) return self.cam(img, targets, aug_smooth, eigen_smooth)[0, :] def show_am(self, image: np.ndarray, pred_instance: InstanceData, grayscale_am: np.ndarray, with_norm_in_bboxes: bool = False): """Normalize the AM to be in the range [0, 1] inside every bounding boxes, and zero outside of the bounding boxes.""" boxes = pred_instance.bboxes labels = pred_instance.labels if with_norm_in_bboxes is True: boxes = boxes.astype(np.int32) renormalized_am = np.zeros(grayscale_am.shape, dtype=np.float32) images = [] for x1, y1, x2, y2 in boxes: img = renormalized_am * 0 img[y1:y2, x1:x2] = scale_cam_image( [grayscale_am[y1:y2, x1:x2].copy()])[0] images.append(img) renormalized_am = np.max(np.float32(images), axis=0) renormalized_am = scale_cam_image([renormalized_am])[0] else: renormalized_am = grayscale_am am_image_renormalized = show_cam_on_image( image / 255, renormalized_am, use_rgb=False) image_with_bounding_boxes = self._draw_boxes( boxes, labels, am_image_renormalized, pred_instance.get('scores')) return image_with_bounding_boxes def _draw_boxes(self, boxes: List, labels: List, image: np.ndarray, scores: Optional[List] = None): """draw boxes on image.""" for i, box in enumerate(boxes): label = labels[i] color = self.COLORS[label] cv2.rectangle(image, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), color, 2) if scores is not None: score = scores[i] text = str(self.classes[label]) + ': ' + str( round(score * 100, 1)) else: text = self.classes[label] cv2.putText( image, text, (int(box[0]), int(box[1] - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1, lineType=cv2.LINE_AA) return image class DetAblationLayer(AblationLayer): """Det AblationLayer.""" def __init__(self): super().__init__() self.activations = None def set_next_batch(self, input_batch_index, activations, num_channels_to_ablate): """Extract the next batch member from activations, and repeat it num_channels_to_ablate times.""" if isinstance(activations, torch.Tensor): return super().set_next_batch(input_batch_index, activations, num_channels_to_ablate) self.activations = [] for activation in activations: activation = activation[ input_batch_index, :, :, :].clone().unsqueeze(0) self.activations.append( activation.repeat(num_channels_to_ablate, 1, 1, 1)) def __call__(self, x): """Go over the activation indices to be ablated, stored in self.indices.""" result = self.activations if isinstance(result, torch.Tensor): return super().__call__(x) channel_cumsum = np.cumsum([r.shape[1] for r in result]) num_channels_to_ablate = result[0].size(0) # batch for i in range(num_channels_to_ablate): pyramid_layer = bisect.bisect_right(channel_cumsum, self.indices[i]) if pyramid_layer > 0: index_in_pyramid_layer = self.indices[i] - channel_cumsum[ pyramid_layer - 1] else: index_in_pyramid_layer = self.indices[i] result[pyramid_layer][i, index_in_pyramid_layer, :, :] = -1000 return result class DetBoxScoreTarget: """Det Score calculation class. In the case of the grad-free method, the calculation method is that for every original detected bounding box specified in "bboxes", assign a score on how the current bounding boxes match it, 1. In Bbox IoU 2. In the classification score. 3. In Mask IoU if ``segms`` exist. If there is not a large enough overlap, or the category changed, assign a score of 0. The total score is the sum of all the box scores. In the case of the grad-based method, the calculation method is the sum of losses after excluding a specific key. """ def __init__(self, pred_instance: InstanceData, match_iou_thr: float = 0.5, device: str = 'cuda:0', ignore_loss_params: Optional[List] = None): self.focal_bboxes = pred_instance.bboxes self.focal_labels = pred_instance.labels self.match_iou_thr = match_iou_thr self.device = device self.ignore_loss_params = ignore_loss_params if ignore_loss_params is not None: assert isinstance(self.ignore_loss_params, list) def __call__(self, results): output = torch.tensor([0.], device=self.device) if 'loss_cls' in results: # grad-based method # results is dict for loss_key, loss_value in results.items(): if 'loss' not in loss_key or \ loss_key in self.ignore_loss_params: continue if isinstance(loss_value, list): output += sum(loss_value) else: output += loss_value return output else: # grad-free method # results is DetDataSample pred_instances = results.pred_instances if len(pred_instances) == 0: return output pred_bboxes = pred_instances.bboxes pred_scores = pred_instances.scores pred_labels = pred_instances.labels for focal_box, focal_label in zip(self.focal_bboxes, self.focal_labels): ious = torchvision.ops.box_iou(focal_box[None], pred_bboxes[..., :4]) index = ious.argmax() if ious[0, index] > self.match_iou_thr and pred_labels[ index] == focal_label: # TODO: Adaptive adjustment of weights based on algorithms score = ious[0, index] + pred_scores[index] output = output + score return output class SpatialBaseCAM(BaseCAM): """CAM that maintains spatial information. Gradients are often averaged over the spatial dimension in CAM visualization for classification, but this is unreasonable in detection tasks. There is no need to average the gradients in the detection task. """ def get_cam_image(self, input_tensor: torch.Tensor, target_layer: torch.nn.Module, targets: List[torch.nn.Module], activations: torch.Tensor, grads: torch.Tensor, eigen_smooth: bool = False) -> np.ndarray: weights = self.get_cam_weights(input_tensor, target_layer, targets, activations, grads) weighted_activations = weights * activations if eigen_smooth: cam = get_2d_projection(weighted_activations) else: cam = weighted_activations.sum(axis=1) return cam class GradCAM(SpatialBaseCAM, Base_GradCAM): """Gradients are no longer averaged over the spatial dimension.""" def get_cam_weights(self, input_tensor, target_layer, target_category, activations, grads): return grads class GradCAMPlusPlus(SpatialBaseCAM, Base_GradCAMPlusPlus): """Gradients are no longer averaged over the spatial dimension.""" def get_cam_weights(self, input_tensor, target_layers, target_category, activations, grads): grads_power_2 = grads**2 grads_power_3 = grads_power_2 * grads # Equation 19 in https://arxiv.org/abs/1710.11063 sum_activations = np.sum(activations, axis=(2, 3)) eps = 0.000001 aij = grads_power_2 / ( 2 * grads_power_2 + sum_activations[:, :, None, None] * grads_power_3 + eps) # Now bring back the ReLU from eq.7 in the paper, # And zero out aijs where the activations are 0 aij = np.where(grads != 0, aij, 0) weights = np.maximum(grads, 0) * aij return weights
19,429
36.875244
79
py
DALLE-pytorch
DALLE-pytorch-main/train_dalle.py
import argparse from pathlib import Path import time from glob import glob import os import shutil import torch import wandb # Quit early if user doesn't have wandb installed. from torch.nn.utils import clip_grad_norm_ from torch.optim import Adam from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.data import DataLoader from dalle_pytorch import __version__ from dalle_pytorch import OpenAIDiscreteVAE, VQGanVAE, DiscreteVAE, DALLE from dalle_pytorch import distributed_utils from dalle_pytorch.loader import TextImageDataset from dalle_pytorch.tokenizer import tokenizer, HugTokenizer, ChineseTokenizer, YttmTokenizer # libraries needed for webdataset support import webdataset as wds from torchvision import transforms as T from PIL import Image from io import BytesIO # argument parsing parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(required=False) group.add_argument('--vae_path', type=str, help='path to your trained discrete VAE') group.add_argument('--dalle_path', type=str, help='path to your partially trained DALL-E') parser.add_argument('--vqgan_model_path', type=str, default = None, help='path to your trained VQGAN weights. This should be a .ckpt file. (only valid when taming option is enabled)') parser.add_argument('--vqgan_config_path', type=str, default = None, help='path to your trained VQGAN config. This should be a .yaml file. (only valid when taming option is enabled)') parser.add_argument('--image_text_folder', type=str, required=True, help='path to your folder of images and text for learning the DALL-E') parser.add_argument('--wds', type = str, default='', help = 'Comma separated list of WebDataset (1) image and (2) text column names. Must contain 2 values, e.g. img,cap.') parser.add_argument('--truncate_captions', dest='truncate_captions', action='store_true', help='Captions passed in which exceed the max token length will be truncated if this is set.') parser.add_argument('--random_resize_crop_lower_ratio', dest='resize_ratio', type=float, default=0.75, help='Random resized crop lower ratio') parser.add_argument('--chinese', dest='chinese', action='store_true') parser.add_argument('--taming', dest='taming', action='store_true') parser.add_argument('--hug', dest='hug', action='store_true') parser.add_argument('--bpe_path', type=str, help='path to your BPE json file') parser.add_argument('--dalle_output_file_name', type=str, default = "dalle", help='output_file_name') parser.add_argument('--fp16', action='store_true', help='(experimental) - Enable DeepSpeed 16 bit precision. Reduces VRAM.') parser.add_argument('--amp', action='store_true', help='Apex "O1" automatic mixed precision. More stable than 16 bit precision. Can\'t be used in conjunction with deepspeed zero stages 1-3.') parser.add_argument('--wandb_name', default='dalle_train_transformer', help='Name W&B will use when saving results.\ne.g. `--wandb_name "coco2017-full-sparse"`') parser.add_argument('--wandb_entity', default=None, help='(optional) Name of W&B team/entity to log to.') parser.add_argument('--stable_softmax', dest='stable_softmax', action='store_true', help='Prevent values from becoming too large during softmax. Helps with stability in fp16 and Mixture of Quantization training.') parser = distributed_utils.wrap_arg_parser(parser) train_group = parser.add_argument_group('Training settings') train_group.add_argument('--flops_profiler', dest = 'flops_profiler', action='store_true', help = 'Exits after printing detailed flops/runtime analysis of forward/backward') train_group.add_argument('--epochs', default = 20, type = int, help = 'Number of epochs') train_group.add_argument('--save_every_n_steps', default = 1000, type = int, help = 'Save a checkpoint every n steps') train_group.add_argument('--keep_n_checkpoints', default = None, type = int, help = '(Careful) Deletes old deepspeed checkpoints if there are more than n') train_group.add_argument('--batch_size', default = 4, type = int, help = 'Batch size') train_group.add_argument('--ga_steps', default = 1, type = int, help = 'Number of steps to accumulate gradients across per each iteration. DeepSpeed only.') train_group.add_argument('--learning_rate', default = 3e-4, type = float, help = 'Learning rate') train_group.add_argument('--clip_grad_norm', default = 0.5, type = float, help = 'Clip gradient norm') train_group.add_argument('--lr_decay', dest = 'lr_decay', action = 'store_true') model_group = parser.add_argument_group('Model settings') model_group.add_argument('--dim', default = 512, type = int, help = 'Model dimension') model_group.add_argument('--text_seq_len', default = 256, type = int, help = 'Text sequence length') model_group.add_argument('--depth', default = 2, type = int, help = 'Model depth') model_group.add_argument('--heads', default = 8, type = int, help = 'Model number of heads') model_group.add_argument('--dim_head', default = 64, type = int, help = 'Model head dimension') train_group.add_argument('--ff_dropout', default = 0.0, type = float, help = 'Feed forward dropout.') train_group.add_argument('--attn_dropout', default = 0.0, type = float, help = 'Feed forward dropout.') model_group.add_argument('--reversible', dest = 'reversible', action='store_true') model_group.add_argument('--loss_img_weight', default = 7, type = int, help = 'Image loss weight') model_group.add_argument('--attn_types', default = 'full', type = str, help = 'comma separated list of attention types. attention type can be: full or sparse or axial_row or axial_col or conv_like.') model_group.add_argument('--shift_tokens', help = 'Use the shift tokens feature', action = 'store_true') model_group.add_argument('--rotary_emb', help = 'Use rotary embeddings', action = 'store_true') model_group.add_argument('--shared_attn_ids', default = None, type = str, help = 'Comma separated list of shared attention layer ids. Default: sharing is disabled') model_group.add_argument('--shared_ff_ids', default = None, type = str, help = 'Comma separated list of shared feed forward layer ids. Default: sharing is disabled') model_group.add_argument('--share_input_output_emb', help = 'Share input and output embeddings', action = 'store_true') args = parser.parse_args() # helpers def exists(val): return val is not None def get_trainable_params(model): return [params for params in model.parameters() if params.requires_grad] def cp_path_to_dir(cp_path, tag): """Convert a checkpoint path to a directory with `tag` inserted. If `cp_path` is already a directory, return it unchanged. """ if not isinstance(cp_path, Path): cp_path = Path(cp_path) if cp_path.is_dir(): return cp_path path_sans_extension = cp_path.parent / cp_path.stem cp_dir = Path(f'{path_sans_extension}-{tag}-cp') return cp_dir # constants WEBDATASET_IMAGE_TEXT_COLUMNS = tuple(args.wds.split(',')) ENABLE_WEBDATASET = True if len(WEBDATASET_IMAGE_TEXT_COLUMNS) == 2 else False DALLE_OUTPUT_FILE_NAME = args.dalle_output_file_name + ".pt" VAE_PATH = args.vae_path VQGAN_MODEL_PATH = args.vqgan_model_path VQGAN_CONFIG_PATH = args.vqgan_config_path DALLE_PATH = args.dalle_path RESUME = exists(DALLE_PATH) EPOCHS = args.epochs BATCH_SIZE = args.batch_size LEARNING_RATE = args.learning_rate GRAD_CLIP_NORM = args.clip_grad_norm LR_DECAY = args.lr_decay SAVE_EVERY_N_STEPS = args.save_every_n_steps KEEP_N_CHECKPOINTS = args.keep_n_checkpoints MODEL_DIM = args.dim TEXT_SEQ_LEN = args.text_seq_len DEPTH = args.depth HEADS = args.heads DIM_HEAD = args.dim_head REVERSIBLE = args.reversible LOSS_IMG_WEIGHT = args.loss_img_weight FF_DROPOUT = args.ff_dropout ATTN_DROPOUT = args.attn_dropout STABLE = args.stable_softmax SHIFT_TOKENS = args.shift_tokens ROTARY_EMB = args.rotary_emb ATTN_TYPES = tuple(args.attn_types.split(',')) SHARED_ATTN_IDS = tuple(args.shared_attn_ids.split(',')) if exists(args.shared_attn_ids) else None SHARED_FF_IDS = tuple(args.shared_ff_ids.split(',')) if exists(args.shared_ff_ids) else None SHARE_INPUT_OUTPUT_EMB = args.share_input_output_emb DEEPSPEED_CP_AUX_FILENAME = 'auxiliary.pt' if not ENABLE_WEBDATASET: # quit early if you used the wrong folder name assert Path(args.image_text_folder).exists(), f'The path {args.image_text_folder} was not found.' else: # quit early if no tar files were found if Path(args.image_text_folder).is_dir(): DATASET = [str(p) for p in Path(args.image_text_folder).glob("**/*") if ".tar" in str(p).lower()] # .name assert len(DATASET) > 0, 'The directory ({}) does not contain any WebDataset/.tar files.'.format(args.image_text_folder) print('Found {} WebDataset .tar(.gz) file(s) under given path {}!'.format(len(DATASET), args.image_text_folder)) elif ('http://' in args.image_text_folder.lower()) | ('https://' in args.image_text_folder.lower()): DATASET = f"pipe:curl -L -s {args.image_text_folder} || true" print('Found {} http(s) link under given path!'.format(len(DATASET), args.image_text_folder)) elif 'gs://' in args.image_text_folder.lower(): DATASET = f"pipe:gsutil cat {args.image_text_folder} || true" print('Found {} GCS link under given path!'.format(len(DATASET), args.image_text_folder)) elif '.tar' in args.image_text_folder: DATASET = args.image_text_folder print('Found WebDataset .tar(.gz) file under given path {}!'.format(args.image_text_folder)) else: raise Exception('No folder, no .tar(.gz) and no url pointing to tar files provided under {}.'.format(args.image_text_folder)) # initialize distributed backend distr_backend = distributed_utils.set_backend_from_args(args) distr_backend.initialize() using_deepspeed = \ distributed_utils.using_backend(distributed_utils.DeepSpeedBackend) is_root = distr_backend.is_root_worker() # tokenizer if exists(args.bpe_path): klass = HugTokenizer if args.hug else YttmTokenizer tokenizer = klass(args.bpe_path) elif args.chinese: tokenizer = ChineseTokenizer() # reconstitute vae if RESUME: dalle_path = Path(DALLE_PATH) if using_deepspeed: cp_dir = cp_path_to_dir(dalle_path, 'ds') assert cp_dir.is_dir(), \ f'DeepSpeed checkpoint directory {cp_dir} not found' dalle_path = cp_dir / DEEPSPEED_CP_AUX_FILENAME else: assert dalle_path.exists(), 'DALL-E model file does not exist' loaded_obj = torch.load(str(dalle_path), map_location='cpu') dalle_params, vae_params, weights = loaded_obj['hparams'], loaded_obj['vae_params'], loaded_obj['weights'] opt_state = loaded_obj.get('opt_state') scheduler_state = loaded_obj.get('scheduler_state') if vae_params is not None: vae = DiscreteVAE(**vae_params) elif args.taming: vae = VQGanVAE(VQGAN_MODEL_PATH, VQGAN_CONFIG_PATH) else: vae = OpenAIDiscreteVAE() resume_epoch = loaded_obj.get('epoch', 0) else: if exists(VAE_PATH): vae_path = Path(VAE_PATH) assert vae_path.exists(), 'VAE model file does not exist' assert not vae_path.is_dir(), \ ('Cannot load VAE model from directory; please use a ' 'standard *.pt checkpoint. ' 'Currently, merging a DeepSpeed-partitioned VAE into a DALLE ' 'model is not supported.') loaded_obj = torch.load(str(vae_path)) vae_params, weights = loaded_obj['hparams'], loaded_obj['weights'] vae = DiscreteVAE(**vae_params) vae.load_state_dict(weights) else: if is_root: print('using pretrained VAE for encoding images to tokens') vae_params = None if args.taming: vae = VQGanVAE(VQGAN_MODEL_PATH, VQGAN_CONFIG_PATH) else: vae = OpenAIDiscreteVAE() dalle_params = dict( num_text_tokens=tokenizer.vocab_size, text_seq_len=TEXT_SEQ_LEN, dim=MODEL_DIM, depth=DEPTH, heads=HEADS, dim_head=DIM_HEAD, reversible=REVERSIBLE, loss_img_weight=LOSS_IMG_WEIGHT, attn_types=ATTN_TYPES, ff_dropout=FF_DROPOUT, attn_dropout=ATTN_DROPOUT, stable=STABLE, shift_tokens=SHIFT_TOKENS, rotary_emb=ROTARY_EMB, shared_attn_ids=SHARED_ATTN_IDS, shared_ff_ids=SHARED_FF_IDS, share_input_output_emb=SHARE_INPUT_OUTPUT_EMB, ) resume_epoch = 0 IMAGE_SIZE = vae.image_size CHANNELS = vae.channels TRANSPARENT = CHANNELS == 4 IMAGE_MODE = 'RGBA' if CHANNELS == 4 else 'RGB' # configure OpenAI VAE for float16s if isinstance(vae, OpenAIDiscreteVAE) and args.fp16: vae.enc.blocks.output.conv.use_float16 = True # helpers def group_weight(model): group_decay, group_no_decay = [], [] for params in model.named_parameters(): if 'transformer' in params[0]: if 'bias' in params[0] or 'norm' in params[0]: group_no_decay.append(params[1]) continue group_decay.append(params[1]) assert len(list(model.parameters())) == len(group_decay) + len(group_no_decay) groups = [dict(params=group_decay), dict(params=group_no_decay, weight_decay=.0)] return groups # create dataset and dataloader is_shuffle = not distributed_utils.using_backend(distributed_utils.HorovodBackend) imagepreproc = T.Compose([ T.Lambda(lambda img: img.convert(IMAGE_MODE) if img.mode != IMAGE_MODE else img), T.RandomResizedCrop(IMAGE_SIZE, scale=(args.resize_ratio, 1.), ratio=(1., 1.)), T.ToTensor(), ]) def imagetransform(b): return Image.open(BytesIO(b)) def tokenize(s): return tokenizer.tokenize( s.decode('utf-8'), TEXT_SEQ_LEN, truncate_text=args.truncate_captions).squeeze(0) if ENABLE_WEBDATASET: DATASET_SIZE = int(1e9) # You need to set a nominal length for the Dataset in order to avoid warnings from DataLoader myimg, mycap = WEBDATASET_IMAGE_TEXT_COLUMNS image_text_mapping = { myimg: imagetransform, mycap: tokenize } image_mapping = { myimg: imagepreproc } def filter_dataset(item): # For e.g. C@H which (rarely) has no caption available. if mycap not in item: return False if myimg not in item: return False return True w_dataset = wds.WebDataset(DATASET, handler=wds.warn_and_continue) filtered_dataset = w_dataset.select(filter_dataset) ds = filtered_dataset.map_dict(**image_text_mapping).map_dict(**image_mapping).to_tuple(mycap, myimg).batched(BATCH_SIZE / distr_backend.get_world_size(), partial=True) else: ds = TextImageDataset( args.image_text_folder, text_len=TEXT_SEQ_LEN, image_size=IMAGE_SIZE, transparent=TRANSPARENT, resize_ratio=args.resize_ratio, truncate_captions=args.truncate_captions, tokenizer=tokenizer, shuffle=is_shuffle, ) assert len(ds) > 0, 'dataset is empty' if is_root: if not ENABLE_WEBDATASET: print(f'{len(ds)} image-text pairs found for training') # data sampler data_sampler = None if not is_shuffle: data_sampler = torch.utils.data.distributed.DistributedSampler( ds, num_replicas=distr_backend.get_world_size(), rank=distr_backend.get_rank() ) # WebLoader for WebDataset and DeepSpeed compatibility if ENABLE_WEBDATASET: dl = wds.WebLoader(ds, batch_size=None, shuffle=False, num_workers=4) # optionally add num_workers=2 (n) argument number_of_batches = DATASET_SIZE // (BATCH_SIZE * distr_backend.get_world_size()) dl = dl.slice(number_of_batches) dl.length = number_of_batches else: # Regular DataLoader for image-text-folder datasets dl = DataLoader(ds, batch_size=BATCH_SIZE, shuffle=is_shuffle, drop_last=True, sampler=data_sampler) # initialize DALL-E dalle = DALLE(vae=vae, **dalle_params) if not using_deepspeed: if args.fp16: dalle = dalle.half() dalle = dalle.cuda() if RESUME and not using_deepspeed: dalle.load_state_dict(weights) # optimizer opt = Adam(get_trainable_params(dalle), lr=LEARNING_RATE) if RESUME and opt_state: opt.load_state_dict(opt_state) # scheduler scheduler = None if LR_DECAY: scheduler = ReduceLROnPlateau( opt, mode="min", factor=0.5, patience=10, cooldown=10, min_lr=1e-6, verbose=True, ) if RESUME and scheduler_state: scheduler.load_state_dict(scheduler_state) # experiment tracker if is_root: model_config = dict( depth=DEPTH, heads=HEADS, dim_head=DIM_HEAD ) run = wandb.init( project=args.wandb_name, entity=args.wandb_entity, resume=False, config=model_config, ) # distribute distr_backend.check_batch_size(BATCH_SIZE) deepspeed_config = { 'train_batch_size': BATCH_SIZE, 'gradient_accumulation_steps': args.ga_steps, 'gradient_clipping': GRAD_CLIP_NORM, 'fp16': { 'enabled': args.fp16, }, 'amp': { 'enabled': args.amp, 'opt_level': 'O1', }, "flops_profiler": { "enabled": args.flops_profiler, "profile_step": 200, "module_depth": -1, "top_modules": 1, "detailed": True, "output_file": None # TODO Can't get this to work. }, } if deepspeed_config.get('zero_optimization', {}).get('stage', 0) >= 2: print(f"Checkpoints made with DeepSpeed ZeRO Stages 2 and 3 will be stored in deepspeed checkpoint folder") print(f"As such, they will require DeepSpeed as a dependency in order to resume from or generate with.") print("See the deespeed conversion script for details on how to convert your ZeRO stage 2/3 checkpoint to a single file.") print("If using a single GPU, consider running with apex automatic mixed precision instead for a similar speedup to ZeRO.") time.sleep(2) (distr_dalle, distr_opt, distr_dl, distr_scheduler) = distr_backend.distribute( args=args, model=dalle, optimizer=opt, model_parameters=get_trainable_params(dalle), training_data=( (None if ENABLE_WEBDATASET else ds) if using_deepspeed else dl ), # Do not pass the LR scheduler to DeepSpeed so we can manually # advance it. lr_scheduler=scheduler if LR_DECAY and not using_deepspeed else None, config_params=deepspeed_config, ) # Prefer scheduler in `deepspeed_config`. if LR_DECAY and distr_scheduler is None: distr_scheduler = scheduler avoid_model_calls = using_deepspeed and args.fp16 if RESUME and using_deepspeed: distr_dalle.load_checkpoint(str(cp_dir)) def save_model(path, epoch=0): save_obj = { 'hparams': dalle_params, 'vae_params': vae_params, 'epoch': epoch, 'version': __version__, 'vae_class_name': vae.__class__.__name__ } if using_deepspeed: cp_dir = cp_path_to_dir(path, 'ds') if KEEP_N_CHECKPOINTS is not None and is_root: checkpoints = sorted(glob(str(cp_dir / "global*")), key=os.path.getmtime, reverse=True) for checkpoint in checkpoints[KEEP_N_CHECKPOINTS:]: shutil.rmtree(checkpoint) distr_dalle.save_checkpoint(cp_dir, client_state=save_obj) if not is_root: return # Save auxiliary values so we can reuse the standard routine # for loading. save_obj = { **save_obj, # Save a nonsense value that directs the user to # further help. 'weights': ( 'To get a working standard checkpoint, ' 'look into consolidating DeepSpeed checkpoints.' ), } torch.save(save_obj, str(cp_dir / DEEPSPEED_CP_AUX_FILENAME)) if deepspeed_config.get('zero_optimization', {}).get('stage', 0) >= 2: # see https://github.com/lucidrains/DALLE-pytorch/wiki/DeepSpeed-Checkpoints return if not is_root: return save_obj = { **save_obj, 'weights': dalle.state_dict(), 'opt_state': opt.state_dict(), 'scheduler_state': (scheduler.state_dict() if scheduler else None) } torch.save(save_obj, path) def save_artifact(model_config, model_path, name = 'trained-dalle'): model_artifact = wandb.Artifact(name, type='model', metadata=dict(model_config)) model_artifact.add_file(model_path) run.log_artifact(model_artifact) # training # Saves a checkpoint before training begins to fail early when mis-configured. # See https://github.com/lucidrains/DALLE-pytorch/wiki/DeepSpeed-Checkpoints save_model(DALLE_OUTPUT_FILE_NAME, epoch=resume_epoch) for epoch in range(resume_epoch, EPOCHS): if data_sampler: data_sampler.set_epoch(epoch) for i, (text, images) in enumerate((dl if ENABLE_WEBDATASET else distr_dl)): if i % 10 == 0 and is_root: t = time.time() if args.fp16: images = images.half() text, images = map(lambda t: t.cuda(), (text, images)) loss = distr_dalle(text, images, return_loss=True) if using_deepspeed: distr_dalle.backward(loss) distr_dalle.step() # Gradients are automatically zeroed after the step else: loss.backward() clip_grad_norm_(distr_dalle.parameters(), GRAD_CLIP_NORM) distr_opt.step() distr_opt.zero_grad() # Collective loss, averaged avg_loss = distr_backend.average_all(loss) log = {} if i % 10 == 0 and is_root: print(epoch, i, f'loss - {avg_loss.item()}') log = { **log, 'epoch': epoch, 'iter': i, 'loss': avg_loss.item() } if i % SAVE_EVERY_N_STEPS == 0: save_model(DALLE_OUTPUT_FILE_NAME, epoch=epoch) if i % 100 == 0 and is_root: sample_text = text[:1] token_list = sample_text.masked_select(sample_text != 0).tolist() decoded_text = tokenizer.decode(token_list) if not avoid_model_calls: # CUDA index errors when we don't guard this image = dalle.generate_images(text[:1], filter_thres=0.9) # topk sampling at 0.9 if not avoid_model_calls: log['image'] = wandb.Image(image, caption=decoded_text) if i % 10 == 9 and is_root: sample_per_sec = BATCH_SIZE * 10 / (time.time() - t) log["sample_per_sec"] = sample_per_sec print(epoch, i, f'sample_per_sec - {sample_per_sec}') if i == 201 and args.flops_profiler: raise StopIteration("Profiler has finished running. Stopping training early.") if is_root: wandb.log(log) if LR_DECAY: distr_scheduler.step(avg_loss) save_model(DALLE_OUTPUT_FILE_NAME, epoch=epoch) if is_root: # save trained model to wandb as an artifact every epoch's end save_artifact(model_config, DALLE_OUTPUT_FILE_NAME) save_model(DALLE_OUTPUT_FILE_NAME, epoch=epoch) if is_root: wandb.save(DALLE_OUTPUT_FILE_NAME) save_artifact(model_config, DALLE_OUTPUT_FILE_NAME) wandb.finish()
23,672
33.967504
199
py
DALLE-pytorch
DALLE-pytorch-main/setup.py
from setuptools import setup, find_packages exec(open('dalle_pytorch/version.py').read()) setup( name = 'dalle-pytorch', packages = find_packages(), include_package_data = True, version = __version__, license='MIT', description = 'DALL-E - Pytorch', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', long_description_content_type = 'text/markdown', url = 'https://github.com/lucidrains/dalle-pytorch', keywords = [ 'artificial intelligence', 'attention mechanism', 'transformers', 'text-to-image' ], install_requires=[ 'axial_positional_embedding', 'DALL-E', 'einops>=0.3.2', 'ftfy', 'packaging', 'pillow', 'regex', 'rotary-embedding-torch', 'taming-transformers-rom1504', 'tokenizers', 'torch>=1.6', 'torchvision', 'transformers', 'tqdm', 'youtokentome', 'WebDataset' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
1,149
23.468085
65
py
DALLE-pytorch
DALLE-pytorch-main/generate.py
import argparse from pathlib import Path from tqdm import tqdm # torch import torch from einops import repeat # vision imports from PIL import Image from torchvision.utils import make_grid, save_image # dalle related classes and utils from dalle_pytorch import __version__ from dalle_pytorch import DiscreteVAE, OpenAIDiscreteVAE, VQGanVAE, DALLE from dalle_pytorch.tokenizer import tokenizer, HugTokenizer, YttmTokenizer, ChineseTokenizer # argument parsing parser = argparse.ArgumentParser() parser.add_argument('--dalle_path', type = str, required = True, help='path to your trained DALL-E') parser.add_argument('--vqgan_model_path', type=str, default = None, help='path to your trained VQGAN weights. This should be a .ckpt file. (only valid when taming option is enabled)') parser.add_argument('--vqgan_config_path', type=str, default = None, help='path to your trained VQGAN config. This should be a .yaml file. (only valid when taming option is enabled)') parser.add_argument('--text', type = str, required = True, help='your text prompt') parser.add_argument('--num_images', type = int, default = 128, required = False, help='number of images') parser.add_argument('--batch_size', type = int, default = 4, required = False, help='batch size') parser.add_argument('--top_k', type = float, default = 0.9, required = False, help='top k filter threshold') parser.add_argument('--outputs_dir', type = str, default = './outputs', required = False, help='output directory') parser.add_argument('--bpe_path', type = str, help='path to your huggingface BPE json file') parser.add_argument('--hug', dest='hug', action = 'store_true') parser.add_argument('--chinese', dest='chinese', action = 'store_true') parser.add_argument('--taming', dest='taming', action='store_true') parser.add_argument('--gentxt', dest='gentxt', action='store_true') args = parser.parse_args() # helper fns def exists(val): return val is not None # tokenizer if exists(args.bpe_path): klass = HugTokenizer if args.hug else YttmTokenizer tokenizer = klass(args.bpe_path) elif args.chinese: tokenizer = ChineseTokenizer() # load DALL-E dalle_path = Path(args.dalle_path) assert dalle_path.exists(), 'trained DALL-E must exist' load_obj = torch.load(str(dalle_path)) dalle_params, vae_params, weights, vae_class_name, version = load_obj.pop('hparams'), load_obj.pop('vae_params'), load_obj.pop('weights'), load_obj.pop('vae_class_name', None), load_obj.pop('version', None) # friendly print if exists(version): print(f'Loading a model trained with DALLE-pytorch version {version}') else: print('You are loading a model trained on an older version of DALL-E pytorch - it may not be compatible with the most recent version') # load VAE if args.taming: vae = VQGanVAE(args.vqgan_model_path, args.vqgan_config_path) elif vae_params is not None: vae = DiscreteVAE(**vae_params) else: vae = OpenAIDiscreteVAE() assert not (exists(vae_class_name) and vae.__class__.__name__ != vae_class_name), f'you trained DALL-E using {vae_class_name} but are trying to generate with {vae.__class__.__name__} - please make sure you are passing in the correct paths and settings for the VAE to use for generation' # reconstitute DALL-E dalle = DALLE(vae = vae, **dalle_params).cuda() dalle.load_state_dict(weights) # generate images image_size = vae.image_size texts = args.text.split('|') for j, text in tqdm(enumerate(texts)): if args.gentxt: text_tokens, gen_texts = dalle.generate_texts(tokenizer, text=text, filter_thres = args.top_k) text = gen_texts[0] else: text_tokens = tokenizer.tokenize([text], dalle.text_seq_len).cuda() text_tokens = repeat(text_tokens, '() n -> b n', b = args.num_images) outputs = [] for text_chunk in tqdm(text_tokens.split(args.batch_size), desc = f'generating images for - {text}'): output = dalle.generate_images(text_chunk, filter_thres = args.top_k) outputs.append(output) outputs = torch.cat(outputs) # save all images file_name = text outputs_dir = Path(args.outputs_dir) / file_name.replace(' ', '_')[:(100)] outputs_dir.mkdir(parents = True, exist_ok = True) for i, image in tqdm(enumerate(outputs), desc = 'saving images'): save_image(image, outputs_dir / f'{i}.png', normalize=True) with open(outputs_dir / 'caption.txt', 'w') as f: f.write(file_name) print(f'created {args.num_images} images at "{str(outputs_dir)}"')
4,695
31.611111
286
py
DALLE-pytorch
DALLE-pytorch-main/train_vae.py
import math from math import sqrt import argparse from pathlib import Path # torch import torch from torch.optim import Adam from torch.optim.lr_scheduler import ExponentialLR # vision imports from torchvision import transforms as T from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder from torchvision.utils import make_grid, save_image # dalle classes and utils from dalle_pytorch import distributed_utils from dalle_pytorch import DiscreteVAE # argument parsing parser = argparse.ArgumentParser() parser.add_argument('--image_folder', type = str, required = True, help='path to your folder of images for learning the discrete VAE and its codebook') parser.add_argument('--image_size', type = int, required = False, default = 128, help='image size') parser = distributed_utils.wrap_arg_parser(parser) train_group = parser.add_argument_group('Training settings') train_group.add_argument('--epochs', type = int, default = 20, help = 'number of epochs') train_group.add_argument('--batch_size', type = int, default = 8, help = 'batch size') train_group.add_argument('--learning_rate', type = float, default = 1e-3, help = 'learning rate') train_group.add_argument('--lr_decay_rate', type = float, default = 0.98, help = 'learning rate decay') train_group.add_argument('--starting_temp', type = float, default = 1., help = 'starting temperature') train_group.add_argument('--temp_min', type = float, default = 0.5, help = 'minimum temperature to anneal to') train_group.add_argument('--anneal_rate', type = float, default = 1e-6, help = 'temperature annealing rate') train_group.add_argument('--num_images_save', type = int, default = 4, help = 'number of images to save') model_group = parser.add_argument_group('Model settings') model_group.add_argument('--num_tokens', type = int, default = 8192, help = 'number of image tokens') model_group.add_argument('--num_layers', type = int, default = 3, help = 'number of layers (should be 3 or above)') model_group.add_argument('--num_resnet_blocks', type = int, default = 2, help = 'number of residual net blocks') model_group.add_argument('--smooth_l1_loss', dest = 'smooth_l1_loss', action = 'store_true') model_group.add_argument('--emb_dim', type = int, default = 512, help = 'embedding dimension') model_group.add_argument('--hidden_dim', type = int, default = 256, help = 'hidden dimension') model_group.add_argument('--kl_loss_weight', type = float, default = 0., help = 'KL loss weight') model_group.add_argument('--transparent', dest = 'transparent', action = 'store_true') args = parser.parse_args() # constants IMAGE_SIZE = args.image_size IMAGE_PATH = args.image_folder EPOCHS = args.epochs BATCH_SIZE = args.batch_size LEARNING_RATE = args.learning_rate LR_DECAY_RATE = args.lr_decay_rate NUM_TOKENS = args.num_tokens NUM_LAYERS = args.num_layers NUM_RESNET_BLOCKS = args.num_resnet_blocks SMOOTH_L1_LOSS = args.smooth_l1_loss EMB_DIM = args.emb_dim HIDDEN_DIM = args.hidden_dim KL_LOSS_WEIGHT = args.kl_loss_weight TRANSPARENT = args.transparent CHANNELS = 4 if TRANSPARENT else 3 IMAGE_MODE = 'RGBA' if TRANSPARENT else 'RGB' STARTING_TEMP = args.starting_temp TEMP_MIN = args.temp_min ANNEAL_RATE = args.anneal_rate NUM_IMAGES_SAVE = args.num_images_save # initialize distributed backend distr_backend = distributed_utils.set_backend_from_args(args) distr_backend.initialize() using_deepspeed = \ distributed_utils.using_backend(distributed_utils.DeepSpeedBackend) # data ds = ImageFolder( IMAGE_PATH, T.Compose([ T.Lambda(lambda img: img.convert(IMAGE_MODE) if img.mode != IMAGE_MODE else img), T.Resize(IMAGE_SIZE), T.CenterCrop(IMAGE_SIZE), T.ToTensor() ]) ) if distributed_utils.using_backend(distributed_utils.HorovodBackend): data_sampler = torch.utils.data.distributed.DistributedSampler( ds, num_replicas=distr_backend.get_world_size(), rank=distr_backend.get_rank()) else: data_sampler = None dl = DataLoader(ds, BATCH_SIZE, shuffle = not data_sampler, sampler=data_sampler) vae_params = dict( image_size = IMAGE_SIZE, num_layers = NUM_LAYERS, num_tokens = NUM_TOKENS, channels = CHANNELS, codebook_dim = EMB_DIM, hidden_dim = HIDDEN_DIM, num_resnet_blocks = NUM_RESNET_BLOCKS ) vae = DiscreteVAE( **vae_params, smooth_l1_loss = SMOOTH_L1_LOSS, kl_div_loss_weight = KL_LOSS_WEIGHT ) if not using_deepspeed: vae = vae.cuda() assert len(ds) > 0, 'folder does not contain any images' if distr_backend.is_root_worker(): print(f'{len(ds)} images found for training') # optimizer opt = Adam(vae.parameters(), lr = LEARNING_RATE) sched = ExponentialLR(optimizer = opt, gamma = LR_DECAY_RATE) if distr_backend.is_root_worker(): # weights & biases experiment tracking import wandb model_config = dict( num_tokens = NUM_TOKENS, smooth_l1_loss = SMOOTH_L1_LOSS, num_resnet_blocks = NUM_RESNET_BLOCKS, kl_loss_weight = KL_LOSS_WEIGHT ) run = wandb.init( project = 'dalle_train_vae', job_type = 'train_model', config = model_config ) # distribute distr_backend.check_batch_size(BATCH_SIZE) deepspeed_config = {'train_batch_size': BATCH_SIZE} (distr_vae, distr_opt, distr_dl, distr_sched) = distr_backend.distribute( args=args, model=vae, optimizer=opt, model_parameters=vae.parameters(), training_data=ds if using_deepspeed else dl, lr_scheduler=sched if not using_deepspeed else None, config_params=deepspeed_config, ) using_deepspeed_sched = False # Prefer scheduler in `deepspeed_config`. if distr_sched is None: distr_sched = sched elif using_deepspeed: # We are using a DeepSpeed LR scheduler and want to let DeepSpeed # handle its scheduling. using_deepspeed_sched = True def save_model(path): save_obj = { 'hparams': vae_params, } if using_deepspeed: cp_path = Path(path) path_sans_extension = cp_path.parent / cp_path.stem cp_dir = str(path_sans_extension) + '-ds-cp' distr_vae.save_checkpoint(cp_dir, client_state=save_obj) # We do not return so we do get a "normal" checkpoint to refer to. if not distr_backend.is_root_worker(): return save_obj = { **save_obj, 'weights': vae.state_dict() } torch.save(save_obj, path) # starting temperature global_step = 0 temp = STARTING_TEMP for epoch in range(EPOCHS): for i, (images, _) in enumerate(distr_dl): images = images.cuda() loss, recons = distr_vae( images, return_loss = True, return_recons = True, temp = temp ) if using_deepspeed: # Gradients are automatically zeroed after the step distr_vae.backward(loss) distr_vae.step() else: distr_opt.zero_grad() loss.backward() distr_opt.step() logs = {} if i % 100 == 0: if distr_backend.is_root_worker(): k = NUM_IMAGES_SAVE with torch.no_grad(): codes = vae.get_codebook_indices(images[:k]) hard_recons = vae.decode(codes) images, recons = map(lambda t: t[:k], (images, recons)) images, recons, hard_recons, codes = map(lambda t: t.detach().cpu(), (images, recons, hard_recons, codes)) images, recons, hard_recons = map(lambda t: make_grid(t.float(), nrow = int(sqrt(k)), normalize = True, range = (-1, 1)), (images, recons, hard_recons)) logs = { **logs, 'sample images': wandb.Image(images, caption = 'original images'), 'reconstructions': wandb.Image(recons, caption = 'reconstructions'), 'hard reconstructions': wandb.Image(hard_recons, caption = 'hard reconstructions'), 'codebook_indices': wandb.Histogram(codes), 'temperature': temp } wandb.save('./vae.pt') save_model(f'./vae.pt') # temperature anneal temp = max(temp * math.exp(-ANNEAL_RATE * global_step), TEMP_MIN) # lr decay # Do not advance schedulers from `deepspeed_config`. if not using_deepspeed_sched: distr_sched.step() # Collective loss, averaged avg_loss = distr_backend.average_all(loss) if distr_backend.is_root_worker(): if i % 10 == 0: lr = distr_sched.get_last_lr()[0] print(epoch, i, f'lr - {lr:6f} loss - {avg_loss.item()}') logs = { **logs, 'epoch': epoch, 'iter': i, 'loss': avg_loss.item(), 'lr': lr } wandb.log(logs) global_step += 1 if distr_backend.is_root_worker(): # save trained model to wandb as an artifact every epoch's end model_artifact = wandb.Artifact('trained-vae', type = 'model', metadata = dict(model_config)) model_artifact.add_file('vae.pt') run.log_artifact(model_artifact) if distr_backend.is_root_worker(): # save final vae and cleanup save_model('./vae-final.pt') wandb.save('./vae-final.pt') model_artifact = wandb.Artifact('trained-vae', type = 'model', metadata = dict(model_config)) model_artifact.add_file('vae-final.pt') run.log_artifact(model_artifact) wandb.finish()
9,727
29.117647
168
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/reversible.py
import torch import torch.nn as nn from operator import itemgetter from torch.autograd.function import Function from torch.utils.checkpoint import get_device_states, set_device_states # for routing arguments into the functions of the reversible layer def route_args(router, args, depth): routed_args = [(dict(), dict()) for _ in range(depth)] matched_keys = [key for key in args.keys() if key in router] for key in matched_keys: val = args[key] for depth, ((f_args, g_args), routes) in enumerate(zip(routed_args, router[key])): new_f_args, new_g_args = map(lambda route: ({key: val} if route else {}), routes) routed_args[depth] = ({**f_args, **new_f_args}, {**g_args, **new_g_args}) return routed_args # following example for saving and setting rng here https://pytorch.org/docs/stable/_modules/torch/utils/checkpoint.html class Deterministic(nn.Module): def __init__(self, net): super().__init__() self.net = net self.cpu_state = None self.cuda_in_fwd = None self.gpu_devices = None self.gpu_states = None def record_rng(self, *args): self.cpu_state = torch.get_rng_state() if torch.cuda._initialized: self.cuda_in_fwd = True self.gpu_devices, self.gpu_states = get_device_states(*args) def forward(self, *args, record_rng = False, set_rng = False, **kwargs): if record_rng: self.record_rng(*args) if not set_rng: return self.net(*args, **kwargs) rng_devices = [] if self.cuda_in_fwd: rng_devices = self.gpu_devices with torch.random.fork_rng(devices=rng_devices, enabled=True): torch.set_rng_state(self.cpu_state) if self.cuda_in_fwd: set_device_states(self.gpu_devices, self.gpu_states) return self.net(*args, **kwargs) # heavily inspired by https://github.com/RobinBruegger/RevTorch/blob/master/revtorch/revtorch.py # once multi-GPU is confirmed working, refactor and send PR back to source class ReversibleBlock(nn.Module): def __init__(self, f, g): super().__init__() self.f = Deterministic(f) self.g = Deterministic(g) def forward(self, x, f_args = {}, g_args = {}): x1, x2 = torch.chunk(x, 2, dim=2) y1, y2 = None, None with torch.no_grad(): y1 = x1 + self.f(x2, record_rng=self.training, **f_args) y2 = x2 + self.g(y1, record_rng=self.training, **g_args) return torch.cat([y1, y2], dim=2) def backward_pass(self, y, dy, f_args = {}, g_args = {}): y1, y2 = torch.chunk(y, 2, dim=2) del y dy1, dy2 = torch.chunk(dy, 2, dim=2) del dy with torch.enable_grad(): y1.requires_grad = True gy1 = self.g(y1, set_rng=True, **g_args) torch.autograd.backward(gy1, dy2) with torch.no_grad(): x2 = y2 - gy1 del y2, gy1 dx1 = dy1 + y1.grad del dy1 y1.grad = None with torch.enable_grad(): x2.requires_grad = True fx2 = self.f(x2, set_rng=True, **f_args) torch.autograd.backward(fx2, dx1, retain_graph=True) with torch.no_grad(): x1 = y1 - fx2 del y1, fx2 dx2 = dy2 + x2.grad del dy2 x2.grad = None x = torch.cat([x1, x2.detach()], dim=2) dx = torch.cat([dx1, dx2], dim=2) return x, dx class _ReversibleFunction(Function): @staticmethod def forward(ctx, x, blocks, args): ctx.args = args for block, kwarg in zip(blocks, args): x = block(x, **kwarg) ctx.y = x.detach() ctx.blocks = blocks return x @staticmethod def backward(ctx, dy): y = ctx.y args = ctx.args for block, kwargs in zip(ctx.blocks[::-1], args[::-1]): y, dy = block.backward_pass(y, dy, **kwargs) return dy, None, None class SequentialSequence(nn.Module): def __init__(self, layers, args_route = {}, layer_dropout = 0.): super().__init__() assert all(len(route) == len(layers) for route in args_route.values()), 'each argument route map must have the same depth as the number of sequential layers' self.layers = layers self.args_route = args_route self.layer_dropout = layer_dropout def forward(self, x, **kwargs): args = route_args(self.args_route, kwargs, len(self.layers)) layers_and_args = list(zip(self.layers, args)) for (f, g), (f_args, g_args) in layers_and_args: x = x + f(x, **f_args) x = x + g(x, **g_args) return x class ReversibleSequence(nn.Module): def __init__(self, blocks, args_route = {}): super().__init__() self.args_route = args_route self.blocks = nn.ModuleList([ReversibleBlock(f=f, g=g) for f, g in blocks]) def forward(self, x, **kwargs): x = torch.cat([x, x], dim=-1) blocks = self.blocks args = route_args(self.args_route, kwargs, len(blocks)) args = list(map(lambda x: {'f_args': x[0], 'g_args': x[1]}, args)) out = _ReversibleFunction.apply(x, blocks, args) return torch.stack(out.chunk(2, dim=-1)).mean(dim=0)
5,390
33.120253
165
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/dalle_pytorch.py
from math import log2, sqrt import torch from torch import nn, einsum import torch.nn.functional as F import numpy as np from axial_positional_embedding import AxialPositionalEmbedding from einops import rearrange from dalle_pytorch import distributed_utils from dalle_pytorch.vae import OpenAIDiscreteVAE, VQGanVAE from dalle_pytorch.transformer import Transformer, DivideMax # helpers def exists(val): return val is not None def default(val, d): return val if exists(val) else d class always(): def __init__(self, val): self.val = val def __call__(self, x, *args, **kwargs): return self.val def is_empty(t): return t.nelement() == 0 def masked_mean(t, mask, dim = 1): t = t.masked_fill(~mask[:, :, None], 0.) return t.sum(dim = 1) / mask.sum(dim = 1)[..., None] def prob_mask_like(shape, prob, device): return torch.zeros(shape, device = device).float().uniform_(0, 1) < prob def set_requires_grad(model, value): for param in model.parameters(): param.requires_grad = value def eval_decorator(fn): def inner(model, *args, **kwargs): was_training = model.training model.eval() out = fn(model, *args, **kwargs) model.train(was_training) return out return inner # sampling helpers def log(t, eps = 1e-20): return torch.log(t.clamp(min = eps)) def gumbel_noise(t): noise = torch.zeros_like(t).uniform_(0, 1) return -log(-log(noise)) def gumbel_sample(t, temperature = 1., dim = -1): return ((t / temperature) + gumbel_noise(t)).argmax(dim = dim) def top_k(logits, thres = 0.5): num_logits = logits.shape[-1] k = max(int((1 - thres) * num_logits), 1) val, ind = torch.topk(logits, k) probs = torch.full_like(logits, float('-inf')) probs.scatter_(1, ind, val) return probs class SharedEmbedding(nn.Embedding): def __init__(self, linear, start_index, end_index, **kwargs): super().__init__(end_index - start_index, linear.weight.shape[1], **kwargs) del self.weight self.linear = linear self.start_index = start_index self.end_index = end_index def forward(self, input): return F.embedding( input, self.linear.weight[self.start_index:self.end_index], self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse) # discrete vae class class ResBlock(nn.Module): def __init__(self, chan): super().__init__() self.net = nn.Sequential( nn.Conv2d(chan, chan, 3, padding = 1), nn.ReLU(), nn.Conv2d(chan, chan, 3, padding = 1), nn.ReLU(), nn.Conv2d(chan, chan, 1) ) def forward(self, x): return self.net(x) + x class DiscreteVAE(nn.Module): def __init__( self, image_size = 256, num_tokens = 512, codebook_dim = 512, num_layers = 3, num_resnet_blocks = 0, hidden_dim = 64, channels = 3, smooth_l1_loss = False, temperature = 0.9, straight_through = False, reinmax = False, kl_div_loss_weight = 0., normalization = ((*((0.5,) * 3), 0), (*((0.5,) * 3), 1)) ): super().__init__() assert log2(image_size).is_integer(), 'image size must be a power of 2' assert num_layers >= 1, 'number of layers must be greater than or equal to 1' has_resblocks = num_resnet_blocks > 0 self.channels = channels self.image_size = image_size self.num_tokens = num_tokens self.num_layers = num_layers self.temperature = temperature self.straight_through = straight_through self.reinmax = reinmax self.codebook = nn.Embedding(num_tokens, codebook_dim) hdim = hidden_dim enc_chans = [hidden_dim] * num_layers dec_chans = list(reversed(enc_chans)) enc_chans = [channels, *enc_chans] dec_init_chan = codebook_dim if not has_resblocks else dec_chans[0] dec_chans = [dec_init_chan, *dec_chans] enc_chans_io, dec_chans_io = map(lambda t: list(zip(t[:-1], t[1:])), (enc_chans, dec_chans)) enc_layers = [] dec_layers = [] for (enc_in, enc_out), (dec_in, dec_out) in zip(enc_chans_io, dec_chans_io): enc_layers.append(nn.Sequential(nn.Conv2d(enc_in, enc_out, 4, stride = 2, padding = 1), nn.ReLU())) dec_layers.append(nn.Sequential(nn.ConvTranspose2d(dec_in, dec_out, 4, stride = 2, padding = 1), nn.ReLU())) for _ in range(num_resnet_blocks): dec_layers.insert(0, ResBlock(dec_chans[1])) enc_layers.append(ResBlock(enc_chans[-1])) if num_resnet_blocks > 0: dec_layers.insert(0, nn.Conv2d(codebook_dim, dec_chans[1], 1)) enc_layers.append(nn.Conv2d(enc_chans[-1], num_tokens, 1)) dec_layers.append(nn.Conv2d(dec_chans[-1], channels, 1)) self.encoder = nn.Sequential(*enc_layers) self.decoder = nn.Sequential(*dec_layers) self.loss_fn = F.smooth_l1_loss if smooth_l1_loss else F.mse_loss self.kl_div_loss_weight = kl_div_loss_weight # take care of normalization within class self.normalization = tuple(map(lambda t: t[:channels], normalization)) self._register_external_parameters() def _register_external_parameters(self): """Register external parameters for DeepSpeed partitioning.""" if ( not distributed_utils.is_distributed or not distributed_utils.using_backend( distributed_utils.DeepSpeedBackend) ): return deepspeed = distributed_utils.backend.backend_module deepspeed.zero.register_external_parameter(self, self.codebook.weight) def norm(self, images): if not exists(self.normalization): return images means, stds = map(lambda t: torch.as_tensor(t).to(images), self.normalization) means, stds = map(lambda t: rearrange(t, 'c -> () c () ()'), (means, stds)) images = images.clone() images.sub_(means).div_(stds) return images @torch.no_grad() @eval_decorator def get_codebook_indices(self, images): logits = self(images, return_logits = True) codebook_indices = logits.argmax(dim = 1).flatten(1) return codebook_indices def decode( self, img_seq ): image_embeds = self.codebook(img_seq) b, n, d = image_embeds.shape h = w = int(sqrt(n)) image_embeds = rearrange(image_embeds, 'b (h w) d -> b d h w', h = h, w = w) images = self.decoder(image_embeds) return images def forward( self, img, return_loss = False, return_recons = False, return_logits = False, temp = None ): device, num_tokens, image_size, kl_div_loss_weight = img.device, self.num_tokens, self.image_size, self.kl_div_loss_weight assert img.shape[-1] == image_size and img.shape[-2] == image_size, f'input must have the correct image size {image_size}' img = self.norm(img) logits = self.encoder(img) if return_logits: return logits # return logits for getting hard image indices for DALL-E training temp = default(temp, self.temperature) one_hot = F.gumbel_softmax(logits, tau = temp, dim = 1, hard = self.straight_through) if self.straight_through and self.reinmax: # use reinmax for better second-order accuracy - https://arxiv.org/abs/2304.08612 # algorithm 2 one_hot = one_hot.detach() π0 = logits.softmax(dim = 1) π1 = (one_hot + (logits / temp).softmax(dim = 1)) / 2 π1 = ((log(π1) - logits).detach() + logits).softmax(dim = 1) π2 = 2 * π1 - 0.5 * π0 one_hot = π2 - π2.detach() + one_hot sampled = einsum('b n h w, n d -> b d h w', one_hot, self.codebook.weight) out = self.decoder(sampled) if not return_loss: return out # reconstruction loss recon_loss = self.loss_fn(img, out) # kl divergence logits = rearrange(logits, 'b n h w -> b (h w) n') log_qy = F.log_softmax(logits, dim = -1) log_uniform = torch.log(torch.tensor([1. / num_tokens], device = device)) kl_div = F.kl_div(log_uniform, log_qy, None, None, 'batchmean', log_target = True) loss = recon_loss + (kl_div * kl_div_loss_weight) if not return_recons: return loss return loss, out # main classes class CLIP(nn.Module): def __init__( self, *, dim_text = 512, dim_image = 512, dim_latent = 512, num_text_tokens = 10000, text_enc_depth = 6, text_seq_len = 256, text_heads = 8, num_visual_tokens = 512, visual_enc_depth = 6, visual_heads = 8, visual_image_size = 256, visual_patch_size = 32, channels = 3 ): super().__init__() self.text_emb = nn.Embedding(num_text_tokens, dim_text) self.text_pos_emb = nn.Embedding(text_seq_len, dim_text) self.text_transformer = Transformer(causal = False, seq_len = text_seq_len, dim = dim_text, depth = text_enc_depth, heads = text_heads, rotary_emb = False) self.to_text_latent = nn.Linear(dim_text, dim_latent, bias = False) assert visual_image_size % visual_patch_size == 0, 'Image dimensions must be divisible by the patch size.' num_patches = (visual_image_size // visual_patch_size) ** 2 patch_dim = channels * visual_patch_size ** 2 self.visual_patch_size = visual_patch_size self.to_visual_embedding = nn.Linear(patch_dim, dim_image) self.visual_pos_emb = nn.Embedding(num_patches, dim_image) self.visual_transformer = Transformer(causal = False, seq_len = num_patches, dim = dim_image, depth = visual_enc_depth, heads = visual_heads, rotary_emb = False) self.to_visual_latent = nn.Linear(dim_image, dim_latent, bias = False) self.temperature = nn.Parameter(torch.tensor(1.)) def forward( self, text, image, text_mask = None, return_loss = False ): b, device, p = text.shape[0], text.device, self.visual_patch_size text_emb = self.text_emb(text) text_emb += self.text_pos_emb(torch.arange(text.shape[1], device = device)) image_patches = rearrange(image, 'b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = p, p2 = p) image_emb = self.to_visual_embedding(image_patches) image_emb += self.visual_pos_emb(torch.arange(image_emb.shape[1], device = device)) enc_text = self.text_transformer(text_emb, mask = text_mask) enc_image = self.visual_transformer(image_emb) if exists(text_mask): text_latents = masked_mean(enc_text, text_mask, dim = 1) else: text_latents = enc_text.mean(dim = 1) image_latents = enc_image.mean(dim = 1) text_latents = self.to_text_latent(text_latents) image_latents = self.to_visual_latent(image_latents) text_latents, image_latents = map(lambda t: F.normalize(t, p = 2, dim = -1), (text_latents, image_latents)) temp = self.temperature.exp() if not return_loss: sim = einsum('n d, n d -> n', text_latents, image_latents) * temp return sim sim = einsum('i d, j d -> i j', text_latents, image_latents) * temp labels = torch.arange(b, device = device) loss = (F.cross_entropy(sim, labels) + F.cross_entropy(sim.t(), labels)) / 2 return loss # main DALL-E class class DALLE(nn.Module): def __init__( self, *, dim, vae, num_text_tokens = 10000, text_seq_len = 256, depth, heads = 8, dim_head = 64, reversible = False, attn_dropout = 0., ff_dropout = 0, sparse_attn = False, attn_types = None, loss_img_weight = 7, stable = False, sandwich_norm = False, shift_tokens = True, rotary_emb = True, shared_attn_ids = None, shared_ff_ids = None, share_input_output_emb = False, optimize_for_inference = False, ): super().__init__() assert isinstance(vae, (DiscreteVAE, OpenAIDiscreteVAE, VQGanVAE)), 'vae must be an instance of DiscreteVAE' image_size = vae.image_size num_image_tokens = vae.num_tokens image_fmap_size = (vae.image_size // (2 ** vae.num_layers)) image_seq_len = image_fmap_size ** 2 num_text_tokens = num_text_tokens + text_seq_len # reserve unique padding tokens for each position (text seq len) self.text_pos_emb = nn.Embedding(text_seq_len + 1, dim) if not rotary_emb else always(0) # +1 for <bos> self.image_pos_emb = AxialPositionalEmbedding(dim, axial_shape = (image_fmap_size, image_fmap_size)) if not rotary_emb else always(0) self.num_text_tokens = num_text_tokens # for offsetting logits index and calculating cross entropy loss self.num_image_tokens = num_image_tokens self.text_seq_len = text_seq_len self.image_seq_len = image_seq_len seq_len = text_seq_len + image_seq_len total_tokens = num_text_tokens + num_image_tokens self.total_tokens = total_tokens self.total_seq_len = seq_len self.vae = vae set_requires_grad(self.vae, False) # freeze VAE from being trained self.transformer = Transformer( dim = dim, causal = True, seq_len = seq_len, depth = depth, heads = heads, dim_head = dim_head, reversible = reversible, attn_dropout = attn_dropout, ff_dropout = ff_dropout, attn_types = attn_types, image_fmap_size = image_fmap_size, sparse_attn = sparse_attn, stable = stable, sandwich_norm = sandwich_norm, shift_tokens = shift_tokens, rotary_emb = rotary_emb, shared_attn_ids = shared_attn_ids, shared_ff_ids = shared_ff_ids, optimize_for_inference = optimize_for_inference, ) self.stable = stable if stable: self.norm_by_max = DivideMax(dim = -1) self.to_logits = nn.Sequential( nn.LayerNorm(dim), nn.Linear(dim, self.total_tokens), ) if share_input_output_emb: self.text_emb = SharedEmbedding(self.to_logits[1], 0, num_text_tokens) self.image_emb = SharedEmbedding(self.to_logits[1], num_text_tokens, total_tokens) else: self.text_emb = nn.Embedding(num_text_tokens, dim) self.image_emb = nn.Embedding(num_image_tokens, dim) seq_range = torch.arange(seq_len) logits_range = torch.arange(total_tokens) seq_range = rearrange(seq_range, 'n -> () n ()') logits_range = rearrange(logits_range, 'd -> () () d') logits_mask = ( ((seq_range >= text_seq_len) & (logits_range < num_text_tokens)) | ((seq_range < text_seq_len) & (logits_range >= num_text_tokens)) ) self.register_buffer('logits_mask', logits_mask, persistent=False) self.loss_img_weight = loss_img_weight @torch.no_grad() @eval_decorator def generate_texts( self, tokenizer, text = None, *, filter_thres = 0.5, temperature = 1. ): text_seq_len = self.text_seq_len if text is None or text == "": text_tokens = torch.tensor([[0]]).cuda() else: text_tokens = torch.tensor(tokenizer.tokenizer.encode(text)).cuda().unsqueeze(0) for _ in range(text_tokens.shape[1], text_seq_len): device = text_tokens.device tokens = self.text_emb(text_tokens) tokens += self.text_pos_emb(torch.arange(text_tokens.shape[1], device = device)) seq_len = tokens.shape[1] output_transf = self.transformer(tokens) if self.stable: output_transf = self.norm_by_max(output_transf) logits = self.to_logits(output_transf) # mask logits to make sure text predicts text (except last token), and image predicts image logits_mask = self.logits_mask[:, :seq_len] max_neg_value = -torch.finfo(logits.dtype).max logits.masked_fill_(logits_mask, max_neg_value) logits = logits[:, -1, :] filtered_logits = top_k(logits, thres = filter_thres) sample = gumbel_sample(filtered_logits, temperature = temperature, dim = -1) text_tokens = torch.cat((text_tokens, sample[:, None]), dim=-1) padding_tokens = set(np.arange(self.text_seq_len) + (self.num_text_tokens - self.text_seq_len)) texts = [tokenizer.tokenizer.decode(text_token, pad_tokens=padding_tokens) for text_token in text_tokens] return text_tokens, texts @torch.no_grad() @eval_decorator def generate_images( self, text, *, clip = None, filter_thres = 0.5, temperature = 1., img = None, num_init_img_tokens = None, cond_scale = 1., use_cache = False, ): vae, text_seq_len, image_seq_len, num_text_tokens = self.vae, self.text_seq_len, self.image_seq_len, self.num_text_tokens total_len = text_seq_len + image_seq_len text = text[:, :text_seq_len] # make sure text is within bounds out = text if exists(img): image_size = vae.image_size assert img.shape[1] == 3 and img.shape[2] == image_size and img.shape[3] == image_size, f'input image must have the correct image size {image_size}' indices = vae.get_codebook_indices(img) num_img_tokens = default(num_init_img_tokens, int(0.4375 * image_seq_len)) # OpenAI used 14 * 32 initial tokens to prime assert num_img_tokens < image_seq_len, 'number of initial image tokens for priming must be less than the total image token sequence length' indices = indices[:, :num_img_tokens] out = torch.cat((out, indices), dim = -1) prev_cache = None cache = {} if use_cache else None for cur_len in range(out.shape[1], total_len): is_image = cur_len >= text_seq_len text, image = out[:, :text_seq_len], out[:, text_seq_len:] logits = self.forward_with_cond_scale(text, image, cond_scale = cond_scale, cache = cache) logits = logits[:, -1, :] filtered_logits = top_k(logits, thres = filter_thres) sample = gumbel_sample(filtered_logits, temperature = temperature, dim = -1) sample -= (num_text_tokens if is_image else 0) # offset sampled token if it is an image token, since logit space is composed of text and then image tokens out = torch.cat((out, sample[:, None]), dim=-1) text_seq = out[:, :text_seq_len] img_seq = out[:, -image_seq_len:] images = vae.decode(img_seq) if exists(clip): scores = clip(text_seq, images, return_loss = False) return images, scores return images def forward_with_cond_scale(self, *args, cond_scale = 1, cache = None, **kwargs): if cond_scale == 1: return self(*args, **kwargs) prev_cache = cache.copy() if exists(cache) else None logits = self(*args, cache = cache, **kwargs) # discovery by Katherine Crowson # https://twitter.com/RiversHaveWings/status/1478093658716966912 null_cond_logits = self(*args, null_cond_prob = 1., cache = prev_cache, **kwargs) return null_cond_logits + (logits - null_cond_logits) * cond_scale def forward( self, text, image = None, return_loss = False, null_cond_prob = 0., cache = None, ): assert text.shape[-1] == self.text_seq_len, f'the length {text.shape[-1]} of the text tokens you passed in does not have the correct length ({self.text_seq_len})' batch, device, total_seq_len = text.shape[0], text.device, self.total_seq_len # randomly remove text condition with <null_cond_prob> probability if null_cond_prob > 0: null_mask = prob_mask_like((batch,), null_cond_prob, device = device) text *= rearrange(~null_mask, 'b -> b 1') # make sure padding in text tokens get unique padding token id text_range = torch.arange(self.text_seq_len, device = device) + (self.num_text_tokens - self.text_seq_len) text = torch.where(text == 0, text_range, text) # add <bos> text = F.pad(text, (1, 0), value = 0) tokens = self.text_emb(text) tokens += self.text_pos_emb(torch.arange(text.shape[1], device = device)) seq_len = tokens.shape[1] if exists(image) and not is_empty(image): is_raw_image = len(image.shape) == 4 if is_raw_image: image_size = self.vae.image_size channels = self.vae.channels assert tuple(image.shape[1:]) == (channels, image_size, image_size), f'invalid image of dimensions {image.shape} passed in during training' image = self.vae.get_codebook_indices(image) image_len = image.shape[1] image_emb = self.image_emb(image) image_emb += self.image_pos_emb(image_emb) tokens = torch.cat((tokens, image_emb), dim = 1) seq_len += image_len # when training, if the length exceeds the total text + image length # remove the last token, since it needs not to be trained if tokens.shape[1] > total_seq_len: seq_len -= 1 tokens = tokens[:, :-1] if self.stable: alpha = 0.1 tokens = tokens * alpha + tokens.detach() * (1 - alpha) if exists(cache) and cache.get('offset'): tokens = tokens[:, -1:] out = self.transformer(tokens, cache=cache) if self.stable: out = self.norm_by_max(out) logits = self.to_logits(out) # mask logits to make sure text predicts text (except last token), and image predicts image logits_mask = self.logits_mask[:, :seq_len] if exists(cache) and cache.get('offset'): logits_mask = logits_mask[:, -1:] max_neg_value = -torch.finfo(logits.dtype).max logits.masked_fill_(logits_mask, max_neg_value) if exists(cache): cache['offset'] = cache.get('offset', 0) + logits.shape[1] if not return_loss: return logits assert exists(image), 'when training, image must be supplied' offsetted_image = image + self.num_text_tokens labels = torch.cat((text[:, 1:], offsetted_image), dim = 1) logits = rearrange(logits, 'b n c -> b c n') loss_text = F.cross_entropy(logits[:, :, :self.text_seq_len], labels[:, :self.text_seq_len]) loss_img = F.cross_entropy(logits[:, :, self.text_seq_len:], labels[:, self.text_seq_len:]) loss = (loss_text + self.loss_img_weight * loss_img) / (self.loss_img_weight + 1) return loss
23,608
34.13244
170
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/vae.py
import io import sys import os import requests import PIL import warnings import hashlib import urllib import yaml from pathlib import Path from tqdm import tqdm from math import sqrt, log from packaging import version from omegaconf import OmegaConf from taming.models.vqgan import VQModel, GumbelVQ import importlib import torch from torch import nn import torch.nn.functional as F from einops import rearrange from dalle_pytorch import distributed_utils # constants CACHE_PATH = os.path.expanduser("~/.cache/dalle") OPENAI_VAE_ENCODER_PATH = 'https://cdn.openai.com/dall-e/encoder.pkl' OPENAI_VAE_DECODER_PATH = 'https://cdn.openai.com/dall-e/decoder.pkl' VQGAN_VAE_PATH = 'https://heibox.uni-heidelberg.de/f/140747ba53464f49b476/?dl=1' VQGAN_VAE_CONFIG_PATH = 'https://heibox.uni-heidelberg.de/f/6ecf2af6c658432c8298/?dl=1' # helpers methods def exists(val): return val is not None def default(val, d): return val if exists(val) else d def load_model(path): with open(path, 'rb') as f: return torch.load(f, map_location = torch.device('cpu')) def map_pixels(x, eps = 0.1): return (1 - 2 * eps) * x + eps def unmap_pixels(x, eps = 0.1): return torch.clamp((x - eps) / (1 - 2 * eps), 0, 1) def download(url, filename = None, root = CACHE_PATH): if ( not distributed_utils.is_distributed or distributed_utils.backend.is_local_root_worker() ): os.makedirs(root, exist_ok = True) filename = default(filename, os.path.basename(url)) download_target = os.path.join(root, filename) download_target_tmp = os.path.join(root, f'tmp.{filename}') if os.path.exists(download_target) and not os.path.isfile(download_target): raise RuntimeError(f"{download_target} exists and is not a regular file") if ( distributed_utils.is_distributed and not distributed_utils.backend.is_local_root_worker() and not os.path.isfile(download_target) ): # If the file doesn't exist yet, wait until it's downloaded by the root worker. distributed_utils.backend.local_barrier() if os.path.isfile(download_target): return download_target with urllib.request.urlopen(url) as source, open(download_target_tmp, "wb") as output: with tqdm(total=int(source.info().get("Content-Length")), ncols=80) as loop: while True: buffer = source.read(8192) if not buffer: break output.write(buffer) loop.update(len(buffer)) os.rename(download_target_tmp, download_target) if ( distributed_utils.is_distributed and distributed_utils.backend.is_local_root_worker() ): distributed_utils.backend.local_barrier() return download_target def make_contiguous(module): with torch.no_grad(): for param in module.parameters(): param.set_(param.contiguous()) # package versions def get_pkg_version(pkg_name): from pkg_resources import get_distribution return get_distribution(pkg_name).version # pretrained Discrete VAE from OpenAI class OpenAIDiscreteVAE(nn.Module): def __init__(self): super().__init__() assert version.parse(get_pkg_version('torch')) < version.parse('1.11.0'), 'torch version must be <= 1.10 in order to use OpenAI discrete vae' self.enc = load_model(download(OPENAI_VAE_ENCODER_PATH)) self.dec = load_model(download(OPENAI_VAE_DECODER_PATH)) make_contiguous(self) self.channels = 3 self.num_layers = 3 self.image_size = 256 self.num_tokens = 8192 @torch.no_grad() def get_codebook_indices(self, img): img = map_pixels(img) z_logits = self.enc.blocks(img) z = torch.argmax(z_logits, dim = 1) return rearrange(z, 'b h w -> b (h w)') def decode(self, img_seq): b, n = img_seq.shape img_seq = rearrange(img_seq, 'b (h w) -> b h w', h = int(sqrt(n))) z = F.one_hot(img_seq, num_classes = self.num_tokens) z = rearrange(z, 'b h w c -> b c h w').float() x_stats = self.dec(z).float() x_rec = unmap_pixels(torch.sigmoid(x_stats[:, :3])) return x_rec def forward(self, img): raise NotImplemented # VQGAN from Taming Transformers paper # https://arxiv.org/abs/2012.09841 def get_obj_from_str(string, reload=False): module, cls = string.rsplit(".", 1) if reload: module_imp = importlib.import_module(module) importlib.reload(module_imp) return getattr(importlib.import_module(module, package=None), cls) def instantiate_from_config(config): if not "target" in config: raise KeyError("Expected key `target` to instantiate.") return get_obj_from_str(config["target"])(**config.get("params", dict())) class VQGanVAE(nn.Module): def __init__(self, vqgan_model_path=None, vqgan_config_path=None): super().__init__() if vqgan_model_path is None: model_filename = 'vqgan.1024.model.ckpt' config_filename = 'vqgan.1024.config.yml' download(VQGAN_VAE_CONFIG_PATH, config_filename) download(VQGAN_VAE_PATH, model_filename) config_path = str(Path(CACHE_PATH) / config_filename) model_path = str(Path(CACHE_PATH) / model_filename) else: model_path = vqgan_model_path config_path = vqgan_config_path config = OmegaConf.load(config_path) model = instantiate_from_config(config["model"]) state = torch.load(model_path, map_location = 'cpu')['state_dict'] model.load_state_dict(state, strict = False) print(f"Loaded VQGAN from {model_path} and {config_path}") self.model = model # f as used in https://github.com/CompVis/taming-transformers#overview-of-pretrained-models f = config.model.params.ddconfig.resolution / config.model.params.ddconfig.attn_resolutions[0] self.num_layers = int(log(f)/log(2)) self.channels = 3 self.image_size = 256 self.num_tokens = config.model.params.n_embed self.is_gumbel = isinstance(self.model, GumbelVQ) self._register_external_parameters() def _register_external_parameters(self): """Register external parameters for DeepSpeed partitioning.""" if ( not distributed_utils.is_distributed or not distributed_utils.using_backend( distributed_utils.DeepSpeedBackend) ): return deepspeed = distributed_utils.backend.backend_module deepspeed.zero.register_external_parameter( self, self.model.quantize.embed.weight if self.is_gumbel else self.model.quantize.embedding.weight) @torch.no_grad() def get_codebook_indices(self, img): b = img.shape[0] img = (2 * img) - 1 _, _, [_, _, indices] = self.model.encode(img) if self.is_gumbel: return rearrange(indices, 'b h w -> b (h w)', b=b) return rearrange(indices, '(b n) -> b n', b = b) def decode(self, img_seq): b, n = img_seq.shape one_hot_indices = F.one_hot(img_seq, num_classes = self.num_tokens).float() z = one_hot_indices @ self.model.quantize.embed.weight if self.is_gumbel \ else (one_hot_indices @ self.model.quantize.embedding.weight) z = rearrange(z, 'b (h w) c -> b c h w', h = int(sqrt(n))) img = self.model.decode(z) img = (img.clamp(-1., 1.) + 1) * 0.5 return img def forward(self, img): raise NotImplemented
7,674
31.939914
149
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/distributed_utils.py
""" Utility functions for optional distributed execution. To use, 1. set the `BACKENDS` to the ones you want to make available, 2. in the script, wrap the argument parser with `wrap_arg_parser`, 3. in the script, set and use the backend by calling `set_backend_from_args`. You can check whether a backend is in use with the `using_backend` function. """ from dalle_pytorch.distributed_backends import \ DeepSpeedBackend, \ DummyBackend, \ HorovodBackend _DEFAULT_BACKEND = DummyBackend() """Which backend to use by default. Assumed to be _not_ distributed.""" BACKENDS = [ _DEFAULT_BACKEND, DeepSpeedBackend(), HorovodBackend(), ] is_distributed = None """Whether we are distributed.""" backend = None """Backend in usage.""" def wrap_arg_parser(parser): """Add arguments to support optional distributed backend usage.""" parser.add_argument( '--distributed_backend', '--distr_backend', type=str, default=None, help='which distributed backend to use. Do not distribute by default', ) for distr_backend in BACKENDS: parser = distr_backend.wrap_arg_parser(parser) return parser def set_backend_from_args(args): """Set and return the backend based on the given `args`.""" global is_distributed, backend # Handle this specially for backwards compatibility. if args.deepspeed: args.distributed_backend = DeepSpeedBackend.BACKEND_NAME if not args.distributed_backend: is_distributed = False backend = _DEFAULT_BACKEND return backend backend_name = args.distributed_backend.lower() for distr_backend in BACKENDS: if distr_backend.BACKEND_NAME.lower() == backend_name: backend = distr_backend if not backend.has_backend(): raise ModuleNotFoundError( f'{backend.BACKEND_NAME} backend selected but ' 'module not available' ) print(f'Using {backend.BACKEND_NAME} for distributed execution') is_distributed = True return backend raise ValueError( 'unknown backend; please check `distributed_utils.BACKENDS`') def require_set_backend(): """Raise an `AssertionError` when the backend has not been set.""" assert backend is not None, ( 'distributed backend is not set. Please call ' '`distributed_utils.set_backend_from_args` at the start of your script' ) def using_backend(test_backend): """Return whether the backend is set to `test_backend`. `test_backend` may be a string of the name of the backend or its class. """ require_set_backend() if isinstance(test_backend, str): return backend.BACKEND_NAME == test_backend return isinstance(backend, test_backend)
2,839
28.278351
79
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/version.py
__version__ = '1.6.6'
22
10.5
21
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/transformer.py
from collections import deque from collections.abc import Iterable from functools import partial from itertools import islice, cycle import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange from dalle_pytorch.reversible import ReversibleSequence, SequentialSequence from dalle_pytorch.attention import Attention, SparseAttention, SparseConvCausalAttention, SparseAxialCausalAttention from rotary_embedding_torch import RotaryEmbedding, broadcat # helpers def exists(val): return val is not None def default(val, d): return val if exists(val) else d def cast_tuple(val, depth = 1): return val if isinstance(val, Iterable) else (val,) * depth # classes class DivideMax(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(self, x): maxes = x.amax(dim = self.dim, keepdim = True).detach() return x / maxes class NonCached(nn.Module): """ A wrapper for layers that don't support the inference cache themselves. Reconstructs the full sequence before the layer and cuts the suffix of the outputs after the layer. """ def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x, *, cache = None, cache_key = None, **kwargs): n = x.shape[-2] if exists(cache): if cache_key in cache: x = torch.cat([cache[cache_key], x], dim=-2) cache[cache_key] = x out = self.fn(x, **kwargs) return out[:, -n:] class CachedAs(nn.Module): """ A wrapper that defines a key for the inference cache. """ def __init__(self, cache_key, fn): super().__init__() self.cache_key = cache_key self.fn = fn def forward(self, x, *, cache=None, **kwargs): return self.fn(x, cache=cache, cache_key=self.cache_key, **kwargs) # https://arxiv.org/abs/2103.17239 class LayerScale(nn.Module): def __init__(self, dim, depth, fn): super().__init__() if depth <= 18: init_eps = 0.1 elif depth > 18 and depth <= 24: init_eps = 1e-5 else: init_eps = 1e-6 scale = torch.zeros(1, 1, dim).fill_(init_eps) self.scale = nn.Parameter(scale) self.fn = fn def forward(self, x, **kwargs): return self.fn(x, **kwargs) * self.scale # layer norm class PreNorm(nn.Module): def __init__(self, dim, fn, sandwich = False): super().__init__() self.norm = nn.LayerNorm(dim) self.norm_out = nn.LayerNorm(dim) if sandwich else nn.Identity() self.fn = fn def forward(self, x, **kwargs): x = self.norm(x) x = self.fn(x, **kwargs) return self.norm_out(x) # feed forward class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim = -1) return x * F.gelu(gates) class FeedForward(nn.Module): def __init__(self, dim, dropout = 0., mult = 4.): super().__init__() self.net = nn.Sequential( nn.Linear(dim, dim * mult * 2), GEGLU(), nn.Dropout(dropout), nn.Linear(dim * mult, dim) ) def forward(self, x, cache=None, cache_key=None): return self.net(x) # token shift classes class PreShiftToken(nn.Module): def __init__(self, fn, image_size, seq_len): super().__init__() self.fn = fn self.image_size = image_size self.seq_len = seq_len self.img_seq_len = image_size ** 2 self.text_len = seq_len - self.img_seq_len + 1 def forward(self, x, cache=None, cache_key=None, **kwargs): seq_len, image_size, text_len = self.seq_len, self.image_size, self.text_len if exists(cache) and cache_key in cache: offset = cache['offset'] assert offset >= text_len, "cached inference for text is not supported" q = cache[cache_key] assert isinstance(q, deque) and len(q) == image_size x_top, x_left, *x_pass = x[:, -1].chunk(4, dim=-1) q.append((x_top, x_left)) x_top = q.popleft()[0] x_left = q[-2][1] if (offset - text_len) % image_size == 0: x_left = torch.zeros_like(x_left) x = torch.cat((x_top, x_left, *x_pass), dim=-1) return self.fn(x[:, None], cache=cache, **kwargs) n = x.shape[1] padding = seq_len - n + 1 # if sequence is shorter than the text length, no image tokens to shift if n < text_len: return self.fn(x, **kwargs) # get text and image tokens x_text, x_img = x[:, :text_len], x[:, text_len:] x_img = F.pad(x_img, (0, 0, 0, padding)) x_img = rearrange(x_img, 'b (h w) d -> b h w d', h = image_size) # shift 1 from the left for text tokens x_text_shift, x_text_pass = x_text.chunk(2, dim = -1) x_text_shift = F.pad(x_text_shift, (0, 0, 1, -1)) x_text = torch.cat((x_text_shift, x_text_pass), dim = -1) # shift from top, left for image tokens x_img_shift_top, x_img_shift_left, *x_img_pass = x_img.chunk(4, dim = -1) x_img_shift_left = F.pad(x_img_shift_left, (0, 0, 1, -1)) x_img_shift_top = F.pad(x_img_shift_top, (0, 0, 0, 0, 1, -1)) x_img = torch.cat((x_img_shift_top, x_img_shift_left, *x_img_pass), dim = -1) # merge text and image sequence back together x_img = rearrange(x_img, 'b h w d -> b (h w) d') x_img = x_img[:, :-padding] x = torch.cat((x_text, x_img), dim = 1) if exists(cache): dummy_top, dummy_left, *_ = x[:, -1].chunk(4, dim=-1) dummy_top, dummy_left = torch.zeros_like(dummy_top), torch.zeros_like(dummy_left) q = deque() x_img = x_img[:, -image_size:] for _ in range(image_size - x_img.shape[1]): q.append((dummy_top, dummy_left)) for i in range(x_img.shape[1]): q.append(x_img[:, i].chunk(4, dim=-1)[:2]) cache[cache_key] = q return self.fn(x, cache=cache, **kwargs) # main transformer class class Transformer(nn.Module): def __init__( self, *, dim, depth, seq_len, reversible = False, causal = True, heads = 8, dim_head = 64, ff_mult = 4, attn_dropout = 0., ff_dropout = 0., attn_types = None, image_fmap_size = None, sparse_attn = False, stable = False, sandwich_norm = False, shift_tokens = False, rotary_emb = True, shared_attn_ids = None, shared_ff_ids = None, optimize_for_inference = False, # use cache-friendly masked attention instead of sparse one ): super().__init__() layers = nn.ModuleList([]) sparse_layer = cast_tuple(sparse_attn, depth) self.seq_len = seq_len self.image_fmap_size = image_fmap_size attn_types = default(attn_types, ('full',)) attn_types = cast_tuple(attn_types) attn_type_layer = islice(cycle(attn_types), depth) shared_attn_ids = cycle(default(shared_attn_ids, range(depth))) shared_ff_ids = cycle(default(shared_ff_ids, range(depth))) shared_attn_layers = {} shared_ff_layers = {} for (ind, sparse_attn, attn_type, attn_id, ff_id) in \ zip(range(depth), sparse_layer, attn_type_layer, shared_attn_ids, shared_ff_ids): if attn_type == 'full': attn_class = partial(Attention, stable = stable) elif attn_type == 'sparse': attn_class = SparseAttention elif attn_type == 'axial_row': if optimize_for_inference: attn_class = partial(Attention, stable = stable, static_mask = self._get_attention_mask(attn_type)) else: attn_class = partial(SparseAxialCausalAttention, seq_len = seq_len, axis = 0, image_size = image_fmap_size, stable = stable) elif attn_type == 'axial_col': if optimize_for_inference: attn_class = partial(Attention, stable = stable, static_mask = self._get_attention_mask(attn_type)) else: attn_class = partial(SparseAxialCausalAttention, seq_len = seq_len, axis = 1, image_size = image_fmap_size, stable = stable) elif attn_type == 'conv_like': attn_class = partial(SparseConvCausalAttention, seq_len = seq_len, image_size = image_fmap_size, stable = stable) else: raise ValueError(f'attention type "{attn_type}" is not valid') attn, reused_attn_type = shared_attn_layers.get(attn_id, (None, None)) if not exists(attn): attn = attn_class(dim, causal = causal, seq_len = seq_len, heads = heads, dim_head = dim_head, dropout = attn_dropout) shared_attn_layers[attn_id] = (attn, attn_type) elif attn_type != reused_attn_type: raise ValueError('attn_types do not match shared_attn_ids ' f'(ind = {ind}, attn_type = "{attn_type}", reused_attn_type = "{reused_attn_type}")') ff = shared_ff_layers.get(ff_id) if not exists(ff): ff = FeedForward(dim, mult = ff_mult, dropout = ff_dropout) shared_ff_layers[ff_id] = ff if isinstance(attn, Attention): attn = CachedAs(f'attn_{ind}', attn) else: # at the moment, other attention classes don't support cache attn = NonCached(attn) if shift_tokens: attn = CachedAs(f'preshift_attn_{ind}', PreShiftToken(attn, image_size = image_fmap_size, seq_len = seq_len)) ff = CachedAs(f'preshift_ff_{ind}', PreShiftToken(ff, image_size = image_fmap_size, seq_len = seq_len)) layers.append(nn.ModuleList([ LayerScale(dim, ind + 1, PreNorm(dim, attn, sandwich = sandwich_norm)), LayerScale(dim, ind + 1, PreNorm(dim, ff, sandwich = sandwich_norm)) ])) execute_type = ReversibleSequence if reversible else SequentialSequence route_attn = ((True, False),) * depth route_all = ((True, True),) * depth attn_route_map = {'mask': route_attn, 'rotary_pos_emb': route_attn, 'cache': route_all} self.layers = execute_type(layers, args_route = attn_route_map) # generate positional embeddings for rotary pos_emb = None if rotary_emb: rot_dim = dim_head // 3 img_seq_len = (image_fmap_size ** 2) text_len = seq_len - img_seq_len + 1 text_pos_emb = RotaryEmbedding(dim = rot_dim) img_axial_pos_emb = RotaryEmbedding(dim = rot_dim, freqs_for = 'pixel') text_freqs = text_pos_emb(torch.arange(text_len)) img_to_text_freqs = text_pos_emb(torch.full((img_seq_len,), 8192)) # image is given a position far away from text text_freqs = torch.cat((text_freqs, img_to_text_freqs), dim = 0) img_freqs_axial = img_axial_pos_emb(torch.linspace(-1, 1, steps = image_fmap_size)) img_freqs = broadcat((rearrange(img_freqs_axial, 'i d -> i () d'), rearrange(img_freqs_axial, 'j d -> () j d')), dim = -1) img_freqs = rearrange(img_freqs, 'h w d -> (h w) d') text_axial_freqs = img_axial_pos_emb(torch.full((text_len,), -10.)) # text is given a position of -10 apart from the image axial positions, which is from range [-1, 1] text_axial_freqs = torch.cat((text_axial_freqs, text_axial_freqs), dim = -1) img_freqs = torch.cat((text_axial_freqs, img_freqs), dim = 0) pos_emb = torch.cat((text_freqs, img_freqs), dim = -1) pos_emb = rearrange(pos_emb, 'n d -> () n d') self.register_buffer('pos_emb', pos_emb) def forward(self, x, **kwargs): return self.layers(x, rotary_pos_emb = self.pos_emb, **kwargs) def _get_attention_mask(self, attn_type): img_seq_len = self.image_fmap_size ** 2 text_len = self.seq_len + 1 - img_seq_len static_mask = torch.zeros(self.seq_len, self.seq_len, dtype=torch.bool) static_mask[:, :text_len] = True if attn_type == 'axial_row': for row in range(self.image_fmap_size): begin = text_len + row * self.image_fmap_size end = text_len + (row + 1) * self.image_fmap_size static_mask[begin:end, begin:end] = True elif attn_type == 'axial_col': for col in range(self.image_fmap_size): begin = text_len + col static_mask[begin::self.image_fmap_size, begin::self.image_fmap_size] = True else: raise ValueError(f'attention type "{attn_type}" can\'t be simulated with a static mask') return static_mask
13,131
36.413105
180
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/tokenizer.py
# take from https://github.com/openai/CLIP/blob/main/clip/simple_tokenizer.py # to give users a quick easy start to training DALL-E without doing BPE import torch import youtokentome as yttm from tokenizers import Tokenizer from tokenizers.processors import ByteLevel from transformers import BertTokenizer import html import os from functools import lru_cache from pathlib import Path import ftfy import regex as re # OpenAI simple tokenizer @lru_cache() def default_bpe(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), "data/bpe_simple_vocab_16e6.txt") @lru_cache() def bytes_to_unicode(): bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) cs = bs[:] n = 0 for b in range(2 ** 8): if b not in bs: bs.append(b) cs.append(2 ** 8 + n) n += 1 cs = [chr(n) for n in cs] return dict(zip(bs, cs)) def get_pairs(word): pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip() def whitespace_clean(text): text = re.sub(r'\s+', ' ', text) text = text.strip() return text class SimpleTokenizer(object): def __init__(self, bpe_path = default_bpe()): self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} merges = Path(bpe_path).read_text(encoding='utf8').split('\n') merges = merges[1:49152 - 256 - 2 + 1] merges = [tuple(merge.split()) for merge in merges] vocab = list(bytes_to_unicode().values()) vocab = vocab + [v + '</w>' for v in vocab] for merge in merges: vocab.append(''.join(merge)) vocab.extend(['<|startoftext|>', '<|endoftext|>']) self.vocab_size = 49408 self.encoder = dict(zip(vocab, range(len(vocab)))) self.decoder = {v: k for k, v in self.encoder.items()} self.bpe_ranks = dict(zip(merges, range(len(merges)))) self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'} self.pat = re.compile( r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) def bpe(self, token): if token in self.cache: return self.cache[token] word = tuple(token[:-1]) + (token[-1] + '</w>',) pairs = get_pairs(word) if not pairs: return token + '</w>' while True: bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf'))) if bigram not in self.bpe_ranks: break first, second = bigram new_word = [] i = 0 while i < len(word): try: j = word.index(first, i) new_word.extend(word[i:j]) i = j except: new_word.extend(word[i:]) break if word[i] == first and i < len(word) - 1 and word[i + 1] == second: new_word.append(first + second) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) word = new_word if len(word) == 1: break else: pairs = get_pairs(word) word = ' '.join(word) self.cache[token] = word return word def encode(self, text): bpe_tokens = [] text = whitespace_clean(basic_clean(text)).lower() for token in re.findall(self.pat, text): token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) return bpe_tokens def decode(self, tokens, remove_start_end = True, pad_tokens = set()): if torch.is_tensor(tokens): tokens = tokens.tolist() if remove_start_end: tokens = [token for token in tokens if token not in (49406, 40407, 0)] text = ''.join([self.decoder[token] for token in tokens if token not in pad_tokens]) text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ') return text def tokenize(self, texts, context_length = 256, truncate_text = False): if isinstance(texts, str): texts = [texts] all_tokens = [self.encode(text) for text in texts] result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) for i, tokens in enumerate(all_tokens): if len(tokens) > context_length: if truncate_text: tokens = tokens[:context_length] else: raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") result[i, :len(tokens)] = torch.tensor(tokens) return result tokenizer = SimpleTokenizer() # huggingface tokenizer class HugTokenizer: def __init__(self, bpe_path = None): bpe_path = Path(bpe_path) assert bpe_path.exists(), f'BPE json path {str(bpe_path)} does not exist' tokenizer = Tokenizer.from_file(str(bpe_path)) tokenizer.post_processor = ByteLevel(trim_offsets = True) self.tokenizer = tokenizer self.vocab_size = tokenizer.get_vocab_size() def decode(self, tokens, pad_tokens = set()): if torch.is_tensor(tokens): tokens = tokens.tolist() ignore_ids = pad_tokens.union({0}) tokens = [token for token in tokens if token not in ignore_ids] return self.tokenizer.decode(tokens, skip_special_tokens = True) def encode(self, text): return self.tokenizer.encode(text).ids def tokenize(self, texts, context_length = 256, truncate_text = False): if isinstance(texts, str): texts = [texts] all_tokens = [self.encode(text) for text in texts] result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) for i, tokens in enumerate(all_tokens): if len(tokens) > context_length: if truncate_text: tokens = tokens[:context_length] else: raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") result[i, :len(tokens)] = torch.tensor(tokens) return result # chinese tokenizer class ChineseTokenizer: def __init__(self): tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') self.tokenizer = tokenizer self.vocab_size = tokenizer.vocab_size def decode(self, tokens, pad_tokens = set()): if torch.is_tensor(tokens): tokens = tokens.tolist() ignore_ids = pad_tokens.union({0}) tokens = [token for token in tokens if token not in ignore_ids] return self.tokenizer.decode(tokens) def encode(self, text): return torch.tensor(self.tokenizer.encode(text, add_special_tokens = False)) def tokenize(self, texts, context_length = 256, truncate_text = False): if isinstance(texts, str): texts = [texts] all_tokens = [self.encode(text) for text in texts] result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) for i, tokens in enumerate(all_tokens): if len(tokens) > context_length: if truncate_text: tokens = tokens[:context_length] else: raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") result[i, :len(tokens)] = torch.tensor(tokens) return result # yttm tokenizer class YttmTokenizer: def __init__(self, bpe_path = None): bpe_path = Path(bpe_path) assert bpe_path.exists(), f'BPE json path {str(bpe_path)} does not exist' tokenizer = yttm.BPE(model = str(bpe_path)) self.tokenizer = tokenizer self.vocab_size = tokenizer.vocab_size() def decode(self, tokens, pad_tokens = set()): if torch.is_tensor(tokens): tokens = tokens.tolist() return self.tokenizer.decode(tokens, ignore_ids = pad_tokens.union({0})) def encode(self, texts): encoded = self.tokenizer.encode(texts, output_type = yttm.OutputType.ID) return list(map(torch.tensor, encoded)) def tokenize(self, texts, context_length = 256, truncate_text = False): if isinstance(texts, str): texts = [texts] all_tokens = self.encode(texts) result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) for i, tokens in enumerate(all_tokens): if len(tokens) > context_length: if truncate_text: tokens = tokens[:context_length] else: raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") result[i, :len(tokens)] = torch.tensor(tokens) return result
9,432
34.329588
120
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/__init__.py
from dalle_pytorch.dalle_pytorch import DALLE, CLIP, DiscreteVAE from dalle_pytorch.vae import OpenAIDiscreteVAE, VQGanVAE from pkg_resources import get_distribution from dalle_pytorch.version import __version__
213
34.666667
64
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/attention.py
from inspect import isfunction from math import ceil import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat from rotary_embedding_torch import apply_rotary_emb # helpers def exists(val): return val is not None def uniq(arr): return{el: True for el in arr}.keys() def default(val, d): if exists(val): return val return d() if isfunction(d) else d def max_neg_value(t): return -torch.finfo(t.dtype).max def stable_softmax(t, dim = -1, alpha = 32 ** 2): t = t / alpha t = t - torch.amax(t, dim = dim, keepdim = True).detach() return (t * alpha).softmax(dim = dim) def apply_pos_emb(pos_emb, qkv): n = qkv[0].shape[-2] pos_emb = pos_emb[..., :n, :] return tuple(map(lambda t: apply_rotary_emb(pos_emb, t), qkv)) # classes class Attention(nn.Module): def __init__(self, dim, seq_len, causal = True, heads = 8, dim_head = 64, dropout = 0., stable = False, static_mask = None): super().__init__() inner_dim = dim_head * heads self.heads = heads self.seq_len = seq_len self.scale = dim_head ** -0.5 self.stable = stable self.causal = causal self.register_buffer('static_mask', static_mask, persistent=False) self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False) self.to_out = nn.Sequential( nn.Linear(inner_dim, dim), nn.Dropout(dropout) ) def forward(self, x, mask = None, rotary_pos_emb = None, cache = None, cache_key = None): b, n, _, h, device = *x.shape, self.heads, x.device softmax = torch.softmax if not self.stable else stable_softmax offset = cache.get('offset', 0) if exists(cache) else 0 qkv = self.to_qkv(x).chunk(3, dim = -1) q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), qkv) if exists(rotary_pos_emb): q, k, v = apply_pos_emb(rotary_pos_emb[..., offset:, :], (q, k, v)) q = q * self.scale if offset > 0: k_top, v_top = cache[cache_key] k = torch.cat([k_top, k], dim=-2) v = torch.cat([v_top, v], dim=-2) if exists(cache): cache[cache_key] = k, v dots = torch.einsum('b h i d, b h j d -> b h i j', q, k) mask_value = max_neg_value(dots) if exists(mask): mask = rearrange(mask, 'b j -> b () () j') dots.masked_fill_(~mask, mask_value) del mask if self.causal and offset == 0: # causality is naturally enforced for the cached inference i, j = dots.shape[-2:] mask = torch.ones(i, j, device = device).triu_(j - i + 1).bool() dots.masked_fill_(mask, mask_value) if exists(self.static_mask): dots.masked_fill_(~self.static_mask[offset:offset + n, :offset + n], mask_value) attn = softmax(dots, dim=-1) out = torch.einsum('b h i j, b h j d -> b h i d', attn, v) out = rearrange(out, 'b h n d -> b n (h d)') out = self.to_out(out) return out # sparse attention with convolutional pattern, as mentioned in the blog post. customizable kernel size and dilation class SparseConvCausalAttention(nn.Module): def __init__(self, dim, seq_len, image_size = 32, kernel_size = 5, dilation = 1, heads = 8, dim_head = 64, dropout = 0., stable = False, **kwargs): super().__init__() assert kernel_size % 2 == 1, 'kernel size must be odd' inner_dim = dim_head * heads self.seq_len = seq_len self.heads = heads self.scale = dim_head ** -0.5 self.image_size = image_size self.kernel_size = kernel_size self.dilation = dilation self.stable = stable self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False) self.to_out = nn.Sequential( nn.Linear(inner_dim, dim), nn.Dropout(dropout) ) def forward(self, x, mask = None, rotary_pos_emb = None): b, n, _, h, img_size, kernel_size, dilation, seq_len, device = *x.shape, self.heads, self.image_size, self.kernel_size, self.dilation, self.seq_len, x.device softmax = torch.softmax if not self.stable else stable_softmax img_seq_len = img_size ** 2 text_len = seq_len + 1 - img_seq_len # padding padding = seq_len - n + 1 mask = default(mask, lambda: torch.ones(b, text_len, device = device).bool()) x = F.pad(x, (0, 0, 0, padding), value = 0) mask = mask[:, :text_len] # derive query / keys / values qkv = self.to_qkv(x).chunk(3, dim = -1) q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h = h), qkv) if exists(rotary_pos_emb): q, k, v = apply_pos_emb(rotary_pos_emb, (q, k, v)) q *= self.scale ((q_text, q_img), (k_text, k_img), (v_text, v_img)) = map(lambda t: (t[:, :-img_seq_len], t[:, -img_seq_len:]), (q, k, v)) # text attention dots_text = einsum('b i d, b j d -> b i j', q_text, k_text) mask_value = max_neg_value(dots_text) i, j = dots_text.shape[-2:] text_causal_mask = torch.ones(i, j, device = device).triu_(j - i + 1).bool() dots_text.masked_fill_(text_causal_mask, mask_value) attn_text = softmax(dots_text, dim = -1) out_text = einsum('b i j, b j d -> b i d', attn_text, v_text) # image attention effective_kernel_size = (kernel_size - 1) * dilation + 1 same_padding = effective_kernel_size // 2 causal_padding = (same_padding * 2, 0, same_padding * 2, 0) k_img, v_img = map(lambda t: rearrange(t, 'b (h w) c -> b c h w', h = img_size), (k_img, v_img)) k_img, v_img = map(lambda t: F.pad(t, causal_padding), (k_img, v_img)) k_img, v_img = map(lambda t: F.unfold(t, kernel_size, dilation = dilation), (k_img, v_img)) k_img, v_img = map(lambda t: rearrange(t, 'b (d j) i -> b i j d', j = kernel_size ** 2), (k_img, v_img)) # let image attend to all of text dots_image = einsum('b i d, b i j d -> b i j', q_img, k_img) dots_image_to_text = einsum('b i d, b j d -> b i j', q_img, k_text) # use padding of 0 on tensor of 1s and unfold for padding mask i, j = dots_image.shape[-2:] ones = torch.ones((img_seq_len,), device = device) ones = rearrange(ones, '(h w) -> () () h w', h = img_size) ones = F.pad(ones, causal_padding, value = 0.) ones = F.unfold(ones, kernel_size, dilation = dilation) ones = rearrange(ones, 'b j i -> b i j') # mask image attention padding_mask = ones == 0. # concat text mask with image causal mask padding_mask = repeat(padding_mask, '() i j -> b i j', b = b * h) mask = repeat(mask, 'b j -> (b h) i j', i = i, h = h) mask = torch.cat((~mask, padding_mask), dim = -1) # image can attend to all of text dots = torch.cat((dots_image_to_text, dots_image), dim = -1) dots.masked_fill_(mask, mask_value) attn = softmax(dots, dim = -1) # aggregate attn_image_to_text, attn_image = attn[..., :text_len], attn[..., text_len:] out_image_to_image = einsum('b i j, b i j d -> b i d', attn_image, v_img) out_image_to_text = einsum('b i j, b j d -> b i d', attn_image_to_text, v_text) out_image = out_image_to_image + out_image_to_text # combine attended values for both text and image out = torch.cat((out_text, out_image), dim = 1) out = rearrange(out, '(b h) n d -> b n (h d)', h = h) out = self.to_out(out) return out[:, :n] # sparse axial causal attention class SparseAxialCausalAttention(nn.Module): def __init__(self, dim, seq_len, image_size = 32, axis = 0, heads = 8, dim_head = 64, dropout = 0., stable = False, **kwargs): super().__init__() assert axis in {0, 1}, 'axis must be either 0 (along height) or 1 (along width)' self.axis = axis inner_dim = dim_head * heads self.seq_len = seq_len self.heads = heads self.scale = dim_head ** -0.5 self.image_size = image_size self.stable = stable self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False) self.to_out = nn.Sequential( nn.Linear(inner_dim, dim), nn.Dropout(dropout) ) def forward(self, x, mask = None, rotary_pos_emb = None): b, n, _, h, img_size, axis, seq_len, device = *x.shape, self.heads, self.image_size, self.axis, self.seq_len, x.device softmax = torch.softmax if not self.stable else stable_softmax img_seq_len = img_size ** 2 text_len = seq_len + 1 - img_seq_len # padding padding = seq_len - n + 1 mask = default(mask, lambda: torch.ones(b, text_len, device = device).bool()) x = F.pad(x, (0, 0, 0, padding), value = 0) mask = mask[:, :text_len] # derive queries / keys / values qkv = self.to_qkv(x).chunk(3, dim = -1) q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h = h), qkv) if exists(rotary_pos_emb): q, k, v = apply_pos_emb(rotary_pos_emb, (q, k, v)) q *= self.scale ((q_text, q_img), (k_text, k_img), (v_text, v_img)) = map(lambda t: (t[:, :-img_seq_len], t[:, -img_seq_len:]), (q, k, v)) # text attention dots_text = einsum('b i d, b j d -> b i j', q_text, k_text) mask_value = max_neg_value(dots_text) i, j = dots_text.shape[-2:] text_causal_mask = torch.ones(i, j, device = device).triu_(j - i + 1).bool() dots_text.masked_fill_(text_causal_mask, mask_value) attn_text = softmax(dots_text, dim = -1) out_text = einsum('b i j, b j d -> b i d', attn_text, v_text) # image attention split_axis_einops = 'b (h w) c -> b h w c' if axis == 0 else 'b (h w) c -> b w h c' merge_axis_einops = 'b x n d -> b (x n) d' if axis == 0 else 'b x n d -> b (n x) d' # split out axis q_img, k_img, v_img = map(lambda t: rearrange(t, split_axis_einops, h = img_size), (q_img, k_img, v_img)) # similarity dots_image_to_image = einsum('b x i d, b x j d -> b x i j', q_img, k_img) dots_image_to_text = einsum('b x i d, b j d -> b x i j', q_img, k_text) dots = torch.cat((dots_image_to_text, dots_image_to_image), dim = -1) # mask so image has full attention to text, but causal along axis bh, x, i, j = dots.shape causal_mask = torch.ones(i, img_size, device = device).triu_(img_size - i + 1).bool() causal_mask = repeat(causal_mask, 'i j -> b x i j', b = bh, x = x) mask = repeat(mask, 'b j -> (b h) x i j', h = h, x = x, i = i) mask = torch.cat((~mask, causal_mask), dim = -1) dots.masked_fill_(mask, mask_value) # attention. attn = softmax(dots, dim = -1) # aggregate attn_image_to_text, attn_image_to_image = attn[..., :text_len], attn[..., text_len:] out_image_to_image = einsum('b x i j, b x j d -> b x i d', attn_image_to_image, v_img) out_image_to_text = einsum('b x i j, b j d -> b x i d', attn_image_to_text, v_text) out_image = out_image_to_image + out_image_to_text # merge back axis out_image = rearrange(out_image, merge_axis_einops, x = img_size) # combine attended values for both text and image out = torch.cat((out_text, out_image), dim = 1) out = rearrange(out, '(b h) n d -> b n (h d)', h = h) out = self.to_out(out) return out[:, :n] # microsoft sparse attention CUDA kernel class SparseAttention(Attention): def __init__( self, *args, block_size = 16, text_seq_len = 256, num_random_blocks = None, **kwargs ): super().__init__(*args, **kwargs) from deepspeed.ops.sparse_attention import SparseSelfAttention, VariableSparsityConfig self.block_size = block_size num_random_blocks = default(num_random_blocks, self.seq_len // block_size // 4) global_block_indices = list(range(ceil(text_seq_len / block_size))) self.attn_fn = SparseSelfAttention( sparsity_config = VariableSparsityConfig( num_heads = self.heads, block = self.block_size, num_random_blocks = num_random_blocks, global_block_indices = global_block_indices, attention = 'unidirectional' if self.causal else 'bidirectional' ), max_seq_length = self.seq_len, attn_mask_mode = 'add' ) def forward(self, x, mask = None, rotary_pos_emb = None): b, n, _, h, device = *x.shape, self.heads, x.device remainder = n % self.block_size mask = default(mask, lambda: torch.ones(b, n, device = device).bool()) if remainder > 0: padding = self.block_size - remainder x = F.pad(x, (0, 0, 0, padding), value = 0) mask = F.pad(mask, (0, padding), value = False) qkv = self.to_qkv(x).chunk(3, dim = -1) q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), qkv) if exists(rotary_pos_emb): q, k, v = apply_pos_emb(rotary_pos_emb, (q, k, v)) key_pad_mask = None if exists(mask): key_pad_mask = ~mask attn_mask = None if self.causal: i, j = q.shape[-2], k.shape[-2] mask = torch.ones(i, j, device = device).triu_(j - i + 1).bool() attn_mask = torch.zeros(i, j, device = device).to(q) mask_value = max_neg_value(q) / 2 attn_mask.masked_fill_(mask, mask_value) out = self.attn_fn(q, k, v, attn_mask = attn_mask, key_padding_mask = key_pad_mask) out = rearrange(out, 'b h n d -> b n (h d)') out = self.to_out(out) return out[:, :n]
14,131
34.418546
165
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/loader.py
from pathlib import Path from random import randint, choice import PIL from torch.utils.data import Dataset from torchvision import transforms as T class TextImageDataset(Dataset): def __init__(self, folder, text_len=256, image_size=128, truncate_captions=False, resize_ratio=0.75, transparent=False, tokenizer=None, shuffle=False ): """ @param folder: Folder containing images and text files matched by their paths' respective "stem" @param truncate_captions: Rather than throw an exception, captions which are too long will be truncated. """ super().__init__() self.shuffle = shuffle path = Path(folder) text_files = [*path.glob('**/*.txt')] image_files = [ *path.glob('**/*.png'), *path.glob('**/*.jpg'), *path.glob('**/*.jpeg'), *path.glob('**/*.bmp') ] text_files = {text_file.stem: text_file for text_file in text_files} image_files = {image_file.stem: image_file for image_file in image_files} keys = (image_files.keys() & text_files.keys()) self.keys = list(keys) self.text_files = {k: v for k, v in text_files.items() if k in keys} self.image_files = {k: v for k, v in image_files.items() if k in keys} self.text_len = text_len self.truncate_captions = truncate_captions self.resize_ratio = resize_ratio self.tokenizer = tokenizer image_mode = 'RGBA' if transparent else 'RGB' self.image_transform = T.Compose([ T.Lambda(lambda img: img.convert(image_mode) if img.mode != image_mode else img), T.RandomResizedCrop(image_size, scale=(self.resize_ratio, 1.), ratio=(1., 1.)), T.ToTensor() ]) def __len__(self): return len(self.keys) def random_sample(self): return self.__getitem__(randint(0, self.__len__() - 1)) def sequential_sample(self, ind): if ind >= self.__len__() - 1: return self.__getitem__(0) return self.__getitem__(ind + 1) def skip_sample(self, ind): if self.shuffle: return self.random_sample() return self.sequential_sample(ind=ind) def __getitem__(self, ind): key = self.keys[ind] text_file = self.text_files[key] image_file = self.image_files[key] descriptions = text_file.read_text().split('\n') descriptions = list(filter(lambda t: len(t) > 0, descriptions)) try: description = choice(descriptions) except IndexError as zero_captions_in_file_ex: print(f"An exception occurred trying to load file {text_file}.") print(f"Skipping index {ind}") return self.skip_sample(ind) tokenized_text = self.tokenizer.tokenize( description, self.text_len, truncate_text=self.truncate_captions ).squeeze(0) try: image_tensor = self.image_transform(PIL.Image.open(image_file)) except (PIL.UnidentifiedImageError, OSError) as corrupt_image_exceptions: print(f"An exception occurred trying to load file {image_file}.") print(f"Skipping index {ind}") return self.skip_sample(ind) # Success return tokenized_text, image_tensor
3,558
33.221154
112
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/distributed_backends/dummy_backend.py
from .distributed_backend import DistributedBackend class DummyBackend(DistributedBackend): """Acts like a distributed backend. Used as a stand-in replacement to obtain a non-distributed program. """ # We define this so we can use `super().__init__` but want this to # throw an error upon import. BACKEND_MODULE_NAME = 'NO MODULE' BACKEND_NAME = 'Dummy' def has_backend(self): return True def wrap_arg_parser(self, parser): return parser def _initialize(self): pass def _get_world_size(self): return 1 def _get_rank(self): return self.ROOT_RANK def _get_local_rank(self): return self.ROOT_RANK def _local_barrier(self): pass def _distribute( self, _args=None, model=None, optimizer=None, _model_parameters=None, training_data=None, lr_scheduler=None, **_kwargs, ): """Return the model, optimizer, dataloader, and learning rate scheduler as is. """ return (model, optimizer, training_data, lr_scheduler) def _average_all(self, tensor): return tensor
1,222
22.075472
79
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/distributed_backends/distributed_backend.py
""" An abstract backend for distributed deep learning. Provides several standard utility methods under a common API. Please check the documentation of the class `DistributedBackend` for details to implement a new backend. """ from importlib import import_module class DistributedBackend: """An abstract backend class for distributed deep learning. Provides several standard utility methods under a common API. Variables that must be overridden: - BACKEND_MODULE_NAME - BACKEND_NAME Methods that must be overridden: - wrap_arg_parser - _initialize - _get_world_size - _get_rank - _get_local_rank - _local_barrier - _distribute - _average_all """ BACKEND_MODULE_NAME = None """Name of the module to import for the backend.""" BACKEND_NAME = None """Name of the backend for printing.""" ROOT_RANK = 0 backend_module = None """The module to access the backend.""" is_initialized = False """Whether the backend is initialized.""" def __init__(self): if self.BACKEND_MODULE_NAME is None: raise NotImplementedError('BACKEND_MODULE_NAME is not set') if self.BACKEND_NAME is None: raise NotImplementedError('BACKEND_NAME is not set') def has_backend(self): """Return whether the backend module is now imported.""" try: self.backend_module = import_module(self.BACKEND_MODULE_NAME) except ModuleNotFoundError: return False return True def check_batch_size(self, batch_size): """Check whether the batch size makes sense for distribution.""" assert batch_size >= self.get_world_size(), \ (f"batch size can't be smaller than number of processes " f'({batch_size} < {self.get_world_size()})') def wrap_arg_parser(self, parser): """Add arguments to support optional distributed backend usage.""" raise NotImplementedError def initialize(self): """Initialize the distributed backend.""" self._initialize() self.is_initialized = True def _initialize(self): """Initialize the distributed backend.""" raise NotImplementedError def require_init(self): """Raise an error when the backend has not been initialized yet.""" assert self.is_initialized, \ (f'{BACKEND_NAME} backend has not been initialized; please call ' f'`distributed_utils.initialize` at the start of your script to ' f'allow optional distributed usage') def get_world_size(self): """Return the amount of distributed processes.""" self.require_init() return self._get_world_size() def _get_world_size(self): """Return the amount of distributed processes.""" raise NotImplementedError def get_rank(self): """Return the global rank of the calling worker process.""" self.require_init() return self._get_rank() def _get_rank(self): """Return the global rank of the calling worker process.""" raise NotImplementedError def get_local_rank(self): """Return the local rank of the calling worker process. The local rank is the rank based on a single node's processes. """ self.require_init() return self._get_local_rank() def _get_local_rank(self): """Return the local rank of the calling worker process. The local rank is the rank based on a single node's processes. """ raise NotImplementedError def is_root_worker(self): """Return whether the calling worker has the root rank.""" return self.get_rank() == self.ROOT_RANK def is_local_root_worker(self): """Return whether the calling worker has the root rank on this node.""" return self.get_local_rank() == self.ROOT_RANK def local_barrier(self): """Wait until all processes on this node have called this function.""" self.require_init() self._local_barrier() def _local_barrier(self): """Wait until all processes on this node have called this function.""" raise NotImplementedError def distribute( self, args=None, model=None, optimizer=None, model_parameters=None, training_data=None, lr_scheduler=None, **kwargs, ): """Return a distributed model engine, optimizer, dataloader, and learning rate scheduler. These are obtained by wrapping the given values with the backend. """ self.require_init() return self._distribute( args, model, optimizer, model_parameters, training_data, lr_scheduler, **kwargs, ) def _distribute( self, args=None, model=None, optimizer=None, model_parameters=None, training_data=None, lr_scheduler=None, **kwargs, ): """Return a distributed model engine, optimizer, dataloader, and learning rate scheduler. These are obtained by wrapping the given values with the backend. """ raise NotImplementedError def average_all(self, tensor): """Return the average of `tensor` over all workers.""" self.require_init() return self._average_all(tensor) def _average_all(self, tensor): """Return the average of `tensor` over all workers.""" raise NotImplementedError
5,671
30.687151
79
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/distributed_backends/deepspeed_backend.py
import json import os import torch from .distributed_backend import DistributedBackend class DeepSpeedBackend(DistributedBackend): """Distributed backend using the DeepSpeed engine.""" BACKEND_MODULE_NAME = 'deepspeed' BACKEND_NAME = 'DeepSpeed' def wrap_arg_parser(self, parser): if not self.has_backend(): parser.add_argument( '--deepspeed', type=lambda _: False, help=( 'whether to use DeepSpeed ' "(ignored since it's not available)" ), ) else: parser = self.backend_module.add_config_arguments(parser) parser.add_argument( '--local_rank', type=int, default=-1, help='local rank passed from distributed launcher', ) return parser def _initialize(self): self.backend_module.init_distributed() if torch.cuda.is_available(): torch.cuda.set_device(self._get_local_rank()) @staticmethod def _require_torch_distributed_init(): """Raise an error when `torch.distributed` has not been initialized yet. """ assert torch.distributed.is_initialized(), \ ('`torch.distributed` is not initialized; please call ' '`DeepSpeedBackend.initialize` at the start of your script') def _get_world_size(self): self._require_torch_distributed_init() return torch.distributed.get_world_size() def _get_rank(self): self._require_torch_distributed_init() return torch.distributed.get_rank() def _get_local_rank(self): self._require_torch_distributed_init() return int(os.environ['LOCAL_RANK']) def _local_barrier(self): self._require_torch_distributed_init() torch.distributed.barrier() def _check_args(self, args, optimizer, lr_scheduler, kwargs): """Return an appropriate optimizer and learning rate scheduler after checking the values passed to `distribute`. """ self._check_argvs(args, optimizer, lr_scheduler, kwargs) (optimizer, lr_scheduler) = self._check_config( args, optimizer, lr_scheduler, kwargs) return (optimizer, lr_scheduler) def _check_argvs(self, args, optimizer, lr_scheduler, kwargs): """Apply several sanity checks to the given command line arguments. """ has_json_config = (hasattr(args, 'deepspeed_config') and args.deepspeed_config is not None) has_dict_config = 'config_params' in kwargs if ( # No config given (not has_json_config and not has_dict_config) # JSON config file does not exist or (not has_dict_config and not os.path.isfile(args.deepspeed_config)) ): # Let DeepSpeed handle these argument errors. return if not args.deepspeed: print( 'WARNING: DeepSpeed backend was selected; setting ' '`args.deepspeed = True`' ) args.deepspeed = True if has_json_config and has_dict_config: print( 'WARNING: DeepSpeed config was given as both JSON file and ' 'Python dictionary. Python dictionary takes precedence.' ) def _check_config(self, args, optimizer, lr_scheduler, kwargs): """Return an appropriate optimizer and learning rate scheduler for the DeepSpeed configuration. """ if 'config_params' in kwargs: config = kwargs['config_params'] else: with open(args.deepspeed_config, 'r') as json_config_file: config = json.load(json_config_file) if 'optimizer' in config and optimizer is not None: print( 'WARNING: Optimizer encountered in both DeepSpeed config and ' 'keyword arguments. Optimizer in DeepSpeed config ' 'takes precedence.' ) optimizer = None if 'scheduler' in config and lr_scheduler is not None: print( 'WARNING: Learning rate scheduler encountered in both ' 'DeepSpeed config and keyword arguments. Learning rate ' 'scheduler in DeepSpeed config takes precedence.' ) # For the LR scheduler, the JSON config already has # precedence. We do this for forward compatibility. lr_scheduler = None return (optimizer, lr_scheduler) def _distribute( self, args=None, model=None, optimizer=None, model_parameters=None, training_data=None, lr_scheduler=None, **kwargs, ): """Return a distributed model engine, optimizer, dataloader, and learning rate scheduler. These are obtained by wrapping the given values with the backend. For the other or other possible arguments, see `deepspeed.initialize`. """ (optimizer, lr_scheduler) = self._check_args( args, optimizer, lr_scheduler, kwargs) return self.backend_module.initialize( args=args, model=model, optimizer=optimizer, model_parameters=model_parameters, training_data=training_data, lr_scheduler=lr_scheduler, **kwargs, ) def _average_all(self, tensor): self._require_torch_distributed_init() # We copy because modification happens in-place averaged = tensor.detach().clone() # We use `all_reduce` because it is better supported than `reduce` torch.distributed.all_reduce(averaged, torch.distributed.ReduceOp.SUM) return averaged / self.get_world_size()
5,987
33.813953
78
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/distributed_backends/horovod_backend.py
import torch from .distributed_backend import DistributedBackend class HorovodBackend(DistributedBackend): """Distributed backend using Horovod.""" BACKEND_MODULE_NAME = 'horovod.torch' BACKEND_NAME = 'Horovod' def wrap_arg_parser(self, parser): return parser def check_batch_size(self, batch_size): # Horovod uses the local batch size to determine the effective # batch size. pass def _initialize(self): self.backend_module.init() if torch.cuda.is_available(): torch.cuda.set_device(self._get_local_rank()) def _get_world_size(self): return self.backend_module.size() def _get_rank(self): return self.backend_module.rank() def _get_local_rank(self): return self.backend_module.local_rank() def _local_barrier(self): # Actually a global barrier but works for our purposes. self.backend_module.join() def _distribute( self, _args=None, model=None, optimizer=None, _model_parameters=None, training_data=None, lr_scheduler=None, **_kwargs, ): optimizer = self.backend_module.DistributedOptimizer(optimizer) self.backend_module.broadcast_parameters( model.state_dict(), root_rank=self.ROOT_RANK) self.backend_module.broadcast_optimizer_state( optimizer, root_rank=self.ROOT_RANK) return (model, optimizer, training_data, lr_scheduler) def _average_all(self, tensor): # Reduce op is average by default averaged = self.backend_module.allreduce(tensor) return averaged
1,703
27.881356
71
py
DALLE-pytorch
DALLE-pytorch-main/dalle_pytorch/distributed_backends/__init__.py
from .deepspeed_backend import DeepSpeedBackend from .distributed_backend import DistributedBackend from .dummy_backend import DummyBackend from .horovod_backend import HorovodBackend
184
36
51
py
covid-vax-stance
covid-vax-stance-main/classifier/classifier_predict.py
# Libraries import torch from torchtext.data import Field, TabularDataset, Iterator import torch.nn as nn import torch.nn.functional as F from transformers import AutoTokenizer, BertForSequenceClassification import os import csv import time import argparse import warnings torch.manual_seed(42) warnings.filterwarnings('ignore') #%% PARSE ARGUMENTS CUDA_DEV = 'cuda:0' if torch.cuda.is_available() else 'cpu' parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("in_path", type=str, help="path to a CSV file or directory where the CSV files are stored") parser.add_argument("--text_col", type=str, default="text", help="Header of the text column in the CSV files") parser.add_argument("--out_dir", type=str, default=".", help="path to the directory where the predicted output files will be stored (default: same directory as the code file)") parser.add_argument("--model_dir", type=str, default="./covid_vax_model/", help="path to the directory where the trained model is stored") parser.add_argument("--device", type=str, default=CUDA_DEV, help="cuda device") parser.add_argument("--max_seq_len", type=int, default=100, help="Maximum Sequence Length") parser.add_argument("--batch_size", type=int, default=16, help="Batch Size") args = parser.parse_args() device = torch.device(args.device) print("RUNNING ON DEVICE:", device) INPATH = args.in_path OUTDIR = args.out_dir MODEL_PATH = args.model_dir TEXT_COL_HEAD = args.text_col MAX_SEQ_LEN = args.max_seq_len BATCH_SIZE = args.batch_size #%% INITTIALIZE TOKENIZER *************************************************** tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH) PAD_INDEX = tokenizer.convert_tokens_to_ids(tokenizer.pad_token) UNK_INDEX = tokenizer.convert_tokens_to_ids(tokenizer.unk_token) # label_field = Field(sequential=False, use_vocab=False, batch_first=True, dtype=torch.float) text_field = Field(use_vocab=False, tokenize=tokenizer.encode, lower=False, include_lengths=False, batch_first=True, fix_length=MAX_SEQ_LEN, pad_token=PAD_INDEX, unk_token=UNK_INDEX) #%% MODULES ***************************************************************** class BERT(nn.Module): def __init__(self): super(BERT, self).__init__() self.encoder = BertForSequenceClassification.from_pretrained(MODEL_PATH, num_labels = 3) def forward(self, text, label= None): output = self.encoder(text, labels=label)[:2] if not label is None: loss, text_fea = output else: text_fea = output[0] loss = None return loss, text_fea classmap = ['Neutral', 'AntiVax', 'ProVax'] def predict(data_path, model): model.eval() # READ CSV FILE AND CREATE AN ITERATOR with open(data_path) as fp: rdr = csv.reader(fp) txtcol = next(rdr).index(TEXT_COL_HEAD) fields = [(None, None)] * (txtcol) + [('text', text_field)] data = TabularDataset(data_path, format='CSV', fields = fields , skip_header = True) test_iter = Iterator(data, batch_size=BATCH_SIZE, device=device, train=False, shuffle=False, sort=False) # PREDICT CLASS PROBABILITIES AND COMPUTE STANCE y_pred = [] raw = [] with torch.no_grad(): for text, _ in test_iter: text = text.type(torch.LongTensor) text = text.to(device) output = model(text) _, output = output raw.extend(F.softmax(output, 1).tolist()) y_pred.extend(torch.argmax(output, 1).tolist()) return [classmap[x] for x in y_pred], raw #%% MAIN ******************************************************************* model = BERT().to(device) print("Model Loaded from:", MODEL_PATH) print("Saving predicted files to:", OUTDIR) if os.path.isfile(INPATH): INDIR, fn = os.path.split(INPATH) files = [fn] else: INDIR = INPATH files = sorted([f for f in next(os.walk(INDIR))[2]]) if not os.path.exists(OUTDIR): os.makedirs(OUTDIR) for fn in files: t0 = time.time() print("\nCalculating for file:", fn, flush = True) path = os.path.join(INDIR, fn) preds, raw = predict(path, model) with open(path) as fp: rdr = csv.reader(fp) head = next(rdr) rdr = list(rdr) with open(os.path.join(OUTDIR, fn), 'w') as fo: wrt = csv.writer(fo) wrt.writerow(head + ['pred', 'p(Neutral)', 'p(AntiVax)', 'p(ProVax)']) for row, pr, rs in zip(rdr, preds, raw): wrt.writerow(row + [pr]+ [round(x, 4) for x in rs]) t1 = time.time() print("Completed in %0.1f mins"%((t1 - t0) / 60))
5,168
33.46
176
py
libgpuarray
libgpuarray-master/setup.py
import sys import os import versioneer import distutils.command.clean import shutil have_cython = False try: import Cython if Cython.__version__ < '0.25': raise Exception('cython is too old or not installed ' '(at least 0.25 required)') from Cython.Build import cythonize have_cython = True except Exception: # for devel version raise def cythonize(args): for arg in args: arg.sources = [(s[:-3] + 'c' if s.endswith('.pyx') else s) for s in arg.sources] # clang gives an error if passed -mno-fused-madd # (and I don't even understand why it's passed in the first place) if sys.platform == 'darwin': from distutils import sysconfig, ccompiler sysconfig_customize_compiler = sysconfig.customize_compiler def customize_compiler(compiler): sysconfig_customize_compiler(compiler) if sys.platform == 'darwin': while '-mno-fused-madd' in compiler.compiler: compiler.compiler.remove('-mno-fused-madd') while '-mno-fused-madd' in compiler.compiler_so: compiler.compiler_so.remove('-mno-fused-madd') while '-mno-fused-madd' in compiler.linker_so: compiler.linker_so.remove('-mno-fused-madd') sysconfig.customize_compiler = customize_compiler ccompiler.customize_compiler = customize_compiler try: from setuptools import setup, Extension as _Extension # setuptools is stupid and rewrites "sources" to change '.pyx' to '.c' # if it can't find Pyrex (and in recent versions, Cython). # # This is a really stupid thing to do behind the users's back (since # it breaks development builds) especially with no way of disabling it # short of the hack below. class Extension(_Extension): def __init__(self, *args, **kwargs): save_sources = kwargs.get('sources', None) _Extension.__init__(self, *args, **kwargs) self.sources = save_sources except ImportError: from distutils.core import setup, Extension import numpy as np to_del = [] for i, a in enumerate(sys.argv): if a == '--disable-cython': to_del.append(i) have_cython = False for i in reversed(to_del): del sys.argv[i] del to_del include_dirs = [np.get_include()] library_dirs = [] if sys.platform == 'win32' and not os.getenv('CONDA_BUILD'): # This is a hack so users don't need to do many steps for windows install # Just use the default location. current_dir = os.path.abspath(os.path.dirname(__file__)) include_dirs += [os.path.join(current_dir, 'src')] default_bin_dir = os.path.join(current_dir, 'lib') if not os.path.isdir(default_bin_dir): raise RuntimeError('default binary dir {} does not exist, you may need to build the C library in release mode'.format(default_bin_dir)) library_dirs += [default_bin_dir] class cmd_clean(distutils.command.clean.clean): def run(self): import glob with open('.clean', 'r') as f: ignores = f.read() for wildcard in filter(bool, ignores.split('\n')): for filename in glob.glob(wildcard): try: os.remove(filename) except OSError: shutil.rmtree(filename, ignore_errors=True) # It's an old-style class in Python 2.7... distutils.command.clean.clean.run(self) ea = [] if sys.platform in ('darwin', 'linux'): # Silence unused stuff warnings ea = ["-Wno-unused-variable", "-Wno-unused-function"] exts = [Extension('pygpu.gpuarray', sources=['pygpu/gpuarray.pyx'], include_dirs=include_dirs, libraries=['gpuarray'], library_dirs=library_dirs, extra_compile_args=ea, define_macros=[('GPUARRAY_SHARED', None)] ), Extension('pygpu.blas', sources=['pygpu/blas.pyx'], include_dirs=include_dirs, libraries=['gpuarray'], library_dirs=library_dirs, extra_compile_args=ea, define_macros=[('GPUARRAY_SHARED', None)] ), Extension('pygpu._elemwise', sources=['pygpu/_elemwise.pyx'], include_dirs=include_dirs, libraries=['gpuarray'], library_dirs=library_dirs, extra_compile_args=ea, define_macros=[('GPUARRAY_SHARED', None)] ), Extension('pygpu.collectives', sources=['pygpu/collectives.pyx'], include_dirs=include_dirs, libraries=['gpuarray'], library_dirs=library_dirs, extra_compile_args=ea, define_macros=[('GPUARRAY_SHARED', None)] )] cmds = versioneer.get_cmdclass() cmds["clean"] = cmd_clean version_data = versioneer.get_versions() if version_data['error'] is not None: raise ValueError("Can't determine version for build: %s\n Please make sure that your git checkout includes tags." % (version_data['error'],)) setup(name='pygpu', version=version_data['version'], cmdclass=cmds, description='numpy-like wrapper on libgpuarray for GPU computations', packages=['pygpu', 'pygpu/tests'], include_package_data=True, package_data={'pygpu': ['gpuarray.h', 'gpuarray_api.h', 'blas_api.h', 'numpy_compat.h', 'collectives.h', 'collectives_api.h']}, ext_modules=cythonize(exts), install_requires=['mako>=0.7', 'six'], )
5,763
34.801242
146
py
libgpuarray
libgpuarray-master/versioneer.py
# Version: 0.18 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy * [![Latest Version] (https://pypip.in/version/versioneer/badge.svg?style=flat) ](https://pypi.python.org/pypi/versioneer/) * [![Build Status] (https://travis-ci.org/warner/python-versioneer.png?branch=master) ](https://travis-ci.org/warner/python-versioneer) This is a tool for managing a recorded version number in distutils-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere to your $PATH * add a `[versioneer]` section to your setup.cfg (see below) * run `versioneer install` in your source tree, commit the results ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes. The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See [details.md](details.md) in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/warner/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other langauges) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/warner/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/warner/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ### Unicode version strings While Versioneer works (and is continually tested) with both Python 2 and Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. Newer releases probably generate unicode version strings on py2. It's not clear that this is wrong, but it may be surprising for applications when then write these strings to a network connection or include them in bytes-oriented APIs like cryptographic checksums. [Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates this question. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the Creative Commons "Public Domain Dedication" license (CC0-1.0), as described in https://creativecommons.org/publicdomain/zero/1.0/ . """ from __future__ import print_function try: import configparser except ImportError: import ConfigParser as configparser import errno import json import os import re import subprocess import sys class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. me = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(me)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(me), versioneer_py)) except NameError: pass return root def get_config_from_root(root): """Read the project setup.cfg file to determine Versioneer config.""" # This might raise EnvironmentError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.SafeConfigParser() with open(setup_cfg, "r") as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory def get(parser, name): if parser.has_option("versioneer", name): return parser.get("versioneer", name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = get(parser, "style") or "" cfg.versionfile_source = get(parser, "versionfile_source") cfg.versionfile_build = get(parser, "versionfile_build") cfg.tag_prefix = get(parser, "tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = get(parser, "parentdir_prefix") cfg.verbose = get(parser, "verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode LONG_VERSION_PY['git'] = ''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%%s*" %% tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%%d" %% pieces["distance"] else: # exception #1 rendered = "0.post.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.18) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except EnvironmentError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version(): """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(): """Get the custom setuptools/distutils subclasses used by Versioneer.""" if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/warner/python-versioneer/issues/52 cmds = {} # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: from py2exe.build_exe import py2exe as _py2exe # py2 class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ INIT_PY_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ def do_setup(): """Main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1)
68,610
36.65697
79
py
libgpuarray
libgpuarray-master/src/head.py
# Used to generate the string tables to embed the cluda headers. # Usage: python head.py <file> # This will output <file>.c def wrt(f, n, b): f.write(b',') n += 1 if n > 10: f.write(b'\n') n = 0 else: f.write(b' ') f.write(b"0x%02x" % (b,)) return n def convert(src, dst): src_name = src.replace('.', '_') with open(src, 'rb') as f: src_data = f.read() with open(dst, 'wb') as f: f.write(b'static const char %s[] = {\n' % (src_name.encode('utf-8'),)) first = True n = 0 for b in bytearray(src_data): if b == 0: raise ValueError('NUL in file') if first: f.write(b"0x%02x" % (b,)) first = False else: n = wrt(f, n, b) wrt(f, n, 0) f.write(b'};\n') if __name__ == '__main__': import sys convert(sys.argv[1], sys.argv[1] + '.c')
953
23.461538
78
py
libgpuarray
libgpuarray-master/src/gen_types.py
import sys from mako import exceptions from mako.template import Template TYPEMAP = {} i = 0 def add_type(name, C, sz): global i TYPEMAP[i] = ("ga_"+name, sz), name, C i+=1 add_type("bool", "uint8_t", 1) add_type("byte", "int8_t", 1) add_type("ubyte", "uint8_t", 1) for name, sz in [("short", 2), ("int", 4), ("long", 8)]: add_type(name, "int%s_t"%(sz*8,), sz) add_type("u"+name, "uint%s_t"%(sz*8,), sz) add_type("longlong", "int128_t", 16) add_type("ulonglong", "uint128_t", 16) add_type("float", "float", 4) add_type("double", "double", 8) add_type("quad", "ga_quad", 16) add_type("cfloat", "ga_cfloat", 8) add_type("cdouble", "ga_cdouble", 16) add_type("cquad", "ga_cquad", 32) assert i <= 23 i=23 # to sync with numpy. add_type("half", "half_t", 2); add_type("size", "size_t", "sizeof(size_t)"); add_type("ssize", "ssize_t", "sizeof(ssize_t)"); decls = """ #ifdef _MSC_VER typedef signed __int8 int8_t; typedef unsigned __int8 uint8_t; typedef signed __int16 int16_t; typedef unsigned __int16 uint16_t; typedef signed __int32 int32_t; typedef unsigned __int32 uint32_t; typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif typedef struct _int128 { union int128_u { int8_t as_int8[16]; int16_t as_int16[8]; int32_t as_int32[4]; int64_t as_int64[2]; } value; } int128_t; typedef struct _uint128 { union uint128_u { uint8_t as_uint8[16]; uint16_t as_uint16[8]; uint32_t as_uint32[4]; uint64_t as_uint64[2]; } value; } uint128_t; typedef struct _quad { union { struct { int16_t exp; uint16_t hi; uint32_t lo; } s; uint128_t raw; } u; } ga_quad; typedef uint16_t half_t; typedef struct _cfloat { float r; float i; } ga_cfloat; typedef struct _cdouble { double r; double i; } ga_cdouble; typedef struct _cquad { ga_quad r; ga_quad i; } ga_cquad; """ ntypes = i VECTORMAP = {} i = 0 def add_type(name, sz): global i VECTORMAP[i] = ("ga_"+name, sz, "GA_"+name.upper()), name i+=1 for s in [2, 3, 4, 8, 16]: add_type("byte"+str(s), s) add_type("ubyte"+str(s), s) for name, sz in [("short", 2), ("int", 4), ("long", 8)]: for s in [2, 3, 4, 8, 16]: add_type(name+str(s), sz*s) add_type("u"+name+str(s), sz*s) for name, sz in [("float", 4), ("double", 8), ("half", 2)]: for s in [2, 4, 8, 16]: add_type(name+str(s), sz*s) nvec = i head_tmpl = Template(""" /* This file is generated by gen_types.py */ /** \\file types.h * \\brief Type declarations and access. */ #ifndef GPUARRAY_TYPES_H #define GPUARRAY_TYPES_H #include <sys/types.h> #include <stddef.h> #include <gpuarray/config.h> #ifdef __cplusplus extern "C" { #endif #ifdef CONFUSE_EMACS } #endif /** * Structure that holds the properties of a type. */ typedef struct _gpuarray_type { /** * Type name to use in the buffers. */ const char *cluda_name; /** * Size of one element (in bytes). */ size_t size; /** * Alignement requirement for the type. */ size_t align; /** * Code for the type. */ int typecode; } gpuarray_type; /** * List of all built-in types. */ enum GPUARRAY_TYPES { GA_BUFFER = -1, % for i, v in sorted(TYPEMAP.items()): GA_${v[1].upper()} = ${i}, % endfor /** \\cond INTERNAL_DOCS */ GA_NBASE = ${ntypes}, GA_DELIM = 255, /* To be forward-compatible with numpy */ /** \\endcond */ % for i, v in sorted(VECTORMAP.items()): GA_${v[1].upper()}, % endfor /** \\cond INTERNAL_DOCS */ GA_NVEC, GA_ENDVEC = 512 /** \\endcond */ }; #ifdef __cplusplus } #endif #endif /* GPUARRAY_TYPES */ """) impl_tmpl = Template(""" /* This file is generated by gen_types.py */ #include "gpuarray/types.h" #include <stdlib.h> /* For NULL */ ${decls} % for k, v in TYPEMAP.items(): typedef struct {char c; ${v[2]} x; } st_${v[1]}; #define ${v[1].upper()}_ALIGN (sizeof(st_${v[1]}) - sizeof(${v[2]})) % endfor const gpuarray_type scalar_types[] = { % for i in range(ntypes): % if i in TYPEMAP: {"${TYPEMAP[i][0][0]}", ${TYPEMAP[i][0][1]}, ${TYPEMAP[i][1].upper()}_ALIGN, GA_${TYPEMAP[i][1].upper()}}, % else: {NULL, 0, 0, -1}, % endif % endfor }; const gpuarray_type vector_types[] = { % for i, v in sorted(VECTORMAP.items()): {"${v[0][0]}", ${v[0][1]}, 0, GA_${v[1].upper()}}, % endfor }; """) try: header = head_tmpl.render(TYPEMAP=TYPEMAP, VECTORMAP=VECTORMAP, ntypes=ntypes) impl = impl_tmpl.render(TYPEMAP=TYPEMAP, VECTORMAP=VECTORMAP, ntypes=ntypes, decls=decls) except Exception: print(exceptions.text_error_template().render()) sys.exit(1) with open("gpuarray/types.h", "w") as f: f.write(header) with open("gpuarray_types.c", "w") as f: f.write(impl)
4,777
19.245763
108
py
libgpuarray
libgpuarray-master/pygpu/reduction.py
import math import re from mako.template import Template import numpy from . import gpuarray from .tools import ScalarArg, ArrayArg, check_args, prod, lru_cache from .dtypes import parse_c_arg_backend def parse_c_args(arguments): return tuple(parse_c_arg_backend(arg, ScalarArg, ArrayArg) for arg in arguments.split(',')) INDEX_RE = re.compile('([a-zA-Z_][a-zA-Z0-9_]*)\[i\]') def massage_op(operation): return INDEX_RE.sub('\g<1>[0]', operation) def _ceil_log2(x): # nearest power of 2 (going up) if x != 0: return int(math.ceil(math.log(x, 2))) else: return 0 basic_kernel = Template(""" #include "cluda.h" ${preamble} #define REDUCE(a, b) (${reduce_expr}) KERNEL void ${name}(const unsigned int n, ${out_arg.decltype()} out, const unsigned int out_off % for d in range(nd): , const unsigned int dim${d} % endfor % for arg in arguments: % if arg.isarray(): , ${arg.decltype()} ${arg.name}_data , const unsigned int ${arg.name}_offset % for d in range(nd): , const int ${arg.name}_str_${d} % endfor % else: , ${arg.decltype()} ${arg.name} % endif % endfor ) { LOCAL_MEM ${out_arg.ctype()} ldata[${local_size}]; const unsigned int lid = LID_0; unsigned int i; GLOBAL_MEM char *tmp; % for arg in arguments: % if arg.isarray(): tmp = (GLOBAL_MEM char *)${arg.name}_data; tmp += ${arg.name}_offset; ${arg.name}_data = (${arg.decltype()})tmp; % endif % endfor tmp = (GLOBAL_MEM char *)out; tmp += out_off; out = (${out_arg.decltype()})tmp; i = GID_0; % for i in range(nd-1, -1, -1): % if not redux[i]: % if i > 0: const unsigned int pos${i} = i % dim${i}; i = i / dim${i}; % else: const unsigned int pos${i} = i; % endif % endif % endfor ${out_arg.ctype()} acc = ${neutral}; for (i = lid; i < n; i += LDIM_0) { int ii = i; int pos; % for arg in arguments: % if arg.isarray(): GLOBAL_MEM char *${arg.name}_p = (GLOBAL_MEM char *)${arg.name}_data; % endif % endfor % for i in range(nd-1, -1, -1): % if redux[i]: % if i > 0: pos = ii % dim${i}; ii = ii / dim${i}; % else: pos = ii; % endif % for arg in arguments: % if arg.isarray(): ${arg.name}_p += pos * ${arg.name}_str_${i}; % endif % endfor % else: % for arg in arguments: % if arg.isarray(): ${arg.name}_p += pos${i} * ${arg.name}_str_${i}; % endif % endfor % endif % endfor % for arg in arguments: % if arg.isarray(): ${arg.decltype()} ${arg.name} = (${arg.decltype()})${arg.name}_p; % endif % endfor acc = REDUCE((acc), (${map_expr})); } ldata[lid] = acc; <% cur_size = local_size %> % while cur_size > 1: <% cur_size = cur_size // 2 %> local_barrier(); if (lid < ${cur_size}) { ldata[lid] = REDUCE(ldata[lid], ldata[lid+${cur_size}]); } % endwhile local_barrier(); if (lid == 0) out[GID_0] = ldata[0]; } """) class ReductionKernel(object): def __init__(self, context, dtype_out, neutral, reduce_expr, redux, map_expr=None, arguments=None, preamble="", init_nd=None): self.context = context self.neutral = neutral self.redux = tuple(redux) if not any(self.redux): raise ValueError("Reduction is along no axes") self.dtype_out = dtype_out self.out_arg = ArrayArg(numpy.dtype(self.dtype_out), 'out') if isinstance(arguments, str): self.arguments = parse_c_args(arguments) elif arguments is None: self.arguments = [ArrayArg(numpy.dtype(self.dtype_out), '_reduce_input')] else: self.arguments = arguments if (self.dtype_out == numpy.dtype('float16') or any(ar.dtype == numpy.dtype('float16') for ar in self.arguments)): raise NotImplementedError('float16 not supported for the ' 'reduction interface') self.reduce_expr = reduce_expr if map_expr is None: if len(self.arguments) != 1: raise ValueError("Don't know what to do with more than one " "argument. Specify map_expr to explicitly " "state what you want.") self.operation = "%s[i]" % (self.arguments[0].name,) self.expression = "%s[0]" % (self.arguments[0].name,) else: self.operation = map_expr self.expression = massage_op(map_expr) if not any(isinstance(arg, ArrayArg) for arg in self.arguments): raise ValueError("ReductionKernel can only be used with " "functions that have at least one vector " "argument.") have_small = False have_double = False have_complex = False for arg in self.arguments: if arg.dtype.itemsize < 4 and type(arg) == ArrayArg: have_small = True if arg.dtype in [numpy.float64, numpy.complex128]: have_double = True if arg.dtype in [numpy.complex64, numpy.complex128]: have_complex = True self.flags = dict(have_small=have_small, have_double=have_double, have_complex=have_complex) self.preamble = preamble self.init_local_size = min(context.lmemsize // self.out_arg.dtype.itemsize, context.maxlsize0) # this is to prep the cache if init_nd is not None: self._get_basic_kernel(self.init_local_size, init_nd) def _find_kernel_ls(self, tmpl, max_ls, *tmpl_args): local_size = min(self.init_local_size, max_ls) count_lim = _ceil_log2(local_size) local_size = int(2**count_lim) loop_count = 0 while loop_count <= count_lim: k, src, spec = tmpl(local_size, *tmpl_args) if local_size <= k.maxlsize: return k, src, spec, local_size else: local_size //= 2 loop_count += 1 raise RuntimeError("Can't stabilize the local_size for kernel." " Please report this along with your " "reduction code.") def _gen_basic(self, ls, nd): src = basic_kernel.render(preamble=self.preamble, reduce_expr=self.reduce_expr, name="reduk", out_arg=self.out_arg, nd=nd, arguments=self.arguments, local_size=ls, redux=self.redux, neutral=self.neutral, map_expr=self.expression) spec = ['uint32', gpuarray.GpuArray, 'uint32'] spec.extend('uint32' for _ in range(nd)) for i, arg in enumerate(self.arguments): spec.append(arg.spec()) if arg.isarray(): spec.append('uint32') spec.extend('int32' for _ in range(nd)) k = gpuarray.GpuKernel(src, "reduk", spec, context=self.context, **self.flags) return k, src, spec @lru_cache() def _get_basic_kernel(self, maxls, nd): return self._find_kernel_ls(self._gen_basic, maxls, nd) def __call__(self, *args, **kwargs): broadcast = kwargs.pop('broadcast', None) out = kwargs.pop('out', None) if len(kwargs) != 0: raise TypeError('Unexpected keyword argument: %s' % kwargs.keys()[0]) _, nd, dims, strs, offsets = check_args(args, collapse=False, broadcast=broadcast) n = prod(dims) out_shape = tuple(d for i, d in enumerate(dims) if not self.redux[i]) gs = prod(out_shape) if gs == 0: gs = 1 n /= gs if gs > self.context.maxgsize0: raise ValueError("Array too big to be reduced along the " "selected axes") if out is None: out = gpuarray.empty(out_shape, context=self.context, dtype=self.dtype_out) else: if out.shape != out_shape or out.dtype != self.dtype_out: raise TypeError( "Out array is not of expected type (expected %s %s, " "got %s %s)" % (out_shape, self.dtype_out, out.shape, out.dtype)) # Don't compile and cache for nothing for big size if self.init_local_size < n: k, _, _, ls = self._get_basic_kernel(self.init_local_size, nd) else: k, _, _, ls = self._get_basic_kernel(2**_ceil_log2(n), nd) kargs = [n, out, out.offset] kargs.extend(dims) for i, arg in enumerate(args): kargs.append(arg) if isinstance(arg, gpuarray.GpuArray): kargs.append(offsets[i]) kargs.extend(strs[i]) k(*kargs, gs=gs, ls=ls) return out def reduce1(ary, op, neutral, out_type, axis=None, out=None, oper=None): nd = ary.ndim if axis is None: redux = [True] * nd else: redux = [False] * nd if not isinstance(axis, (list, tuple)): axis = (axis,) for ax in axis: if ax < 0: ax += nd if ax < 0 or ax >= nd: raise ValueError('axis out of bounds') redux[ax] = True if oper is None: reduce_expr = "a %s b" % (op,) else: reduce_expr = oper r = ReductionKernel(ary.context, dtype_out=out_type, neutral=neutral, reduce_expr=reduce_expr, redux=redux, arguments=[ArrayArg(ary.dtype, 'a')]) return r(ary, out=out)
10,284
31.140625
77
py
libgpuarray
libgpuarray-master/pygpu/_array.py
from __future__ import division import numpy as np from .elemwise import elemwise1, elemwise2, ielemwise2, compare, arg, GpuElemwise, as_argument from .reduction import reduce1 from .dtypes import dtype_to_ctype, get_np_obj, get_common_dtype from . import gpuarray class ndgpuarray(gpuarray.GpuArray): """ Extension class for gpuarray.GpuArray to add numpy mathematical operations between arrays. These operations are all performed on the GPU but this is not the most efficient way since it will involve the creation of temporaries (just like numpy) for all intermediate results. This class may help transition code from numpy to pygpu by acting more like a drop-in replacement for numpy.ndarray than the raw GpuArray class. """ # add def __add__(self, other): return elemwise2(self, '+', other, self, broadcast=True) def __radd__(self, other): return elemwise2(other, '+', self, self, broadcast=True) def __iadd__(self, other): return ielemwise2(self, '+', other, broadcast=True) # sub def __sub__(self, other): return elemwise2(self, '-', other, self, broadcast=True) def __rsub__(self, other): return elemwise2(other, '-', self, self, broadcast=True) def __isub__(self, other): return ielemwise2(self, '-', other, broadcast=True) # mul def __mul__(self, other): return elemwise2(self, '*', other, self, broadcast=True) def __rmul__(self, other): return elemwise2(other, '*', self, self, broadcast=True) def __imul__(self, other): return ielemwise2(self, '*', other, broadcast=True) # div def __div__(self, other): return elemwise2(self, '/', other, self, broadcast=True) def __rdiv__(self, other): return elemwise2(other, '/', self, self, broadcast=True) def __idiv__(self, other): return ielemwise2(self, '/', other, broadcast=True) # truediv def __truediv__(self, other): np1 = get_np_obj(self) np2 = get_np_obj(other) res = (np1.__truediv__(np2)).dtype return elemwise2(self, '/', other, self, odtype=res, broadcast=True) def __rtruediv__(self, other): np1 = get_np_obj(self) np2 = get_np_obj(other) res = (np2.__truediv__(np1)).dtype return elemwise2(other, '/', self, self, odtype=res, broadcast=True) def __itruediv__(self, other): np2 = get_np_obj(other) kw = {'broadcast': True} if self.dtype == np.float32 or np2.dtype == np.float32: kw['op_tmpl'] = "a = (float)a / (float)b" if self.dtype == np.float64 or np2.dtype == np.float64: kw['op_tmpl'] = "a = (double)a / (double)b" return ielemwise2(self, '/', other, **kw) # floordiv def __floordiv__(self, other): out_dtype = get_common_dtype(self, other, True) kw = {'broadcast': True} if out_dtype.kind == 'f': kw['op_tmpl'] = "res = floor((%(out_t)s)a / (%(out_t)s)b)" return elemwise2(self, '/', other, self, odtype=out_dtype, **kw) def __rfloordiv__(self, other): out_dtype = get_common_dtype(other, self, True) kw = {'broadcast': True} if out_dtype.kind == 'f': kw['op_tmpl'] = "res = floor((%(out_t)s)a / (%(out_t)s)b)" return elemwise2(other, '/', self, self, odtype=out_dtype, **kw) def __ifloordiv__(self, other): out_dtype = self.dtype kw = {'broadcast': True} if out_dtype == np.float32: kw['op_tmpl'] = "a = floor((float)a / (float)b)" if out_dtype == np.float64: kw['op_tmpl'] = "a = floor((double)a / (double)b)" return ielemwise2(self, '/', other, **kw) # mod def __mod__(self, other): out_dtype = get_common_dtype(self, other, True) kw = {'broadcast': True} if out_dtype.kind == 'f': kw['op_tmpl'] = "res = fmod((%(out_t)s)a, (%(out_t)s)b)" return elemwise2(self, '%', other, self, odtype=out_dtype, **kw) def __rmod__(self, other): out_dtype = get_common_dtype(other, self, True) kw = {'broadcast': True} if out_dtype.kind == 'f': kw['op_tmpl'] = "res = fmod((%(out_t)s)a, (%(out_t)s)b)" return elemwise2(other, '%', self, self, odtype=out_dtype, **kw) def __imod__(self, other): out_dtype = get_common_dtype(self, other, self.dtype == np.float64) kw = {'broadcast': True} if out_dtype == np.float32: kw['op_tmpl'] = "a = fmod((float)a, (float)b)" if out_dtype == np.float64: kw['op_tmpl'] = "a = fmod((double)a, (double)b)" return ielemwise2(self, '%', other, **kw) # divmod def __divmod__(self, other): if not isinstance(other, gpuarray.GpuArray): other = np.asarray(other) odtype = get_common_dtype(self, other, True) a_arg = as_argument(self, 'a', read=True) b_arg = as_argument(other, 'b', read=True) args = [arg('div', odtype, write=True), arg('mod', odtype, write=True), a_arg, b_arg] div = self._empty_like_me(dtype=odtype) mod = self._empty_like_me(dtype=odtype) if odtype.kind == 'f': tmpl = ("div = floor((%(out_t)s)a / (%(out_t)s)b)," "mod = fmod((%(out_t)s)a, (%(out_t)s)b)") else: tmpl = ("div = (%(out_t)s)a / (%(out_t)s)b," "mod = a %% b") ksrc = tmpl % {'out_t': dtype_to_ctype(odtype)} k = GpuElemwise(self.context, ksrc, args) k(div, mod, self, other, broadcast=True) return (div, mod) def __rdivmod__(self, other): if not isinstance(other, gpuarray.GpuArray): other = np.asarray(other) odtype = get_common_dtype(other, self, True) a_arg = as_argument(other, 'a', read=True) b_arg = as_argument(self, 'b', read=True) args = [arg('div', odtype, write=True), arg('mod', odtype, write=True), a_arg, b_arg] div = self._empty_like_me(dtype=odtype) mod = self._empty_like_me(dtype=odtype) if odtype.kind == 'f': tmpl = ("div = floor((%(out_t)s)a / (%(out_t)s)b)," "mod = fmod((%(out_t)s)a, (%(out_t)s)b)") else: tmpl = ("div = (%(out_t)s)a / (%(out_t)s)b," "mod = a %% b") ksrc = tmpl % {'out_t': dtype_to_ctype(odtype)} k = GpuElemwise(self.context, ksrc, args) k(div, mod, other, self, broadcast=True) return (div, mod) def __neg__(self): return elemwise1(self, '-') def __pos__(self): return elemwise1(self, '+') def __abs__(self): if self.dtype.kind == 'u': return self.copy() if self.dtype.kind == 'f': oper = "res = fabs(a)" elif self.dtype.itemsize < 4: # cuda 5.5 finds the c++ stdlib definition if we don't cast here. oper = "res = abs((int)a)" else: oper = "res = abs(a)" return elemwise1(self, None, oper=oper) # richcmp def __lt__(self, other): return compare(self, '<', other, broadcast=True) def __le__(self, other): return compare(self, '<=', other, broadcast=True) def __eq__(self, other): return compare(self, '==', other, broadcast=True) def __ne__(self, other): return compare(self, '!=', other, broadcast=True) def __ge__(self, other): return compare(self, '>=', other, broadcast=True) def __gt__(self, other): return compare(self, '>', other, broadcast=True) # misc other things @property def T(self): if self.ndim < 2: return self return self.transpose() """ Since these functions are untested (thus probably wrong), we disable them. def clip(self, a_min, a_max, out=None): oper=('res = a > %(max)s ? %(max)s : ' '(a < %(min)s ? %(min)s : a)' % dict(min=a_min, max=a_max)) return elemwise1(self, '', oper=oper, out=out) def fill(self, value): self[...] = value """ # reductions def all(self, axis=None, out=None): if self.ndim == 0: return self.copy() return reduce1(self, '&&', '1', np.dtype('bool'), axis=axis, out=out) def any(self, axis=None, out=None): if self.ndim == 0: return self.copy() return reduce1(self, '||', '0', np.dtype('bool'), axis=axis, out=out) def prod(self, axis=None, dtype=None, out=None): if dtype is None: dtype = self.dtype # we only upcast integers that are smaller than the plaform default if dtype.kind == 'i': di = np.dtype('int') if di.itemsize > dtype.itemsize: dtype = di if dtype.kind == 'u': di = np.dtype('uint') if di.itemsize > dtype.itemsize: dtype = di return reduce1(self, '*', '1', dtype, axis=axis, out=out) # def max(self, axis=None, out=None); # nd = self.ndim # if nd == 0: # return self.copy() # idx = (0,) * nd # n = str(self.__getitem__(idx).__array__()) # return reduce1(self, '', n, self.dtype, axis=axis, out=out, # oper='max(a, b)') # def min(self, axis=None, out=None): # nd = self.ndim # if nd == 0: # return self.copy() # idx = (0,) * nd # n = str(self.__getitem__(idx).__array__()) # return reduce1(self, '', n, self.dtype, axis=axis, out=out, # oper='min(a, b)') def sum(self, axis=None, dtype=None, out=None): if dtype is None: dtype = self.dtype # we only upcast integers that are smaller than the plaform default if dtype.kind == 'i': di = np.dtype('int') if di.itemsize > dtype.itemsize: dtype = di if dtype.kind == 'u': di = np.dtype('uint') if di.itemsize > dtype.itemsize: dtype = di return reduce1(self, '+', '0', dtype, axis=axis, out=out)
10,320
33.986441
94
py
libgpuarray
libgpuarray-master/pygpu/_version.py
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = " (HEAD -> master)" git_full = "9cec61435c11cf2ffcf7c480c2d524772585c47f" git_date = "2019-02-08 15:41:32 -0500" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "v" cfg.parentdir_prefix = "libgpuarray-" cfg.versionfile_source = "pygpu/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None}
18,503
34.516315
79
py
libgpuarray
libgpuarray-master/pygpu/tools.py
import functools import six from six.moves import reduce from heapq import nsmallest from operator import itemgetter, mul import numpy from .dtypes import dtype_to_ctype, _fill_dtype_registry from .gpuarray import GpuArray _fill_dtype_registry() def as_argument(obj, name): if isinstance(obj, GpuArray): return ArrayArg(obj.dtype, name) else: return ScalarArg(numpy.asarray(obj).dtype, name) class Argument(object): def __init__(self, dtype, name): self.dtype = dtype self.name = name def ctype(self): return dtype_to_ctype(self.dtype) def __hash__(self): return hash(type(self)) ^ hash(self.dtype) ^ hash(self.name) def __eq__(self, other): return (type(self) == type(other) and self.dtype == other.dtype and self.name == other.name) class ArrayArg(Argument): def decltype(self): return "GLOBAL_MEM {} *".format(self.ctype()) def expr(self): return "{}[i]".format(self.name) def isarray(self): return True def spec(self): return GpuArray class ScalarArg(Argument): def decltype(self): return self.ctype() def expr(self): return self.name def isarray(self): return False def spec(self): return self.dtype def check_args(args, collapse=False, broadcast=False): """ Returns the properties of arguments and checks if they all match (are all the same shape) If `collapse` is True dimension collapsing will be performed. If `collapse` is False dimension collapsing will not be performed. If `broadcast` is True array broadcasting will be performed which means that dimensions which are of size 1 in some arrays but not others will be repeated to match the size of the other arrays. If `broadcast` is False no broadcasting takes place. """ # For compatibility with old collapse=None option if collapse is None: collapse = True strs = [] offsets = [] dims = None for arg in args: if isinstance(arg, GpuArray): strs.append(arg.strides) offsets.append(arg.offset) if dims is None: n, nd, dims = arg.size, arg.ndim, arg.shape else: if arg.ndim != nd: raise ValueError("Array order differs") if not broadcast and arg.shape != dims: raise ValueError("Array shape differs") else: strs.append(None) offsets.append(None) if dims is None: raise TypeError("No arrays in kernel arguments, " "something is wrong") tdims = dims if broadcast or collapse: # make the strides and dims editable dims = list(dims) strs = [list(str) if str is not None else str for str in strs] if broadcast: # Set strides to 0s when needed. # Get the full shape in dims (no ones unless all arrays have it). if 1 in dims: for i, ary in enumerate(args): if strs[i] is None: continue shp = ary.shape for i, d in enumerate(shp): if dims[i] != d and dims[i] == 1: dims[i] = d n *= d tdims = tuple(dims) for i, ary in enumerate(args): if strs[i] is None: continue shp = ary.shape if tdims != shp: for j, d in enumerate(shp): if dims[j] != d: # Might want to add a per-dimension enable mechanism if d == 1: strs[i][j] = 0 else: raise ValueError("Array shape differs") if collapse and nd > 1: # remove dimensions that are of size 1 for i in range(nd - 1, -1, -1): if nd > 1 and dims[i] == 1: del dims[i] for str in strs: if str is not None: del str[i] nd -= 1 # collapse contiguous dimensions for i in range(nd - 1, 0, -1): if all(str is None or str[i] * dims[i] == str[i - 1] for str in strs): dims[i - 1] *= dims[i] del dims[i] for str in strs: if str is not None: str[i - 1] = str[i] del str[i] nd -= 1 if broadcast or collapse: # re-wrap dims and tuples dims = tuple(dims) strs = [tuple(str) if str is not None else None for str in strs] return n, nd, dims, tuple(strs), tuple(offsets) def lru_cache(maxsize=20): def decorating_function(user_function): cache = {} last_use = {} time = [0] # workaround for Python 2, which doesn't have nonlocal @functools.wraps(user_function) def wrapper(*key): time[0] += 1 try: result = cache[key] wrapper.hits += 1 except KeyError: result = user_function(*key) cache[key] = result wrapper.misses += 1 # purge least recently used cache entries if len(cache) > wrapper.maxsize: for key0, _ in nsmallest(wrapper.maxsize // 10, six.iteritems(last_use), key=itemgetter(1)): del cache[key0], last_use[key0] last_use[key] = time[0] return result def clear(): cache.clear() last_use.clear() wrapper.hits = wrapper.misses = 0 time[0] = 0 @functools.wraps(user_function) def get(*key): result = cache[key] time[0] += 1 last_use[key] = time[0] wrapper.hits += 1 return result wrapper.hits = wrapper.misses = 0 wrapper.maxsize = maxsize wrapper.clear = clear wrapper.get = get return wrapper return decorating_function def prod(iterable): return reduce(mul, iterable, 1)
6,395
27.681614
76
py
libgpuarray
libgpuarray-master/pygpu/elemwise.py
import numpy from .dtypes import dtype_to_ctype, get_common_dtype from . import gpuarray from ._elemwise import GpuElemwise, arg __all__ = ['GpuElemwise', 'arg', 'as_argument', 'elemwise1', 'elemwise2', 'ielemwise2', 'compare'] def _dtype(o): if hasattr(o, 'dtype'): return o.dtype return numpy.asarray(o).dtype def as_argument(o, name, read=False, write=False): if (not read) and (not write): raise ValueError('argument is neither read not write') return arg(name, _dtype(o), scalar=not isinstance(o, gpuarray.GpuArray), read=read, write=write) def elemwise1(a, op, oper=None, op_tmpl="res = %(op)sa", out=None, convert_f16=True): args = (as_argument(a, 'res', write=True), as_argument(a, 'a', read=True)) if out is None: res = a._empty_like_me() else: res = out if oper is None: oper = op_tmpl % {'op': op} k = GpuElemwise(a.context, oper, args, convert_f16=convert_f16) k(res, a) return res def elemwise2(a, op, b, ary, odtype=None, oper=None, op_tmpl="res = (%(out_t)s)a %(op)s (%(out_t)s)b", broadcast=False, convert_f16=True): ndim_extend = True if not isinstance(a, gpuarray.GpuArray): a = numpy.asarray(a) ndim_extend = False if not isinstance(b, gpuarray.GpuArray): b = numpy.asarray(b) ndim_extend = False if odtype is None: odtype = get_common_dtype(a, b, True) a_arg = as_argument(a, 'a', read=True) b_arg = as_argument(b, 'b', read=True) args = [arg('res', odtype, write=True), a_arg, b_arg] if ndim_extend: if a.ndim != b.ndim: nd = max(a.ndim, b.ndim) if a.ndim < nd: a = a.reshape(((1,) * (nd - a.ndim)) + a.shape) if b.ndim < nd: b = b.reshape(((1,) * (nd - b.ndim)) + b.shape) out_shape = tuple(max(sa, sb) for sa, sb in zip(a.shape, b.shape)) res = gpuarray.empty(out_shape, dtype=odtype, context=ary.context, cls=ary.__class__) else: res = ary._empty_like_me(dtype=odtype) if oper is None: if convert_f16 and odtype == 'float16': odtype = numpy.dtype('float32') oper = op_tmpl % {'op': op, 'out_t': dtype_to_ctype(odtype)} k = GpuElemwise(ary.context, oper, args, convert_f16=convert_f16) k(res, a, b, broadcast=broadcast) return res def ielemwise2(a, op, b, oper=None, op_tmpl="a = a %(op)s b", broadcast=False, convert_f16=True): if not isinstance(b, gpuarray.GpuArray): b = numpy.asarray(b) a_arg = as_argument(a, 'a', read=True, write=True) b_arg = as_argument(b, 'b', read=True) args = [a_arg, b_arg] if oper is None: oper = op_tmpl % {'op': op} k = GpuElemwise(a.context, oper, args, convert_f16=convert_f16) k(a, b, broadcast=broadcast) return a def compare(a, op, b, broadcast=False, convert_f16=True): return elemwise2(a, op, b, a, odtype=numpy.dtype('bool'), op_tmpl="res = (a %(op)s b)", broadcast=broadcast, convert_f16=convert_f16)
3,200
30.07767
78
py
libgpuarray
libgpuarray-master/pygpu/__init__.py
def get_include(): import os.path p = os.path.dirname(__file__) assert os.path.exists(os.path.join(p, 'gpuarray_api.h')) return p from . import gpuarray, elemwise, reduction from .gpuarray import (init, set_default_context, get_default_context, array, zeros, empty, asarray, ascontiguousarray, asfortranarray, register_dtype) from .operations import (split, array_split, hsplit, vsplit, dsplit, concatenate, hstack, vstack, dstack) from ._array import ndgpuarray from ._version import get_versions __version__ = get_versions()['version'] del get_versions def test(): from . import tests from .tests import main if hasattr(main, "NoseTester"): main.NoseTester(package=tests).test()
792
30.72
71
py
libgpuarray
libgpuarray-master/pygpu/dtypes.py
"""Type mapping helpers.""" from __future__ import division import numpy as np from . import gpuarray __copyright__ = "Copyright (C) 2011 Andreas Kloeckner" __license__ = """ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # {{{ registry NAME_TO_DTYPE = {} def register_dtype(dtype, c_names): """ Associate a numpy dtype with its C equivalents. Will register `dtype` for use with the gpuarray module. If the c_names argument is a list then the first element of that list is taken as the primary association and will be used for generated C code. The other types will be mapped to the provided dtype when going in the other direction. Parameters ---------- dtype: numpy.dtype or string type to associate c_names: str or list list of C type names """ if isinstance(c_names, str): c_names = [c_names] dtype = np.dtype(dtype) # register if not already there try: gpuarray.dtype_to_ctype(dtype) except ValueError: gpuarray.register_dtype(dtype, c_names[0]) for nm in c_names: if nm in NAME_TO_DTYPE and NAME_TO_DTYPE[nm] != dtype: raise RuntimeError("name '%s' already registered" % nm) NAME_TO_DTYPE[nm] = dtype def _fill_dtype_registry(): register_dtype(np.bool, ["ga_bool", "bool"]) register_dtype(np.int8, ["ga_byte", "char", "signed char"]) register_dtype(np.uint8, ["ga_ubyte", "unsigned char"]) register_dtype(np.int16, ["ga_short", "short", "signed short", "signed short int", "short signed int"]) register_dtype(np.uint16, ["ga_ushort", "unsigned short", "unsigned short int", "short unsigned int"]) register_dtype(np.int32, ["ga_int", "int", "signed int"]) register_dtype(np.uint32, ["ga_uint", "unsigned", "unsigned int"]) register_dtype(np.int64, ["ga_long", "long int", "signed long int", "long signed int"]) register_dtype(np.uint64, ["ga_ulong", "unsigned long", "unsigned long int", "long unsigned int"]) register_dtype(np.intp, ["ga_ssize", "ssize_t"]) register_dtype(np.uintp, ["ga_size", "size_t"]) register_dtype(np.float32, ["ga_float", "float"]) register_dtype(np.float64, ["ga_double", "double"]) # }}} # {{{ dtype -> ctype def dtype_to_ctype(dtype): """ Return the C type that corresponds to `dtype`. Parameters ---------- dtype: data type a numpy dtype """ if dtype is None: raise ValueError("dtype may not be None") dtype = np.dtype(dtype) return gpuarray.dtype_to_ctype(dtype) # }}} # {{{ c declarator parsing def parse_c_arg_backend(c_arg, scalar_arg_class, vec_arg_class): c_arg = c_arg.replace("const", "").replace("volatile", "") # process and remove declarator import re decl_re = re.compile(r"(\**)\s*([_a-zA-Z0-9]+)(\s*\[[ 0-9]*\])*\s*$") decl_match = decl_re.search(c_arg) if decl_match is None: raise ValueError("couldn't parse C declarator '%s'" % c_arg) name = decl_match.group(2) if decl_match.group(1) or decl_match.group(3) is not None: arg_class = vec_arg_class else: arg_class = scalar_arg_class tp = c_arg[:decl_match.start()] tp = " ".join(tp.split()) try: dtype = NAME_TO_DTYPE[tp] except KeyError: raise ValueError("unknown type '%s'" % tp) return arg_class(dtype, name) # }}} def get_np_obj(obj): """ Returns a numpy object of the same dtype and comportement as the source suitable for output dtype determination. This is used since the casting rules of numpy are rather obscure and the best way to imitate them is to try an operation ans see what it does. """ if isinstance(obj, np.ndarray) and obj.shape == (): return obj try: return np.ones(1, dtype=obj.dtype) except AttributeError: return np.asarray(obj) def get_common_dtype(obj1, obj2, allow_double): """ Returns the proper output type for a numpy operation involving the two provided objects. This may not be suitable for certain obscure numpy operations. If `allow_double` is False, a return type of float64 will be forced to float32 and complex128 will be forced to complex64. """ # Yes, numpy behaves differently depending on whether # we're dealing with arrays or scalars. np1 = get_np_obj(obj1) np2 = get_np_obj(obj2) result = (np1 + np2).dtype if not allow_double: if result == np.float64: result = np.dtype(np.float32) elif result == np.complex128: result = np.dtype(np.complex64) return result def upcast(*args): a = np.array([0], dtype=args[0]) for t in args[1:]: a = a + np.array([0], dtype=t) return a.dtype # vim: foldmethod=marker
5,921
28.172414
75
py
libgpuarray
libgpuarray-master/pygpu/operations.py
from six.moves import range from .gpuarray import _split, _concatenate, dtype_to_typecode from .dtypes import upcast from . import asarray def atleast_1d(*arys): res = [] for ary in arys: ary = asarray(ary) if len(ary.shape) == 0: result = ary.reshape((1,)) else: result = ary res.append(result) if len(res) == 1: return res[0] else: return res def atleast_2d(*arys): res = [] for ary in arys: ary = asarray(ary) if len(ary.shape) == 0: result = ary.reshape((1, 1)) elif len(ary.shape) == 1: result = ary.reshape((1, ary.shape[0])) else: result = ary res.append(result) if len(res) == 1: return res[0] else: return res def atleast_3d(*arys): res = [] for ary in arys: ary = asarray(ary) if len(ary.shape) == 0: result = ary.reshape((1, 1, 1)) elif len(ary.shape) == 1: result = ary.reshape((1, ary.shape[0], 1)) elif len(ary.shape) == 2: result = ary.reshape(ary.shape + (1,)) else: result = ary res.append(result) if len(res) == 1: return res[0] else: return res def split(ary, indices_or_sections, axis=0): try: len(indices_or_sections) except TypeError: if ary.shape[axis] % indices_or_sections != 0: raise ValueError("array split does not result in an " "equal division") return array_split(ary, indices_or_sections, axis) def array_split(ary, indices_or_sections, axis=0): try: indices = list(indices_or_sections) res = _split(ary, indices, axis) except TypeError: if axis < 0: axis += ary.ndim if axis < 0: raise ValueError('axis out of bounds') nsec = int(indices_or_sections) if nsec <= 0: raise ValueError('number of sections must be larger than 0.') neach, extra = divmod(ary.shape[axis], nsec) # this madness is to support the numpy interface # it is supported by tests, but little else divs = (list(range(neach + 1, (neach + 1) * extra + 1, neach + 1)) + list(range((neach + 1) * extra + neach, ary.shape[axis], neach))) res = _split(ary, divs, axis) return res def hsplit(ary, indices_or_sections): if len(ary.shape) == 0: raise ValueError('hsplit only works on arrays of 1 or more dimensions') if len(ary.shape) > 1: axis = 1 else: axis = 0 return split(ary, indices_or_sections, axis=axis) def vsplit(ary, indices_or_sections): if len(ary.shape) < 2: raise ValueError('vsplit only works on arrays of 2 or more dimensions') return split(ary, indices_or_sections, axis=0) def dsplit(ary, indices_or_sections): if len(ary.shape) < 3: raise ValueError('vsplit only works on arrays of 3 or more dimensions') return split(ary, indices_or_sections, axis=2) def concatenate(arys, axis=0, context=None): if len(arys) == 0: raise ValueError("concatenation of zero-length sequences is " "impossible") if axis < 0: axis += arys[0].ndim if axis < 0: raise ValueError('axis out of bounds') al = [asarray(a, context=context) for a in arys] if context is None: context = al[0].context outtype = upcast(*[a.dtype for a in arys]) return _concatenate(al, axis, dtype_to_typecode(outtype), type(al[0]), context) def vstack(tup, context=None): return concatenate([atleast_2d(a) for a in tup], 0, context) def hstack(tup, context=None): tup = [atleast_1d(a) for a in tup] if tup[0].ndim == 1: return concatenate(tup, 0, context) else: return concatenate(tup, 1, context) def dstack(tup, context=None): return concatenate([atleast_3d(a) for a in tup], 2, context)
4,070
27.468531
79
py
libgpuarray
libgpuarray-master/pygpu/basic.py
from string import Template from .gpuarray import GpuArray, GpuKernel, SIZE, dtype_to_ctype import numpy def _generate_kernel(ctx, cols, dtype, upper=True): tmpl = Template(""" #include "cluda.h" KERNEL void extract_tri(GLOBAL_MEM ${ctype} *a, ga_size a_off, ga_uint N) { a = (GLOBAL_MEM ${ctype} *)(((GLOBAL_MEM char *)a) + a_off); unsigned int idx = GID_1 * LDIM_0 * GDIM_0 + GID_0 * LDIM_0 + LID_0; unsigned int ix = idx/${cols}; unsigned int iy = idx%${cols}; if (idx < N) { if (ix ${le} iy) a[idx] = 0.0; } } """) if upper: le = '>' else: le = '<' ctype = dtype_to_ctype(dtype) src = tmpl.substitute(cols=cols, ctype=ctype, le=le) spec = [GpuArray, SIZE, 'uint32'] have_small = False have_double = False have_complex = False if dtype.itemsize < 4: have_small = True if dtype in [numpy.float64, numpy.complex128]: have_double = True if dtype in [numpy.complex64, numpy.complex128]: have_complex = True k = GpuKernel(src, "extract_tri", spec, context=ctx, have_double=have_double, have_small=have_small, have_complex=have_complex) return k def triu(A, inplace=True): if A.ndim != 2: raise ValueError("triu only works for 2d arrays") if A.flags.c_contiguous is A.flags.f_contiguous is False: raise ValueError("triu only works for contiguous arrays") if not inplace: A = A.copy() if A.flags['F_CONTIGUOUS']: upper = False cols = A.shape[0] else: upper = True cols = A.shape[1] k = _generate_kernel(A.context, cols, A.dtype, upper) k(A, A.offset, A.shape[0] * A.shape[1], n=A.shape[0] * A.shape[1]) return A def tril(A, inplace=True): if A.ndim != 2: raise ValueError("tril only works for 2d arrays") if A.flags.c_contiguous is A.flags.f_contiguous is False: raise ValueError("tril only works for contiguous arrays") if not inplace: A = A.copy() if A.flags['F_CONTIGUOUS']: upper = True cols = A.shape[0] else: upper = False cols = A.shape[1] k = _generate_kernel(A.context, cols, A.dtype, upper) k(A, A.offset, A.shape[0] * A.shape[1], n=A.shape[0] * A.shape[1]) return A
2,407
29.871795
79
py
libgpuarray
libgpuarray-master/pygpu/tests/test_collectives.py
from __future__ import print_function import os import sys import unittest from six.moves import range from six import PY3 import pickle import numpy as np from pygpu import gpuarray from pygpu.collectives import COMM_ID_BYTES, GpuCommCliqueId, GpuComm from pygpu.tests.support import (check_all, gen_gpuarray, context as ctx) def get_user_gpu_rank(): for name in ['GPUARRAY_TEST_DEVICE', 'DEVICE']: if name in os.environ: devname = os.environ[name] if devname.startswith("opencl"): return -1 if devname[-1] == 'a': return 0 return int(devname[-1]) return -1 try: from mpi4py import MPI MPI_IMPORTED = True except: MPI_IMPORTED = False print("mpi4py found: " + str(MPI_IMPORTED), file=sys.stderr) @unittest.skipIf(get_user_gpu_rank() == -1, "Collective operations supported on CUDA devices only.") class TestGpuCommCliqueId(unittest.TestCase): def setUp(self): self.cid = GpuCommCliqueId(context=ctx) def _create_in_scope_from_string(self): comm_id = bytearray(b'pipes' * (COMM_ID_BYTES // 5 + 1)) return GpuCommCliqueId(context=ctx, comm_id=comm_id) def test_create_from_string_id(self): cid2 = self._create_in_scope_from_string() a = bytearray(b'pipes' * (COMM_ID_BYTES // 5 + 1)) assert cid2.comm_id == a[:COMM_ID_BYTES], (cid2.comm_id, a[:COMM_ID_BYTES]) b = bytearray(b'mlkies' * (COMM_ID_BYTES // 6 + 1)) cid2.comm_id = b assert cid2.comm_id == b[:COMM_ID_BYTES], (cid2.comm_id, b[:COMM_ID_BYTES]) with self.assertRaises(ValueError): cid2.comm_id = bytearray(b'testestestest') def test_pickle(self): with self.assertRaises(RuntimeError): pickle.dumps(self.cid) with self.assertRaises(RuntimeError): pickle.dumps(self.cid, protocol=0) with self.assertRaises(RuntimeError): pickle.dumps(self.cid, protocol=1) with self.assertRaises(RuntimeError): pickle.dumps(self.cid, protocol=2) if PY3: with self.assertRaises(RuntimeError): pickle.dumps(self.cid, protocol=3) with self.assertRaises(RuntimeError): pickle.dumps(self.cid, protocol=-1) def test_create_from_previous(self): cid2 = GpuCommCliqueId(context=ctx, comm_id=bytearray(b'y' * COMM_ID_BYTES)) cid3 = GpuCommCliqueId(context=ctx, comm_id=cid2.comm_id) assert cid2.comm_id == cid3.comm_id def test_richcmp(self): cid1 = GpuCommCliqueId(context=ctx, comm_id=bytearray(b'y' * COMM_ID_BYTES)) cid2 = GpuCommCliqueId(context=ctx, comm_id=cid1.comm_id) cid3 = GpuCommCliqueId(context=ctx, comm_id=bytearray(b'z' * COMM_ID_BYTES)) assert cid1 == cid2 assert cid1 != cid3 assert cid3 > cid2 assert cid3 >= cid2 assert cid1 >= cid2 assert cid2 < cid3 assert cid2 <= cid3 assert cid2 <= cid1 with self.assertRaises(TypeError): a = cid2 > "asdfasfa" @unittest.skipUnless(MPI_IMPORTED, "Needs mpi4py module") @unittest.skipIf(get_user_gpu_rank() == -1, "Collective operations supported on CUDA devices only") class TestGpuComm(unittest.TestCase): @classmethod def setUpClass(cls): if get_user_gpu_rank() == -1 or not MPI_IMPORTED: return cls.mpicomm = MPI.COMM_WORLD cls.size = cls.mpicomm.Get_size() cls.rank = cls.mpicomm.Get_rank() cls.ctx = gpuarray.init("cuda" + str(cls.rank)) print("*** Collectives testing for", cls.ctx.devname, file=sys.stderr) cls.cid = GpuCommCliqueId(context=cls.ctx) cls.mpicomm.Bcast(cls.cid.comm_id, root=0) cls.gpucomm = GpuComm(cls.cid, cls.size, cls.rank) def test_count(self): assert self.gpucomm.count == self.size, (self.gpucomm.count, self.size) def test_rank(self): assert self.gpucomm.rank == self.rank, (self.gpucomm.rank, self.rank) def test_reduce(self): cpu, gpu = gen_gpuarray((3, 4, 5), order='c', incr=self.rank, ctx=self.ctx) rescpu = np.empty_like(cpu) resgpu = gpu._empty_like_me() if self.rank != 0: self.gpucomm.reduce(gpu, 'sum', resgpu, root=0) self.mpicomm.Reduce([cpu, MPI.FLOAT], None, op=MPI.SUM, root=0) else: self.gpucomm.reduce(gpu, 'sum', resgpu) self.mpicomm.Reduce([cpu, MPI.FLOAT], [rescpu, MPI.FLOAT], op=MPI.SUM, root=0) if self.rank == 0: assert np.allclose(resgpu, rescpu) resgpu = self.gpucomm.reduce(gpu, 'sum', root=0) if self.rank == 0: assert resgpu.shape == gpu.shape, (resgpu.shape, gpu.shape) assert resgpu.dtype == gpu.dtype, (resgpu.dtype, gpu.dtype) assert resgpu.flags['C'] == gpu.flags['C'] assert resgpu.flags['F'] == gpu.flags['F'] assert np.allclose(resgpu, rescpu) else: assert resgpu is None if self.rank == 0: resgpu = self.gpucomm.reduce(gpu, 'sum') assert resgpu.shape == gpu.shape, (resgpu.shape, gpu.shape) assert resgpu.dtype == gpu.dtype, (resgpu.dtype, gpu.dtype) assert resgpu.flags['C'] == gpu.flags['C'] assert resgpu.flags['F'] == gpu.flags['F'] assert np.allclose(resgpu, rescpu) else: resgpu = self.gpucomm.reduce(gpu, 'sum', root=0) assert resgpu is None def test_all_reduce(self): cpu, gpu = gen_gpuarray((3, 4, 5), order='c', incr=self.rank, ctx=self.ctx) rescpu = np.empty_like(cpu) resgpu = gpu._empty_like_me() self.gpucomm.all_reduce(gpu, 'sum', resgpu) self.mpicomm.Allreduce([cpu, MPI.FLOAT], [rescpu, MPI.FLOAT], op=MPI.SUM) assert np.allclose(resgpu, rescpu) resgpu = self.gpucomm.all_reduce(gpu, 'sum') assert resgpu.shape == gpu.shape, (resgpu.shape, gpu.shape) assert resgpu.dtype == gpu.dtype, (resgpu.dtype, gpu.dtype) assert resgpu.flags['C'] == gpu.flags['C'] assert resgpu.flags['F'] == gpu.flags['F'] assert np.allclose(resgpu, rescpu) def test_reduce_scatter(self): texp = self.size * np.arange(5 * self.size) + sum(range(self.size)) exp = texp[self.rank * 5:self.rank * 5 + 5] # order c cpu = np.arange(5 * self.size) + self.rank np.reshape(cpu, (self.size, 5), order='C') gpu = gpuarray.asarray(cpu, context=self.ctx) resgpu = gpuarray.empty((5,), dtype='int64', order='C', context=self.ctx) self.gpucomm.reduce_scatter(gpu, 'sum', resgpu) assert np.allclose(resgpu, exp) # order f cpu = np.arange(5 * self.size) + self.rank np.reshape(cpu, (5, self.size), order='F') gpu = gpuarray.asarray(cpu, context=self.ctx) resgpu = gpuarray.empty((5,), dtype='int64', order='F', context=self.ctx) self.gpucomm.reduce_scatter(gpu, 'sum', resgpu) assert np.allclose(resgpu, exp) # make result order c (one less dim) cpu = np.arange(5 * self.size) + self.rank np.reshape(cpu, (self.size, 5), order='C') gpu = gpuarray.asarray(cpu, context=self.ctx) resgpu = self.gpucomm.reduce_scatter(gpu, 'sum') check_all(resgpu, exp) assert resgpu.flags['C_CONTIGUOUS'] is True # c-contiguous split problem (for size == 1, it can always be split) if self.size != 1: cpu = np.arange(5 * (self.size + 1), dtype='int32') + self.rank np.reshape(cpu, (self.size + 1, 5), order='C') gpu = gpuarray.asarray(cpu, context=self.ctx) with self.assertRaises(TypeError): resgpu = self.gpucomm.reduce_scatter(gpu, 'sum') # make result order f (one less dim) cpu = np.arange(5 * self.size) + self.rank np.reshape(cpu, (5, self.size), order='F') gpu = gpuarray.asarray(cpu, context=self.ctx) resgpu = self.gpucomm.reduce_scatter(gpu, 'sum') check_all(resgpu, exp) assert resgpu.flags['F_CONTIGUOUS'] is True # f-contiguous split problem (for size == 1, it can always be split) if self.size != 1: cpu = np.arange(5 * (self.size + 1), dtype='int32') + self.rank np.reshape(cpu, (5, self.size + 1), order='F') gpu = gpuarray.asarray(cpu, context=self.ctx) with self.assertRaises(TypeError): resgpu = self.gpucomm.reduce_scatter(gpu, 'sum') # make result order c (same dim - less size) texp = self.size * np.arange(5 * self.size * 3) + sum(range(self.size)) exp = texp[self.rank * 15:self.rank * 15 + 15] np.reshape(exp, (3, 5), order='C') cpu = np.arange(5 * self.size * 3) + self.rank np.reshape(cpu, (self.size * 3, 5), order='C') gpu = gpuarray.asarray(cpu, context=self.ctx) resgpu = self.gpucomm.reduce_scatter(gpu, 'sum') check_all(resgpu, exp) assert resgpu.flags['C_CONTIGUOUS'] is True # make result order f (same dim - less size) texp = self.size * np.arange(5 * self.size * 3) + sum(range(self.size)) exp = texp[self.rank * 15:self.rank * 15 + 15] np.reshape(exp, (5, 3), order='F') cpu = np.arange(5 * self.size * 3) + self.rank np.reshape(cpu, (5, self.size * 3), order='F') gpu = gpuarray.asarray(cpu, context=self.ctx) resgpu = self.gpucomm.reduce_scatter(gpu, 'sum') check_all(resgpu, exp) assert resgpu.flags['F_CONTIGUOUS'] is True def test_broadcast(self): if self.rank == 0: cpu, gpu = gen_gpuarray((3, 4, 5), order='c', incr=self.rank, ctx=self.ctx) else: cpu = np.zeros((3, 4, 5), dtype='float32') gpu = gpuarray.asarray(cpu, context=self.ctx) if self.rank == 0: self.gpucomm.broadcast(gpu) else: self.gpucomm.broadcast(gpu, root=0) self.mpicomm.Bcast(cpu, root=0) assert np.allclose(gpu, cpu) def test_all_gather(self): texp = np.arange(self.size * 10, dtype='int32') cpu = np.arange(self.rank * 10, self.rank * 10 + 10, dtype='int32') a = cpu gpu = gpuarray.asarray(a, context=self.ctx) resgpu = self.gpucomm.all_gather(gpu, nd_up=0) check_all(resgpu, texp) a = cpu.reshape((2, 5), order='C') exp = texp.reshape((2 * self.size, 5), order='C') gpu = gpuarray.asarray(a, context=self.ctx) resgpu = self.gpucomm.all_gather(gpu, nd_up=0) check_all(resgpu, exp) a = cpu.reshape((2, 5), order='C') exp = texp.reshape((self.size, 2, 5), order='C') gpu = gpuarray.asarray(a, context=self.ctx) resgpu = self.gpucomm.all_gather(gpu, nd_up=1) check_all(resgpu, exp) a = cpu.reshape((2, 5), order='C') exp = texp.reshape((self.size, 1, 1, 2, 5), order='C') gpu = gpuarray.asarray(a, context=self.ctx) resgpu = self.gpucomm.all_gather(gpu, nd_up=3) check_all(resgpu, exp) a = cpu.reshape((5, 2), order='F') exp = texp.reshape((5, 2 * self.size), order='F') gpu = gpuarray.asarray(a, context=self.ctx, order='F') resgpu = self.gpucomm.all_gather(gpu, nd_up=0) check_all(resgpu, exp) a = cpu.reshape((5, 2), order='F') exp = texp.reshape((5, 2, self.size), order='F') gpu = gpuarray.asarray(a, context=self.ctx, order='F') resgpu = self.gpucomm.all_gather(gpu, nd_up=1) check_all(resgpu, exp) a = cpu.reshape((5, 2), order='F') exp = texp.reshape((5, 2, 1, 1, self.size), order='F') gpu = gpuarray.asarray(a, context=self.ctx, order='F') resgpu = self.gpucomm.all_gather(gpu, nd_up=3) check_all(resgpu, exp) with self.assertRaises(Exception): resgpu = self.gpucomm.all_gather(gpu, nd_up=-2)
12,098
38.410423
100
py
libgpuarray
libgpuarray-master/pygpu/tests/main.py
import os import nose.plugins.builtin from nose.config import Config from nose.plugins.manager import PluginManager from numpy.testing.nosetester import NoseTester from numpy.testing.noseclasses import KnownFailure, NumpyTestProgram class NoseTester(NoseTester): """ Nose test runner. This class enables running nose tests from inside libgpuarray, by calling pygpu.test(). This version is more adapted to what we want than Numpy's one. """ def _test_argv(self, verbose, extra_argv): """ Generate argv for nosetest command Parameters ---------- verbose: int Verbosity value for test outputs, in the range 1-10. Default is 1. extra_argv: list List with any extra arguments to pass to nosetests. """ # self.package_path = os.path.abspath(self.package_path) argv = [__file__, self.package_path] argv += ['--verbosity', str(verbose)] if extra_argv: argv += extra_argv return argv def _show_system_info(self): import pygpu # print ("pygpu version %s" % pygpu.__version__) pygpu_dir = os.path.dirname(pygpu.__file__) print("pygpu is installed in %s" % pygpu_dir) super(NoseTester, self)._show_system_info() def prepare_test_args(self, verbose=1, extra_argv=None, coverage=False, capture=True, knownfailure=True): """ Prepare arguments for the `test` method. Takes the same arguments as `test`. """ # compile argv argv = self._test_argv(verbose, extra_argv) # numpy way of doing coverage if coverage: argv += ['--cover-package=%s' % self.package_name, '--with-coverage', '--cover-tests', '--cover-inclusive', '--cover-erase'] # Capture output only if needed if not capture: argv += ['-s'] # construct list of plugins plugins = [] if knownfailure: plugins.append(KnownFailure()) plugins += [p() for p in nose.plugins.builtin.plugins] return argv, plugins def test(self, verbose=1, extra_argv=None, coverage=False, capture=True, knownfailure=True): """ Run tests for module using nose. Parameters ---------- verbose: int Verbosity value for test outputs, in the range 1-10. Default is 1. extra_argv: list List with any extra arguments to pass to nosetests. coverage: bool If True, report coverage of pygpu code. Default is False. capture: bool If True, capture the standard output of the tests, like nosetests does in command-line. The output of failing tests will be displayed at the end. Default is True. knownfailure: bool If True, tests raising KnownFailureTest will not be considered Errors nor Failure, but reported as "known failures" and treated quite like skipped tests. Default is True. Returns ------- nose.result.TextTestResult The result of running the tests """ # cap verbosity at 3 because nose becomes *very* verbose beyond that verbose = min(verbose, 3) self._show_system_info() cwd = os.getcwd() if self.package_path in os.listdir(cwd): # The tests give weird errors if the package to test is # in current directory. raise RuntimeError(( "This function does not run correctly when, at the time " "pygpu was imported, the working directory was pygpu's " "parent directory. You should exit your Python prompt, change " "directory, then launch Python again, import pygpu, then " "launch pygpu.test().")) argv, plugins = self.prepare_test_args(verbose, extra_argv, coverage, capture, knownfailure) # The "plugins" keyword of NumpyTestProgram gets ignored if config is # specified. Moreover, using "addplugins" instead can lead to strange # errors. So, we specify the plugins in the Config as well. cfg = Config(includeExe=True, plugins=PluginManager(plugins=plugins)) t = NumpyTestProgram(argv=argv, exit=False, config=cfg) return t.result
4,535
34.162791
79
py
libgpuarray
libgpuarray-master/pygpu/tests/test_basic.py
import pygpu from pygpu.basic import (tril, triu) from unittest import TestCase from .support import (guard_devsup, gen_gpuarray, context) import numpy def test_tril(): for dtype in ['float32','float64']: for shape in [(10, 5), (5, 10), (10, 10)]: for order in ['c', 'f']: for inplace in [True, False]: yield run_tril, dtype, shape, order, inplace @guard_devsup def run_tril(dtype, shape, order, inplace): ac, ag = gen_gpuarray(shape, dtype, order=order, ctx=context) result = tril(ag, inplace=inplace) assert numpy.all(numpy.tril(ac) == result) if inplace: assert numpy.all(numpy.tril(ac) == ag) else: assert numpy.all(ac == ag) def test_triu(): for dtype in ['float32','float64']: for shape in [(10, 5), (5, 10), (10, 10)]: for order in ['c', 'f']: for inplace in [True, False]: yield run_triu, dtype, shape, order, inplace @guard_devsup def run_triu(dtype, shape, order, inplace): ac, ag = gen_gpuarray(shape, dtype, order=order, ctx=context) result = triu(ag, inplace=inplace) assert numpy.all(numpy.triu(ac) == result) if inplace: assert numpy.all(numpy.triu(ac) == ag) else: assert numpy.all(ac == ag) class test_errors(TestCase): def runTest(self): self.assertRaises(ValueError, self.run_1d_triu) self.assertRaises(ValueError, self.run_3d_triu) self.assertRaises(ValueError, self.run_1d_tril) self.assertRaises(ValueError, self.run_3d_tril) self.assertRaises(ValueError, self.run_noncontiguous_tril) self.assertRaises(ValueError, self.run_noncontiguous_triu) def run_1d_triu(self): ac, ag = gen_gpuarray((10, ), 'float32', ctx=context) triu(ag) def run_3d_triu(self): ac, ag = gen_gpuarray((10, 10, 10), 'float32', ctx=context) triu(ag) def run_1d_tril(self): ac, ag = gen_gpuarray((10, ), 'float32', ctx=context) tril(ag) def run_3d_tril(self): ac, ag = gen_gpuarray((10, 10, 10), 'float32', ctx=context) tril(ag) def run_noncontiguous_tril(self): a = numpy.random.rand(5, 5) b = pygpu.array(a, context=context) b = b[::-1] assert b.flags.c_contiguous is b.flags.f_contiguous is False tril(b) def run_noncontiguous_triu(self): a = numpy.random.rand(5, 5) b = pygpu.array(a, context=context) b = b[::-1] assert b.flags.c_contiguous is b.flags.f_contiguous is False triu(b)
2,609
29.705882
68
py
libgpuarray
libgpuarray-master/pygpu/tests/test_reduction.py
import numpy from nose.tools import assert_raises from pygpu import gpuarray, ndgpuarray as elemary from pygpu.reduction import ReductionKernel from .support import (guard_devsup, check_meta_content, context, gen_gpuarray, dtypes_no_complex_big, dtypes_no_complex) def test_red_array_basic(): for dtype in dtypes_no_complex_big: for shape, redux in [((10,), [True]), ((20, 30), [True, True]), ((20, 30), [True, False]), ((20, 30), [False, True]), ((8, 5, 10), [True, True, True]), ((8, 5, 10), [True, True, False]), ((8, 5, 10), [True, False, True]), ((8, 5, 10), [False, True, True]), ((8, 5, 10), [True, False, False]), ((8, 5, 10), [False, True, False]), ((8, 5, 10), [False, False, True]), ]: yield red_array_sum, dtype, shape, redux @guard_devsup def red_array_sum(dtype, shape, redux): c, g = gen_gpuarray(shape, dtype, ctx=context) axes = [i for i in range(len(redux)) if redux[i]] axes.reverse() out_c = c # numpy.sum doesn't support multiple axis before 1.7.0 for ax in axes: out_c = numpy.apply_along_axis(sum, ax, out_c).astype(dtype) out_g = ReductionKernel(context, dtype, "0", "a + b", redux)(g) assert out_c.shape == out_g.shape assert out_g.dtype == numpy.dtype(dtype) # since we do not use the same summing algorithm, # there will be differences assert numpy.allclose(out_c, numpy.asarray(out_g), rtol=2e-5) def test_red_big_array(): for redux in [[True, False, False], [True, False, True], [False, True, True], [False, True, False]]: yield red_array_sum, 'float32', (2000, 30, 100), redux # this test needs a guard_devsup because Python 'float' is double, # and placing one directly on a test_* makes nose not know that it's a test def test_red_broadcast(): red_broadcast() @guard_devsup def red_broadcast(): from pygpu.tools import as_argument dtype = float xshape = (5, 10, 15) yshape = (1, 10, 15) redux = [False, True, False] nx, gx = gen_gpuarray(xshape, dtype, ctx=context) ny, gy = gen_gpuarray(yshape, dtype, ctx=context) nz = nx*ny axes = [i for i in range(len(redux)) if redux[i]] axes.reverse() # numpy.sum doesn't support multiple axis before 1.7.0 for ax in axes: nz = numpy.apply_along_axis(sum, ax, nz).astype(dtype) args = [as_argument(gx, 'a'), as_argument(gy, 'b')] gz = ReductionKernel(context, dtype, "0", "a+b", redux, map_expr="a[i]*b[i]", arguments=args)( gx, gy, broadcast=True) assert numpy.allclose(nz, numpy.asarray(gz)) def test_reduction_ops(): for axis in [None, 0, 1]: for op in ['all', 'any']: yield reduction_op, op, 'bool', axis for op in ['prod', 'sum']: # 'min', 'max']: for dtype in dtypes_no_complex: yield reduction_op, op, dtype, axis @guard_devsup def reduction_op(op, dtype, axis): c, g = gen_gpuarray((2, 3), dtype=dtype, ctx=context, cls=elemary) rc = getattr(c, op)(axis=axis) rg = getattr(g, op)(axis=axis) check_meta_content(rg, rc) outc = numpy.empty(rc.shape, dtype=rc.dtype) outg = gpuarray.empty(rg.shape, dtype=rg.dtype, context=context) rc = getattr(c, op)(axis=axis, out=outc) rg = getattr(g, op)(axis=axis, out=outg) check_meta_content(outg, outc) def test_reduction_wrong_type(): c, g = gen_gpuarray((2, 3), dtype='float32', ctx=context, cls=elemary) out1 = gpuarray.empty((2, 3), dtype='int32', context=context) out2 = gpuarray.empty((3, 2), dtype='float32', context=context) try: g.sum(out=out1) assert False, "Expected a TypeError out of the sum" except TypeError: pass try: g.sum(out=out2) assert False, "Expected a TypeError out of the sum" except TypeError: pass def test_reduction_0d(): c, g = gen_gpuarray((), dtype='bool', ctx=context, cls=elemary) rc = c.any() rg = g.any() assert numpy.all(rc == numpy.asarray(rg)) rc = c.all() rg = g.all() assert numpy.all(rc == numpy.asarray(rg)) def test_reduction_f16(): c, g = gen_gpuarray((3,), dtype='float16', ctx=context, cls=elemary) assert_raises(NotImplementedError, g.sum)
4,645
30.181208
78
py
libgpuarray
libgpuarray-master/pygpu/tests/test_blas.py
from itertools import product import numpy from nose.plugins.skip import SkipTest from .support import (guard_devsup, gen_gpuarray, context) try: import scipy.linalg.blas try: fblas = scipy.linalg.blas.fblas except AttributeError: fblas = scipy.linalg.blas except ImportError as e: raise SkipTest("no scipy blas to compare against") import pygpu.blas as gblas from pygpu.gpuarray import (GpuArrayException, UnsupportedException) def guard_devsup_blasdouble(func): def f(*args, **kwargs): try: func(*args, **kwargs) except UnsupportedException as e: raise SkipTest("operation not supported") except GpuArrayException as e: if 'float64' in args and "does not support double precision" in str(e): raise SkipTest("double precision not supported") raise return f def test_dot(): bools = [True, False] for N, dtype, offseted_i, sliced in product( [1, 256, 1337], ['float32', 'float64'], bools, bools): yield dot, N, dtype, offseted_i, sliced, True, False for overwrite, init_z in product(bools, bools): yield dot, 666, 'float32', False, False, overwrite, init_z @guard_devsup_blasdouble def dot(N, dtype, offseted_i, sliced, overwrite, init_z): cX, gX = gen_gpuarray((N,), dtype, offseted_inner=offseted_i, sliced=sliced, ctx=context) cY, gY = gen_gpuarray((N,), dtype, offseted_inner=offseted_i, sliced=sliced, ctx=context) if init_z: gZ = gen_gpuarray((), dtype, offseted_inner=offseted_i, sliced=sliced, ctx=context)[1] else: gZ = None # Always check against double precision: scipy's single precision # has enough error that this sometimes fails when we're closer cr = fblas.ddot(cX, cY) gr = gblas.dot(gX, gY, gZ, overwrite_z=overwrite) numpy.testing.assert_allclose(cr, numpy.asarray(gr), rtol=1e-6) def test_gemv(): bools = [False, True] for shape, order, trans, offseted_i, sliced in product( [(100, 128), (128, 50)], 'fc', bools, bools, [1, 2, -1, -2]): yield (gemv, shape, 'float32', order, trans, offseted_i, sliced, True, False) for overwrite, init_y in product(bools, bools): yield (gemv, (4, 3), 'float32', 'f', False, False, 1, overwrite, init_y) yield gemv, (32, 32), 'float64', 'f', False, False, 1, True, False for alpha, beta, overwrite in product( [0, 1, -1, 0.6], [0, 1, -1, 0.6], bools): yield (gemv, (32, 32), 'float32', 'f', False, False, 1, overwrite, True, alpha, beta) @guard_devsup_blasdouble def gemv(shp, dtype, order, trans, offseted_i, sliced, overwrite, init_y, alpha=1.0, beta=0.0): cA, gA = gen_gpuarray(shp, dtype, order=order, offseted_inner=offseted_i, sliced=sliced, ctx=context) if trans: shpX = (shp[0],) shpY = (shp[1],) else: shpX = (shp[1],) shpY = (shp[0],) cX, gX = gen_gpuarray(shpX, dtype, offseted_inner=offseted_i, sliced=sliced, ctx=context) if init_y: cY, gY = gen_gpuarray(shpY, dtype, ctx=context) else: cY, gY = None, None if dtype == 'float32': cr = fblas.sgemv(alpha, cA, cX, beta, cY, trans=trans, overwrite_y=overwrite) else: cr = fblas.dgemv(alpha, cA, cX, beta, cY, trans=trans, overwrite_y=overwrite) gr = gblas.gemv(alpha, gA, gX, beta, gY, trans_a=trans, overwrite_y=overwrite) numpy.testing.assert_allclose(cr, numpy.asarray(gr), rtol=1e-6) def test_gemm(): bools = [False, True] for (m, n, k), order, trans, offseted_o in product( [(48, 15, 32), (15, 32, 48)], list(product(*['fc']*3)), list(product(bools, bools)), bools): yield (gemm, m, n, k, 'float32', order, trans, offseted_o, 1, False, False) for sliced, overwrite, init_res in product([1, 2, -1, -2], bools, bools): yield (gemm, 4, 3, 2, 'float32', ('f', 'f', 'f'), (False, False), False, sliced, overwrite, init_res) yield (gemm, 32, 32, 32, 'float64', ('f', 'f', 'f'), (False, False), False, 1, False, False) for alpha, beta, overwrite in product( [0, 1, -1, 0.6], [0, 1, -1, 0.6], bools): yield (gemm, 32, 23, 32, 'float32', ('f', 'f', 'f'), (False, False), False, 1, overwrite, True, alpha, beta) @guard_devsup_blasdouble def gemm(m, n, k, dtype, order, trans, offseted_o, sliced, overwrite, init_res, alpha=1.0, beta=0.0): if trans[0]: shpA = (k, m) else: shpA = (m, k) if trans[1]: shpB = (n, k) else: shpB = (k, n) cA, gA = gen_gpuarray(shpA, dtype, order=order[0], offseted_outer=offseted_o, sliced=sliced, ctx=context) cB, gB = gen_gpuarray(shpB, dtype, order=order[1], offseted_outer=offseted_o, sliced=sliced, ctx=context) if init_res: cC, gC = gen_gpuarray((m, n), dtype, order=order[2], ctx=context) else: cC, gC = None, None if dtype == 'float32': cr = fblas.sgemm(alpha, cA, cB, beta, cC, trans_a=trans[0], trans_b=trans[1], overwrite_c=overwrite) else: cr = fblas.dgemm(alpha, cA, cB, beta, cC, trans_a=trans[0], trans_b=trans[1], overwrite_c=overwrite) gr = gblas.gemm(alpha, gA, gB, beta, gC, trans_a=trans[0], trans_b=trans[1], overwrite_c=overwrite) numpy.testing.assert_allclose(cr, numpy.asarray(gr), rtol=1e-6) def test_ger(): bools = [False, True] for (m, n), order, sliced_x, sliced_y in product( [(4, 5)], 'fc', [1, 2, -2, -1], [1, 2, -2, -1]): yield ger, m, n, 'float32', order, sliced_x, sliced_y, False yield ger, 4, 5, 'float64', 'f', 1, 1, False for init_res, overwrite in product(bools, bools): yield ger, 4, 5, 'float32', 'f', 1, 1, init_res, overwrite @guard_devsup_blasdouble def ger(m, n, dtype, order, sliced_x, sliced_y, init_res, overwrite=False): cX, gX = gen_gpuarray((m,), dtype, order, sliced=sliced_x, ctx=context) cY, gY = gen_gpuarray((n,), dtype, order, sliced=sliced_y, ctx=context) if init_res: cA, gA = gen_gpuarray((m, n), dtype, order, ctx=context) else: cA, gA = None, None if dtype == 'float32': cr = fblas.sger(1.0, cX, cY, a=cA, overwrite_a=overwrite) else: cr = fblas.dger(1.0, cX, cY, a=cA, overwrite_a=overwrite) gr = gblas.ger(1.0, gX, gY, gA, overwrite_a=overwrite) numpy.testing.assert_allclose(cr, numpy.asarray(gr), rtol=1e-6) def test_rgemmBatch_3d(): bools = [False, True] for b, (m, n, k), order, trans, offseted_o in product( [1, 17, 31], [(24, 7, 16), (7, 16, 24)], list(product('fc', 'fc', 'c')), list(product(bools, bools)), bools): yield (rgemmBatch_3d, b, m, n, k, 'float32', order, trans, offseted_o, 1, False, False) for sliced, overwrite, init_res in product([1, 2, -1, -2], bools, bools): yield (rgemmBatch_3d, 5, 4, 3, 2, 'float32', ('f', 'f', 'c'), (False, False), False, sliced, overwrite, init_res) yield (rgemmBatch_3d, 16, 16, 16, 16, 'float64', ('f', 'f', 'c'), (False, False), False, 1, False, False) for alpha, beta, overwrite in product( [0, 1, -1, 0.6], [0, 1, -1, 0.6], bools): yield (rgemmBatch_3d, 16, 16, 9, 16, 'float32', ('f', 'f', 'c'), (False, False), False, 1, overwrite, True, alpha, beta) @guard_devsup_blasdouble def rgemmBatch_3d(b, m, n, k, dtype, order, trans, offseted_o, sliced, overwrite, init_res, alpha=1.0, beta=0.0): if trans[0]: shpA = (b, k, m) else: shpA = (b, m, k) if trans[1]: shpB = (b, n, k) else: shpB = (b, k, n) cA, gA = gen_gpuarray(shpA, dtype, order=order[0], offseted_outer=offseted_o, sliced=sliced, ctx=context) cB, gB = gen_gpuarray(shpB, dtype, order=order[1], offseted_outer=offseted_o, sliced=sliced, ctx=context) if init_res: cC, gC = gen_gpuarray((b, m, n), dtype, order=order[2], ctx=context) else: cC, gC = None, None cr = numpy.empty((b, m, n), dtype=dtype) if dtype == 'float32': fn_gemm_c = fblas.sgemm else: fn_gemm_c = fblas.dgemm for i in range(b): cCi = cC if cC is None else cC[i] cr[i] = fn_gemm_c(alpha, cA[i], cB[i], beta, cCi, trans_a=trans[0], trans_b=trans[1], overwrite_c=overwrite) gr = gblas.gemmBatch_3d(alpha, gA, gB, beta, gC, trans_a=trans[0], trans_b=trans[1], overwrite_c=overwrite) numpy.testing.assert_allclose(cr, numpy.asarray(gr), rtol=1e-5)
9,194
36.684426
83
py
libgpuarray
libgpuarray-master/pygpu/tests/support.py
from __future__ import print_function import os import sys import numpy from nose.plugins.skip import SkipTest from pygpu import gpuarray if numpy.__version__ < '1.6.0': skip_single_f = True else: skip_single_f = False dtypes_all = ["float32", "float64", "int8", "int16", "uint8", "uint16", "int32", "int64", "uint32", "uint64"] dtypes_no_complex = dtypes_all # Sometimes int8 is just a source of trouble (like with overflows) dtypes_no_complex_big = ["float32", "float64", "int16", "uint16", "int32", "int64", "uint32", "uint64"] def get_env_dev(): for name in ['GPUARRAY_TEST_DEVICE', 'DEVICE']: if name in os.environ: return os.environ[name] raise RuntimeError( "No test device specified. Specify one using the DEVICE " "or GPUARRAY_TEST_DEVICE environment variables.") context = gpuarray.init(get_env_dev()) print("*** Testing for", context.devname, file=sys.stderr) def guard_devsup(func): def f(*args, **kwargs): try: func(*args, **kwargs) except gpuarray.UnsupportedException as e: raise SkipTest("operation not supported") return f def rand(shape, dtype): r = numpy.random.randn(*shape) * 10 if r.dtype.startswith('u'): r = numpy.absolute(r) return r.astype(dtype) def check_flags(x, y): assert isinstance(x, gpuarray.GpuArray) if y.size == 0 and y.flags["C_CONTIGUOUS"] and y.flags["F_CONTIGUOUS"]: # Different numpy version have different value for # C_CONTIGUOUS in that case. pass elif x.flags["C_CONTIGUOUS"] != y.flags["C_CONTIGUOUS"]: # Numpy 1.10 can set c/f contiguous more frequently by # ignoring strides on dimensions of size 1. assert x.flags["C_CONTIGUOUS"] is True, (x.flags, y.flags) assert x.flags["F_CONTIGUOUS"] is False, (x.flags, y.flags) assert y.flags["C_CONTIGUOUS"] is False, (x.flags, y.flags) # That depend of numpy version. # assert y.flags["F_CONTIGUOUS"] is True, (x.flags, y.flags) else: if not (skip_single_f and x.shape == ()): # Numpy below 1.6.0 does not have a consistent handling of # f-contiguous for 0-d arrays if not any([s == 1 for s in x.shape]): # Numpy 1.10 can set f contiguous more frequently by # ignoring strides on dimensions of size 1. assert x.flags["F_CONTIGUOUS"] == y.flags["F_CONTIGUOUS"], ( x.flags, y.flags) else: assert x.flags["F_CONTIGUOUS"] assert x.flags["WRITEABLE"] == y.flags["WRITEABLE"], (x.flags, y.flags) # Don't check for OWNDATA since it is always true for a GpuArray assert x.flags["ALIGNED"] == y.flags["ALIGNED"], (x.flags, y.flags) assert x.flags["UPDATEIFCOPY"] == y.flags["UPDATEIFCOPY"], (x.flags, y.flags) def check_meta_only(x, y): assert isinstance(x, gpuarray.GpuArray) assert x.shape == y.shape assert x.dtype == y.dtype if y.size != 0: assert x.strides == y.strides def check_content(x, y): assert isinstance(x, gpuarray.GpuArray) assert numpy.allclose(numpy.asarray(x), numpy.asarray(y)) def check_meta(x, y): check_meta_only(x, y) check_flags(x, y) def check_all(x, y): check_meta(x, y) check_content(x, y) def check_meta_content(x, y): check_meta_only(x, y) check_content(x, y) def gen_gpuarray(shape_orig, dtype='float32', offseted_outer=False, offseted_inner=False, sliced=1, order='c', nozeros=False, incr=0, ctx=None, cls=None): if sliced is True: sliced = 2 elif sliced is False: sliced = 1 shape = numpy.asarray(shape_orig).copy() if sliced != 1 and len(shape) > 0: shape[0] *= numpy.absolute(sliced) if offseted_outer and len(shape) > 0: shape[0] += 1 if offseted_inner and len(shape) > 0: shape[-1] += 1 low = 0.0 if nozeros: low = 1.0 a = numpy.random.uniform(low, 10.0, shape) a += incr a = numpy.asarray(a, dtype=dtype) b = gpuarray.array(a, context=ctx, cls=cls) assert order in ['c', 'f'] if order == 'f' and len(shape) > 0: a = numpy.asfortranarray(a) b = gpuarray.asfortranarray(b) if order == 'f' and len(shape) > 0 and b.size > 1: assert b.flags['F_CONTIGUOUS'] if offseted_outer and len(shape) > 0: b = b[1:] a = a[1:] if offseted_inner and len(shape) > 0: # The b[..., 1:] act as the test for this subtensor case. b = b[..., 1:] a = a[..., 1:] if sliced != 1 and len(shape) > 0: a = a[::sliced] b = b[::sliced] if False and shape_orig == (): assert a.shape == (1,) assert b.shape == (1,) else: assert a.shape == shape_orig, (a.shape, shape_orig) assert b.shape == shape_orig, (b.shape, shape_orig) assert numpy.allclose(a, numpy.asarray(b)), (a, numpy.asarray(b)) return a, b
5,147
29.461538
76
py
libgpuarray
libgpuarray-master/pygpu/tests/test_tools.py
from pygpu.tools import check_args from .support import context, gen_gpuarray def test_check_args_simple(): ac, ag = gen_gpuarray((50,), 'float32', ctx=context) bc, bg = gen_gpuarray((50,), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag, bg)) assert n == 50 assert nd == 1 assert dims == (50,) assert strs == ((4,), (4,)) assert offsets == (0, 0) ac, ag = gen_gpuarray((50, 1, 20), 'float32', ctx=context) bc, bg = gen_gpuarray((50, 1, 20), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag, bg)) assert n == 1000 assert nd == 3 assert dims == (50, 1, 20) assert strs == ((80, 80, 4), (80, 80, 4)) assert offsets == (0, 0) def test_check_args_collapse_1(): ac, ag = gen_gpuarray((50, 1, 20), 'float32', ctx=context) bc, bg = gen_gpuarray((50, 1, 20), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag, bg), collapse=False) assert n == 1000 assert nd == 3 assert dims == (50, 1, 20) assert strs == ((80, 80, 4), (80, 80, 4)) assert offsets == (0, 0) n, nd, dims, strs, offsets = check_args((ag, bg), collapse=True) assert n == 1000 assert nd == 1 assert dims == (1000,) assert strs == ((4,), (4,)) assert offsets == (0, 0) def test_check_args_collapse_2(): ac, ag = gen_gpuarray((50, 1, 20), 'float32', ctx=context, sliced=2, offseted_inner=True) bc, bg = gen_gpuarray((50, 1, 20), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag, bg), collapse=True) assert n == 1000 assert nd == 2 assert dims == (50, 20) assert strs == ((168, 4), (80, 4)) assert offsets == (4, 0) def test_check_args_collapse_3(): ac, ag = gen_gpuarray((50, 2, 10), 'float32', ctx=context, sliced=2, offseted_outer=True) bc, bg = gen_gpuarray((50, 2, 10), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag, bg), collapse=True) assert n == 1000 assert nd == 2 assert dims == (50, 20) assert strs == ((160, 4), (80, 4)) assert offsets == (80, 0) def test_check_args_collapse_4(): ac, ag = gen_gpuarray((1,), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag,), collapse=False) assert n == 1 assert nd == 1 assert dims == (1,) assert strs == ((4,),) assert offsets == (0,) ac, ag = gen_gpuarray((1, 1), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag,), collapse=True) assert n == 1 assert nd == 1 assert dims == (1,) assert strs == ((4,),) assert offsets == (0,) def test_check_args_broadcast_1(): ac, ag = gen_gpuarray((1,), 'float32', ctx=context) bc, bg = gen_gpuarray((50,), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag, bg), broadcast=True) assert n == 50 assert nd == 1 assert dims == (50,) assert strs == ((0,), (4,)) assert offsets == (0, 0) def test_check_args_broadcast_2(): ac, ag = gen_gpuarray((50, 1, 20), 'float32', ctx=context, sliced=2, offseted_inner=True) bc, bg = gen_gpuarray((50, 1, 20), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag, bg), collapse=True, broadcast=True) assert n == 1000 assert nd == 2 assert dims == (50, 20) assert strs == ((168, 4), (80, 4)) assert offsets == (4, 0) def test_check_args_broadcast_3(): ac, ag = gen_gpuarray((10, 20, 30), 'float32', ctx=context) bc, bg = gen_gpuarray((1, 1, 1), 'float32', ctx=context) n, nd, dims, strs, offsets = check_args((ag, bg), broadcast=True) assert n == 6000 assert nd == 3 assert dims == (10, 20, 30) assert strs == ((2400, 120, 4), (0, 0, 0)) assert offsets == (0, 0)
3,878
31.596639
72
py
libgpuarray
libgpuarray-master/pygpu/tests/test_gpu_ndarray.py
from __future__ import print_function import unittest import copy from six.moves import range from six import PY3 import pickle import numpy from nose.tools import assert_raises import pygpu from pygpu.gpuarray import GpuArray, GpuKernel from .support import (guard_devsup, check_meta, check_flags, check_all, check_content, gen_gpuarray, context as ctx, dtypes_all, dtypes_no_complex, skip_single_f) def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] for prod in result: yield tuple(prod) def permutations(elements): if len(elements) <= 1: yield elements else: for perm in permutations(elements[1:]): for i in range(len(elements)): yield perm[:i] + elements[:1] + perm[i:] def test_hash(): g = pygpu.empty((2, 3), context=ctx) exc = None try: hash(g) except TypeError as e: exc = e assert exc is not None def test_bool(): for data in [numpy.empty((0, 33)), [[1]], [[0]], [], [0], [1], 0, 1]: assert (bool(pygpu.asarray(data, context=ctx)) == bool(numpy.asarray(data))) def test_transfer(): for shp in [(), (5,), (6, 7), (4, 8, 9), (1, 8, 9)]: for dtype in dtypes_all: for offseted in [True, False]: yield transfer, shp, dtype, offseted def transfer(shp, dtype, offseted): a, b = gen_gpuarray(shp, dtype, offseted, ctx=ctx) # Test that passing dtype doesn't break. c = numpy.asarray(b, dtype=dtype) c = numpy.asarray(b) assert numpy.allclose(c, a) assert a.shape == b.shape == c.shape assert a.strides == b.strides == c.strides assert a.dtype == b.dtype == c.dtype == dtype assert c.flags.c_contiguous def test_cast(): for shp in [(), (5,), (6, 7), (4, 8, 9), (1, 8, 9)]: for dtype1 in dtypes_no_complex: for dtype2 in dtypes_no_complex: yield cast, shp, dtype1, dtype2 @guard_devsup def cast(shp, dtype1, dtype2): a, b = gen_gpuarray(shp, dtype1, False, ctx=ctx) ac = a.astype(dtype2) bc = b.astype(dtype2) assert ac.dtype == bc.dtype assert ac.shape == bc.shape assert numpy.allclose(a, numpy.asarray(b)) def test_transfer_not_contiguous(): for shp in [(5,), (6, 7), (4, 8, 9), (1, 8, 9)]: for dtype in dtypes_all: yield transfer_not_contiguous, shp, dtype @guard_devsup def transfer_not_contiguous(shp, dtype): a = numpy.random.rand(*shp) * 10 b = pygpu.array(a, context=ctx) a = a[::-1] b = b[::-1] c = numpy.asarray(b) assert numpy.allclose(c, a) assert a.shape == b.shape == c.shape # the result array (c) is C contiguous assert a.strides == b.strides == (-c.strides[0],) + c.strides[1:] assert a.dtype == b.dtype == c.dtype assert c.flags.c_contiguous def test_transfer_fortran(): for shp in [(5,), (6, 7), (4, 8, 9), (1, 8, 9)]: for dtype in dtypes_all: yield transfer_fortran, shp, dtype @guard_devsup def transfer_fortran(shp, dtype): a = numpy.random.rand(*shp) * 10 b = pygpu.array(a, context=ctx) a_ = numpy.asfortranarray(a) if len(shp) > 1: assert a_.strides != a.strides a = a_ b = pygpu.asfortranarray(b) c = numpy.asarray(b) assert a.shape == b.shape == c.shape assert a.dtype == b.dtype == c.dtype assert a.flags.f_contiguous assert c.flags.f_contiguous assert a.strides == b.strides == c.strides assert numpy.allclose(c, a) def test_ascontiguousarray(): for shp in [(), (5,), (6, 7), (4, 8, 9), (1, 8, 9)]: for dtype in dtypes_all: for offseted_o in [True, False]: for offseted_i in [True, True]: for sliced in [1, 2, -1, -2]: for order in ['f', 'c']: yield (ascontiguousarray, shp, dtype, offseted_o, offseted_i, sliced, order) @guard_devsup def ascontiguousarray(shp, dtype, offseted_o, offseted_i, sliced, order): cpu, gpu = gen_gpuarray(shp, dtype, offseted_o, offseted_i, sliced, order, ctx=ctx) a = numpy.ascontiguousarray(cpu) b = pygpu.ascontiguousarray(gpu) # numpy upcast with a view to 1d scalar. if (sliced != 1 or shp == () or (offseted_i and len(shp) > 1)): assert b is not gpu if sliced == 1 and not offseted_i: assert (a.data is cpu.data) == (b.bytes is gpu.bytes) else: assert b is gpu assert a.shape == b.shape assert a.dtype == b.dtype assert a.flags.c_contiguous assert b.flags['C_CONTIGUOUS'] assert a.strides == b.strides assert numpy.allclose(cpu, a) assert numpy.allclose(cpu, b) def test_asfortranarray(): for shp in [(), (5,), (6, 7), (4, 8, 9), (1, 8, 9)]: for dtype in dtypes_all: for offseted_outer in [True, False]: for offseted_inner in [True, False]: for sliced in [1, 2, -1, -2]: for order in ['f', 'c']: yield (asfortranarray, shp, dtype, offseted_outer, offseted_inner, sliced, order) @guard_devsup def asfortranarray(shp, dtype, offseted_outer, offseted_inner, sliced, order): cpu, gpu = gen_gpuarray(shp, dtype, offseted_outer, offseted_inner, sliced, order, ctx=ctx) a = numpy.asfortranarray(cpu) b = pygpu.asfortranarray(gpu) # numpy upcast with a view to 1d scalar. if gpu.flags['F_CONTIGUOUS']: assert ctx.kind != b'cuda' or b.gpudata == gpu.gpudata elif (sliced != 1 or shp == () or (offseted_outer and len(shp) > 1) or (order != 'f' and len(shp) > 1)): assert b is not gpu else: assert b is gpu assert a.shape == b.shape assert a.dtype == b.dtype assert a.flags.f_contiguous assert b.flags['F_CONTIGUOUS'] if not any([s == 1 for s in cpu.shape]): # Older version then Numpy 1.10 do not set c/f contiguous more # frequently as we do. This cause extra copy. assert a.strides == b.strides assert numpy.allclose(cpu, a) assert numpy.allclose(cpu, b) def test_zeros(): for shp in [(), (0,), (5,), (0, 0), (1, 0), (0, 1), (6, 7), (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (4, 8, 9), (1, 8, 9)]: for order in ["C", "F"]: for dtype in dtypes_all: yield zeros, shp, order, dtype @guard_devsup def zeros(shp, order, dtype): x = pygpu.zeros(shp, dtype, order, context=ctx) y = numpy.zeros(shp, dtype, order) check_all(x, y) def test_zeros_no_dtype(): # no dtype and order param x = pygpu.zeros((), context=ctx) y = numpy.zeros(()) check_meta(x, y) def test_zero_noparam(): try: pygpu.zeros() assert False except TypeError: pass def test_empty(): for shp in [(), (0,), (5,), (0, 0), (1, 0), (0, 1), (6, 7), (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (4, 8, 9), (1, 8, 9)]: for order in ["C", "F"]: for dtype in dtypes_all: yield empty, shp, order, dtype def empty(shp, order, dtype): x = pygpu.empty(shp, dtype, order, context=ctx) y = numpy.empty(shp, dtype, order) check_meta(x, y) def test_empty_no_dtype(): x = pygpu.empty((), context=ctx) # no dtype and order param y = numpy.empty(()) check_meta(x, y) def test_empty_no_params(): try: pygpu.empty() assert False except TypeError: pass def test_mapping_getitem_ellipsis(): for shp in [(), (5,), (6, 7), (4, 8, 9), (1, 8, 9)]: for dtype in dtypes_all: for offseted in [True, False]: yield mapping_getitem_ellipsis, shp, dtype, offseted def mapping_getitem_ellipsis(shp, dtype, offseted): a, a_gpu = gen_gpuarray(shp, dtype, offseted, ctx=ctx) b = a_gpu[...] if ctx.kind == b'cuda': assert b.gpudata == a_gpu.gpudata assert b.strides == a.strides assert b.shape == a.shape b_cpu = numpy.asarray(b) assert numpy.allclose(a, b_cpu) def test_getitem_none(): for shp in [(), (5,), (6, 7), (4, 8, 9), (1, 8, 9)]: yield getitem_none, shp def getitem_none(shp): a, a_gpu = gen_gpuarray(shp, ctx=ctx) assert numpy.allclose(a_gpu[..., None], a[..., None]) for _ in range(5): # Choose something to slice with, always works indcs = tuple(numpy.random.choice([0, slice(None), slice(1, None)], size=len(shp))) indcs = indcs[:1] + (None,) + indcs[1:] assert numpy.allclose(a_gpu[indcs], a[indcs]) if shp: assert numpy.allclose(a_gpu[1:, None], a[1:, None]) def test_mapping_setitem(): for shp in [(9,), (8, 9), (4, 8, 9), (1, 8, 9)]: for dtype in dtypes_all: for offseted in [True, False]: yield mapping_setitem_ellipsis, shp, dtype, offseted yield mapping_setitem_ellipsis2, shp, dtype, offseted yield mapping_setitem_firstaxis, shp, dtype, offseted @guard_devsup def mapping_setitem_ellipsis(shp, dtype, offseted): a, a_gpu = gen_gpuarray(shp, dtype, offseted, ctx=ctx) a[...] = 2 a_gpu[...] = 2 assert numpy.allclose(a, numpy.asarray(a_gpu)) @guard_devsup def mapping_setitem_ellipsis2(shp, dtype, offseted): a, a_gpu = gen_gpuarray(shp, dtype, offseted, ctx=ctx) b, b_gpu = gen_gpuarray(shp[1:], dtype, False, ctx=ctx) a[:] = b a_gpu[:] = b_gpu assert numpy.allclose(a, numpy.asarray(a_gpu)) @guard_devsup def mapping_setitem_firstaxis(shp, dtype, offseted): a, a_gpu = gen_gpuarray(shp, dtype, offseted, ctx=ctx) b, b_gpu = gen_gpuarray(shp[1:], dtype, False, ctx=ctx) a[0] = b a_gpu[0] = b_gpu assert numpy.allclose(a, numpy.asarray(a_gpu)) class WriteReadTest(unittest.TestCase): def setUp(self): self.cpu, self.gpu = gen_gpuarray((3, 4, 5), ctx=ctx) self.cpu[0, 0, 0] = 80 def test_write(self): self.gpu.write(self.cpu) res = numpy.asarray(self.gpu) assert numpy.allclose(self.cpu, res) self.cpu[0, 0, 0] = 160 self.cpu.setflags(write=False) self.gpu.write(self.cpu) res = numpy.asarray(self.gpu) assert numpy.allclose(self.cpu, res) self.cpu = numpy.ndarray((2, 4, 5), dtype="float32", order='C') self.assertRaises(ValueError, self.gpu.write, self.cpu) self.cpu = numpy.ndarray((3, 4, 5), dtype="float64", order='C') self.assertRaises(ValueError, self.gpu.write, self.cpu) cpu2 = numpy.random.random((3, 4, 5)) cpu2 = numpy.asarray(cpu2, dtype='float32', order='F') self.gpu.write(cpu2) res = numpy.asarray(self.gpu) assert numpy.allclose(cpu2, res) cpu2 = numpy.random.random((3, 4, 2, 5)) cpu2 = numpy.asarray(cpu2, dtype='float32', order='C') self.gpu.write(cpu2[:, :, 0, :]) res = numpy.asarray(self.gpu) assert numpy.allclose(cpu2[:, :, 0, :], res) cpu2 = numpy.random.random((3, 4, 2, 5)) cpu2 = numpy.asarray(cpu2, dtype='float32', order='F') self.gpu.write(cpu2[:, :, 0, :]) res = numpy.asarray(self.gpu) assert numpy.allclose(cpu2[:, :, 0, :], res) def test_read(self): self.gpu.read(self.cpu) res = numpy.asarray(self.gpu) assert numpy.allclose(self.cpu, res) self.cpu = numpy.ndarray((3, 4, 5), dtype="float32", order='C') self.cpu.setflags(write=False) self.assertRaises(ValueError, self.gpu.read, self.cpu) self.cpu = numpy.ndarray((2, 4, 5), dtype="float32", order='C') self.assertRaises(ValueError, self.gpu.read, self.cpu) self.cpu = numpy.ndarray((3, 4, 5), dtype="float64", order='C') self.assertRaises(ValueError, self.gpu.read, self.cpu) self.cpu = numpy.ndarray((3, 4, 5), dtype="float32", order='F') self.assertRaises(ValueError, self.gpu.read, self.cpu) self.cpu = numpy.ndarray((3, 4, 2, 5), dtype="float32", order='C') self.assertRaises(ValueError, self.gpu.read, self.cpu[:, :, 0, :]) def test_copy_view(): for shp in [(5,), (6, 7), (4, 8, 9), (1, 8, 9)]: for dtype in dtypes_all: for offseted in [False, True]: # order1 is the order of the original data for order1 in ['c', 'f']: # order2 is the order wanted after copy for order2 in ['c', 'f']: yield copy_view, shp, dtype, offseted, order1, order2 def check_memory_region(a, a_op, b, b_op): assert (numpy.may_share_memory(a, a_op) == pygpu.gpuarray.may_share_memory(b, b_op)) @guard_devsup def copy_view(shp, dtype, offseted, order1, order2): # TODO test copy unbroadcast! a, b = gen_gpuarray(shp, dtype, offseted, order=order1, ctx=ctx) assert numpy.allclose(a, numpy.asarray(b)) check_flags(b, a) c = b.copy(order2) assert numpy.allclose(a, numpy.asarray(c)) check_flags(c, a.copy(order2)) check_memory_region(a, a.copy(order2), b, c) d = copy.copy(b) assert numpy.allclose(a, numpy.asarray(d)) check_flags(d, copy.copy(a)) check_memory_region(a, copy.copy(a), b, d) e = b.view() assert numpy.allclose(a, numpy.asarray(e)) check_flags(e, a.view()) check_memory_region(a, a.view(), b, e) f = copy.deepcopy(b) assert numpy.allclose(a, numpy.asarray(f)) check_flags(f, copy.deepcopy(a)) check_memory_region(a, copy.deepcopy(a), b, f) g = copy.copy(b.view()) assert numpy.allclose(a, numpy.asarray(g)) check_memory_region(a, copy.copy(a.view()), b, g) check_flags(g, copy.copy(a.view())) def test_shape(): for shps in [((), (1,)), ((5,), (1, 5)), ((5,), (5, 1)), ((2, 3), (6,)), ((6,), (2, 3)), ((1,), ()), ((4,), (-1,)), ((4, 3), (-1,)), ((4, 3), (-1, 3)), ((4, 3), (4, -1)), ((4, 3), (3, -1)), ((4, 3), (12, -1)), ((4, 3), (-1, 12)), ((5, 4, 3, 2), (2, -1, 12)), ((4, 2), (2, 2, -1)), # ((4, 3), (13, -1)), ]: for offseted in [True, False]: for order1 in ['c', 'f']: if -1 not in shps[1]: yield shape_, shps, offseted, order1 for order2 in ['a', 'c', 'f']: yield reshape, shps, offseted, order1, order2 def shape_(shps, offseted, order): ac, ag = gen_gpuarray(shps[0], 'float32', offseted, order=order, ctx=ctx) try: ac.shape = shps[1] except AttributeError: # If numpy says it can't be done, we don't try to test it return ag.shape = shps[1] assert ac.strides == ag.strides, (ac.strides, ag.strides) # np.allclose don't test shapes assert ac.shape == ag.shape, (ac.shape, ag.shape) assert numpy.allclose(ac, numpy.asarray(ag)) def reshape(shps, offseted, order1, order2): ac, ag = gen_gpuarray(shps[0], 'float32', offseted, order=order1, ctx=ctx) outc = ac.reshape(shps[1], order=order2) outg = ag.reshape(shps[1], order=order2) assert outc.shape == outg.shape assert outc.strides == outg.strides assert numpy.allclose(outc, numpy.asarray(outg)) def test_strides(): yield strides_, (4, 4), 'c', 1, (4, 4) yield strides_, (4, 4), 'c', 1, (4, 16) yield strides_, (4, 4), 'c', 1, (16, 4) yield strides_, (4, 4), 'c', 1, (16, 8) yield strides_, (4, 4), 'c', 1, (16, 0) yield strides_, (4, 4), 'c', -1, (-20, 4) yield strides_, (4, 4), 'c', -1, (-12, 4) def set_strides(a, newstr): a.strides = newstr def strides_(shp, order, sliced, newstr): ac, ag = gen_gpuarray(shp, 'float32', sliced=sliced, order=order, ctx=ctx) try: ac.strides = newstr except ValueError: assert_raises(ValueError, set_strides, ag, newstr) return ag.strides = newstr check_flags(ag, ac) assert numpy.allclose(ac, numpy.asarray(ag)) def test_transpose(): for shp in [(2, 3), (4, 8, 9), (1, 2, 3, 4)]: for offseted in [True, False]: for order in ['c', 'f']: for sliced in [1, 2, -2, -1]: yield transpose, shp, offseted, sliced, order for perm in permutations(list(range(len(shp)))): yield (transpose_perm, shp, perm, offseted, sliced, order) def transpose(shp, offseted, sliced, order): ac, ag = gen_gpuarray(shp, 'float32', offseted, sliced=sliced, order=order, ctx=ctx) rc = ac.transpose() rg = ag.transpose() check_all(rg, rc) # also check that we are exactly equal since this only a copy op assert numpy.all(rc == numpy.asarray(rg)) # Test NumPy interface rg = numpy.transpose(ag) check_all(rg, rc) # also check that we are exactly equal since this only a copy op assert numpy.all(rc == numpy.asarray(rg)) def transpose_perm(shp, perm, offseted, sliced, order): ac, ag = gen_gpuarray(shp, 'float32', offseted, sliced=sliced, order=order, ctx=ctx) rc = ac.transpose(perm) rg = ag.transpose(perm) check_all(rg, rc) # also check that we are exactly equal since this only a copy op assert numpy.all(rc == numpy.asarray(rg)) # Test NumPy interface rg = numpy.transpose(ag, perm) check_all(rg, rc) # also check that we are exactly equal since this only a copy op assert numpy.all(rc == numpy.asarray(rg)) def test_transpose_args(): ac, ag = gen_gpuarray((4, 3, 2), 'float32', ctx=ctx) rc = ac.transpose(0, 2, 1) rg = ag.transpose(0, 2, 1) check_all(rg, rc) # also check that we are exactly equal since this only a copy op assert numpy.all(rc == numpy.asarray(rg)) def test_len(): for shp in [(5,), (6, 7), (4, 8, 9), (1, 8, 9)]: for dtype in dtypes_all: for offseted in [True, False]: yield len_, shp, dtype, offseted def len_(shp, dtype, offseted): a, a_gpu = gen_gpuarray(shp, dtype, offseted, ctx=ctx) assert len(a_gpu) == shp[0] def test_mapping_getitem_w_int(): for dtype in dtypes_all: for offseted in [True, False]: yield mapping_getitem_w_int, dtype, offseted @guard_devsup def mapping_getitem_w_int(dtype, offseted): # test vector dim = (2,) a, _a = gen_gpuarray(dim, dtype, offseted, ctx=ctx) _cmp(_a[...], a[...]) _cmp(_a[...], a[...]) _cmp(_a[...], a[...]) _cmp(_a[...], a[...]) _cmp(_a[...], a[...]) _cmp(_a[-1], a[-1]) _cmp(_a[1], a[1]) _cmp(_a[0], a[0]) _cmp(_a[::1], a[::1]) _cmpNs(_a[::-1], a[::-1]) _cmp(_a[...], a[...]) _cmpf(_a, 2) # test scalar dim = () a, _a = gen_gpuarray(dim, dtype, offseted, ctx=ctx) _cmp(_a[...], a[...]) _cmpf(_a, 0) _cmpf(_a, slice(1)) # test 4d-tensor dim = (5, 4, 3, 2) a, _a = gen_gpuarray(dim, dtype, offseted, ctx=ctx) _cmpf(_a, slice(-1), slice(-1), 10, -10) _cmpf(_a, slice(-1), slice(-1), -10, slice(-1)) _cmpf(_a, 0, slice(0, -1, -20), -10) _cmpf(_a, 10) _cmpf(_a, (10, 0, 0, 0)) _cmpf(_a, -10) # test with integer _cmp(_a[1], a[1]) _cmp(_a[-1], a[-1]) _cmp(_a[numpy.int64(1)], a[numpy.int64(1)]) _cmp(_a[numpy.int64(-1)], a[numpy.int64(-1)]) # test with slice _cmp(_a[1:], a[1:]) _cmp(_a[1:2], a[1:2]) _cmp(_a[-1:1], a[-1:1]) _cmp(_a[6:7:], a[6:7:]) # test with tuple (mix slice, integer, numpy.int64) _cmpNs(_a[0, 0, ::numpy.int64(-1), ::-1], a[0, 0, ::-1, ::-1]) _cmpNs(_a[:, :, ::numpy.int64(-1), ::-1], a[:, :, ::-1, ::-1]) _cmpNs(_a[:, :, numpy.int64(1), -1], a[:, :, 1, -1]) _cmpNs(_a[:, :, ::-1, ::-1], a[:, :, ::-1, ::-1]) _cmpNs(_a[:, :, ::-10, ::-10], a[:, :, ::-10, ::-10]) _cmpNs(_a[:, :, 1, -1], a[:, :, 1, -1]) _cmpNs(_a[:, :, -1, :], a[:, :, -1, :]) _cmpNs(_a[:, ::-2, -1, :], a[:, ::-2, -1, :]) _cmpNs(_a[:, ::-20, -1, :], a[:, ::-20, -1, :]) _cmpNs(_a[:, ::-2, -1], a[:, ::-2, -1]) _cmpNs(_a[0, ::-2, -1], a[0, ::-2, -1]) _cmp(_a[-1, -1, -1, -2], a[-1, -1, -1, -2]) # test ellipse _cmp(_a[...], a[...]) def _cmp(x, y): assert isinstance(x, GpuArray) assert x.shape == y.shape assert x.dtype == y.dtype assert x.strides == y.strides assert x.flags["C_CONTIGUOUS"] == y.flags["C_CONTIGUOUS"], (x.flags, y.flags) if y.size == 0: # F_CONTIGUOUS flags change definition with different numpy version # TODO: ideally, we should be F_CONTIGUOUS in that case. pass elif not (skip_single_f and y.shape == ()): assert x.flags["F_CONTIGUOUS"] == y.flags["F_CONTIGUOUS"], (x.flags, y.flags) else: assert x.flags["F_CONTIGUOUS"] # GpuArrays always own their data so don't check that flag. if x.flags["WRITEABLE"] != y.flags["WRITEABLE"]: assert x.ndim == 0 assert x.flags["ALIGNED"] == y.flags["ALIGNED"], (x.flags, y.flags) assert x.flags["UPDATEIFCOPY"] == y.flags["UPDATEIFCOPY"], (x.flags, y.flags) x = numpy.asarray(x) assert x.shape == y.shape assert x.dtype == y.dtype assert x.strides == y.strides if not numpy.all(x == y): print(x) print(y) assert numpy.all(x == y), (x, y) def _cmpNs(x, y): """ Don't compare the stride after the transfer There is a copy that have been made on the gpu before the transfer """ assert x.shape == y.shape assert x.dtype == y.dtype assert x.strides == y.strides assert x.flags["C_CONTIGUOUS"] == y.flags["C_CONTIGUOUS"] assert x.flags["F_CONTIGUOUS"] == y.flags["F_CONTIGUOUS"] assert x.flags["WRITEABLE"] == y.flags["WRITEABLE"] assert x.flags["ALIGNED"] == y.flags["ALIGNED"] # we don't check owndata since it is always true for GpuArrays assert x.flags["UPDATEIFCOPY"] == y.flags["UPDATEIFCOPY"] x_ = numpy.asarray(x) assert x_.shape == y.shape assert x_.dtype == y.dtype assert numpy.all(x_ == y), (x_, y) def _cmpf(x, *y): try: x.__getitem__(y) except IndexError: pass else: raise Exception("Did not generate out or bound error") def _cmpfV(x, *y): try: if len(y) == 1: x.__getitem__(*y) else: x.__getitem__(y) except ValueError: pass else: raise Exception("Did not generate value error") def test_take1(): yield do_take1, (4, 3), [2, 0], False yield do_take1, (4, 3), [2, 0], True yield do_take1, (12, 4, 3), [1, 1, 1, 1, 1, 2, 2, 3, 3, 0, 0, 9], False def do_take1(shp, idx, offseted): c, g = gen_gpuarray(shp, dtype='float32', ctx=ctx, order='c') ci = numpy.asarray(idx) gi = pygpu.asarray(ci, context=ctx) rc = c.take(ci, axis=0) rg = g.take1(gi) check_content(rg, rc) def test_flags(): for fl in ['C', 'F', 'W', 'B', 'O', 'A', 'U', 'CA', 'FA', 'FNC', 'FORC', 'CARRAY', 'FARRAY', 'FORTRAN', 'BEHAVED', 'OWNDATA', 'ALIGNED', 'WRITEABLE', 'CONTIGUOUS', 'UPDATEIFCOPY', 'C_CONTIGUOUS', 'F_CONTIGUOUS']: yield flag_dict, fl for p in ['c_contiguous', 'f_contiguous', 'contiguous', 'fortran', 'updateifcopy', 'owndata', 'aligned', 'writeable', 'behaved', 'carray', 'forc', 'fnc', 'farray']: yield flag_prop, p def flag_dict(fl): c2, g2 = gen_gpuarray((2, 3), dtype='float32', ctx=ctx, order='c') c3, g3 = gen_gpuarray((2, 3), dtype='float32', ctx=ctx, order='f') assert c2.flags[fl] == g2.flags[fl] assert c3.flags[fl] == g3.flags[fl] def flag_prop(p): c2, g2 = gen_gpuarray((2, 3), dtype='float32', ctx=ctx, order='c') c3, g3 = gen_gpuarray((2, 3), dtype='float32', ctx=ctx, order='f') assert getattr(c2.flags, p) == getattr(g2.flags, p) assert getattr(c3.flags, p) == getattr(g3.flags, p) class TestPickle(unittest.TestCase): def test_GpuArray(self): with self.assertRaises(RuntimeError): pickle.dumps(pygpu.zeros((32,), context=ctx)) with self.assertRaises(RuntimeError): pickle.dumps(pygpu.zeros((32,), context=ctx), protocol=0) with self.assertRaises(RuntimeError): pickle.dumps(pygpu.zeros((32,), context=ctx), protocol=1) with self.assertRaises(RuntimeError): pickle.dumps(pygpu.zeros((32,), context=ctx), protocol=2) if PY3: with self.assertRaises(RuntimeError): pickle.dumps(pygpu.zeros((32,), context=ctx), protocol=3) with self.assertRaises(RuntimeError): pickle.dumps(pygpu.zeros((32,), context=ctx), protocol=-1) def test_GpuContext(self): with self.assertRaises(RuntimeError): pickle.dumps(ctx) with self.assertRaises(RuntimeError): pickle.dumps(ctx, protocol=0) with self.assertRaises(RuntimeError): pickle.dumps(ctx, protocol=1) with self.assertRaises(RuntimeError): pickle.dumps(ctx, protocol=2) if PY3: with self.assertRaises(RuntimeError): pickle.dumps(ctx, protocol=3) with self.assertRaises(RuntimeError): pickle.dumps(ctx, protocol=-1) def test_GpuKernel(self): k = GpuKernel("#include \"cluda.h\"\nKERNEL void " "k(GLOBAL_MEM ga_float *in)" "{in[0] = 0;}", "k", [], context=ctx) with self.assertRaises(RuntimeError): pickle.dumps(k) with self.assertRaises(RuntimeError): pickle.dumps(k, protocol=0) with self.assertRaises(RuntimeError): pickle.dumps(k, protocol=1) with self.assertRaises(RuntimeError): pickle.dumps(k, protocol=2) if PY3: with self.assertRaises(RuntimeError): pickle.dumps(k, protocol=3) with self.assertRaises(RuntimeError): pickle.dumps(k, protocol=-1)
26,790
31.162065
79
py
libgpuarray
libgpuarray-master/pygpu/tests/__init__.py
0
0
0
py
libgpuarray
libgpuarray-master/pygpu/tests/test_operations.py
import numpy import pygpu from .support import (gen_gpuarray, context, SkipTest) def test_array_split(): xc, xg = gen_gpuarray((8,), 'float32', ctx=context) rc = numpy.array_split(xc, 3) rg = pygpu.array_split(xg, 3) assert len(rc) == len(rg) for pc, pg in zip(rc, rg): numpy.testing.assert_allclose(pc, numpy.asarray(pg)) xc, xg = gen_gpuarray((8,), 'float32', ctx=context) rc = numpy.array_split(xc, 3, axis=-1) rg = pygpu.array_split(xg, 3, axis=-1) assert len(rc) == len(rg) for pc, pg in zip(rc, rg): numpy.testing.assert_allclose(pc, numpy.asarray(pg)) def test_split(): for spl in (3, [3, 5, 6, 10]): yield xsplit, '', (9,), spl def test_xsplit(): if tuple(int(v) for v in numpy.version.version.split('.')[:2]) < (1, 11): raise SkipTest("Numpy version too old") for l in ('h', 'v'): for spl in (2, [3, 6]): yield xsplit, l, (4, 4), spl yield xsplit, l, (2, 2, 2), 2 for spl in (2, [3, 6]): yield xsplit, 'd', (2, 2, 4), spl def xsplit(l, shp, spl): xc, xg = gen_gpuarray(shp, 'float32', ctx=context) n = l + 'split' rc = getattr(numpy, n)(xc, spl) rg = getattr(pygpu, n)(xg, spl) assert len(rc) == len(rg) for pc, pg in zip(rc, rg): numpy.testing.assert_allclose(pc, numpy.asarray(pg)) def test_concatenate(): ac, ag = gen_gpuarray((2, 2), 'float32', ctx=context) bc, bg = gen_gpuarray((1, 2), 'float32', ctx=context) rc = numpy.concatenate((ac, bc), axis=0) rg = pygpu.concatenate((ag, bg), axis=0) numpy.testing.assert_allclose(rc, numpy.asarray(rg)) rc = numpy.concatenate((ac, bc.T), axis=1) rg = pygpu.concatenate((ag, bg.T), axis=1) numpy.testing.assert_allclose(rc, numpy.asarray(rg)) rc = numpy.concatenate((ac, bc.T), axis=-1) rg = pygpu.concatenate((ag, bg.T), axis=-1) numpy.testing.assert_allclose(rc, numpy.asarray(rg)) def test_hstack(): for shp in [(3,), (3, 1)]: yield xstack, 'h', (shp, shp), (), context def test_vstack(): for shp in [(3,), (3, 1)]: yield xstack, 'v', (shp, shp), (), context def test_dstack(): for shp in [(3,), (3, 1)]: yield xstack, 'd', (shp, shp), (), context def xstack(l, shps, tup, ctx): tupc = list(tup) tupg = list(tup) for shp in shps: tc, tg = gen_gpuarray(shp, 'float32', ctx=context) tupc.append(tc) tupg.append(tg) n = l + 'stack' rc = getattr(numpy, n)(tuple(tupc)) rg = getattr(pygpu, n)(tuple(tupg), ctx) numpy.testing.assert_allclose(rc, numpy.asarray(rg))
2,636
25.636364
77
py
libgpuarray
libgpuarray-master/pygpu/tests/test_elemwise.py
import operator import numpy from mako.template import Template from unittest import TestCase from pygpu import gpuarray, ndgpuarray as elemary from pygpu.dtypes import dtype_to_ctype, get_common_dtype from pygpu.elemwise import as_argument, ielemwise2 from pygpu._elemwise import GpuElemwise, arg from six import PY2 from .support import (guard_devsup, context, gen_gpuarray, check_meta_content) dtypes_test = ['float32', 'int8', 'uint64'] operators1 = [operator.neg, operator.pos, operator.abs] operators2 = [operator.add, operator.sub, operator.floordiv, operator.mod, operator.mul, operator.truediv, operator.eq, operator.ne, operator.lt, operator.le, operator.gt, operator.ge] if PY2: operators2.append(operator.div) ioperators2 = [operator.iadd, operator.isub, operator.ifloordiv, operator.imod, operator.imul, operator.itruediv] if PY2: ioperators2.append(operator.idiv) elems = [2, 0.3, numpy.asarray(3, dtype='int8'), numpy.asarray(7, dtype='uint32'), numpy.asarray(2.45, dtype='float32')] def test_elemwise1_ops_array(): for op in operators1: for dtype in dtypes_test: yield elemwise1_ops_array, op, dtype @guard_devsup def elemwise1_ops_array(op, dtype): c, g = gen_gpuarray((50,), dtype, ctx=context, cls=elemary) out_c = op(c) out_g = op(g) assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) def test_elemwise2_ops_array(): for op in operators2: for dtype1 in dtypes_test: for dtype2 in dtypes_test: yield elemwise2_ops_array, op, dtype1, dtype2, (50,) def test_ielemwise2_ops_array(): for op in ioperators2: for dtype1 in dtypes_test: for dtype2 in dtypes_test: yield ielemwise2_ops_array, op, dtype1, dtype2, (50,) class test_elemwise_output_not_broadcasted(TestCase): def test_all(self): test_values = [((1, 4), (6, 4)), ((2, 1, 8, 7), (2, 2, 8, 7))] for shapea, shapeb in test_values: # Sould fail: dimensions are not all equal. self.assertRaises(ValueError, self.run_ielemwise2, shapea, shapeb, False) # Should fail: broascast should not be done on output. self.assertRaises(ValueError, self.run_ielemwise2, shapea, shapeb, True) # Should fail: dimensions are not all equal. self.assertRaises(ValueError, self.check_elemwise2, shapeb, shapeb, shapea, False) # Should fail: broadcast should not be done on output. self.assertRaises(ValueError, self.check_elemwise2, shapeb, shapeb, shapea, True) # Should pass: output would be done on read-only input. self.run_ielemwise2(shapeb, shapea, broadcast=True) # Should pass: output would be done on read-only inputs. self.check_elemwise2(shapea, shapea, shapeb, broadcast=True) self.check_elemwise2(shapea, shapeb, shapeb, broadcast=True) self.check_elemwise2(shapeb, shapea, shapeb, broadcast=True) @guard_devsup def run_ielemwise2(self, shapea, shapeb, broadcast=True): na, ga = gen_gpuarray(shapea, ctx=context, cls=elemary) nb, gb = gen_gpuarray(shapeb, ctx=context, cls=elemary) ielemwise2(ga, '+', gb, broadcast=broadcast) na += nb assert numpy.allclose(na, numpy.asarray(ga), atol=1e-6) @guard_devsup def check_elemwise2(self, shapea, shapeb, output_shape, broadcast=True): # We rewrite this version of elemwise2 to skip the scaling of output # that is done in the official elemwise2 function. na, ga = gen_gpuarray(shapea, ctx=context, cls=elemary) nb, gb = gen_gpuarray(shapeb, ctx=context, cls=elemary) odtype = get_common_dtype(ga, gb, True) res = gpuarray.empty(output_shape, dtype=odtype, context=ga.context, cls=ga.__class__) a_arg = as_argument(ga, 'a', read=True) b_arg = as_argument(gb, 'b', read=True) res_arg = as_argument(res, 'res', write=True) args = [res_arg, a_arg, b_arg] oper = "res = (%(out_t)s)a %(op)s (%(out_t)s)b" % { 'op': '+', 'out_t': dtype_to_ctype(odtype)} k = GpuElemwise(ga.context, oper, args, convert_f16=True) k(res, ga, gb, broadcast=broadcast) nres = na + nb assert numpy.allclose(nres, numpy.asarray(res), atol=1e-6) @guard_devsup def elemwise2_ops_array(op, dtype1, dtype2, shape): ac, ag = gen_gpuarray(shape, dtype1, ctx=context, cls=elemary) bc, bg = gen_gpuarray(shape, dtype2, nozeros=True, ctx=context, cls=elemary) out_c = op(ac, bc) out_g = op(ag, bg) assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) @guard_devsup def ielemwise2_ops_array(op, dtype1, dtype2, shape): incr = 0 if op == operator.isub and dtype1[0] == 'u': # array elements are smaller than 10 by default, so we avoid underflow incr = 10 ac, ag = gen_gpuarray(shape, dtype1, incr=incr, ctx=context, cls=elemary) bc, bg = gen_gpuarray(shape, dtype2, nozeros=True, ctx=context, cls=elemary) try: out_c = op(ac, bc) except TypeError: # TODO: currently, we use old Numpy semantic and tolerate more case. # So we can't test that we raise the same error return out_g = op(ag, bg) assert out_g is ag assert numpy.allclose(out_c, numpy.asarray(out_g), atol=1e-6) def test_elemwise_f16(): yield elemwise1_ops_array, operator.neg, 'float16' yield elemwise2_ops_array, operator.add, 'float16', 'float16', (50,) yield ielemwise2_ops_array, operator.iadd, 'float16', 'float16', (50,) def test_elemwise2_ops_mixed(): for op in operators2: for dtype in dtypes_test: for elem in elems: yield elemwise2_ops_mixed, op, dtype, (50,), elem def test_ielemwise2_ops_mixed(): for op in ioperators2: for dtype in dtypes_test: for elem in elems: yield ielemwise2_ops_mixed, op, dtype, (50,), elem @guard_devsup def elemwise2_ops_mixed(op, dtype, shape, elem): c, g = gen_gpuarray(shape, dtype, ctx=context, cls=elemary) out_c = op(c, elem) out_g = op(g, elem) assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) c, g = gen_gpuarray(shape, dtype, nozeros=True, ctx=context, cls=elemary) out_c = op(elem, c) out_g = op(elem, g) assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) @guard_devsup def ielemwise2_ops_mixed(op, dtype, shape, elem): incr = 0 if op == operator.isub and dtype[0] == 'u': # array elements are smaller than 10 by default, so we avoid underflow incr = 10 c, g = gen_gpuarray(shape, dtype, incr=incr, ctx=context, cls=elemary) try: out_c = op(c, elem) except TypeError: # TODO: currently, we use old Numpy semantic and tolerate more case. # So we can't test that we raise the same error return out_g = op(g, elem) assert out_g is g assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) def test_divmod(): for dtype1 in dtypes_test: for dtype2 in dtypes_test: yield divmod_array, dtype1, dtype2, (50,) for dtype in dtypes_test: for elem in elems: yield divmod_mixed, dtype, (50,), elem @guard_devsup def divmod_array(dtype1, dtype2, shape): ac, ag = gen_gpuarray(shape, dtype1, ctx=context, cls=elemary) bc, bg = gen_gpuarray(shape, dtype2, nozeros=True, ctx=context, cls=elemary) out_c = divmod(ac, bc) out_g = divmod(ag, bg) assert out_c[0].shape == out_g[0].shape assert out_c[1].shape == out_g[1].shape assert out_c[0].dtype == out_g[0].dtype assert out_c[1].dtype == out_g[1].dtype assert numpy.allclose(out_c[0], numpy.asarray(out_g[0])) assert numpy.allclose(out_c[1], numpy.asarray(out_g[1])) @guard_devsup def divmod_mixed(dtype, shape, elem): c, g = gen_gpuarray(shape, dtype, nozeros=True, ctx=context, cls=elemary) out_c = divmod(c, elem) out_g = divmod(g, elem) assert out_c[0].shape == out_g[0].shape assert out_c[1].shape == out_g[1].shape assert out_c[0].dtype == out_g[0].dtype assert out_c[1].dtype == out_g[1].dtype assert numpy.allclose(out_c[0], numpy.asarray(out_g[0])) assert numpy.allclose(out_c[1], numpy.asarray(out_g[1])) out_c = divmod(elem, c) out_g = divmod(elem, g) assert out_c[0].shape == out_g[0].shape assert out_c[1].shape == out_g[1].shape assert out_c[0].dtype == out_g[0].dtype assert out_c[1].dtype == out_g[1].dtype assert numpy.allclose(out_c[0], numpy.asarray(out_g[0])) assert numpy.allclose(out_c[1], numpy.asarray(out_g[1])) def test_elemwise_bool(): a = gpuarray.empty((2,), context=context) exc = None try: bool(a) except ValueError as e: exc = e assert exc is not None a = gpuarray.zeros((1,), context=context) assert not bool(a) a = gpuarray.zeros((), context=context) assert not bool(a) def test_broadcast(): for shapea, shapeb in [((3, 5), (3, 5)), ((1, 5), (3, 5)), ((3, 5), (3, 1)), ((1, 5), (3, 1)), ((3, 1), (3, 5)), ((3, 5), (3, 1)), ((1, 1), (1, 1)), ((3, 4, 5), (4, 5)), ((4, 5), (3, 4, 5)), ((), ())]: yield broadcast, shapea, shapeb def broadcast(shapea, shapeb): ac, ag = gen_gpuarray(shapea, 'float32', ctx=context, cls=elemary) bc, bg = gen_gpuarray(shapeb, 'float32', ctx=context, cls=elemary) rc = ac + bc rg = ag + bg check_meta_content(rg, rc) _inf_preamb_tpl = Template(''' WITHIN_KERNEL ${flt} infinity() {return INFINITY;} WITHIN_KERNEL ${flt} neg_infinity() {return -INFINITY;} ''') def test_infinity(): for dtype in ['float32', 'float64']: yield infinity, dtype @guard_devsup def infinity(dtype): ac, ag = gen_gpuarray((2,), dtype, ctx=context, cls=elemary) out_g = ag._empty_like_me() flt = 'ga_float' if dtype == 'float32' else 'ga_double' out_arg = arg('out', out_g.dtype, scalar=False, read=False, write=True) preamble = _inf_preamb_tpl.render(flt=flt) # +infinity ac[:] = numpy.inf expr_inf = 'out = infinity()' kernel = GpuElemwise(context, expr_inf, [out_arg], preamble=preamble) kernel(out_g) assert numpy.array_equal(ac, numpy.asarray(out_g)) # -infinity ac[:] = -numpy.inf expr_neginf = 'out = neg_infinity()' kernel = GpuElemwise(context, expr_neginf, [out_arg], preamble=preamble) kernel(out_g) assert numpy.array_equal(ac, numpy.asarray(out_g))
11,580
32.37464
79
py
libgpuarray
libgpuarray-master/doc/conf.py
# -*- Coding: utf-8 -*- # # gpuarray documentation build configuration file, created by # sphinx-quickstart on Wed Nov 21 16:23:37 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) import versioneer # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.napoleon', # 'sphinx.ext.linkcode', 'breathe'] todo_include_todos = True napoleon_google_docstring = False napoleon_include_special_with_doc = False # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'gpuarray' copyright = u'2012--2017, Arnaud Bergeron' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # We need this hokey-pokey because versioneer needs the current # directory to be the root of the project to work. _curpath = os.getcwd() os.chdir(os.path.dirname(os.path.dirname(__file__))) # The full version, including alpha/beta/rc tags. release = versioneer.get_version() # The short X.Y version. version = '.'.join(release.split('.')[:2]) os.chdir(_curpath) del _curpath # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_dirs = ['_build', 'scripts'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- if os.environ.get('READTHEDOCS') != 'True': try: import sphinx_rtd_theme except ImportError: pass else: html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme = 'sphinx_rtd_theme' def setup(app): app.add_stylesheet('fix_rtd.css') # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'gpuarraydoc' # Options for the linkcode extension # ---------------------------------- # Resolve function # This function is used to populate the (source) links in the API # XXX: This is broken for now since it doesn't work for cython modules def linkcode_resolve(domain, info): def find_source(): obj = sys.modules[info['module']] for part in info['fullname'].split('.'): obj = getattr(obj, part) import inspect import os fn = inspect.getsourcefile(obj) fn = os.path.relpath(fn, start=os.path.dirname(pygpu.__file__)) source, lineno = inspect.getsourcelines(obj) return fn, lineno, lineno + len(source) - 1 if domain != 'py' or not info['module']: return None try: filename = 'libgpuarray/pygpu/%s#L%d-L%d' % find_source() except Exception: filename = info['module'].replace('.', '/') + '.py' import subprocess tag = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, universal_newlines=True).communicate()[0][:-1] return "https://github.com/Theano/libgpuarray/blob/%s/%s" % (tag, filename) # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'gpuarray.tex', u'libgpuarray Documentation', u'Arnaud Bergeron', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'gpuarray', u'libgpuarray Documentation', [u'Arnaud Bergeron'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'gpuarray', u'libgpuarray Documentation', u'Arnaud Bergeron', 'gpuarray', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' breathe_projects = { "gpuarray": "_doxybuild/xml/", } breathe_default_project = "gpuarray" breathe_domain_by_extension = { "h": "c", "c": "c", }
9,714
30.852459
80
py
GENESIM
GENESIM-master/example.py
""" This is an example script that will apply k-cross-validation on all datasets with a load function in `data.load_datasets` and for all implemented tree constructors, ensemble techniques and GENESIM. In the end, a confusion matrices will be stored at path `output/dataset_name_CVk.png` and the average model complexity and computational time required for each of the algorithms will be printed out. Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. """ import time from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis from sklearn.grid_search import GridSearchCV from sklearn.metrics import confusion_matrix from sklearn.cross_validation import StratifiedKFold, KFold import matplotlib.pyplot as plt import numpy as np from sklearn.neural_network import MLPClassifier import constructors.ISM from constructors.ensemble import RFClassification, XGBClassification, bootstrap from constructors.genesim import GENESIM from constructors.inTrees import inTreesClassifier from constructors.treeconstructor import QUESTConstructor, GUIDEConstructor, C45Constructor, CARTConstructor from data.load_all_datasets import load_all_datasets from decisiontree import DecisionTree if __name__ == "__main__": algorithms = {QUESTConstructor().get_name(): QUESTConstructor(), GUIDEConstructor().get_name(): GUIDEConstructor(), CARTConstructor().get_name(): CARTConstructor(), C45Constructor().get_name(): C45Constructor(), RFClassification().get_name(): RFClassification(), XGBClassification().get_name(): XGBClassification() } genesim = GENESIM() inTrees_clf = inTreesClassifier() NR_FOLDS = 5 for dataset in load_all_datasets(): df = dataset['dataframe'] label_col = dataset['label_col'] feature_cols = dataset['feature_cols'] conf_matrices, avg_nodes, times = {}, {}, {} for algorithm in algorithms: conf_matrices[algorithm] = [] avg_nodes[algorithm] = [] times[algorithm] = [] conf_matrices['GENESIM'], avg_nodes['GENESIM'], times['GENESIM'] = [], [], [] conf_matrices['ISM'], avg_nodes['ISM'], times['ISM'] = [], [], [] conf_matrices['inTrees'], avg_nodes['inTrees'], times['inTrees'] = [], [], [] skf = StratifiedKFold(df[label_col], n_folds=NR_FOLDS, shuffle=True, random_state=None) for fold, (train_idx, test_idx) in enumerate(skf): print 'Fold', fold+1, '/', NR_FOLDS, 'for dataset', dataset['name'] train = df.iloc[train_idx, :].reset_index(drop=True) X_train = train.drop(label_col, axis=1) y_train = train[label_col] test = df.iloc[test_idx, :].reset_index(drop=True) X_test = test.drop(label_col, axis=1) y_test = test[label_col] for algorithm in algorithms: print algorithm start = time.time() clf = algorithms[algorithm].construct_classifier(train, feature_cols, label_col) end = time.time() times[algorithm].append(end-start) predictions = clf.evaluate_multiple(X_test).astype(int) conf_matrix = confusion_matrix(y_test, predictions) print conf_matrix diagonal_sum = sum( [conf_matrix[i][i] for i in range(len(conf_matrix))]) norm_diagonal_sum = sum( [float(conf_matrix[i][i]) / float(sum(conf_matrix[i])) for i in range(len(conf_matrix))]) total_count = np.sum(conf_matrix) print 'Accuracy:', float(diagonal_sum) / float(total_count) print 'Balanced accuracy:', float(norm_diagonal_sum) / float(conf_matrix.shape[0]) conf_matrices[algorithm].append(confusion_matrix(y_test, predictions)) if type(clf) is DecisionTree: avg_nodes[algorithm].append(clf.count_nodes()) else: avg_nodes[algorithm].append(clf.nr_clf) _constructors = [CARTConstructor(), QUESTConstructor(), GUIDEConstructor()] print 'inTrees' start = time.time() orl = inTrees_clf.construct_rule_list(train, label_col, _constructors, nr_bootstraps=25) end = time.time() times['inTrees'].append(end-start) predictions = orl.evaluate_multiple(X_test).astype(int) conf_matrices['inTrees'].append(confusion_matrix(y_test, predictions)) conf_matrix = confusion_matrix(y_test, predictions) print conf_matrix diagonal_sum = sum( [conf_matrix[i][i] for i in range(len(conf_matrix))]) norm_diagonal_sum = sum( [float(conf_matrix[i][i]) / float(sum(conf_matrix[i])) for i in range(len(conf_matrix))]) total_count = np.sum(conf_matrix) correct = 0 for i in range(len(conf_matrix)): correct += conf_matrix[i][i] + conf_matrix[i][max(i - 1, 0)] * ((i - 1) >= 0) + \ conf_matrix[i][min(i + 1, len(conf_matrix[i]) - 1)] * ((i + 1) <= len(conf_matrix[i]) - 1) # print 'Accuracy [-1, +1]:', float(correct) / float(total_count) print 'Accuracy:', float(diagonal_sum) / float(total_count) print 'Balanced accuracy:', float(norm_diagonal_sum) / float(conf_matrix.shape[0]) avg_nodes['inTrees'].append(len(orl.rule_list)) print 'ISM' start = time.time() ism_tree = constructors.ISM.ism(bootstrap(train, label_col, _constructors, boosting=True, nr_classifiers=5), train, label_col, min_nr_samples=1, calc_fracs_from_ensemble=False) ism_pruned = ism_tree.cost_complexity_pruning(X_train, y_train, 'ism', ism_constructors=_constructors, ism_calc_fracs=False, n_folds=3, ism_nr_classifiers=5, ism_boosting=True) end = time.time() times['ISM'].append(end - start) predictions = ism_pruned.evaluate_multiple(X_test).astype(int) conf_matrices['ISM'].append(confusion_matrix(y_test, predictions)) avg_nodes['ISM'].append(ism_pruned.count_nodes()) conf_matrix = confusion_matrix(y_test, predictions) print conf_matrix diagonal_sum = sum( [conf_matrix[i][i] for i in range(len(conf_matrix))]) norm_diagonal_sum = sum( [float(conf_matrix[i][i]) / float(sum(conf_matrix[i])) for i in range(len(conf_matrix))]) total_count = np.sum(conf_matrix) correct = 0 for i in range(len(conf_matrix)): correct += conf_matrix[i][i] + conf_matrix[i][max(i - 1, 0)] * ((i - 1) >= 0) + \ conf_matrix[i][min(i + 1, len(conf_matrix[i]) - 1)] * ((i + 1) <= len(conf_matrix[i]) - 1) # print 'Accuracy [-1, +1]:', float(correct) / float(total_count) print 'Accuracy:', float(diagonal_sum) / float(total_count) print 'Balanced accuracy:', float(norm_diagonal_sum) / float(conf_matrix.shape[0]) avg_nodes['ISM'].append(ism_pruned.count_nodes()) print 'GENESIM' # train_gen = train.rename(columns={'Class': 'cat'}) start = time.time() genetic = genesim.genetic_algorithm(train, label_col, _constructors, seed=None, num_iterations=40, num_crossovers=15, population_size=250, val_fraction=0.4, prune=True, max_samples=3, tournament_size=15, nr_bootstraps=40) end = time.time() times['GENESIM'].append(end - start) predictions = genetic.evaluate_multiple(X_test).astype(int) conf_matrices['GENESIM'].append(confusion_matrix(y_test, predictions)) conf_matrix = confusion_matrix(y_test, predictions) print conf_matrix diagonal_sum = sum( [conf_matrix[i][i] for i in range(len(conf_matrix))]) norm_diagonal_sum = sum( [float(conf_matrix[i][i]) / float(sum(conf_matrix[i])) for i in range(len(conf_matrix))]) total_count = np.sum(conf_matrix) correct = 0 for i in range(len(conf_matrix)): correct += conf_matrix[i][i] + conf_matrix[i][max(i - 1, 0)] * ((i - 1) >= 0) + \ conf_matrix[i][min(i + 1, len(conf_matrix[i]) - 1)] * ((i + 1) <= len(conf_matrix[i]) - 1) # print 'Accuracy [-1, +1]:', float(correct) / float(total_count) print 'Accuracy:', float(diagonal_sum) / float(total_count) print 'Balanced accuracy:', float(norm_diagonal_sum) / float(conf_matrix.shape[0]) avg_nodes['GENESIM'].append(genetic.count_nodes()) print times print avg_nodes fig = plt.figure() fig.suptitle('Accuracy on ' + dataset['name'] + ' dataset using ' + str(NR_FOLDS) + ' folds', fontsize=20) counter = 0 conf_matrices_mean = {} for key in conf_matrices: conf_matrices_mean[key] = np.zeros(conf_matrices[key][0].shape) for i in range(len(conf_matrices[key])): conf_matrices_mean[key] = np.add(conf_matrices_mean[key], conf_matrices[key][i]) cm_normalized = np.around( conf_matrices_mean[key].astype('float') / conf_matrices_mean[key].sum(axis=1)[:, np.newaxis], 4) diagonal_sum = sum( [conf_matrices_mean[key][i][i] for i in range(len(conf_matrices_mean[key]))]) norm_diagonal_sum = sum( [conf_matrices_mean[key][i][i]/sum(conf_matrices_mean[key][i]) for i in range(len(conf_matrices_mean[key]))]) total_count = np.sum(conf_matrices_mean[key]) print key print conf_matrices_mean[key] correct = 0 for i in range(len(conf_matrices_mean[key])): correct += conf_matrices_mean[key][i][i] + conf_matrices_mean[key][i][max(i - 1, 0)] * ((i - 1) >= 0) + \ conf_matrices_mean[key][i][min(i + 1, len(conf_matrices_mean[key][i]) - 1)] * ((i + 1) <= len(conf_matrices_mean[key][i]) - 1) print 'Accuracy [-1, +1]:', float(correct) / float(total_count) print 'Accuracy:', float(diagonal_sum) / float(total_count) print 'Balanced accuracy:', float(norm_diagonal_sum) / conf_matrices_mean[key].shape[0] ax = fig.add_subplot(2, np.math.ceil(len(conf_matrices) / 2.0), counter + 1) cax = ax.matshow(cm_normalized, cmap=plt.cm.Blues, vmin=0.0, vmax=1.0) ax.set_title(key + '(' + str(sum(avg_nodes[key])/len(avg_nodes[key])) + ')', y=1.08) for (j, i), label in np.ndenumerate(cm_normalized): ax.text(i, j, label, ha='center', va='center') if counter == len(conf_matrices) - 1: fig.colorbar(cax, fraction=0.046, pad=0.04) counter += 1 F = plt.gcf() Size = F.get_size_inches() F.set_size_inches(Size[0] * 2, Size[1] * 1.75, forward=True) plt.show() rand_nr = str(int(10000*np.random.rand())) plt.savefig('output/' + dataset['name'] + '_CV'+str(NR_FOLDS)+'.png', bbox_inches='tight')
11,794
53.105505
153
py
GENESIM
GENESIM-master/decisiontree.py
""" Contains the decisiontree object used throughout this project. Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. """ from copy import deepcopy, copy import sklearn from graphviz import Source import matplotlib.pyplot as plt import numpy as np import json import operator from pandas import Series from sklearn.cross_validation import StratifiedKFold from sklearn.metrics import accuracy_score import constructors.ISM import constructors.ensemble class DecisionTree(object): """This class contains the main object used throughout this project: a decision tree. It contains methods to visualise and evaluate the trees.""" def __init__(self, right=None, left=None, label='', value=None, data=None, parent=None): """Create a node of a decision tree""" self.right = right '''right child, taken when a sample[`decisiontree.DecisionTree.label`] > `decisiontree.DecisionTree.value`''' self.left = left '''left child, taken when sample[`decisiontree.DecisionTree.label`] <= `decisiontree.DecisionTree.value`''' self.label = label '''string representation of the attribute the node splits on''' self.value = value '''the value where the node splits on (if `None`, then we're in a leaf)''' self.data = data '''dataframe of samples in the subtree''' self.parent = parent '''the parent of the node (used for pruning)''' self.class_probabilities = {} '''probability estimates for the leaves''' def evaluate(self, feature_vector): """Create a prediction for a sample (using its feature vector) **Params** ---------- - `feature_vector` (pandas Series or dict) - the sample to evaluate, must be a `pandas Series` object or a `dict`. It is important that the attribute keys in the sample are the same as the labels occuring in the tree. **Returns** ----------- the predicted class label """ if self.value is None: return self.label else: # feature_vector should only contain 1 row if feature_vector[self.label] <= self.value: return self.left.evaluate(feature_vector) else: return self.right.evaluate(feature_vector) def evaluate_multiple(self, feature_vectors): """Create a prediction for multiple samples by calling `decisiontree.DecisionTree.evaluate` **Params** ---------- - `feature_vectors` (pandas DataFrame or list of dict) - the samples to evaluate **Returns** ----------- a list of predicted class labels for each sample """ results = [] for _index, feature_vector in feature_vectors.iterrows(): results.append(self.evaluate(feature_vector)) return np.asarray(results) def plot_confusion_matrix(self, actual_labels, feature_vectors, normalized=False, plot=False): """Create a prediction for each of the samples and compare them to the actual labels by generating a confusion matrix **Params** ---------- - `actual_labels` (pandas Series or list) - the real class labels - `feature_vectors` (pandas DataFrame or list of dict) - the samples to evaluate - `normalized` (boolean) - if `True`, then generate a normalized confusion matrix - `plot` (boolean) - if `True`, then generate a plot. **Returns** ----------- the confusion matrix """ predicted_labels = self.evaluate_multiple(feature_vectors) confusion_matrix = sklearn.metrics.confusion_matrix(actual_labels, predicted_labels) if plot: confusion_matrix.plot(normalized=normalized) plt.show() return confusion_matrix def cost_complexity_pruning(self, feature_vectors, labels, tree_constructor, n_folds=3, cv=True, val_features=None, val_labels=None, ism_constructors=[], ism_calc_fracs=False, ism_nr_classifiers=3, ism_boosting=False): """Apply cost-complexity pruning ([\[1\]](http://mlwiki.org/index.php/Cost-Complexity_Pruning), [\[2\]](http://support.sas.com/documentation/cdl/en/stathpug/68163/HTML/default/viewer.htm#stathpug_hpsplit_details06.htm), [\[3\]](ftp://public.dhe.ibm.com/software/analytics/spss/support/Stats/Docs/Statistics/Algorithms/14.0/TREE-pruning.pdf)) to the tree **Params** ---------- - `feature_vectors` (pandas DataFrame or list of dict) - the training feature vectors for each sample - `labels` (pandas Series or list) - the training class labels for each sample - `tree_constructor` (boolean) - with which `constructors.treeconstructor.TreeConstructor` is the original decision tree made - `n_folds` (int) - if `cv` is `True`, this is the number of folds used to calculate the best alpha - `cv` (boolean) - if this is `True`, cross-validation will be applied to calculate the best alpha, else a validation set is used - `val_features` (pandas DataFrame or list of dict) - if `cv` is `False`, these are the validation feature vectors to calculate best alpha - `val_labels` (pandas Series or list) - if `cv` is `False`, these are the validation class labels to calculate best alpha - `ism_constructors` (list) - a list of constructors from which to construct the ensemble - `ism_calc_fracs` (boolean) - if `True`, then all probabilities are estimated by using the ensemble - `ism_nr_classifiers` (int) - how many times do we need to bag for each of the constructors? - `ism_boosting` (boolean) - only used when the model to prune is ISM. When this is `True`, boosting will be applied too to create an ensemble **Returns** ----------- a pruned decision tree """ self._set_parents() self.populate_samples(feature_vectors, labels.values) root_samples = sum(self.class_probabilities.values()) betas = [] subtrees = self._generate_subtree_sequence(root_samples) if len(subtrees) == 0: return self # Something went wrong, pruning failed if not cv: __min = (1, 99) best_tree = None for tree in subtrees: predictions = tree.evaluate_multiple(val_features).astype(int) err, nodes = 1 - accuracy_score(val_labels.values, predictions), tree.count_nodes() if (err, nodes) < __min: __min = (err, nodes) best_tree = tree return best_tree else: subtrees_by_alpha = {y:x for x,y in subtrees.iteritems()} subtrees_by_beta = {} alphas = sorted(subtrees.values()) for i in range(len(alphas)-1): beta = np.sqrt(alphas[i]*alphas[i+1]) betas.append(beta) subtrees_by_beta[beta] = subtrees_by_alpha[alphas[i]] beta_errors = {} for beta in betas: beta_errors[beta] = [] skf = StratifiedKFold(labels, n_folds=n_folds, shuffle=True) for train_index, test_index in skf: X_train = feature_vectors.iloc[train_index, :].reset_index(drop=True) y_train = labels.iloc[train_index].reset_index(drop=True) train = X_train.copy() train[y_train.name] = Series(y_train, index=train.index) X_test = feature_vectors.iloc[test_index, :].reset_index(drop=True) y_test = labels.iloc[test_index].reset_index(drop=True) if tree_constructor == 'ism': constructed_tree = constructors.ISM.ism(constructors.ensemble.bootstrap(train, y_train.name, ism_constructors, nr_classifiers=ism_nr_classifiers, boosting=ism_boosting), train, y_train.name, calc_fracs_from_ensemble=ism_calc_fracs) else: constructed_tree = tree_constructor.construct_classifier(train, X_train.columns, y_train.name) for beta in betas: tree_copy = deepcopy(constructed_tree) tree_copy.populate_samples(X_train, y_train.values) pruned_tree = tree_copy._minimize_cost_complexity(root_samples, beta) predictions = pruned_tree.evaluate_multiple(X_test).astype(int) beta_errors[beta].append(1 - accuracy_score(predictions, y_test)) for beta in beta_errors: beta_errors[beta] = np.mean(beta_errors[beta]) return subtrees_by_beta[min(beta_errors.iteritems(), key=operator.itemgetter(1))[0]] # <editor-fold desc="Visualisation and conversion methods"> def visualise(self, output_path, _view=True, show_probabilities=True): """Visualise the tree with [graphviz](http://www.graphviz.org/), using `decisiontree.DecisionTree.convert_to_dot` **Params** ---------- - `output_path` (string) - where the file needs to be saved - `show_probabilities` (boolean) - if this is `True`, probabilities will be displayed in the leafs too - `_view` (boolean) - open the pdf after generation or not **Returns** ----------- a pdf with the rendered dot code of the tree """ src = Source(self.convert_to_dot(show_probabilities=show_probabilities)) src.render(output_path, view=_view) def _get_number_of_subnodes(self, count=0): """Private method using in convert_node_to_dot, in order to give the right child of a node the right count :param count: intern parameter, don't set it :return: the number of subnodes of a specific node, not including himself """ if self.value is None: return count else: return self.left._get_number_of_subnodes(count=count + 1) + self.right._get_number_of_subnodes(count=count + 1) def convert_to_dot(self, show_probabilities=True): """Converts a decision tree object to DOT code **Params** ---------- - `show_probabilities` (boolean) - if this is `True`, probabilities will be displayed in the leafs too **Returns** ----------- a string with the dot code for the decision tree """ s = 'digraph DT{\n' s += 'node[fontname="Arial"];\n' s += self._convert_node_to_dot(show_probabilities=show_probabilities) s += '}' return s def _convert_node_to_dot(self, count=1, show_probabilities=True): """Convert node to dot format in order to visualize our tree using graphviz :param count: parameter used to give nodes unique names\ :param show_probabilities: if this is True, probabilities will be plotted in the leafs too :return: intermediate string of the tree in dot format, without preamble (this is no correct dot format yet!) """ if self.value is None: if len(self.class_probabilities) > 0 and show_probabilities: s = 'Node' + str(count) + ' [label="' + str(self.label) + '\n'+self.class_probabilities.__str__()+'" shape="box"];\n' else: s = 'Node' + str(count) + ' [label="' + str(self.label) + '" shape="box"];\n' else: if len(self.class_probabilities) > 0 and show_probabilities: s = 'Node' + str(count) + ' [label="' + str(self.label) + ' <= ' + str(self.value) + '\n'+self.class_probabilities.__str__() +'"];\n' else: s = 'Node' + str(count) + ' [label="' + str(self.label) + ' <= ' + str(self.value) + '"];\n' s += self.left._convert_node_to_dot(count=count + 1) s += 'Node' + str(count) + ' -> ' + 'Node' + str(count + 1) + ' [label="true"];\n' number_of_subnodes = self.left._get_number_of_subnodes() s += self.right._convert_node_to_dot(count=count + number_of_subnodes + 2) s += 'Node' + str(count) + '->' + 'Node' + str(count + number_of_subnodes + 2) + ' [label="false"];\n' return s def convert_to_string(self, tab=0): """Converts a decision tree object to a string representation **Params** ---------- - `tab` (int) - recursive parameter to tabulate the different levels of the tree **Returns** ----------- a string representation of the decision tree """ if self.value is None: print('\t' * tab + '[', self.label, ']') else: print('\t' * tab + self.label, ' <= ', str(self.value)) print('\t' * (tab + 1) + 'LEFT:') self.left.convert_to_string(tab=tab + 1) print('\t' * (tab + 1) + 'RIGHT:') self.right.convert_to_string(tab=tab + 1) def convert_to_json(self): """Converts a decision tree object to a JSON representation **Returns** ----------- a string with the JSON code for the decision tree """ json = "{\n" json += "\t\"name\": \"" + str(self.label) + " <= " + str(self.value) + "\",\n" json += "\t\"rule\": \"null\",\n" json += "\t\"children\": [\n" json += DecisionTree._convert_node_to_json(self.left, "True") + ",\n" json += DecisionTree._convert_node_to_json(self.right, "False") + "\n" json += "\t]\n" json += "}\n" return json @staticmethod def _convert_node_to_json(node, rule, count=2): json = "\t"*count + "{\n" if node.value is None: if len(node.class_probabilities) > 0: json += "\t"*count + "\"name\": \"" + str(node.label) + "( " + str(node.class_probabilities) + ")\",\n" else: json += "\t"*count + "\"name\": \"" + str(node.label) + " \",\n" json += "\t"*count + "\"rule\": \"" + rule + "\"\n" else: json += "\t"*count + "\"name\": \"" + str(node.label) + " <= " + str(node.value) + "\",\n" json += "\t"*count + "\"rule\": \"" + rule + "\",\n" json += "\t"*count + "\"children\": [\n" json += DecisionTree._convert_node_to_json(node.left, "True", count=count + 1) + ",\n" json += DecisionTree._convert_node_to_json(node.right, "False", count=count + 1) + "\n" json += "\t"*count + "]\n" json += "\t"*count + "}" return json @staticmethod def convert_from_json(json_file): """Converts a json file to a decision tree object **Params** ---------- - `json_file` (string) - the JSON file to convert **Returns** ----------- a decision tree object parsed from the JSON file """ tree_json = json.loads(json_file) tree = DecisionTree() split_name = tree_json['name'].split(" <= ") label, value = split_name[0], split_name[1] tree.label = label tree.value = value tree.left = DecisionTree._convert_json_to_node(tree_json['children'][0]) tree.right = DecisionTree._convert_json_to_node(tree_json['children'][1]) return tree @staticmethod def _convert_json_to_node(_dict): tree = DecisionTree() split_name = _dict['name'].split(" <= ") if len(split_name) > 1: label, value = split_name[0], split_name[1] tree.label = label tree.value = value if 'children' in _dict: tree.left = DecisionTree._convert_json_to_node(_dict['children'][0]) tree.right = DecisionTree._convert_json_to_node(_dict['children'][1]) else: tree.label = split_name[0] tree.value = None tree.left = None tree.right = None return tree # </editor-fold> # <editor-fold desc="Probability estimation methods"> @staticmethod def _init_tree(tree, labels): for label in np.unique(labels): tree.class_probabilities[str(int(label))] = 0.0 if tree.value is not None: DecisionTree._init_tree(tree.left, labels) DecisionTree._init_tree(tree.right, labels) def populate_samples(self, feature_vectors, labels): """Use the given data to calculate probability estimates at each leaf **Params** ---------- - `feature_vectors` (pandas DataFrame or list of dict) - the training feature vectors for each sample - `labels` (pandas Series or list) - the training class labels for each sample **Returns** ----------- nothing, the decision tree object where this method was called on will be changed """ index = 0 DecisionTree._init_tree(self, np.unique(labels)) for _index, feature_vector in feature_vectors.iterrows(): current_node = self while current_node.value is not None: current_node.class_probabilities[str(int(labels[index]))] += 1 if feature_vector[current_node.label] <= current_node.value: current_node = current_node.left else: current_node = current_node.right current_node.class_probabilities[str(int(labels[index]))] += 1 index += 1 return # </editor-fold> # <editor-fold desc="Pruning methods"> def _set_parents(self): if self.value is not None: self.left.parent = self self.left._set_parents() self.right.parent = self self.right._set_parents() def count_nodes(self): """Count the total number of nodes in the tree, used as metric for model complexity""" if self.value is None: return 1 else: left = 0 if self.left is not None: left = self.left.count_nodes() right = 0 if self.right is not None: right = self.right.count_nodes() return left + right + 1 def count_leaves(self): """Count the total number of leaves (`decisiontree.DecisionTree.value` = `None`) in the tree, used as metric for model complexity""" if self.value is None: return 1 else: return self.left.count_leaves() + self.right.count_leaves() def _get_leaves(self): if self.value is None: return [self] else: leaves=[] leaves.extend(self.left._get_leaves()) leaves.extend(self.right._get_leaves()) return leaves def _get_nodes(self): if self.value is not None: nodes = [self] else: nodes = [] if self.left is not None: nodes.extend(self.left._get_nodes()) if self.right is not None: nodes.extend(self.right._get_nodes()) return nodes def _calc_leaf_error(self, total_train_samples): return sum([(sum(leaf.class_probabilities.values()) / total_train_samples) * (1 - leaf.class_probabilities[str(leaf.label)]/sum(leaf.class_probabilities.values())) if sum(leaf.class_probabilities.values()) > 0 else 0 for leaf in self._get_leaves()]) def _calc_node_error(self, total_train_samples): return (1 - max(self.class_probabilities.iteritems(), key=operator.itemgetter(1))[1]/sum(self.class_probabilities.values())) \ * (sum(self.class_probabilities.values()) / total_train_samples) def _calculate_alpha(self, total_train_samples): if self.count_leaves() > 1: return (self._calc_node_error(total_train_samples) - self._calc_leaf_error(total_train_samples)) / (self.count_leaves() - 1) else: return (self._calc_node_error(total_train_samples) - self._calc_leaf_error(total_train_samples)) def _calculate_cost_complexity(self, total_train_samples, alpha): return self._calc_leaf_error(total_train_samples) + alpha * self.count_leaves() def _prune_node(self, node, parents=[], directions=[], nodes=[], direction='left'): if self == node: # print'match' self_copy = copy(self) self.label = max(self.class_probabilities.items(), key=operator.itemgetter(1))[0] self.value = None self.right = None self.left = None # return self_copy, parent, direction parents.append(self.parent) directions.append(direction) nodes.append(self_copy) else: if self.left is not None and self.left.value is not None: self.left._prune_node(node, parents, directions, nodes, 'left') if self.right is not None and self.right.value is not None: self.right._prune_node(node, parents, directions, nodes, 'right') def _generate_subtree(self, total_train_samples, alphas={}): # print self.label, self.value if self.value is not None: calc_alpha = self._calculate_alpha(total_train_samples) alphas[self] = (calc_alpha, self.count_nodes()) if self.left.value is not None: self.left._generate_subtree(total_train_samples, alphas) if self.right.value is not None: self.right._generate_subtree(total_train_samples, alphas) return alphas def _generate_subtree_sequence(self, total_train_samples): subtrees = {} current_tree = deepcopy(self) while current_tree.left is not None or current_tree.right is not None: generated_trees = current_tree._generate_subtree(total_train_samples, {}) # print generated_trees.values() best = min(generated_trees.items(), key=operator.itemgetter(1)) tree, alpha = best[0], best[1][0] current_tree._prune_node(tree) subtrees[deepcopy(current_tree)] = alpha return subtrees def _minimize_cost_complexity(self, total_train_samples, alpha): while 1: min_complexity, min_nodes = self._calculate_cost_complexity(total_train_samples, alpha), self.count_nodes() # print 'Can we improve?', (min_complexity, min_nodes) best_node_to_prune = None for node in self._get_nodes(): # Make a copy of the node label_copy = node.label value_copy = node.value right_copy = node.right left_copy = node.left # Prune the node node.label = max(node.class_probabilities.items(), key=operator.itemgetter(1))[0] node.value = None node.right = None node.left = None # Calculate hypothetical cost complexity complexity, nodes = self._calculate_cost_complexity(total_train_samples, alpha), self.count_nodes() # Restore the node node.label = label_copy node.value = value_copy node.left = left_copy node.right = right_copy # We found a new best node? if (complexity, nodes) <= (min_complexity, min_nodes): best_node_to_prune = node min_complexity = complexity min_nodes = nodes # Did we find a better node? if best_node_to_prune is not None: # print 'best_node:', best_node_to_prune.label, best_node_to_prune.value, min_complexity best_node_to_prune.label = max(best_node_to_prune.class_probabilities.items(), key=operator.itemgetter(1))[0] best_node_to_prune.value = None best_node_to_prune.right = None best_node_to_prune.left = None else: # print 'No new best node found' return self # </editor-fold> def _code_folding_does_not_work_in_pycharm_without_a_final_stub_method_here(self): pass
24,478
42.02109
152
py
GENESIM
GENESIM-master/RFTest.py
from sklearn.cross_validation import StratifiedKFold from sklearn.metrics import confusion_matrix from constructors.ensemble import RFClassification from data.load_all_datasets import load_all_datasets import numpy as np from decisiontree import DecisionTree from refined_rf import RefinedRandomForest rf = RFClassification() NR_FOLDS = 5 def _convert_to_tree(dt, features): """Convert a sklearn object to a `decisiontree.decisiontree` object""" n_nodes = dt.tree_.node_count children_left = dt.tree_.children_left children_right = dt.tree_.children_right feature = dt.tree_.feature threshold = dt.tree_.threshold classes = dt.classes_ # The tree structure can be traversed to compute various properties such # as the depth of each node and whether or not it is a leaf. node_depth = np.zeros(shape=n_nodes) decision_trees = [None] * n_nodes for i in range(n_nodes): decision_trees[i] = DecisionTree() is_leaves = np.zeros(shape=n_nodes, dtype=bool) stack = [(0, -1)] # seed is the root node id and its parent depth while len(stack) > 0: node_id, parent_depth = stack.pop() node_depth[node_id] = parent_depth + 1 # If we have a test node if children_left[node_id] != children_right[node_id]: stack.append((children_left[node_id], parent_depth + 1)) stack.append((children_right[node_id], parent_depth + 1)) else: is_leaves[node_id] = True for i in range(n_nodes): if children_left[i] > 0: decision_trees[i].left = decision_trees[children_left[i]] if children_right[i] > 0: decision_trees[i].right = decision_trees[children_right[i]] if is_leaves[i]: decision_trees[i].label = dt.classes_[np.argmax(dt.tree_.value[i][0])] decision_trees[i].value = None else: decision_trees[i].label = features[feature[i]] decision_trees[i].value = threshold[i] return decision_trees[0] for dataset in load_all_datasets(): df = dataset['dataframe'] label_col = dataset['label_col'] feature_cols = dataset['feature_cols'] skf = StratifiedKFold(df[label_col], n_folds=NR_FOLDS, shuffle=True, random_state=1337) for fold, (train_idx, test_idx) in enumerate(skf): print 'Fold', fold+1, '/', NR_FOLDS, 'for dataset', dataset['name'] train = df.iloc[train_idx, :].reset_index(drop=True) X_train = train.drop(label_col, axis=1) y_train = train[label_col] test = df.iloc[test_idx, :].reset_index(drop=True) X_test = test.drop(label_col, axis=1) y_test = test[label_col] rf.construct_classifier(train, feature_cols, label_col) for estimator in rf.clf.estimators_: print estimator.tree_ print _convert_to_tree(estimator, feature_cols) predictions = rf.evaluate_multiple(X_test).astype(int) conf_matrix = confusion_matrix(y_test, predictions) print conf_matrix diagonal_sum = sum( [conf_matrix[i][i] for i in range(len(conf_matrix))]) norm_diagonal_sum = sum( [float(conf_matrix[i][i]) / float(sum(conf_matrix[i])) for i in range(len(conf_matrix))]) total_count = np.sum(conf_matrix) print 'Accuracy:', float(diagonal_sum) / float(total_count) print 'Balanced accuracy:', float(norm_diagonal_sum) / float(conf_matrix.shape[0])
3,492
35.385417
91
py
GENESIM
GENESIM-master/__init__.py
0
0
0
py
GENESIM
GENESIM-master/constructors/genesim.py
""" Contains the code for the innovative algorithm called GENESIM Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. """ import copy import multiprocessing from collections import Counter from pandas import DataFrame, concat import numpy as np import time import sys from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.metrics import accuracy_score from constructors.ensemble import bootstrap, RFClassification, XGBClassification from decisiontree import DecisionTree import os class LineSegment(object): """ Auxiliary class, used for the intersection algorithm. A region is composed of multiple lines (one for each dimension) """ def __init__(self, lower_bound, upper_bound, region_index): self.lower_bound = lower_bound '''The lower bound of the line segment''' self.upper_bound = upper_bound '''The upper bound of the line segment''' self.region_index = region_index '''To which region does this line segment belong to''' class GENESIM(object): def _decision_tree_to_decision_table(self, tree, feature_vectors): """ Convert each path from the root to a leaf into a region, store it into a table :param tree: the constructed tree :param feature_vectors: the feature vectors of all samples :return: a set of regions in a k-dimensional space (k=|feature_vector|), corresponding to the decision tree """ # Initialize an empty region (will be passed on recursively) region = {} for column in feature_vectors.columns: region[column] = [float("-inf"), float("inf")] region["class"] = None regions = self._tree_to_decision_table(tree, region, []) return regions def _tree_to_decision_table(self, tree, region, regions): """ Recursive method used to convert the decision tree to a decision_table (do not call this one!) """ left_region = copy.deepcopy(region) # Take a deepcopy or we're fucked right_region = copy.deepcopy(region) # Take a deepcopy or we're fucked left_region[tree.label][1] = tree.value right_region[tree.label][0] = tree.value if tree.left.value is None: if tree.left.class_probabilities is not None: left_region["class"] = tree.left.class_probabilities else: left_region["class"] = {tree.left.label: 1.0} regions.append(left_region) else: self._tree_to_decision_table(tree.left, left_region, regions) if tree.right.value is None: if tree.right.class_probabilities is not None: right_region["class"] = tree.right.class_probabilities else: left_region["class"] = {tree.left.label: 1.0} regions.append(right_region) else: self._tree_to_decision_table(tree.right, right_region, regions) return regions def _find_lines(self, regions, features, feature_mins, feature_maxs): if len(regions) <= 0: return {} for region in regions: for feature in features: if region[feature][0] == float("-inf"): region[feature][0] = feature_mins[feature] if region[feature][1] == float("inf"): region[feature][1] = feature_maxs[feature] lines = {} # First convert the region information into dataframes columns = [] for feature in features: columns.append(feature+'_lb') columns.append(feature+'_ub') columns.append('class') regions_df = DataFrame(columns=columns) for region in regions: entry = [] for feature in features: entry.append(region[feature][0]) entry.append(region[feature][1]) entry.append(region['class']) regions_df.loc[len(regions_df)] = entry for feature in features: other_features = list(set(features) - set([feature])) lb_bool_serie = [True]*len(regions_df) ub_bool_serie = [True]*len(regions_df) for other_feature in other_features: lb_bool_serie &= (regions_df[other_feature+'_lb'] == feature_mins[other_feature]).values ub_bool_serie &= (regions_df[other_feature+'_ub'] == feature_maxs[other_feature]).values lower_upper_regions = concat([regions_df[lb_bool_serie], regions_df[ub_bool_serie]]) lines[feature] = [] for value in np.unique(lower_upper_regions[lower_upper_regions.duplicated(feature+'_lb', False)][feature+'_lb']): if feature_mins[feature] != value and feature_maxs[feature] != value: lines[feature].append(value) return lines def _regions_to_tree_improved(self, features_df, labels_df, regions, features, feature_mins, feature_maxs, max_samples=1): lines = self._find_lines(regions, features, feature_mins, feature_maxs) lines_keys = [key for key in lines.keys() if len(lines[key]) > 0] if lines is None or len(lines) <= 0 or len(lines_keys) <= 0: return DecisionTree(label=str(np.argmax(np.bincount(labels_df[labels_df.columns[0]].values.astype(int)))), value=None, data=features_df) random_label = np.random.choice(lines_keys) random_value = np.random.choice(lines[random_label]) data = DataFrame(features_df) data[labels_df.columns[0]] = labels_df best_split_node = DecisionTree(data=data, label=random_label, value=random_value, left=DecisionTree(data=data[data[random_label] <= random_value]), right=DecisionTree(data=data[data[random_label] > random_value])) node = DecisionTree(label=best_split_node.label, value=best_split_node.value, data=best_split_node.data) feature_mins_right = feature_mins.copy() feature_mins_right[node.label] = node.value feature_maxs_left = feature_maxs.copy() feature_maxs_left[node.label] = node.value regions_left = [] regions_right = [] for region in regions: if region[best_split_node.label][0] < best_split_node.value: regions_left.append(region) else: regions_right.append(region) if len(best_split_node.left.data) >= max_samples and len(best_split_node.right.data) >= max_samples: node.left = self._regions_to_tree_improved(best_split_node.left.data.drop(labels_df.columns[0], axis=1), best_split_node.left.data[[labels_df.columns[0]]], regions_left, features, feature_mins, feature_maxs_left) node.right = self._regions_to_tree_improved(best_split_node.right.data.drop(labels_df.columns[0], axis=1), best_split_node.right.data[[labels_df.columns[0]]], regions_right, features, feature_mins_right, feature_maxs) else: node.label = str(np.argmax(np.bincount(labels_df[labels_df.columns[0]].values.astype(int)))) node.value = None return node def _intersect(self, line1_lb, line1_ub, line2_lb, line2_ub): if line1_ub <= line2_lb: return False if line1_lb >= line2_ub: return False return True def _calculate_intersection(self, regions1, regions2, features, feature_maxs, feature_mins): """ Fancy method to calculate intersections. O(d*n*log(n)) instead of O(d*n^2) Instead of brute force, we iterate over each possible dimension, we project each region to that one dimension, creating a line segment. We then construct a set S_i for each dimension containing pairs of line segments that intersect in dimension i. In the end, the intersection of all these sets results in the intersecting regions. For all these intersection regions, their intersecting region is calculated and added to a new set, which is returned in the end :param regions1: first set of regions :param regions2: second set of regions :param features: list of dimension names :return: new set of regions, which are the intersections of the regions in 1 and 2 """ # print "Merging ", len(regions1), " with ", len(regions2), " regions." S_intersections = [None] * len(features) for i in range(len(features)): # Create B1 and B2: 2 arrays of line segments box_set1 = [] for region_index in range(len(regions1)): box_set1.append(LineSegment(regions1[region_index][features[i]][0], regions1[region_index][features[i]][1], region_index)) box_set2 = [] for region_index in range(len(regions2)): box_set2.append(LineSegment(regions2[region_index][features[i]][0], regions2[region_index][features[i]][1], region_index)) # Sort the two boxsets by their lower bound box_set1 = sorted(box_set1, key=lambda segment: segment.lower_bound) box_set2 = sorted(box_set2, key=lambda segment: segment.lower_bound) # Create a list of unique lower bounds, we iterate over these bounds later unique_lower_bounds = [] for j in range(max(len(box_set1), len(box_set2))): if j < len(box_set1) and box_set1[j].lower_bound not in unique_lower_bounds: unique_lower_bounds.append(box_set1[j].lower_bound) if j < len(box_set2) and box_set2[j].lower_bound not in unique_lower_bounds: unique_lower_bounds.append(box_set2[j].lower_bound) # Sort them unique_lower_bounds = sorted(unique_lower_bounds) box1_active_set = [] box2_active_set = [] intersections = [] for lower_bound in unique_lower_bounds: # Update all active sets, a region is added when it's lower bound is lower than the current one # It is removed when its upper bound is higher than the current lower bound for j in range(len(box_set1)): if box_set1[j].upper_bound <= lower_bound: if box_set1[j] in box1_active_set: box1_active_set.remove(box_set1[j]) elif box_set1[j].lower_bound <= lower_bound: if box_set1[j] not in box1_active_set: box1_active_set.append(box_set1[j]) else: break for j in range(len(box_set2)): if box_set2[j].upper_bound <= lower_bound: if box_set2[j] in box2_active_set: box2_active_set.remove(box_set2[j]) elif box_set2[j].lower_bound <= lower_bound: if box_set2[j] not in box2_active_set: box2_active_set.append(box_set2[j]) else: break # All regions from the active set of B1 intersect with the regions in the active set of B2 for segment1 in box1_active_set: for segment2 in box2_active_set: intersections.append((segment1.region_index, segment2.region_index)) S_intersections[i] = intersections # The intersection of all these S_i's are the intersecting regions intersection_regions_indices = S_intersections[0] for k in range(1, len(S_intersections)): intersection_regions_indices = self._tuple_list_intersections(intersection_regions_indices, S_intersections[k]) # Create a new set of regions intersected_regions = [] for intersection_region_pair in intersection_regions_indices: region = {} for feature in features: region[feature] = [max(regions1[intersection_region_pair[0]][feature][0], regions2[intersection_region_pair[1]][feature][0]), min(regions1[intersection_region_pair[0]][feature][1], regions2[intersection_region_pair[1]][feature][1])] # Convert all -inf and inf to the mins and max from those features if region[feature][0] == float("-inf"): region[feature][0] = feature_mins[feature] if region[feature][1] == float("inf"): region[feature][1] = feature_maxs[feature] region['class'] = {} for key in set(set(regions1[intersection_region_pair[0]]['class'].iterkeys()) | set(regions2[intersection_region_pair[1]]['class'].iterkeys())): prob_1 = (regions1[intersection_region_pair[0]]['class'][key] if key in regions1[intersection_region_pair[0]]['class'] else 0) prob_2 = (regions2[intersection_region_pair[1]]['class'][key] if key in regions2[intersection_region_pair[1]]['class'] else 0) if prob_1 and prob_2: region['class'][key] = (regions1[intersection_region_pair[0]]['class'][key] + regions2[intersection_region_pair[1]]['class'][key]) / 2 else: if prob_1: region['class'][key] = prob_1 else: region['class'][key] = prob_2 intersected_regions.append(region) return intersected_regions def _tuple_list_intersections(self, list1, list2): # Make sure the length of list1 is larger than the length of list2 if len(list2) > len(list1): return self._tuple_list_intersections(list2, list1) else: list1 = set(list1) list2 = set(list2) intersections = [] for tuple in list2: if tuple in list1: intersections.append(tuple) return intersections def _fitness(self, tree, test_features_df, test_labels_df, cat_name, alpha=1, beta=0): return alpha*(1-accuracy_score(test_labels_df[cat_name].values.astype(int), tree.evaluate_multiple(test_features_df).astype(int))) + beta*tree.count_nodes() def _mutate_shift_random(self, tree, feature_vectors, labels): # tree.visualise('beforeMutationShift') internal_nodes = list(set(tree._get_nodes()) - set(tree._get_leaves())) tree = copy.deepcopy(tree) # print 'nr internal nodes =', len(internal_nodes) if len(internal_nodes) > 1: random_node = np.random.choice(internal_nodes) random_value = np.random.choice(np.unique(feature_vectors[random_node.label].values)) random_node.value = random_value tree.populate_samples(feature_vectors, labels) # tree.visualise('afterMutationShift') # raw_input() return tree def _mutate_swap_subtrees(self, tree, feature_vectors, labels): # tree.visualise('beforeMutationSwap') tree = copy.deepcopy(tree) tree._set_parents() nodes = tree._get_nodes() if len(nodes) > 1: node1 = np.random.choice(nodes) node2 = np.random.choice(nodes) parent1 = node1.parent parent2 = node2.parent if parent1 is not None and parent2 is not None: # We don't want the root node if parent1.left == node1: parent1.left = node2 else: parent1.right = node2 if parent2.left == node2: parent2.left = node1 else: parent2.right = node1 tree.populate_samples(feature_vectors, labels) return tree def _tournament_selection_and_merging(self, trees, train_features_df, train_labels_df, test_features_df, test_labels_df, cat_name, feature_cols, feature_maxs, feature_mins, max_samples, return_dict, seed, tournament_size=3): np.random.seed(seed) _tournament_size = min(len(trees) / 2, tournament_size) trees = copy.deepcopy(trees) best_fitness_1 = sys.float_info.max best_tree_1 = None for i in range(_tournament_size): tree = np.random.choice(trees) trees.remove(tree) fitness = self._fitness(tree, test_features_df, test_labels_df, cat_name) if tree is not None and tree.count_nodes() > 1 and fitness < best_fitness_1: best_fitness_1 = fitness best_tree_1 = tree best_fitness_2 = sys.float_info.max best_tree_2 = None for i in range(_tournament_size): tree = np.random.choice(trees) trees.remove(tree) fitness = self._fitness(tree, test_features_df, test_labels_df, cat_name) if tree is not None and tree.count_nodes() > 1 and fitness < best_fitness_2: best_fitness_2 = fitness best_tree_2 = tree if best_tree_1 is not None and best_tree_2 is not None: region1 = self._decision_tree_to_decision_table(best_tree_1, train_features_df) region2 = self._decision_tree_to_decision_table(best_tree_2, train_features_df) merged_regions = self._calculate_intersection(region1, region2, feature_cols, feature_maxs, feature_mins) return_dict[seed] = self._regions_to_tree_improved(train_features_df, train_labels_df, merged_regions, feature_cols, feature_mins, feature_maxs, max_samples=max_samples) return return_dict[seed] else: return_dict[seed] = None return None def _convert_sklearn_to_tree(self, dt, features): """Convert a sklearn object to a `decisiontree.decisiontree` object""" n_nodes = dt.tree_.node_count children_left = dt.tree_.children_left children_right = dt.tree_.children_right feature = dt.tree_.feature threshold = dt.tree_.threshold classes = dt.classes_ # The tree structure can be traversed to compute various properties such # as the depth of each node and whether or not it is a leaf. node_depth = np.zeros(shape=n_nodes) decision_trees = [None] * n_nodes for i in range(n_nodes): decision_trees[i] = DecisionTree() is_leaves = np.zeros(shape=n_nodes, dtype=bool) stack = [(0, -1)] # seed is the root node id and its parent depth while len(stack) > 0: node_id, parent_depth = stack.pop() node_depth[node_id] = parent_depth + 1 # If we have a test node if children_left[node_id] != children_right[node_id]: stack.append((children_left[node_id], parent_depth + 1)) stack.append((children_right[node_id], parent_depth + 1)) else: is_leaves[node_id] = True for i in range(n_nodes): if children_left[i] > 0: decision_trees[i].left = decision_trees[children_left[i]] if children_right[i] > 0: decision_trees[i].right = decision_trees[children_right[i]] if is_leaves[i]: decision_trees[i].label = dt.classes_[np.argmax(dt.tree_.value[i][0])] decision_trees[i].value = None else: decision_trees[i].label = features[feature[i]] decision_trees[i].value = threshold[i] return decision_trees[0] def parse_xgb_tree_string(self, tree_string, training_data, feature_cols, label_col, the_class): # Get class distribution _classes = np.unique(training_data[label_col].values) class_distributions = {} for _class in _classes: data = training_data[training_data[label_col] != _class] class_counts = Counter(data[label_col].values) total = sum(class_counts.values(), 0.0) for key in class_counts: class_counts[key] /= total class_distributions[_class] = class_counts # Get the unique values per feature unique_values_per_feature = {} for feature_col in feature_cols: # Just use a simple sorted list of np.unique (faster than SortedList or a set to get index of elements after testing) unique_values_per_feature[feature_col] = sorted(np.unique(training_data[feature_col].values)) return self.parse_xgb_tree(tree_string, _class=the_class, class_distributions=class_distributions, unique_values_per_feature=unique_values_per_feature, n_samples=len(training_data)) def get_closest_value(self, x, values): for i in range(len(values) - 1): if values[i + 1] > x: return float(values[i]) return x def parse_xgb_tree(self, tree_string, _class=0, class_distributions={}, unique_values_per_feature={}, n_samples=0): # There is some magic involved! The leaf values need to be converted to class distributions somehow! # For binary classification problems: convert to probability by calculating 1/(1+exp(-value)) # For multi_class: the tree_string contains n_estimators * n_classes decision trees # WARNING: Classes are sorted according to output of np.unique # Ordered as follows [tree_1-class_1, ..., tree_1-class_k, tree_2-class_1, ....] # The problem is: tree_i is different for each class... # One possibility is to assign the probability to that class by calculating logistic function # And dividing the rest of the probability (sum to 1) according to the distribution of the remaining classes # Next problem is: everything is expressed as "feature < threshold" instead "feature <= threshold" # Solution is: take the infimum of those feature values decision_trees = {} # Binary classification binary_classification = len(class_distributions.keys()) == 2 for line in tree_string.split('\n'): if line != '': _id, rest = line.split(':') _id = _id.lstrip() if rest[:4] != 'leaf': feature = rest.split('<')[0][1:] highest_lower_threshold = self.get_closest_value(float(rest.split('<')[1].split(']')[0]), unique_values_per_feature[feature]) decision_trees[_id] = DecisionTree(right=None, left=None, label=feature, value=highest_lower_threshold, parent=None) else: leaf_value = float(rest.split('=')[1]) if binary_classification: probability = 1 / (1 + np.exp(leaf_value)) other_class = class_distributions[_class].keys()[0] class_probs = {_class: int(n_samples * probability), other_class: int(n_samples * (1 - probability))} if probability > 0.5: most_probable_class = _class else: most_probable_class = other_class else: probability = 1 / (1 + np.exp(-leaf_value)) class_probs = {} remainder_samples = int(n_samples - probability * n_samples) class_probs[_class] = int(probability * n_samples) most_probable_class, most_samples = _class, class_probs[_class] for other_class in class_distributions[_class]: amount_samples = int(remainder_samples * class_distributions[_class][other_class]) class_probs[other_class] = amount_samples if amount_samples > most_samples: most_probable_class = other_class most_samples = amount_samples decision_trees[_id] = DecisionTree(right=None, left=None, label=most_probable_class, value=None, parent=None) decision_trees[_id].class_probabilities = class_probs # Make another pass to link the different decision trees together for line in tree_string.split('\n'): if line != '': _id, rest = line.split(':') _id = _id.lstrip() tree = decision_trees[_id] if rest[:4] != 'leaf': rest = rest.split(']')[1].lstrip() links = rest.split(',') for link in links: word, link_id = link.split('=') if word == 'yes' or word == 'missing': tree.left = decision_trees[link_id] else: tree.right = decision_trees[link_id] return decision_trees['0'] def genetic_algorithm(self, data, label_col, tree_constructors, population_size=15, num_crossovers=3, val_fraction=0.25, num_iterations=5, seed=1337, tournament_size=3, prune=False, max_samples=3, nr_bootstraps=5, mutation_prob=0.25, tree_path='trees'): """ Construct an ensemble using different induction algorithms, combined with bagging and bootstrapping and convert it to a single, interpretable model **Params** ---------- - `data` (pandas DataFrame) - a `Dataframe` containing all the training data - `label_col` (string) - the name of the class label column - `tree_constructors` (list) - which induction algorithms must be used to create an ensemble with. Must be of type `constructors.treeconstructor.TreeConstructor` - `population_size` (int) - the maximum size of the population, the least fittest ones get discarded - `num_crossovers` (int) - how many pairs of decision trees get merged in each iteration - `val_fraction` (int) - how much percent of the data will be used as validation set to calculate fitness with - `num_iterations` (int) - how many iterations does the algorithm need to run - `seed` (int) - a seed for reproducible results - `prune` (boolean) - if `True`, then prune each obtained tree by using the validation set - `max_samples` (int) - pre-prune condition when converting a region back to a tree - `nr_bootstraps` (int) - how many bootstraps are used to created the ensemble with? - `mutation_prob` (float) - how much percent chance does an individual have to mutate each iteration **Returns** ----------- a DecisionTree object """ if not os.path.exists(tree_path): os.makedirs(tree_path) np.random.seed(seed) feature_mins = {} feature_maxs = {} feature_column_names = list(set(data.columns) - set([label_col])) for feature in feature_column_names: feature_mins[feature] = np.min(data[feature]) feature_maxs[feature] = np.max(data[feature]) labels_df = DataFrame() labels_df[label_col] = data[label_col].copy() features_df = data.copy() features_df = features_df.drop(label_col, axis=1) data = features_df.copy() data[label_col] = labels_df[label_col] sss = StratifiedShuffleSplit(labels_df[label_col], 1, test_size=val_fraction, random_state=seed) for train_index, test_index in sss: train_features_df, test_features_df = features_df.iloc[train_index, :].copy(), features_df.iloc[test_index, :].copy() train_labels_df, test_labels_df = labels_df.iloc[train_index, :].copy(), labels_df.iloc[test_index, :].copy() train_features_df = train_features_df.reset_index(drop=True) test_features_df = test_features_df.reset_index(drop=True) train_labels_df = train_labels_df.reset_index(drop=True) test_labels_df = test_labels_df.reset_index(drop=True) train = data.iloc[train_index, :].copy().reset_index(drop=True) tree_list = bootstrap(train, label_col, tree_constructors, boosting=True, nr_classifiers=nr_bootstraps) for constructor in tree_constructors: tree = constructor.construct_classifier(train, train_features_df.columns, label_col) tree.populate_samples(train_features_df, train_labels_df[label_col].values) tree_list.append(tree) # Adding the random forest trees to the population rf = RFClassification() xgb = XGBClassification() feature_cols = list(train_features_df.columns) rf.construct_classifier(train, feature_cols, label_col) xgb_model = xgb.construct_classifier(train, feature_cols, label_col) # print 'Random forest number of estimators:', len(rf.clf.estimators_) for i, estimator in enumerate(rf.clf.estimators_): tree = self._convert_sklearn_to_tree(estimator, feature_cols) # print tree.get_binary_vector(train_features_df.iloc[0]) tree.populate_samples(train_features_df, train_labels_df[label_col].values) predicted_labels = tree.evaluate_multiple(test_features_df).astype(int) # accuracy = accuracy_score(test_labels_df[label_col].values.astype(str), predicted_labels.astype(str)) # print 'RF tree', i, '/', len(rf.clf.estimators_), ':', accuracy tree_list.append(tree) n_classes = len(np.unique(train[label_col].values)) if n_classes > 2: for idx, tree_string in enumerate(xgb_model.clf._Booster.get_dump()): tree = self.parse_xgb_tree_string(tree_string, train, feature_cols, label_col, np.unique(train[label_col].values)[idx % n_classes]) tree_list.append(tree) else: for tree_string in xgb_model.clf._Booster.get_dump(): tree = self.parse_xgb_tree_string(tree_string, train, feature_cols, label_col, 0) tree_list.append(tree) tree_list = [tree for tree in tree_list if tree is not None ] start = time.clock() for k in range(num_iterations): # print "Calculating accuracy and sorting" tree_accuracy = [] for tree in tree_list: predicted_labels = tree.evaluate_multiple(test_features_df) accuracy = accuracy_score(test_labels_df[label_col].values.astype(int), predicted_labels.astype(int)) tree_accuracy.append((tree, accuracy, tree.count_nodes())) tree_list = [x[0] for x in sorted(tree_accuracy, key=lambda x: (-x[1], x[2]))[:min(len(tree_list), population_size)]] best_tree = tree_list[0] with open(tree_path+os.sep+'it_'+str(k)+'.tree', 'w+') as fp: fp.write(best_tree.convert_to_json()) # print("----> Best tree till now: ", [(x[1], x[2]) for x in sorted(tree_accuracy, key=lambda x: (-x[1], x[2]))[:min(len(tree_list), population_size)]]) # Crossovers #mngr = multiprocessing.Manager() #return_dict = mngr.dict() #jobs = [] for i in range(num_crossovers): # p = multiprocessing.Process(target=self._tournament_selection_and_merging, args=[tree_list, train_features_df, train_labels_df, # test_features_df, test_labels_df, label_col, # feature_column_names, feature_maxs, feature_mins, # max_samples, return_dict, k * i + i, tournament_size]) # jobs.append(p) # p.start() # for proc in jobs: # proc.join() new_tree = self._tournament_selection_and_merging(tree_list, train_features_df, train_labels_df, test_features_df, test_labels_df, label_col, feature_column_names, feature_maxs, feature_mins, max_samples, {}, k*i+i, tournament_size) # for new_tree in return_dict.values(): if new_tree is not None: # print 'new tree added', accuracy_score(test_labels_df[label_col].values.astype(int), new_tree.evaluate_multiple(test_features_df).astype(int)) tree_list.append(new_tree) if prune: # print 'Pruning the tree...', new_tree.count_nodes() new_tree = new_tree.cost_complexity_pruning(train_features_df, train_labels_df[label_col], None, cv=False, val_features=test_features_df, val_labels=test_labels_df[label_col]) # print 'Done', new_tree.count_nodes(), accuracy_score(test_labels_df[label_col].values.astype(int), new_tree.evaluate_multiple(test_features_df).astype(int)) tree_list.append(new_tree) # Mutation phase for tree in tree_list: value = np.random.rand() if value < mutation_prob: new_tree1 = self._mutate_shift_random(tree, train_features_df, train_labels_df[label_col].values) # print 'new mutation added', accuracy_score(test_labels_df[label_col].values.astype(int), #new_tree1.evaluate_multiple(test_features_df).astype(int)) new_tree2 = self._mutate_swap_subtrees(tree, train_features_df, train_labels_df[label_col].values) # print 'new mutation added', accuracy_score(test_labels_df[label_col].values.astype(int), #new_tree2.evaluate_multiple(test_features_df).astype(int)) tree_list.append(new_tree1) tree_list.append(new_tree2) end = time.clock() print "Took ", (end - start), " seconds" start = end tree_accuracy = [] for tree in tree_list: predicted_labels = tree.evaluate_multiple(test_features_df) accuracy = accuracy_score(test_labels_df[label_col].values.astype(int), predicted_labels.astype(int)) tree_accuracy.append((tree, accuracy, tree.count_nodes())) # print [x for x in sorted(tree_accuracy, key=lambda x: (-x[1], x[2]))[:min(len(tree_list), population_size)]] best_tree = sorted(tree_accuracy, key=lambda x: (-x[1], x[2]))[0][0] return best_tree
36,137
49.542657
182
py
GENESIM
GENESIM-master/constructors/inTrees.py
""" inTrees / STEL -------------- Merges different decision trees in an ensemble together in an ordered rule list Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. Reference: Houtao Deng "Interpreting Tree Ensembles with inTrees" """ import sys import re import numpy as np import pandas as pd import rpy2 from rpy2.robjects import pandas2ri pandas2ri.activate() import rpy2.robjects as ro from rpy2.robjects.packages import importr from constructors import ensemble sys.path.append('../') def convert_to_r_posixct(obj): """ Convert DatetimeIndex or np.datetime array to R POSIXct using m8[s] format. Parameters ---------- obj : source pandas object (one of [DatetimeIndex, np.datetime]) Returns ------- An R POSIXct vector (rpy2.robjects.vectors.POSIXct) """ import time from rpy2.rinterface import StrSexpVector # convert m8[ns] to m8[s] vals = robj.vectors.FloatSexpVector(obj.values.view('i8') / 1E9) as_posixct = robj.baseenv.get('as.POSIXct') origin = StrSexpVector([time.strftime("%Y-%m-%d", time.gmtime(0)), ]) # We will be sending ints as UTC tz = obj.tz.zone if hasattr( obj, 'tz') and hasattr(obj.tz, 'zone') else 'UTC' tz = StrSexpVector([tz]) utc_tz = StrSexpVector(['UTC']) posixct = as_posixct(vals, origin=origin, tz=utc_tz) posixct.do_slot_assign('tzone', tz) return posixct class Condition: """ Class which represents one part of the rule (which can be seen as a conjunction of conditions) """ def __init__(self, feature, test, value): self.feature = feature '''The feature on which the test is performed''' self.test = test '''What kind of test is done. Must be either `==`, `>` or `<=`''' self.value = value '''The threshold value''' def evaluate(self, feature_vector): """Create a prediction for a sample (using its feature vector) **Params** ---------- - `feature_vector` (pandas Series or dict) - the sample to evaluate, must be a `pandas Series` object or a `dict`. It is important that the attribute keys in the sample are the same as the labels occuring in the rules. **Returns** ----------- `True` if feature_vector[<feature>] <test> <value>, where <test> is equal to `==`, `>` or `<=` """ if self.value is None: return True elif self.test == '==': return feature_vector[self.feature] == self.value elif self.test == '>': return feature_vector[self.feature] > self.value else: return feature_vector[self.feature] <= self.value class Rule: """ Class which represents a rule, which is a conjunction of conditions """ def __init__(self, index, conditions, prediction): self.index = index '''The index of this rule in a rule list (which is traversed sequentially until a match is found).''' self.rules = conditions '''A list of `constructors.inTrees.Condition`''' self.prediction = prediction '''This is returned when a sample fully complies to the rule (`True` for all conditions)''' def evaluate(self, feature_vector): """Create a prediction for a sample (using its feature vector) **Params** ---------- - `feature_vector` (pandas Series or dict) - the sample to evaluate, must be a `pandas Series` object or a `dict`. It is important that the attribute keys in the sample are the same as the labels occuring in the rules. **Returns** ----------- `True` if `True` for each condition in conditions """ for rule in self.rules: if not rule.evaluate(feature_vector): return False, -1 return True, self.prediction class OrderedRuleList: """ Class which represents a list of rules. To make a prediction, the list is traversed and when a rule is found where the sample complies to, its prediction is returned. """ def __init__(self, rule_list): self.rule_list = rule_list '''A list of `constructors.inTrees.Rule`''' def _evaluate(self, feature_vector): for ruleset in sorted(self.rule_list, key=lambda x: x.index): # Sort to make sure they are evaluated in order rule_evaluation_result, rule_evaluation_pred = ruleset.evaluate(feature_vector) if rule_evaluation_result: return rule_evaluation_pred return None def print_rules(self): """Print the rules""" for rule_set in self.rule_list: print '*' + ' & '.join([str(rule.feature)+' '+str(rule.test)+' '+str(rule.value) for rule in rule_set.rules]), '==>', rule_set.prediction def evaluate_multiple(self, feature_vectors): """Wrapper method to evaluate multiple vectors at once (just a for loop where evaluate is called) **Params** ---------- - `feature_vectors` (pandas DataFrame or list of dicts) - the samples to evaluate **Returns** ----------- a class label """ results = [] for _index, feature_vector in feature_vectors.iterrows(): results.append(self._evaluate(feature_vector)) return np.asarray(results) class inTreesClassifier: def __init__(self): pass def _convert_to_r_dataframe(self, df, strings_as_factors=False): """ Convert a pandas DataFrame to a R data.frame. Parameters ---------- df: The DataFrame being converted strings_as_factors: Whether to turn strings into R factors (default: False) Returns ------- A R data.frame """ import rpy2.rlike.container as rlc columns = rlc.OrdDict() # FIXME: This doesn't handle MultiIndex for column in df: value = df[column] value_type = value.dtype.type if value_type == np.datetime64: value = convert_to_r_posixct(value) else: value = [item if pd.notnull(item) else rpy2.rinterface.NA_Integer#com.NA_TYPES[value_type] for item in value] value = rpy2.robjects.vectors.FloatVector(value)#com.VECTOR_TYPES[value_type](value) if not strings_as_factors: I = ro.baseenv.get("I") value = I(value) columns[column] = value r_dataframe = ro.DataFrame(columns) del columns r_dataframe.rownames = ro.StrVector(list(df.index)) r_dataframe.colnames = list(df.columns) return r_dataframe def _tree_to_R_object(self, tree, feature_mapping): node_mapping = {} nodes = tree._get_nodes() nodes.extend(tree._get_leaves()) for i, node in enumerate(nodes): node_mapping[node] = i+1 vectors = [] for node in nodes: if node.value is not None: vectors.append([node_mapping[node], node_mapping[node.left], node_mapping[node.right], feature_mapping[node.label], node.value, 1, 0]) else: vectors.append([node_mapping[node], 0, 0, 0, 0.0, -1, node.label]) df = pd.DataFrame(vectors) df.columns = ['id', 'left daughter', 'right daughter', 'split var', 'split point', 'status', 'prediction'] df = df.set_index('id') df.index.name = None return self._convert_to_r_dataframe(df) def construct_rule_list(self, train_df, label_col, tree_constructors, nr_bootstraps=3): """ Construct an `constructors.inTrees.OrderedRuleList` from an ensemble of decision trees **Params** ---------- - `train_df` (pandas DataFrame) - the training data - `label_col` (string) - the column identifier for the class labels - `tree_constructors` (`constructors.treeconstructor.TreeConstructor`) - the decision tree induction algorithms used to create an ensemble with - `nr_bootstraps` (pandas DataFrame) - how many times do we apply bootstrapping for each TreeConstructor? The size of the ensemble will be equal to |tree_constructors|*nr_bootstraps **Returns** ----------- an OrderedRuleList """ y_train = train_df[label_col] X_train = train_df.copy() X_train = X_train.drop(label_col, axis=1) importr('randomForest') importr('inTrees') ro.globalenv["X"] = pandas2ri.py2ri(X_train) ro.globalenv["target"] = ro.FactorVector(y_train.values.tolist()) feature_mapping = {} feature_mapping_reverse = {} for i, feature in enumerate(X_train.columns): feature_mapping[feature] = i + 1 feature_mapping_reverse[i + 1] = feature treeList = [] for tree in ensemble.bootstrap(train_df, label_col, tree_constructors, nr_classifiers=nr_bootstraps): if tree.count_nodes() > 1: treeList.append(self._tree_to_R_object(tree, feature_mapping)) ro.globalenv["treeList"] = ro.Vector([len(treeList), ro.Vector(treeList)]) ro.r('names(treeList) <- c("ntree", "list")') rules = ro.r('buildLearner(getRuleMetric(extractRules(treeList, X), X, target), X, target)') rules=list(rules) conditions=rules[int(0.6*len(rules)):int(0.8*len(rules))] predictions=rules[int(0.8*len(rules)):] # Create a OrderedRuleList rulesets = [] for idx, (condition, prediction) in enumerate(zip(conditions, predictions)): # Split each condition in Rules to form a RuleSet rulelist = [] condition_split = [x.lstrip().rstrip() for x in condition.split('&')] for rule in condition_split: feature = feature_mapping_reverse[int(re.findall(r',[0-9]+]', rule)[0][1:-1])] lte = re.findall(r'<=', rule) gt = re.findall(r'>', rule) eq = re.findall(r'==', rule) cond = lte[0] if len(lte) else (gt[0] if len(gt) else eq[0]) extract_value = re.findall(r'[=>]-?[0-9\.]+', rule) if len(extract_value): value = float(re.findall(r'[=>]-?[0-9\.]+', rule)[0][1:]) else: feature = 'True' value = None rulelist.append(Condition(feature, cond, value)) rulesets.append(Rule(idx, rulelist, prediction)) return OrderedRuleList(rulesets)
10,783
33.899676
157
py
GENESIM
GENESIM-master/constructors/treeconstructor.py
""" Contains wrappers around well-known decision tree induction algorithms: C4.5, CART, QUEST and GUIDE. Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. """ import pandas as pd import numpy as np from sklearn.cross_validation import StratifiedKFold from sklearn.metrics import accuracy_score from sklearn.tree import DecisionTreeClassifier import Orange import operator import os import time import subprocess import decisiontree class TreeConstructor(object): """This class is an interface for all tree induction algorithms.""" def __init__(self): """In the init method, all hyper-parameters should be set.""" pass def get_name(self): """Get the name of the induction algorithm implemented.""" raise NotImplementedError("This method needs to be implemented") def construct_classifier(self, train, features, label_col): """Construct a `decisiontree.DecisionTree` object from the given training data **Params** ---------- - `train` (pandas DataFrame) - a `Dataframe` containing all the training data - `features` (list) - the names of the feature columns - `label_col` (string) - the name of the class label column **Returns** ----------- a DecisionTree object """ raise NotImplementedError("This method needs to be implemented") # <editor-fold desc="Conversion methods between Orange and pandas"> def _series2descriptor(d, discrete=False): if d.dtype is np.dtype("float"): return Orange.feature.Continuous(str(d.name)) elif d.dtype is np.dtype("int"): return Orange.feature.Continuous(str(d.name), number_of_decimals=0) else: t = d.unique() if discrete or len(t) < len(d) / 2: t.sort() return Orange.feature.Discrete(str(d.name), values=list(t.astype("str"))) else: return Orange.feature.String(str(d.name)) def _df2domain(df): featurelist = [_series2descriptor(df.iloc[:, col]) for col in xrange(len(df.columns))] return Orange.data.Domain(featurelist) def _df2table(df): # It seems they are using native python object/lists internally for Orange.data types (?) # And I didn't find a constructor suitable for pandas.DataFrame since it may carry # multiple dtypes # --> the best approximate is Orange.data.Table.__init__(domain, numpy.ndarray), # --> but the dtype of numpy array can only be "int" and "float" # --> * refer to src/orange/lib_kernel.cpp 3059: # --> * if (((*vi)->varType != TValue::INTVAR) && ((*vi)->varType != TValue::FLOATVAR)) # --> Documents never mentioned >_< # So we use numpy constructor for those int/float columns, python list constructor for other tdomain = _df2domain(df) ttables = [_series2table(df.iloc[:, i], tdomain[i]) for i in xrange(len(df.columns))] return Orange.data.Table(ttables) def _series2table(series, variable): if series.dtype is np.dtype("int") or series.dtype is np.dtype("float"): # Use numpy # Table._init__(Domain, numpy.ndarray) return Orange.data.Table(Orange.data.Domain(variable), series.values[:, np.newaxis]) else: # Build instance list # Table.__init__(Domain, list_of_instances) tdomain = Orange.data.Domain(variable) tinsts = [Orange.data.Instance(tdomain, [i]) for i in series] return Orange.data.Table(tdomain, tinsts) # 5x performance def _column2df(col): if type(col.domain[0]) is Orange.feature.Continuous: return (col.domain[0].name, pd.Series(col.to_numpy()[0].flatten())) else: tmp = pd.Series(np.array(list(col)).flatten()) # type(tmp) -> np.array( dtype=list (Orange.data.Value) ) tmp = tmp.apply(lambda x: str(x[0])) return (col.domain[0].name, tmp) def _table2df(tab): # Orange.data.Table().to_numpy() cannot handle strings # So we must build the array column by column, # When it comes to strings, python list is used series = [_column2df(tab.select(i)) for i in xrange(len(tab.domain))] series_name = [i[0] for i in series] # To keep the order of variables unchanged series_data = dict(series) return pd.DataFrame(series_data, columns=series_name) # </editor-fold> class C45Constructor(TreeConstructor): """This class contains an implementation of C4.5, written by Quinlan. It uses an extern library for this called [Orange](http://docs.orange.biolab.si/2/reference/rst/Orange.classification.tree.html#Orange.classification.tree.C45Learner).""" def __init__(self, gain_ratio=False, cf=0.15): super(C45Constructor, self).__init__() self.gain_ratio = gain_ratio '''boolean value that indicates if either gain ratio or information gain is used as split metric''' self.cf = cf '''pruning confidence level: the lower this value, the more pruning will be done''' def get_name(self): return "C4.5" def construct_classifier(self, train, features, label_col, param_opt=True): training_feature_vectors = train[features].copy() labels = train[label_col].copy() if param_opt: optimal_clf = C45Constructor.get_best_c45_classifier(train, label_col, StratifiedKFold(train[label_col], n_folds=3, shuffle=True, random_state=None)) self.cf = optimal_clf.cf # First call df2table on the feature table orange_feature_table = _df2table(training_feature_vectors) # Convert classes to strings and call df2table orange_labels_table = _df2table(pd.DataFrame(labels.map(str))) # Merge two tables orange_table = Orange.data.Table([orange_feature_table, orange_labels_table]) return self._orange_dt_to_my_dt(Orange.classification.tree.C45Learner(orange_table, gain_ratio=self.gain_ratio, cf=self.cf, min_objs=2, subset=False).tree) def _orange_dt_to_my_dt(self, orange_dt_root): # Check if leaf if orange_dt_root.node_type == Orange.classification.tree.C45Node.Leaf: return decisiontree.DecisionTree(left=None, right=None, label=str(int(orange_dt_root.leaf)), data=None, value=None) else: dt = decisiontree.DecisionTree(label=orange_dt_root.tested.name, data=None, value=orange_dt_root.cut) dt.left = self._orange_dt_to_my_dt(orange_dt_root.branch[0]) dt.right = self._orange_dt_to_my_dt(orange_dt_root.branch[1]) return dt @staticmethod def get_best_c45_classifier(train, label_col, skf_tune): """Returns a `treeconstructor.C45Constructor` with optimized hyper-parameters using [Grid Search](https://en.wikipedia.org/wiki/Hyperparameter_optimization#Grid_search) **Params** ---------- - `train` (pandas DataFrame) - `a pandas Dataframe` with all training data - `label_col` (string) - the column identifier for the label in the `train` Dataframe - `skf_tune` (`sklearn.cross_validation.StratifiedKFold`) - cross-validation object to tune parameters **Returns** ----------- a C45Constructor with optimized hyper-parameters """ c45 = C45Constructor() cfs = np.arange(0.05, 1.05, 0.05) cfs_errors = {} for cf in cfs: cfs_errors[cf] = [] for train_tune_idx, val_tune_idx in skf_tune: train_tune = train.iloc[train_tune_idx, :] X_train_tune = train_tune.drop(label_col, axis=1) y_train_tune = train_tune[label_col] val_tune = train.iloc[val_tune_idx, :] X_val_tune = val_tune.drop(label_col, axis=1) y_val_tune = val_tune[label_col] for cf in cfs: c45.cf = cf tree = c45.construct_classifier(train_tune, X_train_tune.columns, label_col, param_opt=False) predictions = tree.evaluate_multiple(X_val_tune).astype(int) cfs_errors[cf].append(1 - accuracy_score(predictions, y_val_tune, normalize=True)) for cf in cfs: cfs_errors[cf] = np.mean(cfs_errors[cf]) c45.cf = min(cfs_errors.items(), key=operator.itemgetter(1))[0] return c45 class CARTConstructor(TreeConstructor): """This class contains an implementation of CART, written by Breiman. It uses an extern library for this called [sklearn](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html).""" def __init__(self, criterion='gini', min_samples_leaf=1, min_samples_split=2, max_depth=10): super(CARTConstructor, self).__init__() self.min_samples_leaf = min_samples_leaf '''pre-prune condition: when the current number of samples is lower than this threshold, then stop''' self.min_samples_split = min_samples_split '''pre-prune condition: when a split causes the number of samples in one of the two partitions to be lower than this threshold, then stop''' self.max_depth = max_depth '''pre-prune condition: when a depth equal to this parameter is reached, then stop''' self.criterion = criterion '''defines which split criterion to use, is either equal to `gini` or `entropy`''' def get_name(self): return "CART" def construct_classifier(self, train, features, label_col, param_opt=True): training_feature_vectors = train[features] labels = train[label_col] train = training_feature_vectors.copy() label_col = labels.name train[label_col] = labels if param_opt: optimal_clf = CARTConstructor.get_best_cart_classifier(train, label_col, StratifiedKFold(train[label_col], n_folds=3, shuffle=True, random_state=None)) self.max_depth = optimal_clf.max_depth self.min_samples_split = optimal_clf.min_samples_split self.features = list(training_feature_vectors.columns) self.y = labels.values self.X = training_feature_vectors[self.features] self.dt = DecisionTreeClassifier(criterion=self.criterion, min_samples_leaf=self.min_samples_leaf, min_samples_split=self.min_samples_split, max_depth=self.max_depth) self.dt.fit(self.X, self.y) return self._convert_to_tree() def _convert_to_tree(self): """Convert a sklearn object to a `decisiontree.decisiontree` object""" n_nodes = self.dt.tree_.node_count children_left = self.dt.tree_.children_left children_right = self.dt.tree_.children_right feature = self.dt.tree_.feature threshold = self.dt.tree_.threshold classes = self.dt.classes_ # The tree structure can be traversed to compute various properties such # as the depth of each node and whether or not it is a leaf. node_depth = np.zeros(shape=n_nodes) decision_trees = [None] * n_nodes for i in range(n_nodes): decision_trees[i] = decisiontree.DecisionTree() is_leaves = np.zeros(shape=n_nodes, dtype=bool) stack = [(0, -1)] # seed is the root node id and its parent depth while len(stack) > 0: node_id, parent_depth = stack.pop() node_depth[node_id] = parent_depth + 1 # If we have a test node if children_left[node_id] != children_right[node_id]: stack.append((children_left[node_id], parent_depth + 1)) stack.append((children_right[node_id], parent_depth + 1)) else: is_leaves[node_id] = True for i in range(n_nodes): if children_left[i] > 0: decision_trees[i].left = decision_trees[children_left[i]] if children_right[i] > 0: decision_trees[i].right = decision_trees[children_right[i]] if is_leaves[i]: decision_trees[i].label = self.dt.classes_[np.argmax(self.dt.tree_.value[i][0])] decision_trees[i].value = None else: decision_trees[i].label = self.features[feature[i]] decision_trees[i].value = threshold[i] return decision_trees[0] @staticmethod def get_best_cart_classifier(train, label_col, skf_tune): """Returns a `treeconstructor.CARTConstructor` with optimized hyper-parameters using [Grid Search](https://en.wikipedia.org/wiki/Hyperparameter_optimization#Grid_search) **Params** ---------- - `train` (pandas DataFrame) - `a pandas Dataframe` with all training data - `label_col` (string) - the column identifier for the label in the `train` Dataframe - `skf_tune` (`sklearn.cross_validation.StratifiedKFold`) - cross-validation object to tune parameters **Returns** ----------- a CARTConstructor with optimized hyper-parameters """ cart = CARTConstructor() max_depths = np.arange(1,21,2) max_depths = np.append(max_depths, None) min_samples_splits = np.arange(2,20,1) errors = {} for max_depth in max_depths: for min_samples_split in min_samples_splits: errors[(max_depth, min_samples_split)] = [] for train_tune_idx, val_tune_idx in skf_tune: train_tune = train.iloc[train_tune_idx, :] X_train_tune = train_tune.drop(label_col, axis=1) y_train_tune = train_tune[label_col] val_tune = train.iloc[val_tune_idx, :] X_val_tune = val_tune.drop(label_col, axis=1) y_val_tune = val_tune[label_col] for max_depth in max_depths: for min_samples_split in min_samples_splits: cart.max_depth = max_depth cart.min_samples_split = min_samples_split tree = cart.construct_classifier(train_tune, X_train_tune.columns, label_col, param_opt=False) predictions = tree.evaluate_multiple(X_val_tune).astype(int) errors[((max_depth, min_samples_split))].append(1 - accuracy_score(predictions, y_val_tune, normalize=True)) for max_depth in max_depths: for min_samples_split in min_samples_splits: errors[(max_depth, min_samples_split)] = np.mean(errors[(max_depth, min_samples_split)]) best_params = min(errors.items(), key=operator.itemgetter(1))[0] cart.max_depth = best_params[0] cart.min_samples_split = best_params[1] return cart class QUESTConstructor(TreeConstructor): """This class contains a wrapper around an implementation of [QUEST](http://www.stat.wisc.edu/~loh/quest.html), written by Loh.""" def __init__(self): super(QUESTConstructor, self).__init__() def get_name(self): return "QUEST" def construct_classifier(self, train, features, label_col): training_feature_vectors = train[features] labels = train[label_col] self._create_desc_and_data_file(training_feature_vectors, labels) input = open("in.txt", "w") output = file('out.txt', 'w') p = subprocess.Popen(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1])+'/quest > log.txt', stdin=subprocess.PIPE, shell=True) p.stdin.write("2\n") p.stdin.write("in.txt\n") p.stdin.write("1\n") p.stdin.write("out.txt\n") p.stdin.write("1\n") p.stdin.write("dsc.txt\n") p.stdin.write("1\n") p.stdin.write("\n") p.wait() input.close() output.close() while not os.path.exists('in.txt'): time.sleep(1) p = subprocess.Popen(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1])+'/quest < in.txt > log.txt', stdin=subprocess.PIPE, shell=True) p.wait() output = file('out.txt', 'r') lines = output.readlines() output.close() start_index, end_index, counter = 0, 0, 0 for line in lines: if line == ' Classification tree:\n': start_index = counter+2 if line == ' Information for each node:\n': end_index = counter-1 counter += 1 tree = self._decision_tree_from_text(lines[start_index:end_index]) self._remove_files() return tree def _decision_tree_from_text(self, lines): dt = decisiontree.DecisionTree() if '<=' in lines[0] or '>' in lines[0]: # Intermediate node node_name = lines[0].split(':')[0].lstrip() label, value = lines[0].split(':')[1].split('<=') label = ' '.join(label.lstrip().rstrip().split('.')) value = value.lstrip().split()[0] dt.label = label dt.value = float(value) dt.left = self._decision_tree_from_text(lines[1:]) counter = 1 while lines[counter].split(':')[0].lstrip() != node_name: counter+=1 dt.right = self._decision_tree_from_text(lines[counter + 1:]) else: # Terminal node dt.label = int(eval(lines[0].split(':')[1].lstrip())) return dt def _create_desc_and_data_file(self, training_feature_vectors, labels): dsc = open("dsc.txt", "w") data = open("data.txt", "w") dsc.write("data.txt\n") dsc.write("\"?\"\n") dsc.write("column, var, type\n") count = 1 for col in training_feature_vectors.columns: dsc.write(str(count) + ' \"' + str(col) + '\" n\n') count += 1 dsc.write(str(count) + ' ' + str(labels.name) + ' d') for i in range(len(training_feature_vectors)): sample = training_feature_vectors.iloc[i,:] for col in training_feature_vectors.columns: data.write(str(sample[col]) + ' ') if i != len(training_feature_vectors)-1: data.write(str(labels[i])+'\n') else: data.write(str(labels[i])) data.close() dsc.close() def _remove_files(self): os.remove('data.txt') os.remove('in.txt') os.remove('dsc.txt') os.remove('out.txt') os.remove('log.txt') class GUIDEConstructor(TreeConstructor): """This class contains a wrapper around an implementation of [GUIDE](http://www.stat.wisc.edu/~loh/guide.html), written by Loh.""" def __init__(self): super(GUIDEConstructor, self).__init__() def get_name(self): return "GUIDE" def construct_classifier(self, train, features, label_col): training_feature_vectors = train[features] labels = train[label_col] self._create_desc_and_data_file(training_feature_vectors, labels) input = open("in.txt", "w") output = file('out.txt', 'w') p = subprocess.Popen(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1])+'/guide > log.txt', stdin=subprocess.PIPE, shell=True) p.stdin.write("1\n") p.stdin.write("in.txt\n") p.stdin.write("1\n") p.stdin.write("1\n") p.stdin.write("out.txt\n") p.stdin.write("1\n") p.stdin.write("1\n") p.stdin.write("1\n") p.stdin.write("2\n") p.stdin.write("1\n") p.stdin.write("3\n") p.stdin.write("1\n") p.stdin.write('dsc.txt\n') p.stdin.write("\n") p.stdin.write("\n") p.stdin.write("\n") p.stdin.write("1\n") p.stdin.write("1\n") p.stdin.write("\n") p.stdin.write("\n") p.stdin.write("\n") p.stdin.write("2\n") p.stdin.write("1\n") p.stdin.write("1\n") p.stdin.write("1\n") p.stdin.write("1\n") p.stdin.write("\n") p.wait() input.close() output.close() while not os.path.exists('in.txt'): time.sleep(1) p = subprocess.Popen(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1])+'/guide < in.txt > log.txt', shell=True) p.wait() output = file('out.txt', 'r') lines = output.readlines() output.close() start_index, end_index, counter = 0, 0, 0 for line in lines: if line == ' Classification tree:\n': start_index = counter+2 if line == ' ***************************************************************\n': end_index = counter-1 counter += 1 tree = self._decision_tree_from_text(lines[start_index:end_index]) # self.remove_files() # tree.visualise('GUIDE') return tree def _decision_tree_from_text(self, lines): dt = decisiontree.DecisionTree() if '<=' in lines[0] or '>' in lines[0] or '=' in lines[0]: # Intermediate node node_name = lines[0].split(':')[0].lstrip() # print(lines[0]) label, value = lines[0].split(':')[1].split('<=') label = ' '.join(label.lstrip().rstrip().split('.')) value = value.lstrip().split()[0] dt.label = label dt.value = float(value) dt.left = self._decision_tree_from_text(lines[1:]) counter = 1 while lines[counter].split(':')[0].lstrip() != node_name: counter+=1 dt.right = self._decision_tree_from_text(lines[counter + 1:]) else: # Terminal node # print lines[0] dt.label = int(lines[0].split(':')[1].lstrip().split('.')[0]) return dt def _create_desc_and_data_file(self, training_feature_vectors, labels): dsc = open("dsc.txt", "w") data = open("data.txt", "w") dsc.write("data.txt\n") dsc.write("\"?\"\n") dsc.write("1\n") count = 1 for col in training_feature_vectors.columns: dsc.write(str(count) + ' \"' + str(col) + '\" n\n') count += 1 dsc.write(str(count) + ' ' + str(labels.name) + ' d') for i in range(len(training_feature_vectors)): sample = training_feature_vectors.iloc[i,:] for col in training_feature_vectors.columns: data.write(str(sample[col]) + ' ') if i != len(training_feature_vectors)-1: data.write(str(labels[i])+'\n') else: data.write(str(labels[i])) data.close() dsc.close() def _remove_files(self): os.remove('data.txt') os.remove('in.txt') os.remove('dsc.txt') os.remove('out.txt') os.remove('log.txt')
23,107
38.772806
151
py
GENESIM
GENESIM-master/constructors/__init__.py
""" Contains implementations for different classifiers: decision tree induction algorithms, ensemble techniques and GENESIM: GENetic Extraction of a Single, Interpretable Model Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. """
264
43.166667
111
py
GENESIM
GENESIM-master/constructors/ensemble.py
""" Contains wrappers around well-known ensemble techniques: Random Forest and XGBoost. Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. """ import time from bayes_opt import BayesianOptimization from sklearn.cross_validation import cross_val_score from sklearn.ensemble import AdaBoostClassifier from xgboost import XGBClassifier from sklearn.ensemble import RandomForestClassifier import numpy as np import decisiontree class EnsembleConstructor(object): """This class is an interface for all tree induction algorithms.""" def __init__(self): """In the init method, all hyper-parameters should be set.""" self.clf = None def get_name(self): """Get the name of the induction algorithm implemented.""" raise NotImplementedError("This method needs to be implemented") def construct_classifier(self, train, features, label_col): """Construct an ensemble classifier. **Params** ---------- - `train` (pandas DataFrame) - a `Dataframe` containing all the training data - `features` (pandas Series or list) - the names of the feature columns - `label_col` (string) - the name of the class label column **Returns** ----------- an ensemble classifier """ raise NotImplementedError("This method needs to be implemented") def evaluate_multiple(self, feature_vectors): """Evaluate multiple samples **Params** ---------- - `feature_vectors` (pandas DataFrame) - a `Dataframe` containing all the feature vectors **Returns** ----------- a list of predicted class labels """ return self.clf.predict(feature_vectors) class XGBClassification(EnsembleConstructor): def get_name(self): return 'XGBoost' def __init__(self): super(XGBClassification, self).__init__() self.nr_clf = 0 self.time = 0 def construct_classifier(self, train, features, label_col): data = train[features] target = train[label_col] def xgbcv(nr_classifiers, learning_rate, max_depth, min_child_weight, subsample, colsample_bytree, gamma, reg_lambda): nr_classifiers = int(nr_classifiers) max_depth = int(max_depth) min_child_weight = int(min_child_weight) return cross_val_score(XGBClassifier(learning_rate=learning_rate, n_estimators=nr_classifiers, gamma=gamma, subsample=subsample, colsample_bytree=colsample_bytree, nthread=1, scale_pos_weight=1, reg_lambda=reg_lambda, min_child_weight=min_child_weight, max_depth=max_depth), data, target, 'accuracy', cv=5).mean() params = { 'nr_classifiers': (50, 1000), 'learning_rate': (0.01, 0.3), 'max_depth': (5, 10), 'min_child_weight': (2, 10), 'subsample': (0.7, 0.8), 'colsample_bytree': (0.5, 0.99), 'gamma': (0.01, 1.), 'reg_lambda': (0, 1) } xgbBO = BayesianOptimization(xgbcv, params, verbose=0) xgbBO.maximize(init_points=10, n_iter=20, n_restarts_optimizer=50) # xgbBO.maximize(init_points=1, n_iter=1, n_restarts_optimizer=100) best_params = xgbBO.res['max']['max_params'] best_nr_classifiers = int(best_params['nr_classifiers']) self.nr_clf = best_nr_classifiers best_max_depth = int(best_params['max_depth']) best_min_child_weight = int(best_params['min_child_weight']) best_colsample_bytree = best_params['colsample_bytree'] best_subsample = best_params['subsample'] best_reg_lambda = best_params['reg_lambda'] best_learning_rate = best_params['learning_rate'] best_gamma = best_params['gamma'] print(best_nr_classifiers) self.clf = XGBClassifier(learning_rate=best_learning_rate, n_estimators=best_nr_classifiers, gamma=best_gamma, subsample=best_subsample, colsample_bytree=best_colsample_bytree, nthread=1, scale_pos_weight=1, reg_lambda=best_reg_lambda, min_child_weight=best_min_child_weight, max_depth=best_max_depth) start = time.time() self.clf.fit(data, target) self.time = time.time() - start return self def evaluate_multiple(self, feature_vectors): return self.clf.predict(feature_vectors) class RFClassification(EnsembleConstructor): def get_name(self): return 'RF' def __init__(self): super(RFClassification, self).__init__() self.nr_clf = 0 self.time = 0 def construct_classifier(self, train, features, label_col): data = train[features] target = train[label_col] def rfcv(nr_classifiers, max_depth, min_samples_leaf, bootstrap, criterion, max_features): nr_classifiers = int(nr_classifiers) max_depth = int(max_depth) min_samples_leaf = int(min_samples_leaf) if np.round(bootstrap): bootstrap = True else: bootstrap = False if np.round(criterion): criterion = 'gini' else: criterion = 'entropy' if np.round(max_features): max_features = None else: max_features = 1.0 return cross_val_score(RandomForestClassifier(n_estimators=nr_classifiers, max_depth=max_depth, min_samples_leaf=min_samples_leaf, bootstrap=bootstrap, criterion=criterion, max_features=max_features), data, target, 'accuracy', cv=5).mean() params = { 'nr_classifiers': (10, 1000), 'max_depth': (5, 10), 'min_samples_leaf': (2, 10), 'bootstrap': (0, 1), 'criterion': (0, 1), 'max_features': (0, 1) } rfBO = BayesianOptimization(rfcv, params, verbose=0) rfBO.maximize(init_points=10, n_iter=20, n_restarts_optimizer=50) # rfBO.maximize(init_points=1, n_iter=1, n_restarts_optimizer=50) best_params = rfBO.res['max']['max_params'] best_nr_classifiers = int(best_params['nr_classifiers']) self.nr_clf = best_nr_classifiers best_max_depth = int(best_params['max_depth']) best_min_samples_leaf = int(best_params['min_samples_leaf']) best_bootstrap = best_params['bootstrap'] best_criterion = best_params['criterion'] best_max_features = best_params['max_features'] if np.round(best_bootstrap): best_bootstrap = True else: best_bootstrap = False if np.round(best_criterion): best_criterion = 'gini' else: best_criterion = 'entropy' if np.round(best_max_features): best_max_features = None else: best_max_features = 1.0 self.clf = RandomForestClassifier(n_estimators=best_nr_classifiers, max_depth=best_max_depth, min_samples_leaf=best_min_samples_leaf, bootstrap=best_bootstrap, criterion=best_criterion, max_features=best_max_features) start = time.time() self.clf.fit(data, target) self.time = time.time() - start return self def evaluate_multiple(self, feature_vectors): return self.clf.predict(feature_vectors) def bootstrap(data, class_label, tree_constructors, bootstrap_features=False, nr_classifiers=3, boosting=True): """ Bootstrapping ensemble technique **Params** ---------- - `data` (DataFrame): containing all the data to be bootstrapped - `class_label` (string): the column in the dataframe that contains the target variables - `tree_constructors` (list): the induction algorithms (`constructors.treeconstructor.TreeConstructor`) used - `bootstrap_features` (boolean): if `True`, then apply bootstrapping to the features as well - `nr_classifiers` (int): for each `tree_constructor`, how many times must we bootstrap - `boosting` (boolean): if `True`, then do create models with AdaBoost too **Returns** ----------- a vector of fitted classifiers, converted to DecisionTree (`decisiontree.DecisionTree`) """ def _convert_to_tree(classifier, features): n_nodes = classifier.tree_.node_count children_left = classifier.tree_.children_left children_right = classifier.tree_.children_right feature = classifier.tree_.feature threshold = classifier.tree_.threshold classes = classifier.classes_ # The tree structure can be traversed to compute various properties such # as the depth of each node and whether or not it is a leaf. node_depth = np.zeros(shape=n_nodes) decision_trees = [None] * n_nodes for i in range(n_nodes): decision_trees[i] = decisiontree.DecisionTree() is_leaves = np.zeros(shape=n_nodes, dtype=bool) stack = [(0, -1)] # seed is the root node id and its parent depth while len(stack) > 0: node_id, parent_depth = stack.pop() node_depth[node_id] = parent_depth + 1 # If we have a test node if children_left[node_id] != children_right[node_id]: stack.append((children_left[node_id], parent_depth + 1)) stack.append((children_right[node_id], parent_depth + 1)) else: is_leaves[node_id] = True for i in range(n_nodes): if children_left[i] > 0: decision_trees[i].left = decision_trees[children_left[i]] if children_right[i] > 0: decision_trees[i].right = decision_trees[children_right[i]] if is_leaves[i]: decision_trees[i].label = classes[np.argmax(classifier.tree_.value[i][0])] decision_trees[i].value = None else: decision_trees[i].label = features[feature[i]] decision_trees[i].value = threshold[i] return decision_trees[0] idx = np.random.randint(0, len(data), (nr_classifiers, len(data))) decision_trees = [] if boosting: ada = AdaBoostClassifier(base_estimator=None, n_estimators=nr_classifiers, learning_rate=0.25, random_state=1337) X_train = data.drop(class_label, axis=1).reset_index(drop=True) y_train = data[class_label].reset_index(drop=True) ada.fit(X_train, y_train) for estimator in ada.estimators_: dt = _convert_to_tree(estimator, X_train.columns) dt.data = data dt.populate_samples(X_train, y_train) decision_trees.append(dt) for indices in idx: if bootstrap_features: features = list(set(np.random.randint(0, len(data.columns), (1, len(data.columns))).tolist()[0])) X_bootstrap = data.iloc[indices, features].reset_index(drop=True) if class_label in X_bootstrap.columns: X_bootstrap = X_bootstrap.drop(class_label, axis=1) y_bootstrap = data.iloc[indices][class_label].reset_index(drop=True) else: X_bootstrap = data.iloc[indices, :].drop(class_label, axis=1).reset_index(drop=True) y_bootstrap = data.iloc[indices][class_label].reset_index(drop=True) X = data.drop(class_label, axis=1).reset_index(drop=True) y = data[class_label].reset_index(drop=True) train_bootstrap = X_bootstrap.copy() train_bootstrap[y_bootstrap.name] = y_bootstrap for tree_constructor in tree_constructors: tree = tree_constructor.construct_classifier(train_bootstrap, X_bootstrap.columns, y_bootstrap.name) # print 'Number of nodes in stub:', tree_constructor.get_name(), count_nodes(tree) # print tree_constructor.get_name(), tree.count_nodes() tree.data = data.iloc[indices, :].reset_index(drop=True) tree.populate_samples(X, y) decision_trees.append(tree) return decision_trees
12,560
38.5
121
py
GENESIM
GENESIM-master/constructors/ISM.py
""" Interpretable Single Model -------------------------- Merges different decision trees in an ensemble together in a single, interpretable decision tree Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. Reference: Van Assche, Anneleen, and Hendrik Blockeel. "Seeing the forest through the trees: Learning a comprehensible model from an ensemble." European Conference on Machine Learning. Springer Berlin Heidelberg, 2007. """ from collections import Counter import math import numpy as np import decisiontree def _extract_tests(tree, _tests=set()): """ Given a decision tree, extract all tests from the nodes :param tree: the decision tree to extract tests from (decisiontree.py) :param _tests: recursive parameter, don't touch :return: a set of possible tests (feature_label <= threshold_value); each entry is a tuple (label, value) """ if tree.value is not None: _tests.add((tree.label, tree.value)) _extract_tests(tree.left, _tests) _extract_tests(tree.right, _tests) return _tests def _calculate_entropy(probabilities): """ Calculate the entropy of given probabilities :param probabilities: a list of floats between [0, 1] (sum(probabilities) must be 1) :return: the entropy """ return sum([-prob * np.log(prob)/np.log(2) if prob != 0 else 0 for prob in probabilities]) def _get_most_occurring_class(data, class_label): """ Get the most occurring class in a dataframe of data :param data: a pandas dataframe :param class_label: the column of the class labels :return: the most occurring class """ return Counter(data[class_label].values.tolist()).most_common(1)[0][0] def _calculate_prob(tree, label, value, prior_tests, negate=False): """ Estimate the probabilities from a decision tree by propagating down from the root to the leaves :param tree: the decision tree to estimate the probabilities from :param label: the label of the test being evaluated :param value: the value of the test being evaluated :param prior_tests: tests that are already in the conjunctions :param negate: is it a negative or positive test :return: a vector of probabilities for each class """ if tree.value is None: # If the value is None, we're at a leaf, return a vector of probabilities return np.divide(list(map(float, list(tree.class_probabilities.values()))), float(sum(list(tree.class_probabilities.values())))) else: if (tree.label, tree.value) in prior_tests: # The test in the current node is already in the conjunction, take the correct path if prior_tests[(tree.label, tree.value)]: return _calculate_prob(tree.left, label, value, prior_tests, negate) else: return _calculate_prob(tree.right, label, value, prior_tests, negate) elif not (tree.label == label and tree.value == value): # The test of current node is not yet in conjunction and is not the test we're looking for # Keep propagating (but add weights (estimate how many times the test succeeds/fails))! samples_sum = sum(list(tree.class_probabilities.values())) if samples_sum == 0: left_fraction = 1.0 right_fraction = 1.0 else: left_fraction = sum(list(tree.left.class_probabilities.values())) / samples_sum right_fraction = sum(list(tree.right.class_probabilities.values())) / samples_sum return np.add(left_fraction * _calculate_prob(tree.left, label, value, prior_tests, negate), right_fraction * _calculate_prob(tree.right, label, value, prior_tests, negate)) elif not negate: # We found the test we are looking for # If negate is False, then it is a positive test and we take the left subtree return _calculate_prob(tree.left, label, value, prior_tests, negate) else: return _calculate_prob(tree.right, label, value, prior_tests, negate) def _calculate_prob_dict(tree, label, value, prior_tests, negate=False): """ Wrapper around calculate_prob, so we know which probability belongs to which class """ return dict(zip(tree.class_probabilities.keys(), _calculate_prob(tree, label, value, prior_tests, negate))) def ism(decision_trees, data, class_label, min_nr_samples=1, calc_fracs_from_ensemble=False): """ Return a single decision tree from an ensemble of decision tree, using the normalized information gain as split criterion, estimated from the ensemble. This is a wrapper function around `constructors.ISM.build_dt_from_ensemble`, which first calculate the required parameters for this method. **Params** ---------- - `decision_trees` (list of `decisiontree.DecisionTree` objects): the ensemble of decision trees to be merged - `data` (pandas DataFrame): the data frame with training data - `class_label` (string): the column identifier for the column with class labels in the data - `min_nr_samples` (int): pre-prune condition, stop searching if number of samples is smaller or equal than threshold - `calc_fracs_from_ensemble` (boolean): if `True`, the different probabilities are calculated using the ensemble. Else, the data is used **Returns** ----------- a single decision tree based on the ensemble of decision trees """ X = data.drop(class_label, axis=1).reset_index(drop=True) y = data[class_label].reset_index(drop=True) non_empty_decision_trees = [] for tree in decision_trees: if tree.count_nodes() > 1: non_empty_decision_trees.append(tree) decision_trees = non_empty_decision_trees prior_entropy = 0 tests = set() tests.clear() for dt in decision_trees: tests = tests | _extract_tests(dt, set()) prior_entropy += _calculate_entropy(np.divide(list(dt.class_probabilities.values()), sum(dt.class_probabilities.values()))) prior_entropy /= len(decision_trees) combined_dt = build_dt_from_ensemble(decision_trees, data, class_label, tests, prior_entropy, {}, min_nr_samples, calc_fracs_from_ensemble) combined_dt.populate_samples(X, y) return combined_dt def _add_reduce_by_key(A, B): """ Reduces two dicts by key using add operator :param A: dict one :param B: dict two :return: a new dict, containing a of the values if the two dicts have the same key, else just the value """ return {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)} def build_dt_from_ensemble(decision_trees, data, class_label, tests, prior_entropy, prior_tests={}, min_nr_samples=1, calc_fracs_from_ensemble=False): """ Given an ensemble of decision trees, build a single decision tree using estimates from the ensemble **Params** ---------- - `decision_trees` (list of `decisiontree.DecisionTree` objects): the ensemble of decision trees to be merged - `data` (pandas DataFrame): the data frame with training data - `class_label` (string): the column identifier for the column with class labels in the data - `tests` (set of tuples): all possible tests (extracted from the ensemble) - `prior_entropy` (float): recursive parameter to calculate information gain - `prior_tests` (set of tuples): the tests that are already picked for our final decision tree - `min_nr_samples` (int): pre-prune condition, stop searching if number of samples is smaller or equal than threshold - `calc_fracs_from_ensemble` (boolean): if `True`, the different probabilities are calculated using the ensemble. Else, the data is used **Returns** ----------- a single decision tree, calculated using information from the ensemble """ # Pre-pruning conditions: # - if the length of data is <= min_nr_samples # - when we have no tests left # - when there is only 1 unique class in the data left # print len(data), len(tests), np.unique(data[class_label].values) if len(data) > min_nr_samples and len(tests) > 0 and len(np.unique(data[class_label].values)) > 1: max_ig = 0 best_pos_data, best_neg_data, best_pos_entropy, best_neg_entropy = [None]*4 best_dt = decisiontree.DecisionTree() # Find the test that results in the maximum information gain for test in tests: pos_avg_probs, neg_avg_probs, pos_fraction, neg_fraction = {}, {}, 0.0, 0.0 for dt in decision_trees: pos_prob_dict = _calculate_prob_dict(dt, test[0], test[1], prior_tests, False) neg_prob_dict = _calculate_prob_dict(dt, test[0], test[1], prior_tests, True) if not any(math.isnan(x) for x in pos_prob_dict.values()) and not any(math.isnan(x) for x in neg_prob_dict.values()): pos_avg_probs = _add_reduce_by_key(pos_avg_probs, _calculate_prob_dict(dt, test[0], test[1], prior_tests, False)) neg_avg_probs = _add_reduce_by_key(neg_avg_probs, _calculate_prob_dict(dt, test[0], test[1], prior_tests, True)) if calc_fracs_from_ensemble and len(data) > 0: pos_fraction += float(len(dt.data[dt.data[test[0]] <= test[1]]))/len(dt.data) neg_fraction += float(len(dt.data[dt.data[test[0]] > test[1]]))/len(dt.data) for key in pos_avg_probs: pos_avg_probs[key] /= len(decision_trees) for key in neg_avg_probs: neg_avg_probs[key] /= len(decision_trees) if calc_fracs_from_ensemble: pos_fraction /= float(len(decision_trees)) neg_fraction /= float(len(decision_trees)) pos_entropy = _calculate_entropy(np.divide(list(pos_avg_probs.values()), len(decision_trees))) neg_entropy = _calculate_entropy(np.divide(list(neg_avg_probs.values()), len(decision_trees))) pos_data = data[data[test[0]] <= test[1]].copy() neg_data = data[data[test[0]] > test[1]].copy() if not calc_fracs_from_ensemble: pos_fraction = float(len(pos_data)) / float(len(data)) neg_fraction = float(len(neg_data)) / float(len(data)) weighted_entropy = pos_fraction * pos_entropy + neg_fraction * neg_entropy information_gain = prior_entropy - weighted_entropy if information_gain > max_ig and len(pos_data) > 0 and len(neg_data) > 0: max_ig, best_dt.label, best_dt.value = information_gain, test[0], test[1] best_pos_data, best_neg_data, best_pos_entropy, best_neg_entropy = pos_data, neg_data, pos_entropy, neg_entropy # print max_ig if max_ig == 0: # If we can't find a test that results in an information gain, we can pre-prune return decisiontree.DecisionTree(value=None, label=_get_most_occurring_class(data, class_label)) # Update some variables and do recursive calls left_prior_tests = prior_tests.copy() left_prior_tests.update({(best_dt.label, best_dt.value): True}) new_tests = tests.copy() new_tests.remove((best_dt.label, best_dt.value)) best_dt.left = build_dt_from_ensemble(decision_trees, best_pos_data, class_label, new_tests, best_pos_entropy, left_prior_tests, min_nr_samples) right_prior_tests = prior_tests.copy() right_prior_tests.update({(best_dt.label, best_dt.value): False}) best_dt.right = build_dt_from_ensemble(decision_trees, best_neg_data, class_label, new_tests, best_neg_entropy, right_prior_tests, min_nr_samples) return best_dt else: return decisiontree.DecisionTree(value=None, label=_get_most_occurring_class(data, class_label))
12,135
45.676923
141
py
GENESIM
GENESIM-master/data/load_datasets.py
"""Contains data set loading functions. If you want the test script to include a new dataset, a new function must be written in this module that returns a pandas Dataframe, the feature column names, the label column name and the dataset name. Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. """ from sklearn import datasets import pandas as pd import numpy as np import os # def load_wine(): # columns = ['Class', 'Alcohol', 'Acid', 'Ash', 'Alcalinity', 'Magnesium', 'Phenols', 'Flavanoids', 'Nonflavanoids', # 'Proanthocyanins', 'Color', 'Hue', 'Diluted', 'Proline'] # features = ['Alcohol', 'Acid', 'Ash', 'Alcalinity', 'Magnesium', 'Phenols', 'Flavanoids', 'Nonflavanoids', # 'Proanthocyanins', 'Color', 'Hue', 'Diluted', 'Proline'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'wine.data')) # df.columns = columns # df['Class'] = np.subtract(df['Class'], 1) # # return df, features, 'Class', 'wine' # # # def load_cars(): # columns = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety', 'Class'] # features = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'car.data')) # df.columns = columns # df = df.reindex(np.random.permutation(df.index)).reset_index(drop=1) # # mapping_buy_maint = {'low': 0, 'med': 1, 'high': 2, 'vhigh': 3} # mapping_doors = {'2': 0, '3': 1, '4': 2, '5more': 3} # mapping_persons = {'2': 0, '4': 1, 'more': 2} # mapping_lug = {'small': 0, 'med': 1, 'big': 2} # mapping_safety = {'low': 0, 'med': 1, 'high': 2} # mapping_class = {'unacc': 0, 'acc': 1, 'good': 2, 'vgood': 3} # # df['maint'] = df['maint'].map(mapping_buy_maint) # df['buying'] = df['buying'].map(mapping_buy_maint) # df['doors'] = df['doors'].map(mapping_doors) # df['persons'] = df['persons'].map(mapping_persons) # df['lug_boot'] = df['lug_boot'].map(mapping_lug) # df['safety'] = df['safety'].map(mapping_safety) # df['Class'] = df['Class'].map(mapping_class).astype(int) # # return df, features, 'Class', 'cars' # # # def load_wisconsin_breast_cancer(): # columns = ['ID', 'ClumpThickness', 'CellSizeUniform', 'CellShapeUniform', 'MargAdhesion', 'EpithCellSize', 'BareNuclei', # 'BlandChromatin', 'NormalNuclei', 'Mitoses', 'Class'] # features = ['ClumpThickness', 'CellSizeUniform', 'CellShapeUniform', 'MargAdhesion', 'EpithCellSize', 'BareNuclei', # 'BlandChromatin', 'NormalNuclei', 'Mitoses'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'breast-cancer-wisconsin.data')) # df.columns = columns # df['Class'] = np.subtract(np.divide(df['Class'], 2), 1) # df = df.drop('ID', axis=1).reset_index(drop=True) # df['BareNuclei'] = df['BareNuclei'].replace('?', int(np.mean(df['BareNuclei'][df['BareNuclei'] != '?'].map(int)))) # df = df.applymap(int) # # return df, features, 'Class', 'wisconsinBreast' from sklearn.preprocessing import LabelEncoder # def load_heart(): # columns = ['age', 'sex', 'chest pain type', 'resting blood pressure', 'serum cholestoral', 'fasting blood sugar', \ # 'resting electrocardio', 'max heartrate', 'exercise induced', 'oldpeak', 'slope peak', \ # 'vessels', 'thal', 'Class'] # features = ['age', 'sex', 'chest pain type', 'resting blood pressure', 'serum cholestoral', 'fasting blood sugar', \ # 'resting electrocardio', 'max heartrate', 'exercise induced', 'oldpeak', 'slope peak', \ # 'vessels', 'thal'] # # columns_copy = [] # for column in columns: # column=column[:10] # columns_copy.append(column) # columns = columns_copy # # features_copy = [] # for feature in features: # feature=feature[:10] # features_copy.append(feature) # features=features_copy # # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'heart.dat'), sep=' ') # df.columns = columns # df['Class'] = np.subtract(df['Class'], 1) # return df, features, 'Class', 'heart' # def load_glass(): # columns = ['id', 'RI', 'Na', 'Mg', 'Al', 'Si', 'K', 'Ca', 'Ba', 'Fe', 'Class'] # features = ['RI', 'Na', 'Mg', 'Al', 'Si', 'K', 'Ca', 'Ba', 'Fe'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'glass.data')) # df.columns = columns # df = df.drop('id', axis=1).reset_index(drop=True) # df['Class'] = np.subtract(df['Class'], 1) # df = df[df['Class'] != 3] # df['Class'] = df['Class'].map({0:0, 1:1, 2:2, 4: 3, 5: 4, 6: 5}).astype(int) # return df, features, 'Class', 'glass' # # # def load_austra(): # columns = ['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','X11','X12','X13','X14','Class'] # features = ['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','X11','X12','X13','X14'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'austra.data')) # df.columns = columns # df['Class'] = df['Class'].map({'y0': 0, 'y1': 1}).astype(int) # return df, features, 'Class', 'austra' # # # def load_led7(): # columns = ['X1','X2','X3','X4','X5','X6','X7','Class'] # features = ['X1','X2','X3','X4','X5','X6','X7'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'led7.data')) # df.columns = columns # df['Class'] = df['Class'].map({'y0': 0, 'y1': 1, 'y2': 2, 'y3': 3, 'y4': 4, 'y5': 5, 'y6': 6, # 'y7': 7, 'y8': 8, 'y9': 9}).astype(int) # df = df[df['Class'] < 8] # return df, features, 'Class', 'led7' # # # def load_lymph(): # columns = ['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','X11','X12','X13','X14','X15','X16','X17','X18','Class'] # features = ['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','X11','X12','X13','X14','X15','X16','X17','X18'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'lymph.data')) # df.columns = columns # df = df[df['Class'] != 'y1'] # df = df[df['Class'] != 'y4'] # df['Class'] = df['Class'].map({'y2': 0, 'y3': 1}).astype(int) # return df, features, 'Class', 'lymph' # # # def load_pima(): # columns = ['X1','X2','X3','X4','X5','X6','X7','X8','Class'] # features = ['X1','X2','X3','X4','X5','X6','X7','X8'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'pima.data')) # df.columns = columns # df['Class'] = df['Class'].map({'y0': 0, 'y1': 1}).astype(int) # return df, features, 'Class', 'pima' # # # def load_vehicle(): # columns = ['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','X11','X12','X13','X14','X15','X16','X17','X18','Class'] # features = ['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','X11','X12','X13','X14','X15','X16','X17','X18'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'vehicle.data')) # df.columns = columns # df['Class'] = df['Class'].map({'y1': 0, 'y2': 1, 'y3': 2, 'y4': 3}).astype(int) # return df, features, 'Class', 'vehicle' # # # def load_iris(): # iris = datasets.load_iris() # df = pd.DataFrame(iris.data) # features = ["SepalLength", "SepalWidth", "PetalLength", "PetalWidth"] # df.columns = features # df['Class'] = iris.target # # return df, features, 'Class', 'iris' # # # def load_ecoli(): # columns = ['name', 'mcg', 'gvh', 'lip', 'chg', 'aac', 'alm1', 'alm2', 'Class'] # features = ['mcg', 'gvh', 'lip', 'chg', 'aac', 'alm1', 'alm2'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'ecoli.data'), delim_whitespace=True, header=0) # df.columns = columns # df = df.drop('name', axis=1).reset_index(drop=True) # mapping_class = {'cp': 0, 'im': 1, 'pp': 2, 'imU': 3, 'om': 4, 'omL': 5, 'imL': 6, 'imS': 7} # df['Class'] = df['Class'].map(mapping_class).astype(int) # df = df[df['Class'] < 5] # return df, features, 'Class', 'ecoli' # # # def load_yeast(): # columns = ['name', 'mcg', 'gvh', 'alm', 'mit', 'erl', 'pox', 'vac', 'nuc', 'Class'] # features = ['mcg', 'gvh', 'alm', 'mit', 'erl', 'pox', 'vac', 'nuc'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'yeast.data'), delim_whitespace=True, header=0) # df.columns = columns # df = df.drop('name', axis=1).reset_index(drop=True) # mapping_class = {'CYT': 0, 'NUC': 1, 'MIT': 2, 'ME3': 3, 'ME2': 4, 'ME1': 5, 'EXC': 6, 'VAC': 7, 'POX': 8, 'ERL': 9} # df['Class'] = df['Class'].map(mapping_class) # df = df[df['Class'] < 8] # return df, features, 'Class', 'yeast' # # # def load_waveform(): # columns = ['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','X11','X12','X13','X14','X15','X16','X17','X18','X19','X20','X21','Class'] # features = ['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','X11','X12','X13','X14','X15','X16','X17','X18','X19','X20','X21'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'waveform.data')) # df.columns = columns # df['Class'] = df['Class'].map({'y0': 0, 'y1': 1, 'y2': 2}).astype(int) # return df, features, 'Class', 'waveform' # # # def load_magic(): # columns = ['fLength', 'fWidth', 'fSize', 'fConc', 'fConc1', 'fAsym', 'fM3Long', 'fM3Trans', 'fAlpha', 'fDist', 'Class'] # features = ['fLength', 'fWidth', 'fSize', 'fConc', 'fConc1', 'fAsym', 'fM3Long', 'fM3Trans', 'fAlpha', 'fDist'] # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'magic04.data')) # df.columns = columns # for feature in features: # if np.min(df[feature]) < 0: # df[feature] += np.min(df[feature]) * (-1) # mapping_class = {'g': 0, 'h': 1} # df['Class'] = df['Class'].map(mapping_class).astype(int) # return df, features, 'Class', 'magic' # # # def load_shuttle(): # columns = ['feature1', 'feature2', 'feature3', 'feature4', 'feature5', 'feature6', 'feature7', 'feature8', # 'feature9', 'Class'] # features = ['feature1', 'feature2', 'feature3', 'feature4', 'feature5', 'feature6', 'feature7', 'feature8', # 'feature9'] # # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'shuttle.tst'), sep=' ') # df.columns = columns # for feature in features: # if np.min(df[feature]) < 0: # df[feature] += np.min(df[feature]) * (-1) # df = df[df['Class'] < 6] # df['Class'] = np.subtract(df['Class'], 1) # df = df.reset_index(drop=True) # # return df, features, 'Class', 'shuttle' # # # def load_shuttle_full(): # columns = ['feature1', 'feature2', 'feature3', 'feature4', 'feature5', 'feature6', 'feature7', 'feature8', # 'feature9', 'Class'] # features = ['feature1', 'feature2', 'feature3', 'feature4', 'feature5', 'feature6', 'feature7', 'feature8', # 'feature9'] # # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'shuttle_full.trn'), sep=' ') # df.columns = columns # for feature in features: # if np.min(df[feature]) < 0: # df[feature] += np.min(df[feature]) * (-1) # df = df[df['Class'] < 6] # df['Class'] = np.subtract(df['Class'], 1) # df = df.reset_index(drop=True) # # return df, features, 'Class', 'shuttleFull' # # # def load_nursery(): # columns = ['parents', 'has_nurs', 'form', 'children', 'housing', 'finance', 'social', 'health', 'Class'] # features = ['parents', 'has_nurs', 'form', 'children', 'housing', 'finance', 'social', 'health'] # # mapping_parents = {'usual': 0, 'pretentious': 1, 'great_pret': 2} # mapping_has_nurs = {'proper': 0, 'less_proper': 1, 'improper': 2, 'critical': 3, 'very_crit': 4} # mapping_form = {'complete': 0, 'completed': 1, 'incomplete': 2, 'foster': 3} # mapping_housing = {'convenient': 0, 'less_conv': 1, 'critical': 2} # mapping_finance = {'convenient': 0, 'inconv': 1} # mapping_social = {'nonprob': 0, 'slightly_prob': 1, 'problematic': 2} # mapping_health = {'recommended': 0, 'priority': 1, 'not_recom': 2} # mapping_class = {'not_recom': 1, 'recommend': 0, 'very_recom': 2, 'priority': 3, 'spec_prior': 4} # # df = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'nursery.data'), sep=',') # df = df.dropna() # df.columns = columns # # df['parents'] = df['parents'].map(mapping_parents) # df['has_nurs'] = df['has_nurs'].map(mapping_has_nurs) # df['form'] = df['form'].map(mapping_form) # df['children'] = df['children'].map(lambda x: 4 if x == 'more' else int(x)) # df['housing'] = df['housing'].map(mapping_housing) # df['finance'] = df['finance'].map(mapping_finance) # df['social'] = df['social'].map(mapping_social) # df['health'] = df['health'].map(mapping_health) # df['Class'] = df['Class'].map(mapping_class) # # df = df[df['Class'] != 0] # df['Class'] = np.subtract(df['Class'], 1) # df = df.reset_index(drop=True) # # return df, features, 'Class', 'nursery' # def load_aa_gent(): # label_col = 'RPE' # # 'H5060', 'H6070', 'Variabele A', # feature_cols = ['S1', 'S2', 'S3', 'S4', 'S5', 'H7080', 'H8090', 'H90100', 'H5060', 'H6070', 'Idnummer', # 'Aantal sprints', 'Gemiddelde snelheid (m/s)', 'Totaal tijd (s)', 'Totaal afstand (m)',# 'Variabele A', 'Variabele B', # 'Temperature', 'Humidity', 'Windspeed', 'Visibility', 'Weather Type', 'Variabele B']#, 'overall', 'phy', 'pac'] # #, 'ID', 'temperature', 'humidity', 'windspeed', 'visibility', 'weather_type'] # cols = feature_cols + [label_col] + ['Datum'] # df = pd.read_csv('aa_gent_with_player_features.csv') # df = df[cols] # df['Snelheid'] = df['Gemiddelde snelheid (m/s)'] # Kan evt weggelaten worden? # df['Variabele B'] = df['Variabele B'].fillna(df['Variabele B'].mean()) # df['Tijd'] = df['Totaal tijd (s)'] # df['Afstand'] = df['Totaal afstand (m)'] # df = df.drop(['Gemiddelde snelheid (m/s)', 'Totaal tijd (s)', 'Totaal afstand (m)'], axis=1) # print df.head(5) # df[label_col] = df[label_col].map({1: 2, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 9}).astype(int) # df = df.drop(['Datum'], axis=1) # # df = df.drop(['temperature', 'humidity', 'windspeed', 'visibility', 'weather_type'], axis=1) # df = pd.get_dummies(df, columns=['Idnummer']) # #df = pd.get_dummies(df, columns=['Weather Type']) # feature_cols = list(df.columns) # feature_cols.remove('RPE') # print feature_cols # return df, feature_cols, label_col, 'AA Gent' # df = pd.read_csv('data/aa_gent.csv', sep=";") # # label_col = 'RPE' # feature_cols = ['S1', 'S2', 'S3', 'S4', 'S5', 'HF-zone 80-90', # 'HF-zone 70-80', 'HF-zone 90-100', 'Aantal sprints', # 'Gem v', 'Tijd (s)', 'Afstand'] # print df[label_col].value_counts() # df = df[feature_cols + [label_col]] # df[label_col] = df[label_col].map({1: 2, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 9}).astype(int) # return df, feature_cols, label_col, 'AA Gent' def load_migbase(): migbase = pd.read_csv(os.path.join(os.sep.join(os.path.realpath(__file__).split(os.sep)[:-1]), 'migbase_noise20.csv'), sep=',') if 'Unnamed: 0' in migbase.columns: migbase = migbase.drop('Unnamed: 0', axis=1) #encoders = {} col_mapping = {} for col in migbase: # encoders[col] = LabelEncoder() # migbase[col] = encoders[col].fit_transform(migbase[col]) col_mapping[col] = col[:10] migbase = migbase.rename(index=str, columns=col_mapping) feature_cols = list(migbase.columns) feature_cols.remove('CLASS') return migbase, feature_cols, 'CLASS', 'migbase'
16,311
47.692537
143
py
GENESIM
GENESIM-master/data/__init__.py
""" Contains the data files and two python files that are responsible for loading them in easily. In `data.load_datasets`, a load function for each dataset must be written. In `data.load_all_datasets` python introspection is used to easily load in all datasets with a load function. Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. """
370
52
118
py
GENESIM
GENESIM-master/data/load_all_datasets.py
""" Uses python introspection to call all function in `data.load_datasets` Written by Gilles Vandewiele in commission of IDLab - INTEC from University Ghent. """ import data.load_datasets from inspect import getmembers, isfunction def load_all_datasets(): """ Uses python introspection to call all function in `data.load_datasets` **Returns** ----------- a list of loaded datasets """ datasets = [] for o in getmembers(data.load_datasets): if isfunction(o[1]): df, feature_cols, label_col, name = o[1]() datasets.append({'dataframe': df, 'feature_cols': feature_cols, 'label_col': label_col, 'name': name}) return datasets
696
26.88
114
py
WiFi-CSI-Sensing-Benchmark
WiFi-CSI-Sensing-Benchmark-main/NTU_Fi_model.py
import torch import torchvision import torch.nn as nn import torch.nn.functional as F from einops import rearrange, reduce, repeat from einops.layers.torch import Rearrange, Reduce class NTU_Fi_MLP(nn.Module): def __init__(self, num_classes): super(NTU_Fi_MLP,self).__init__() self.fc = nn.Sequential( nn.Linear(3*114*500,1024), nn.ReLU(), nn.Linear(1024,128), nn.ReLU(), ) self.classifier = nn.Linear(128,num_classes) def forward(self,x): x = x.view(-1,3*114*500) x = self.fc(x) x = self.classifier(x) return x class NTU_Fi_LeNet(nn.Module): def __init__(self, num_classes): super(NTU_Fi_LeNet,self).__init__() self.encoder = nn.Sequential( #input size: (3,114,500) nn.Conv2d(3,32,(15,23),stride=9), nn.ReLU(True), nn.Conv2d(32,64,3,stride=(1,3)), nn.ReLU(True), nn.Conv2d(64,96,(7,3),stride=(1,3)), nn.ReLU(True), ) self.fc = nn.Sequential( nn.Linear(96*4*6,128), nn.ReLU(), nn.Linear(128,num_classes) ) def forward(self,x): x = self.encoder(x) x = x.view(-1,96*4*6) out = self.fc(x) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_channels, out_channels, i_downsample=None, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0) self.batch_norm1 = nn.BatchNorm2d(out_channels) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1) self.batch_norm2 = nn.BatchNorm2d(out_channels) self.conv3 = nn.Conv2d(out_channels, out_channels*self.expansion, kernel_size=1, stride=1, padding=0) self.batch_norm3 = nn.BatchNorm2d(out_channels*self.expansion) self.i_downsample = i_downsample self.stride = stride self.relu = nn.ReLU() def forward(self, x): identity = x.clone() x = self.relu(self.batch_norm1(self.conv1(x))) x = self.relu(self.batch_norm2(self.conv2(x))) x = self.conv3(x) x = self.batch_norm3(x) #downsample if needed if self.i_downsample is not None: identity = self.i_downsample(identity) #add identity x+=identity x=self.relu(x) return x class Block(nn.Module): expansion = 1 def __init__(self, in_channels, out_channels, i_downsample=None, stride=1): super(Block, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=1, bias=False) self.batch_norm1 = nn.BatchNorm2d(out_channels) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, stride=stride, bias=False) self.batch_norm2 = nn.BatchNorm2d(out_channels) self.i_downsample = i_downsample self.stride = stride self.relu = nn.ReLU() def forward(self, x): identity = x.clone() x = self.relu(self.batch_norm1(self.conv1(x))) x = self.batch_norm2(self.conv2(x)) if self.i_downsample is not None: identity = self.i_downsample(identity) x += identity x = self.relu(x) return x class NTU_Fi_ResNet(nn.Module): def __init__(self, ResBlock, layer_list, num_classes): super(NTU_Fi_ResNet, self).__init__() self.reshape = nn.Sequential( nn.Conv2d(3,3,(15,23),stride=(3,9)), nn.ReLU(), nn.Conv2d(3,3,kernel_size=(3,23),stride=1), nn.ReLU() ) self.in_channels = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.batch_norm1 = nn.BatchNorm2d(64) self.relu = nn.ReLU() self.max_pool = nn.MaxPool2d(kernel_size = 3, stride=2, padding=1) self.layer1 = self._make_layer(ResBlock, layer_list[0], planes=64) self.layer2 = self._make_layer(ResBlock, layer_list[1], planes=128, stride=2) self.layer3 = self._make_layer(ResBlock, layer_list[2], planes=256, stride=2) self.layer4 = self._make_layer(ResBlock, layer_list[3], planes=512, stride=2) self.avgpool = nn.AdaptiveAvgPool2d((1,1)) self.fc = nn.Linear(512*ResBlock.expansion, num_classes) def forward(self, x): x = self.reshape(x) x = self.relu(self.batch_norm1(self.conv1(x))) x = self.max_pool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.reshape(x.shape[0], -1) x = self.fc(x) return x def _make_layer(self, ResBlock, blocks, planes, stride=1): ii_downsample = None layers = [] if stride != 1 or self.in_channels != planes*ResBlock.expansion: ii_downsample = nn.Sequential( nn.Conv2d(self.in_channels, planes*ResBlock.expansion, kernel_size=1, stride=stride), nn.BatchNorm2d(planes*ResBlock.expansion) ) layers.append(ResBlock(self.in_channels, planes, i_downsample=ii_downsample, stride=stride)) self.in_channels = planes*ResBlock.expansion for i in range(blocks-1): layers.append(ResBlock(self.in_channels, planes)) return nn.Sequential(*layers) def NTU_Fi_ResNet18(num_classes): return NTU_Fi_ResNet(Block, [2,2,2,2], num_classes = num_classes) def NTU_Fi_ResNet50(num_classes): return NTU_Fi_ResNet(Bottleneck, [3,4,6,3], num_classes = num_classes) def NTU_Fi_ResNet101(num_classes): return NTU_Fi_ResNet(Bottleneck, [3,4,23,3], num_classes = num_classes) class NTU_Fi_RNN(nn.Module): def __init__(self,num_classes): super(NTU_Fi_RNN,self).__init__() self.rnn = nn.RNN(342,64,num_layers=1) self.fc = nn.Linear(64,num_classes) def forward(self,x): x = x.view(-1,342,500) x = x.permute(2,0,1) _, ht = self.rnn(x) outputs = self.fc(ht[-1]) return outputs class NTU_Fi_GRU(nn.Module): def __init__(self,num_classes): super(NTU_Fi_GRU,self).__init__() self.gru = nn.GRU(342,64,num_layers=1) self.fc = nn.Linear(64,num_classes) def forward(self,x): x = x.view(-1,342,500) x = x.permute(2,0,1) _, ht = self.gru(x) outputs = self.fc(ht[-1]) return outputs class NTU_Fi_LSTM(nn.Module): def __init__(self,num_classes): super(NTU_Fi_LSTM,self).__init__() self.lstm = nn.LSTM(342,64,num_layers=1) self.fc = nn.Linear(64,num_classes) def forward(self,x): x = x.view(-1,342,500) x = x.permute(2,0,1) _, (ht,ct) = self.lstm(x) outputs = self.fc(ht[-1]) return outputs class NTU_Fi_BiLSTM(nn.Module): def __init__(self,num_classes): super(NTU_Fi_BiLSTM,self).__init__() self.lstm = nn.LSTM(342,64,num_layers=1,bidirectional=True) self.fc = nn.Linear(64,num_classes) def forward(self,x): x = x.view(-1,342,500) x = x.permute(2,0,1) _, (ht,ct) = self.lstm(x) outputs = self.fc(ht[-1]) return outputs class NTU_Fi_CNN_GRU(nn.Module): def __init__(self,num_classes): super(NTU_Fi_CNN_GRU,self).__init__() self.encoder = nn.Sequential( nn.Conv1d(1,16,12,6), nn.ReLU(), nn.MaxPool1d(2), nn.Conv1d(16,32,7,3), nn.ReLU(), ) self.mean = nn.AvgPool1d(32) self.gru = nn.GRU(8,128,num_layers=1) self.classifier = nn.Sequential( nn.Dropout(0.5), nn.Linear(128,num_classes), nn.Softmax(dim=1) ) def forward(self,x): batch_size = len(x) # batch x 3 x 114 x 500 x = x.view(batch_size,3*114,500) x = x.permute(0,2,1) # batch x 500 x 342 x = x.reshape(batch_size*500,1, 3*114) # (batch x 500) x 1 x 342 x = self.encoder(x) # (batch x 500) x 32 x 8 x = x.permute(0,2,1) x = self.mean(x) x = x.reshape(batch_size, 500, 8) # batch x 500 x 8 x = x.permute(1,0,2) # 500 x batch x 8 _, ht = self.gru(x) outputs = self.classifier(ht[-1]) return outputs class PatchEmbedding(nn.Module): def __init__(self, in_channels = 1, patch_size_w = 9, patch_size_h = 25, emb_size = 9*25, img_size = 342*500): self.patch_size_w = patch_size_w self.patch_size_h = patch_size_h super().__init__() self.projection = nn.Sequential( nn.Conv2d(in_channels, emb_size, kernel_size = (patch_size_w, patch_size_h), stride = (patch_size_w, patch_size_h)), Rearrange('b e (h) (w) -> b (h w) e'), ) self.cls_token = nn.Parameter(torch.randn(1,1,emb_size)) self.position = nn.Parameter(torch.randn(int(img_size/emb_size) + 1, emb_size)) def forward(self, x): x = x.view(-1,1,342,500) b, _, _, _ = x.shape x = self.projection(x) cls_tokens = repeat(self.cls_token, '() n e -> b n e', b=b) x = torch.cat([cls_tokens, x], dim=1) x += self.position return x class MultiHeadAttention(nn.Module): def __init__(self, emb_size = 225, num_heads = 5, dropout = 0.0): super().__init__() self.emb_size = emb_size self.num_heads = num_heads self.qkv = nn.Linear(emb_size, emb_size*3) self.att_drop = nn.Dropout(dropout) self.projection = nn.Linear(emb_size, emb_size) def forward(self, x, mask = None): qkv = rearrange(self.qkv(x), "b n (h d qkv) -> (qkv) b h n d", h=self.num_heads, qkv=3) queries, keys, values = qkv[0], qkv[1], qkv[2] energy = torch.einsum('bhqd, bhkd -> bhqk', queries, keys) if mask is not None: fill_value = torch.finfo(torch.float32).min energy.mask_fill(~mask, fill_value) scaling = self.emb_size ** (1/2) att = F.softmax(energy, dim=-1) / scaling att = self.att_drop(att) # sum up over the third axis out = torch.einsum('bhal, bhlv -> bhav ', att, values) out = rearrange(out, "b h n d -> b n (h d)") out = self.projection(out) return out class ResidualAdd(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x, **kwargs): res = x x = self.fn(x, **kwargs) x += res return x class FeedForwardBlock(nn.Sequential): def __init__(self, emb_size, expansion = 4, drop_p = 0.): super().__init__( nn.Linear(emb_size, expansion * emb_size), nn.GELU(), nn.Dropout(drop_p), nn.Linear(expansion * emb_size, emb_size), ) class TransformerEncoderBlock(nn.Sequential): def __init__(self, emb_size = 225, drop_p = 0.5, forward_expansion = 4, forward_drop_p = 0., ** kwargs): super().__init__( ResidualAdd(nn.Sequential( nn.LayerNorm(emb_size), MultiHeadAttention(emb_size, **kwargs), nn.Dropout(drop_p) )), ResidualAdd(nn.Sequential( nn.LayerNorm(emb_size), FeedForwardBlock( emb_size, expansion=forward_expansion, drop_p=forward_drop_p), nn.Dropout(drop_p) ) )) class TransformerEncoder(nn.Sequential): def __init__(self, depth = 1, **kwargs): super().__init__(*[TransformerEncoderBlock(**kwargs) for _ in range(depth)]) class ClassificationHead(nn.Sequential): def __init__(self, emb_size, num_classes): super().__init__( Reduce('b n e -> b e', reduction='mean'), nn.LayerNorm(emb_size), nn.Linear(emb_size, num_classes)) class NTU_Fi_ViT(nn.Sequential): def __init__(self, in_channels = 1, patch_size_w = 9, patch_size_h = 25, emb_size = 225, img_size = 342*500, depth = 1, *, num_classes, **kwargs): super().__init__( PatchEmbedding(in_channels, patch_size_w, patch_size_h, emb_size, img_size), TransformerEncoder(depth, emb_size=emb_size, **kwargs), ClassificationHead(emb_size, num_classes) )
13,031
32.674419
128
py
WiFi-CSI-Sensing-Benchmark
WiFi-CSI-Sensing-Benchmark-main/dataset.py
import numpy as np import glob import scipy.io as sio import torch from torch.utils.data import Dataset, DataLoader def UT_HAR_dataset(root_dir): data_list = glob.glob(root_dir+'/UT_HAR/data/*.csv') label_list = glob.glob(root_dir+'/UT_HAR/label/*.csv') WiFi_data = {} for data_dir in data_list: data_name = data_dir.split('/')[-1].split('.')[0] with open(data_dir, 'rb') as f: data = np.load(f) data = data.reshape(len(data),1,250,90) data_norm = (data - np.min(data)) / (np.max(data) - np.min(data)) WiFi_data[data_name] = torch.Tensor(data_norm) for label_dir in label_list: label_name = label_dir.split('/')[-1].split('.')[0] with open(label_dir, 'rb') as f: label = np.load(f) WiFi_data[label_name] = torch.Tensor(label) return WiFi_data # dataset: /class_name/xx.mat class CSI_Dataset(Dataset): """CSI dataset.""" def __init__(self, root_dir, modal='CSIamp', transform=None, few_shot=False, k=5, single_trace=True): """ Args: root_dir (string): Directory with all the images. modal (CSIamp/CSIphase): CSI data modal transform (callable, optional): Optional transform to be applied on a sample. """ self.root_dir = root_dir self.modal=modal self.transform = transform self.data_list = glob.glob(root_dir+'/*/*.mat') self.folder = glob.glob(root_dir+'/*/') self.category = {self.folder[i].split('/')[-2]:i for i in range(len(self.folder))} def __len__(self): return len(self.data_list) def __getitem__(self, idx): if torch.is_tensor(idx): idx = idx.tolist() sample_dir = self.data_list[idx] y = self.category[sample_dir.split('/')[-2]] x = sio.loadmat(sample_dir)[self.modal] # normalize x = (x - 42.3199)/4.9802 # sampling: 2000 -> 500 x = x[:,::4] x = x.reshape(3, 114, 500) if self.transform: x = self.transform(x) x = torch.FloatTensor(x) return x,y class Widar_Dataset(Dataset): def __init__(self,root_dir): self.root_dir = root_dir self.data_list = glob.glob(root_dir+'/*/*.csv') self.folder = glob.glob(root_dir+'/*/') self.category = {self.folder[i].split('/')[-2]:i for i in range(len(self.folder))} def __len__(self): return len(self.data_list) def __getitem__(self, idx): if torch.is_tensor(idx): idx = idx.tolist() sample_dir = self.data_list[idx] y = self.category[sample_dir.split('/')[-2]] x = np.genfromtxt(sample_dir, delimiter=',') # normalize x = (x - 0.0025)/0.0119 # reshape: 22,400 -> 22,20,20 x = x.reshape(22,20,20) # interpolate from 20x20 to 32x32 # x = self.reshape(x) x = torch.FloatTensor(x) return x,y
3,086
29.564356
105
py
WiFi-CSI-Sensing-Benchmark
WiFi-CSI-Sensing-Benchmark-main/UT_HAR_model.py
import torch import torchvision import torch.nn as nn import torch.nn.functional as F from einops import rearrange, reduce, repeat from einops.layers.torch import Rearrange, Reduce class UT_HAR_MLP(nn.Module): def __init__(self): super(UT_HAR_MLP,self).__init__() self.fc = nn.Sequential( nn.Linear(250*90,1024), nn.ReLU(), nn.Linear(1024,128), nn.ReLU(), nn.Linear(128,7) ) def forward(self,x): x = x.view(-1,250*90) x = self.fc(x) return x class UT_HAR_LeNet(nn.Module): def __init__(self): super(UT_HAR_LeNet,self).__init__() self.encoder = nn.Sequential( #input size: (1,250,90) nn.Conv2d(1,32,7,stride=(3,1)), nn.ReLU(True), nn.MaxPool2d(2), nn.Conv2d(32,64,(5,4),stride=(2,2),padding=(1,0)), nn.ReLU(True), nn.MaxPool2d(2), nn.Conv2d(64,96,(3,3),stride=1), nn.ReLU(True), nn.MaxPool2d(2) ) self.fc = nn.Sequential( nn.Linear(96*4*4,128), nn.ReLU(), nn.Linear(128,7) ) def forward(self,x): x = self.encoder(x) x = x.view(-1,96*4*4) out = self.fc(x) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_channels, out_channels, i_downsample=None, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0) self.batch_norm1 = nn.BatchNorm2d(out_channels) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1) self.batch_norm2 = nn.BatchNorm2d(out_channels) self.conv3 = nn.Conv2d(out_channels, out_channels*self.expansion, kernel_size=1, stride=1, padding=0) self.batch_norm3 = nn.BatchNorm2d(out_channels*self.expansion) self.i_downsample = i_downsample self.stride = stride self.relu = nn.ReLU() def forward(self, x): identity = x.clone() x = self.relu(self.batch_norm1(self.conv1(x))) x = self.relu(self.batch_norm2(self.conv2(x))) x = self.conv3(x) x = self.batch_norm3(x) if self.i_downsample is not None: identity = self.i_downsample(identity) x+=identity x=self.relu(x) return x class Block(nn.Module): expansion = 1 def __init__(self, in_channels, out_channels, i_downsample=None, stride=1): super(Block, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=1, bias=False) self.batch_norm1 = nn.BatchNorm2d(out_channels) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, stride=stride, bias=False) self.batch_norm2 = nn.BatchNorm2d(out_channels) self.i_downsample = i_downsample self.stride = stride self.relu = nn.ReLU() def forward(self, x): identity = x.clone() x = self.relu(self.batch_norm1(self.conv1(x))) x = self.batch_norm2(self.conv2(x)) if self.i_downsample is not None: identity = self.i_downsample(identity) x += identity x = self.relu(x) return x class UT_HAR_ResNet(nn.Module): def __init__(self, ResBlock, layer_list, num_classes=7): super(UT_HAR_ResNet, self).__init__() self.reshape = nn.Sequential( nn.Conv2d(1,3,7,stride=(3,1)), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(3,3,kernel_size=(10,11),stride=1), nn.ReLU() ) self.in_channels = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.batch_norm1 = nn.BatchNorm2d(64) self.relu = nn.ReLU() self.max_pool = nn.MaxPool2d(kernel_size = 3, stride=2, padding=1) self.layer1 = self._make_layer(ResBlock, layer_list[0], planes=64) self.layer2 = self._make_layer(ResBlock, layer_list[1], planes=128, stride=2) self.layer3 = self._make_layer(ResBlock, layer_list[2], planes=256, stride=2) self.layer4 = self._make_layer(ResBlock, layer_list[3], planes=512, stride=2) self.avgpool = nn.AdaptiveAvgPool2d((1,1)) self.fc = nn.Linear(512*ResBlock.expansion, num_classes) def forward(self, x): x = self.reshape(x) x = self.relu(self.batch_norm1(self.conv1(x))) x = self.max_pool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.reshape(x.shape[0], -1) x = self.fc(x) return x def _make_layer(self, ResBlock, blocks, planes, stride=1): ii_downsample = None layers = [] if stride != 1 or self.in_channels != planes*ResBlock.expansion: ii_downsample = nn.Sequential( nn.Conv2d(self.in_channels, planes*ResBlock.expansion, kernel_size=1, stride=stride), nn.BatchNorm2d(planes*ResBlock.expansion) ) layers.append(ResBlock(self.in_channels, planes, i_downsample=ii_downsample, stride=stride)) self.in_channels = planes*ResBlock.expansion for i in range(blocks-1): layers.append(ResBlock(self.in_channels, planes)) return nn.Sequential(*layers) def UT_HAR_ResNet18(): return UT_HAR_ResNet(Block, [2,2,2,2]) def UT_HAR_ResNet50(): return UT_HAR_ResNet(Bottleneck, [3,4,6,3]) def UT_HAR_ResNet101(): return UT_HAR_ResNet(Bottleneck, [3,4,23,3]) class UT_HAR_RNN(nn.Module): def __init__(self,hidden_dim=64): super(UT_HAR_RNN,self).__init__() self.rnn = nn.RNN(90,hidden_dim,num_layers=1) self.fc = nn.Linear(hidden_dim,7) def forward(self,x): x = x.view(-1,250,90) x = x.permute(1,0,2) _, ht = self.rnn(x) outputs = self.fc(ht[-1]) return outputs class UT_HAR_GRU(nn.Module): def __init__(self,hidden_dim=64): super(UT_HAR_GRU,self).__init__() self.gru = nn.GRU(90,hidden_dim,num_layers=1) self.fc = nn.Linear(hidden_dim,7) def forward(self,x): x = x.view(-1,250,90) x = x.permute(1,0,2) _, ht = self.gru(x) outputs = self.fc(ht[-1]) return outputs class UT_HAR_LSTM(nn.Module): def __init__(self,hidden_dim=64): super(UT_HAR_LSTM,self).__init__() self.lstm = nn.LSTM(90,hidden_dim,num_layers=1) self.fc = nn.Linear(hidden_dim,7) def forward(self,x): x = x.view(-1,250,90) x = x.permute(1,0,2) _, (ht,ct) = self.lstm(x) outputs = self.fc(ht[-1]) return outputs class UT_HAR_BiLSTM(nn.Module): def __init__(self,hidden_dim=64): super(UT_HAR_BiLSTM,self).__init__() self.lstm = nn.LSTM(90,hidden_dim,num_layers=1,bidirectional=True) self.fc = nn.Linear(hidden_dim,7) def forward(self,x): x = x.view(-1,250,90) x = x.permute(1,0,2) _, (ht,ct) = self.lstm(x) outputs = self.fc(ht[-1]) return outputs class UT_HAR_CNN_GRU(nn.Module): def __init__(self): super(UT_HAR_CNN_GRU,self).__init__() self.encoder = nn.Sequential( #input size: (250,90) nn.Conv1d(250,250,12,3), nn.ReLU(True), nn.Conv1d(250,250,5,2), nn.ReLU(True), nn.Conv1d(250,250,5,1) # 250 x 8 ) self.gru = nn.GRU(8,128,num_layers=1) self.classifier = nn.Sequential( nn.Dropout(0.5), nn.Linear(128,7), nn.Softmax(dim=1) ) def forward(self,x): # batch x 1 x 250 x 90 x = x.view(-1,250,90) x = self.encoder(x) # batch x 250 x 8 x = x.permute(1,0,2) # 250 x batch x 8 _, ht = self.gru(x) outputs = self.classifier(ht[-1]) return outputs class PatchEmbedding(nn.Module): def __init__(self, in_channels = 1, patch_size_w = 50, patch_size_h = 18, emb_size = 50*18, img_size = 250*90): self.patch_size_w = patch_size_w self.patch_size_h = patch_size_h super().__init__() self.projection = nn.Sequential( nn.Conv2d(in_channels, emb_size, kernel_size = (patch_size_w, patch_size_h), stride = (patch_size_w, patch_size_h)), Rearrange('b e (h) (w) -> b (h w) e'), ) self.cls_token = nn.Parameter(torch.randn(1,1,emb_size)) self.position = nn.Parameter(torch.randn(int(img_size/emb_size) + 1, emb_size)) def forward(self, x): b, _, _, _ = x.shape x = self.projection(x) cls_tokens = repeat(self.cls_token, '() n e -> b n e', b=b) x = torch.cat([cls_tokens, x], dim=1) x += self.position return x class MultiHeadAttention(nn.Module): def __init__(self, emb_size = 900, num_heads = 5, dropout = 0.0): super().__init__() self.emb_size = emb_size self.num_heads = num_heads self.qkv = nn.Linear(emb_size, emb_size*3) self.att_drop = nn.Dropout(dropout) self.projection = nn.Linear(emb_size, emb_size) def forward(self, x, mask = None): qkv = rearrange(self.qkv(x), "b n (h d qkv) -> (qkv) b h n d", h=self.num_heads, qkv=3) queries, keys, values = qkv[0], qkv[1], qkv[2] energy = torch.einsum('bhqd, bhkd -> bhqk', queries, keys) if mask is not None: fill_value = torch.finfo(torch.float32).min energy.mask_fill(~mask, fill_value) scaling = self.emb_size ** (1/2) att = F.softmax(energy, dim=-1) / scaling att = self.att_drop(att) # sum up over the third axis out = torch.einsum('bhal, bhlv -> bhav ', att, values) out = rearrange(out, "b h n d -> b n (h d)") out = self.projection(out) return out class ResidualAdd(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x, **kwargs): res = x x = self.fn(x, **kwargs) x += res return x class FeedForwardBlock(nn.Sequential): def __init__(self, emb_size, expansion = 4, drop_p = 0.): super().__init__( nn.Linear(emb_size, expansion * emb_size), nn.GELU(), nn.Dropout(drop_p), nn.Linear(expansion * emb_size, emb_size), ) class TransformerEncoderBlock(nn.Sequential): def __init__(self, emb_size = 900, drop_p = 0., forward_expansion = 4, forward_drop_p = 0., ** kwargs): super().__init__( ResidualAdd(nn.Sequential( nn.LayerNorm(emb_size), MultiHeadAttention(emb_size, **kwargs), nn.Dropout(drop_p) )), ResidualAdd(nn.Sequential( nn.LayerNorm(emb_size), FeedForwardBlock( emb_size, expansion=forward_expansion, drop_p=forward_drop_p), nn.Dropout(drop_p) ) )) class TransformerEncoder(nn.Sequential): def __init__(self, depth = 1, **kwargs): super().__init__(*[TransformerEncoderBlock(**kwargs) for _ in range(depth)]) class ClassificationHead(nn.Sequential): def __init__(self, emb_size = 900, n_classes = 7): super().__init__( Reduce('b n e -> b e', reduction='mean'), nn.LayerNorm(emb_size), nn.Linear(emb_size, n_classes)) class UT_HAR_ViT(nn.Sequential): def __init__(self, in_channels = 1, patch_size_w = 50, patch_size_h = 18, emb_size = 900, img_size = 250*90, depth = 1, n_classes = 7, **kwargs): super().__init__( PatchEmbedding(in_channels, patch_size_w, patch_size_h, emb_size, img_size), TransformerEncoder(depth, emb_size=emb_size, **kwargs), ClassificationHead(emb_size, n_classes) )
12,505
32.52815
128
py
WiFi-CSI-Sensing-Benchmark
WiFi-CSI-Sensing-Benchmark-main/run.py
import numpy as np import torch import torch.nn as nn import argparse from util import load_data_n_model def train(model, tensor_loader, num_epochs, learning_rate, criterion, device): model = model.to(device) optimizer = torch.optim.Adam(model.parameters(), lr = learning_rate) for epoch in range(num_epochs): model.train() epoch_loss = 0 epoch_accuracy = 0 for data in tensor_loader: inputs,labels = data inputs = inputs.to(device) labels = labels.to(device) labels = labels.type(torch.LongTensor) optimizer.zero_grad() outputs = model(inputs) outputs = outputs.to(device) outputs = outputs.type(torch.FloatTensor) loss = criterion(outputs,labels) loss.backward() optimizer.step() epoch_loss += loss.item() * inputs.size(0) predict_y = torch.argmax(outputs,dim=1).to(device) epoch_accuracy += (predict_y == labels.to(device)).sum().item() / labels.size(0) epoch_loss = epoch_loss/len(tensor_loader.dataset) epoch_accuracy = epoch_accuracy/len(tensor_loader) print('Epoch:{}, Accuracy:{:.4f},Loss:{:.9f}'.format(epoch+1, float(epoch_accuracy),float(epoch_loss))) return def test(model, tensor_loader, criterion, device): model.eval() test_acc = 0 test_loss = 0 for data in tensor_loader: inputs, labels = data inputs = inputs.to(device) labels.to(device) labels = labels.type(torch.LongTensor) outputs = model(inputs) outputs = outputs.type(torch.FloatTensor) outputs.to(device) loss = criterion(outputs,labels) predict_y = torch.argmax(outputs,dim=1).to(device) accuracy = (predict_y == labels.to(device)).sum().item() / labels.size(0) test_acc += accuracy test_loss += loss.item() * inputs.size(0) test_acc = test_acc/len(tensor_loader) test_loss = test_loss/len(tensor_loader.dataset) print("validation accuracy:{:.4f}, loss:{:.5f}".format(float(test_acc),float(test_loss))) return def main(): root = './Data/' parser = argparse.ArgumentParser('WiFi Imaging Benchmark') parser.add_argument('--dataset', choices = ['UT_HAR_data','NTU-Fi-HumanID','NTU-Fi_HAR','Widar']) parser.add_argument('--model', choices = ['MLP','LeNet','ResNet18','ResNet50','ResNet101','RNN','GRU','LSTM','BiLSTM', 'CNN+GRU','ViT']) args = parser.parse_args() train_loader, test_loader, model, train_epoch = load_data_n_model(args.dataset, args.model, root) criterion = nn.CrossEntropyLoss() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) train( model=model, tensor_loader= train_loader, num_epochs= train_epoch, learning_rate=1e-3, criterion=criterion, device=device ) test( model=model, tensor_loader=test_loader, criterion=criterion, device= device ) return if __name__ == "__main__": main()
3,185
33.258065
140
py
WiFi-CSI-Sensing-Benchmark
WiFi-CSI-Sensing-Benchmark-main/self_supervised_model.py
import torch import torch.nn as nn from einops import rearrange, reduce, repeat from einops.layers.torch import Rearrange, Reduce import torch.nn.functional as F class MLP_Parrallel(nn.Module): def __init__(self): super(MLP_Parrallel, self).__init__() self.encoder_1 = MLP_encoder() self.encoder_2 = MLP_encoder() self.classifier = nn.Linear(128,14) def forward(self, x1, x2, flag='unsupervised'): if flag == 'supervised': x1 = self.encoder_1(x1, flag=flag) x2 = self.encoder_2(x2, flag=flag) y1 = self.classifier(x1) y2 = self.classifier(x2) return y1, y2 x1 = self.encoder_1(x1) x2 = self.encoder_2(x2) return x1, x2 class MLP_encoder(nn.Module): def __init__(self,hidden_states = 256): super(MLP_encoder, self).__init__() self.encoder = nn.Sequential( nn.Linear(3*114*500,1024), nn.ReLU(), nn.Linear(1024,128), nn.ReLU(), ) self.mapping = nn.Linear(128, hidden_states) self.bn = nn.BatchNorm1d(hidden_states) def forward(self, x, flag='unsupervised'): x = x.view(-1, 3*114*500) x = self.encoder(x) if flag == 'supervised': return x else: x = self.bn(self.mapping(x)) return x class CNN_Parrallel(nn.Module): def __init__(self): super(CNN_Parrallel, self).__init__() self.encoder_1 = CNN_encoder() self.encoder_2 = CNN_encoder() self.classifier = nn.Sequential( nn.Linear(96*4*6,128), nn.ReLU(), nn.Linear(128,14) ) def forward(self, x1, x2, flag='unsupervised'): if flag == 'supervised': x1 = self.encoder_1(x1, flag=flag) x2 = self.encoder_2(x2, flag=flag) y1 = self.classifier(x1) y2 = self.classifier(x2) return y1, y2 x1 = self.encoder_1(x1) x2 = self.encoder_2(x2) return x1, x2 class CNN_encoder(nn.Module): def __init__(self,hidden_states = 256): super(CNN_encoder, self).__init__() self.encoder = nn.Sequential( #input size: (3,114,500) nn.Conv2d(3,32,(15,23),stride=9), nn.ReLU(True), nn.Conv2d(32,64,3,stride=(1,3)), nn.ReLU(True), nn.Conv2d(64,96,(7,3),stride=(1,3)), nn.ReLU(True), ) self.mapping = nn.Linear(96*4*6, hidden_states) self.bn = nn.BatchNorm1d(hidden_states) self.conv_channel = 96 self.conv_feat_num = 24 def forward(self, x, flag='unsupervised'): x = self.encoder(x) # classifier x = x.view(-1, self.conv_channel*self.conv_feat_num) if flag == 'supervised': return x else: x = self.bn(self.mapping(x)) return x class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_channels, out_channels, i_downsample=None, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0) self.batch_norm1 = nn.BatchNorm2d(out_channels) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1) self.batch_norm2 = nn.BatchNorm2d(out_channels) self.conv3 = nn.Conv2d(out_channels, out_channels*self.expansion, kernel_size=1, stride=1, padding=0) self.batch_norm3 = nn.BatchNorm2d(out_channels*self.expansion) self.i_downsample = i_downsample self.stride = stride self.relu = nn.ReLU() def forward(self, x): identity = x.clone() x = self.relu(self.batch_norm1(self.conv1(x))) x = self.relu(self.batch_norm2(self.conv2(x))) x = self.conv3(x) x = self.batch_norm3(x) #downsample if needed if self.i_downsample is not None: identity = self.i_downsample(identity) #add identity x+=identity x=self.relu(x) return x class Block(nn.Module): expansion = 1 def __init__(self, in_channels, out_channels, i_downsample=None, stride=1): super(Block, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=1, bias=False) self.batch_norm1 = nn.BatchNorm2d(out_channels) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, stride=stride, bias=False) self.batch_norm2 = nn.BatchNorm2d(out_channels) self.i_downsample = i_downsample self.stride = stride self.relu = nn.ReLU() def forward(self, x): identity = x.clone() x = self.relu(self.batch_norm1(self.conv1(x))) x = self.batch_norm2(self.conv2(x)) if self.i_downsample is not None: identity = self.i_downsample(identity) x += identity x = self.relu(x) return x class ResNet_Parrallel(nn.Module): def __init__(self,ResBlock, layer_list): super(ResNet_Parrallel, self).__init__() self.encoder_1 = ResNet_encoder(ResBlock, layer_list) self.encoder_2 = ResNet_encoder(ResBlock, layer_list) # output: after BN self.classifier = nn.Linear(512*ResBlock.expansion, 14) def forward(self, x1, x2, flag='unsupervised'): if flag == 'supervised': x1 = self.encoder_1(x1, flag=flag) x2 = self.encoder_2(x2, flag=flag) y1 = self.classifier(x1) y2 = self.classifier(x2) return y1, y2 x1 = self.encoder_1(x1) x2 = self.encoder_2(x2) return x1, x2 class ResNet_encoder(nn.Module): def __init__(self, ResBlock, layer_list, hidden_states = 256): super(ResNet_encoder, self).__init__() self.reshape = nn.Sequential( nn.Conv2d(3,3,(15,23),stride=(3,9)), nn.ReLU(), nn.Conv2d(3,3,kernel_size=(3,23),stride=1), nn.ReLU() ) self.in_channels = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.batch_norm1 = nn.BatchNorm2d(64) self.relu = nn.ReLU() self.max_pool = nn.MaxPool2d(kernel_size = 3, stride=2, padding=1) self.layer1 = self._make_layer(ResBlock, layer_list[0], planes=64) self.layer2 = self._make_layer(ResBlock, layer_list[1], planes=128, stride=2) self.layer3 = self._make_layer(ResBlock, layer_list[2], planes=256, stride=2) self.layer4 = self._make_layer(ResBlock, layer_list[3], planes=512, stride=2) self.avgpool = nn.AdaptiveAvgPool2d((1,1)) self.mapping = nn.Linear(512*ResBlock.expansion, hidden_states) self.bn = nn.BatchNorm1d(hidden_states) def forward(self, x, flag='unsupervised'): x = self.reshape(x) x = self.relu(self.batch_norm1(self.conv1(x))) x = self.max_pool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) # classifier x = x.reshape(x.shape[0], -1) if flag == 'supervised': return x else: x = self.bn(self.mapping(x)) return x def _make_layer(self, ResBlock, blocks, planes, stride=1): ii_downsample = None layers = [] if stride != 1 or self.in_channels != planes*ResBlock.expansion: ii_downsample = nn.Sequential( nn.Conv2d(self.in_channels, planes*ResBlock.expansion, kernel_size=1, stride=stride), nn.BatchNorm2d(planes*ResBlock.expansion) ) layers.append(ResBlock(self.in_channels, planes, i_downsample=ii_downsample, stride=stride)) self.in_channels = planes*ResBlock.expansion for i in range(blocks-1): layers.append(ResBlock(self.in_channels, planes)) return nn.Sequential(*layers) def ResNet18_Parrallel(): return ResNet_Parrallel(Block, [2,2,2,2]) def ResNet50_Parrallel(): return ResNet_Parrallel(Bottleneck, [3,4,6,3]) def ResNet101_Parrallel(): return ResNet_Parrallel(Bottleneck, [3,4,23,3]) class RNN_Parrallel(nn.Module): def __init__(self): super(RNN_Parrallel, self).__init__() self.encoder_1 = RNN_encoder() self.encoder_2 = RNN_encoder() self.classifier = nn.Linear(64,14) def forward(self, x1, x2, flag='unsupervised'): if flag == 'supervised': x1 = self.encoder_1(x1, flag=flag) x2 = self.encoder_2(x2, flag=flag) y1 = self.classifier(x1) y2 = self.classifier(x2) return y1, y2 x1 = self.encoder_1(x1) x2 = self.encoder_2(x2) return x1, x2 class RNN_encoder(nn.Module): def __init__(self,hidden_states = 256): super(RNN_encoder, self).__init__() self.encoder = nn.RNN(342,64,num_layers=1) self.mapping = nn.Linear(64, hidden_states) self.bn = nn.BatchNorm1d(hidden_states) def forward(self, x, flag='unsupervised'): x = x.view(-1,342,500) x = x.permute(2,0,1) _, ht = self.encoder(x) # classifier x = ht[-1] if flag == 'supervised': return x else: x = self.bn(self.mapping(x)) return x class GRU_Parrallel(nn.Module): def __init__(self): super(GRU_Parrallel, self).__init__() self.encoder_1 = GRU_encoder() self.encoder_2 = GRU_encoder() self.classifier = nn.Linear(64,14) def forward(self, x1, x2, flag='unsupervised'): if flag == 'supervised': x1 = self.encoder_1(x1, flag=flag) x2 = self.encoder_2(x2, flag=flag) y1 = self.classifier(x1) y2 = self.classifier(x2) return y1, y2 x1 = self.encoder_1(x1) x2 = self.encoder_2(x2) return x1, x2 class GRU_encoder(nn.Module): def __init__(self,hidden_states = 256): super(GRU_encoder, self).__init__() self.encoder = nn.GRU(342,64,num_layers=1) self.mapping = nn.Linear(64, hidden_states) self.bn = nn.BatchNorm1d(hidden_states) def forward(self, x, flag='unsupervised'): x = x.view(-1,342,500) x = x.permute(2,0,1) _, ht = self.encoder(x) # classifier x = ht[-1] if flag == 'supervised': return x else: x = self.bn(self.mapping(x)) return x class LSTM_Parrallel(nn.Module): def __init__(self): super(LSTM_Parrallel, self).__init__() self.encoder_1 = LSTM_encoder() self.encoder_2 = LSTM_encoder() self.classifier = nn.Linear(64,14) def forward(self, x1, x2, flag='unsupervised'): if flag == 'supervised': x1 = self.encoder_1(x1, flag=flag) x2 = self.encoder_2(x2, flag=flag) y1 = self.classifier(x1) y2 = self.classifier(x2) return y1, y2 x1 = self.encoder_1(x1) x2 = self.encoder_2(x2) return x1, x2 class LSTM_encoder(nn.Module): def __init__(self,hidden_states = 256): super(LSTM_encoder, self).__init__() self.encoder = nn.LSTM(342,64,num_layers=1) self.mapping = nn.Linear(64, hidden_states) self.bn = nn.BatchNorm1d(hidden_states) def forward(self, x, flag='unsupervised'): x = x.view(-1,342,500) x = x.permute(2,0,1) _, (ht,ct) = self.encoder(x) # classifier x = ht[-1] if flag == 'supervised': return x else: x = self.bn(self.mapping(x)) return x class BiLSTM_Parrallel(nn.Module): def __init__(self): super(BiLSTM_Parrallel, self).__init__() self.encoder_1 = BiLSTM_encoder() self.encoder_2 = BiLSTM_encoder() self.classifier = nn.Linear(64,14) def forward(self, x1, x2, flag='unsupervised'): if flag == 'supervised': x1 = self.encoder_1(x1, flag=flag) x2 = self.encoder_2(x2, flag=flag) y1 = self.classifier(x1) y2 = self.classifier(x2) return y1, y2 x1 = self.encoder_1(x1) x2 = self.encoder_2(x2) return x1, x2 class BiLSTM_encoder(nn.Module): def __init__(self,hidden_states = 256): super(BiLSTM_encoder, self).__init__() self.encoder = nn.LSTM(342,64,num_layers=1,bidirectional=True) self.mapping = nn.Linear(64, hidden_states) self.bn = nn.BatchNorm1d(hidden_states) def forward(self, x, flag='unsupervised'): x = x.view(-1,342,500) x = x.permute(2,0,1) _, (ht,ct) = self.encoder(x) # classifier x = ht[-1] if flag == 'supervised': return x else: x = self.bn(self.mapping(x)) return x class CNN_GRU_Parrallel(nn.Module): def __init__(self): super(CNN_GRU_Parrallel, self).__init__() self.encoder_1 = CNN_GRU_encoder() self.encoder_2 = CNN_GRU_encoder() self.classifier = nn.Sequential( nn.Dropout(0.5), nn.Linear(128,14), nn.Softmax(dim=1) ) def forward(self, x1, x2, flag='unsupervised'): if flag == 'supervised': x1 = self.encoder_1(x1, flag=flag) x2 = self.encoder_2(x2, flag=flag) y1 = self.classifier(x1) y2 = self.classifier(x2) return y1, y2 x1 = self.encoder_1(x1) x2 = self.encoder_2(x2) return x1, x2 class CNN_GRU_encoder(nn.Module): def __init__(self,hidden_states = 256): super(CNN_GRU_encoder, self).__init__() self.encoder = nn.Sequential( nn.Conv1d(1,16,12,6), nn.ReLU(), nn.MaxPool1d(2), nn.Conv1d(16,32,7,3), nn.ReLU(), ) self.mean = nn.AvgPool1d(32) self.gru = nn.GRU(8,128,num_layers=1) self.mapping = nn.Linear(128, hidden_states) self.bn = nn.BatchNorm1d(hidden_states) def forward(self, x, flag='unsupervised'): batch_size = len(x) # batch x 3 x 114 x 500 x = x.view(batch_size,3*114,500) x = x.permute(0,2,1) # batch x 500 x 342 x = x.reshape(batch_size*500,1, 3*114) # (batch x 500) x 1 x 342 x = self.encoder(x) # (batch x 500) x 32 x 8 # try 32, (32x8) x = x.permute(0,2,1) x = self.mean(x) x = x.reshape(batch_size, 500, 8) # batch x 500 x 8 x = x.permute(1,0,2) # 500 x batch x 8 _, ht = self.gru(x) # classifier x = ht[-1] if flag == 'supervised': return x else: x = self.bn(self.mapping(x)) return x class PatchEmbedding(nn.Module): def __init__(self, in_channels = 1, patch_size_w = 9, patch_size_h = 25, emb_size = 9*25, img_size = 342*500): self.patch_size_w = patch_size_w self.patch_size_h = patch_size_h super().__init__() self.projection = nn.Sequential( nn.Conv2d(in_channels, emb_size, kernel_size = (patch_size_w, patch_size_h), stride = (patch_size_w, patch_size_h)), Rearrange('b e (h) (w) -> b (h w) e'), ) self.cls_token = nn.Parameter(torch.randn(1,1,emb_size)) self.position = nn.Parameter(torch.randn(int(img_size/emb_size) + 1, emb_size)) def forward(self, x): x = x.view(-1,1,342,500) b, _, _, _ = x.shape x = self.projection(x) cls_tokens = repeat(self.cls_token, '() n e -> b n e', b=b) x = torch.cat([cls_tokens, x], dim=1) x += self.position return x class MultiHeadAttention(nn.Module): def __init__(self, emb_size = 225, num_heads = 5, dropout = 0.0): super().__init__() self.emb_size = emb_size self.num_heads = num_heads self.qkv = nn.Linear(emb_size, emb_size*3) self.att_drop = nn.Dropout(dropout) self.projection = nn.Linear(emb_size, emb_size) def forward(self, x, mask = None): qkv = rearrange(self.qkv(x), "b n (h d qkv) -> (qkv) b h n d", h=self.num_heads, qkv=3) queries, keys, values = qkv[0], qkv[1], qkv[2] energy = torch.einsum('bhqd, bhkd -> bhqk', queries, keys) if mask is not None: fill_value = torch.finfo(torch.float32).min energy.mask_fill(~mask, fill_value) scaling = self.emb_size ** (1/2) att = F.softmax(energy, dim=-1) / scaling att = self.att_drop(att) # sum up over the third axis out = torch.einsum('bhal, bhlv -> bhav ', att, values) out = rearrange(out, "b h n d -> b n (h d)") out = self.projection(out) return out class ResidualAdd(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x, **kwargs): res = x x = self.fn(x, **kwargs) x += res return x class FeedForwardBlock(nn.Sequential): def __init__(self, emb_size, expansion = 4, drop_p = 0.): super().__init__( nn.Linear(emb_size, expansion * emb_size), nn.GELU(), nn.Dropout(drop_p), nn.Linear(expansion * emb_size, emb_size), ) class TransformerEncoderBlock(nn.Sequential): def __init__(self, emb_size = 225, drop_p = 0.5, forward_expansion = 4, forward_drop_p = 0., ** kwargs): super().__init__( ResidualAdd(nn.Sequential( nn.LayerNorm(emb_size), MultiHeadAttention(emb_size, **kwargs), nn.Dropout(drop_p) )), ResidualAdd(nn.Sequential( nn.LayerNorm(emb_size), FeedForwardBlock( emb_size, expansion=forward_expansion, drop_p=forward_drop_p), nn.Dropout(drop_p) ) )) class TransformerEncoder(nn.Sequential): def __init__(self, depth = 1, **kwargs): super().__init__(*[TransformerEncoderBlock(**kwargs) for _ in range(depth)]) class ClassificationHead(nn.Sequential): def __init__(self, emb_size, num_classes): super().__init__( Reduce('b n e -> b e', reduction='mean'), nn.LayerNorm(emb_size), nn.Linear(emb_size, num_classes)) class ViTEncoder(nn.Sequential): def __init__(self, in_channels = 1, patch_size_w = 9, patch_size_h = 25, emb_size = 225, img_size = 342*500, depth = 1, *, num_classes = 14, **kwargs): super().__init__( PatchEmbedding(in_channels, patch_size_w, patch_size_h, emb_size, img_size), TransformerEncoder(depth, emb_size=emb_size, **kwargs) ) class ViT_Parrallel(nn.Module): def __init__(self, emb_size = 225, num_classes = 14, ): super(ViT_Parrallel, self).__init__() self.encoder_1 = ViT_encoder() self.encoder_2 = ViT_encoder() self.classifier = ClassificationHead(emb_size, num_classes) def forward(self, x1, x2, flag='unsupervised'): if flag == 'supervised': x1 = self.encoder_1(x1, flag=flag) x2 = self.encoder_2(x2, flag=flag) y1 = self.classifier(x1) y2 = self.classifier(x2) return y1, y2 x1 = self.encoder_1(x1) x2 = self.encoder_2(x2) return x1, x2 class ViT_encoder(nn.Module): def __init__(self,hidden_states = 256): super(ViT_encoder, self).__init__() self.encoder = ViTEncoder() self.mapping = nn.Sequential( Reduce('b n e -> b e', reduction='mean'), nn.Linear(225, hidden_states) ) self.bn = nn.BatchNorm1d(hidden_states) def forward(self, x, flag='unsupervised'): x = self.encoder(x) if flag == 'supervised': return x else: x = self.bn(self.mapping(x)) return x
20,995
30.763994
128
py
WiFi-CSI-Sensing-Benchmark
WiFi-CSI-Sensing-Benchmark-main/util.py
from dataset import * from UT_HAR_model import * from NTU_Fi_model import * from widar_model import * from self_supervised_model import * import torch def load_data_n_model(dataset_name, model_name, root): classes = {'UT_HAR_data':7,'NTU-Fi-HumanID':14,'NTU-Fi_HAR':6,'Widar':22} if dataset_name == 'UT_HAR_data': print('using dataset: UT-HAR DATA') data = UT_HAR_dataset(root) train_set = torch.utils.data.TensorDataset(data['X_train'],data['y_train']) test_set = torch.utils.data.TensorDataset(torch.cat((data['X_val'],data['X_test']),0),torch.cat((data['y_val'],data['y_test']),0)) train_loader = torch.utils.data.DataLoader(train_set,batch_size=64,shuffle=True, drop_last=True) # drop_last=True test_loader = torch.utils.data.DataLoader(test_set,batch_size=256,shuffle=False) if model_name == 'MLP': print("using model: MLP") model = UT_HAR_MLP() train_epoch = 200 elif model_name == 'LeNet': print("using model: LeNet") model = UT_HAR_LeNet() train_epoch = 200 #40 elif model_name == 'ResNet18': print("using model: ResNet18") model = UT_HAR_ResNet18() train_epoch = 200 #70 elif model_name == 'ResNet50': print("using model: ResNet50") model = UT_HAR_ResNet50() train_epoch = 200 #100 elif model_name == 'ResNet101': print("using model: ResNet101") model = UT_HAR_ResNet101() train_epoch = 200 #100 elif model_name == 'RNN': print("using model: RNN") model = UT_HAR_RNN() train_epoch = 3000 elif model_name == 'GRU': print("using model: GRU") model = UT_HAR_GRU() train_epoch = 200 elif model_name == 'LSTM': print("using model: LSTM") model = UT_HAR_LSTM() train_epoch = 200 elif model_name == 'BiLSTM': print("using model: BiLSTM") model = UT_HAR_BiLSTM() train_epoch = 200 elif model_name == 'CNN+GRU': print("using model: CNN+GRU") model = UT_HAR_CNN_GRU() train_epoch = 200 #20 elif model_name == 'ViT': print("using model: ViT") model = UT_HAR_ViT() train_epoch = 200 #100 return train_loader, test_loader, model, train_epoch elif dataset_name == 'NTU-Fi-HumanID': print('using dataset: NTU-Fi-HumanID') num_classes = classes['NTU-Fi-HumanID'] train_loader = torch.utils.data.DataLoader(dataset=CSI_Dataset(root + 'NTU-Fi-HumanID/test_amp/'), batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=CSI_Dataset(root + 'NTU-Fi-HumanID/train_amp/'), batch_size=64, shuffle=False) if model_name == 'MLP': print("using model: MLP") model = NTU_Fi_MLP(num_classes) train_epoch = 50 #15 elif model_name == 'LeNet': print("using model: LeNet") model = NTU_Fi_LeNet(num_classes) train_epoch = 50 #20 elif model_name == 'ResNet18': print("using model: ResNet18") model = NTU_Fi_ResNet18(num_classes) train_epoch = 50 #30 elif model_name == 'ResNet50': print("using model: ResNet50") model = NTU_Fi_ResNet50(num_classes) train_epoch = 50 #40 elif model_name == 'ResNet101': print("using model: ResNet101") model = NTU_Fi_ResNet101(num_classes) train_epoch = 50 elif model_name == 'RNN': print("using model: RNN") model = NTU_Fi_RNN(num_classes) train_epoch = 75 elif model_name == 'GRU': print("using model: GRU") model = NTU_Fi_GRU(num_classes) train_epoch = 50 #40 elif model_name == 'LSTM': print("using model: LSTM") model = NTU_Fi_LSTM(num_classes) train_epoch = 50 elif model_name == 'BiLSTM': print("using model: BiLSTM") model = NTU_Fi_BiLSTM(num_classes) train_epoch = 50 elif model_name == 'CNN+GRU': print("using model: CNN+GRU") model = NTU_Fi_CNN_GRU(num_classes) train_epoch = 200 #20 elif model_name == 'ViT': print("using model: ViT") model = NTU_Fi_ViT(num_classes=num_classes) train_epoch = 50 return train_loader, test_loader, model, train_epoch elif dataset_name == 'NTU-Fi_HAR': print('using dataset: NTU-Fi_HAR') num_classes = classes['NTU-Fi_HAR'] train_loader = torch.utils.data.DataLoader(dataset=CSI_Dataset(root + 'NTU-Fi_HAR/train_amp/'), batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=CSI_Dataset(root + 'NTU-Fi_HAR/test_amp/'), batch_size=64, shuffle=False) if model_name == 'MLP': print("using model: MLP") model = NTU_Fi_MLP(num_classes) train_epoch = 30 #10 elif model_name == 'LeNet': print("using model: LeNet") model = NTU_Fi_LeNet(num_classes) train_epoch = 30 #10 elif model_name == 'ResNet18': print("using model: ResNet18") model = NTU_Fi_ResNet18(num_classes) train_epoch = 30 elif model_name == 'ResNet50': print("using model: ResNet50") model = NTU_Fi_ResNet50(num_classes) train_epoch = 30 #40 elif model_name == 'ResNet101': print("using model: ResNet101") model = NTU_Fi_ResNet101(num_classes) train_epoch = 30 elif model_name == 'RNN': print("using model: RNN") model = NTU_Fi_RNN(num_classes) train_epoch = 70 elif model_name == 'GRU': print("using model: GRU") model = NTU_Fi_GRU(num_classes) train_epoch = 30 #20 elif model_name == 'LSTM': print("using model: LSTM") model = NTU_Fi_LSTM(num_classes) train_epoch = 30 #20 elif model_name == 'BiLSTM': print("using model: BiLSTM") model = NTU_Fi_BiLSTM(num_classes) train_epoch = 30 #20 elif model_name == 'CNN+GRU': print("using model: CNN+GRU") model = NTU_Fi_CNN_GRU(num_classes) train_epoch = 100 #20 elif model_name == 'ViT': print("using model: ViT") model = NTU_Fi_ViT(num_classes=num_classes) train_epoch = 30 return train_loader, test_loader, model, train_epoch elif dataset_name == 'Widar': print('using dataset: Widar') num_classes = classes['Widar'] train_loader = torch.utils.data.DataLoader(dataset=Widar_Dataset(root + 'Widardata/train/'), batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=Widar_Dataset(root + 'Widardata/test/'), batch_size=128, shuffle=False) if model_name == 'MLP': print("using model: MLP") model = Widar_MLP(num_classes) train_epoch = 30 #20 elif model_name == 'LeNet': print("using model: LeNet") model = Widar_LeNet(num_classes) train_epoch = 100 #40 elif model_name == 'ResNet18': print("using model: ResNet18") model = Widar_ResNet18(num_classes) train_epoch = 100 elif model_name == 'ResNet50': print("using model: ResNet50") model = Widar_ResNet50(num_classes) train_epoch = 100 #40 elif model_name == 'ResNet101': print("using model: ResNet101") model = Widar_ResNet101(num_classes) train_epoch = 100 elif model_name == 'RNN': print("using model: RNN") model = Widar_RNN(num_classes) train_epoch = 500 elif model_name == 'GRU': print("using model: GRU") model = Widar_GRU(num_classes) train_epoch = 200 elif model_name == 'LSTM': print("using model: LSTM") model = Widar_LSTM(num_classes) train_epoch = 200 #20 elif model_name == 'BiLSTM': print("using model: BiLSTM") model = Widar_BiLSTM(num_classes) train_epoch = 200 elif model_name == 'CNN+GRU': print("using model: CNN+GRU") model = Widar_CNN_GRU(num_classes) train_epoch = 200 #20 elif model_name == 'ViT': print("using model: ViT") model = Widar_ViT(num_classes=num_classes) train_epoch = 200 return train_loader, test_loader, model, train_epoch def load_unsupervised_data_n_model(model_name,root): HAR_train_dataset=CSI_Dataset(root+'NTU-Fi_HAR/train_amp/') HAR_test_dataset=CSI_Dataset(root+'NTU-Fi_HAR/test_amp/') unsupervised_train_dataset = torch.utils.data.ConcatDataset([HAR_train_dataset,HAR_test_dataset]) unsupervised_train_loader = torch.utils.data.DataLoader(dataset=unsupervised_train_dataset, batch_size=64, shuffle=True) supervised_train_loader = torch.utils.data.DataLoader(dataset=CSI_Dataset(root+'NTU-Fi-HumanID/test_amp/'), batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=CSI_Dataset(root+'NTU-Fi-HumanID/train_amp/'), batch_size=64, shuffle=False) if model_name == 'MLP': print("using model: MLP_Parrallel") model = MLP_Parrallel() elif model_name == 'LeNet': print("using model: CNN_Parrallel") model = CNN_Parrallel() elif model_name == 'ResNet18': print("using model: ResNet18_Parrallel") model = ResNet18_Parrallel() elif model_name == 'ResNet50': print("using model: ResNet50_Parralle") model = ResNet50_Parrallel() elif model_name == 'ResNet101': print("using model: ResNet101_Parrallel") model = ResNet101_Parrallel() elif model_name == 'RNN': print("using model: RNN_Parrallel") model = RNN_Parrallel() elif model_name == 'GRU': print("using model: GRU_Parrallel") model = GRU_Parrallel() elif model_name == 'LSTM': print("using model: LSTM_Parrallel") model = LSTM_Parrallel() elif model_name == 'BiLSTM': print("using model: BiLSTM_Parrallel") model = BiLSTM_Parrallel() elif model_name == 'CNN+GRU': print("using model: CNN_GRU_Parrallel") model = CNN_GRU_Parrallel() elif model_name == 'ViT': print("using model: ViT_Parrallel") model = ViT_Parrallel() return unsupervised_train_loader, supervised_train_loader, test_loader, model
10,985
41.416988
140
py
WiFi-CSI-Sensing-Benchmark
WiFi-CSI-Sensing-Benchmark-main/widar_model.py
import torch import torchvision import torch.nn as nn import torch.nn.functional as F from einops import rearrange, reduce, repeat from einops.layers.torch import Rearrange, Reduce class Widar_MLP(nn.Module): def __init__(self, num_classes): super(Widar_MLP,self).__init__() self.fc = nn.Sequential( nn.Linear(22*20*20,1024), nn.ReLU(), nn.Linear(1024,128), nn.ReLU(), nn.Linear(128,num_classes) ) def forward(self,x): x = x.view(-1,22*20*20) x = self.fc(x) return x class Widar_LeNet(nn.Module): def __init__(self, num_classes): super(Widar_LeNet,self).__init__() self.encoder = nn.Sequential( #input size: (22,20,20) nn.Conv2d(22,32,6,stride=2), nn.ReLU(True), nn.Conv2d(32,64,3,stride=1), nn.ReLU(True), nn.Conv2d(64,96,3,stride=1), nn.ReLU(True), ) self.fc = nn.Sequential( nn.Linear(96*4*4,128), nn.ReLU(), nn.Linear(128,num_classes) ) def forward(self,x): x = self.encoder(x) x = x.view(-1,96*4*4) out = self.fc(x) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_channels, out_channels, i_downsample=None, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0) self.batch_norm1 = nn.BatchNorm2d(out_channels) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1) self.batch_norm2 = nn.BatchNorm2d(out_channels) self.conv3 = nn.Conv2d(out_channels, out_channels*self.expansion, kernel_size=1, stride=1, padding=0) self.batch_norm3 = nn.BatchNorm2d(out_channels*self.expansion) self.i_downsample = i_downsample self.stride = stride self.relu = nn.ReLU() def forward(self, x): identity = x.clone() x = self.relu(self.batch_norm1(self.conv1(x))) x = self.relu(self.batch_norm2(self.conv2(x))) x = self.conv3(x) x = self.batch_norm3(x) #downsample if needed if self.i_downsample is not None: identity = self.i_downsample(identity) #add identity x+=identity x=self.relu(x) return x class Block(nn.Module): expansion = 1 def __init__(self, in_channels, out_channels, i_downsample=None, stride=1): super(Block, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=1, bias=False) self.batch_norm1 = nn.BatchNorm2d(out_channels) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, stride=stride, bias=False) self.batch_norm2 = nn.BatchNorm2d(out_channels) self.i_downsample = i_downsample self.stride = stride self.relu = nn.ReLU() def forward(self, x): identity = x.clone() x = self.relu(self.batch_norm1(self.conv1(x))) x = self.batch_norm2(self.conv2(x)) if self.i_downsample is not None: identity = self.i_downsample(identity) x += identity x = self.relu(x) return x class Widar_ResNet(nn.Module): def __init__(self, ResBlock, layer_list, num_classes): super(Widar_ResNet, self).__init__() self.reshape = nn.Sequential( nn.ConvTranspose2d(22,3,7,stride=1), nn.ReLU(), nn.ConvTranspose2d(3,3,kernel_size=7,stride=1), nn.ReLU() ) self.in_channels = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.batch_norm1 = nn.BatchNorm2d(64) self.relu = nn.ReLU() self.max_pool = nn.MaxPool2d(kernel_size = 3, stride=2, padding=1) self.layer1 = self._make_layer(ResBlock, layer_list[0], planes=64) self.layer2 = self._make_layer(ResBlock, layer_list[1], planes=128, stride=2) self.layer3 = self._make_layer(ResBlock, layer_list[2], planes=256, stride=2) self.layer4 = self._make_layer(ResBlock, layer_list[3], planes=512, stride=2) self.avgpool = nn.AdaptiveAvgPool2d((1,1)) self.fc = nn.Linear(512*ResBlock.expansion, num_classes) def forward(self, x): x = self.reshape(x) x = self.relu(self.batch_norm1(self.conv1(x))) x = self.max_pool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.reshape(x.shape[0], -1) x = self.fc(x) return x def _make_layer(self, ResBlock, blocks, planes, stride=1): ii_downsample = None layers = [] if stride != 1 or self.in_channels != planes*ResBlock.expansion: ii_downsample = nn.Sequential( nn.Conv2d(self.in_channels, planes*ResBlock.expansion, kernel_size=1, stride=stride), nn.BatchNorm2d(planes*ResBlock.expansion) ) layers.append(ResBlock(self.in_channels, planes, i_downsample=ii_downsample, stride=stride)) self.in_channels = planes*ResBlock.expansion for i in range(blocks-1): layers.append(ResBlock(self.in_channels, planes)) return nn.Sequential(*layers) def Widar_ResNet18(num_classes): return Widar_ResNet(Block, [2,2,2,2], num_classes = num_classes) def Widar_ResNet50(num_classes): return Widar_ResNet(Bottleneck, [3,4,6,3], num_classes = num_classes) def Widar_ResNet101(num_classes): return Widar_ResNet(Bottleneck, [3,4,23,3], num_classes = num_classes) class Widar_RNN(nn.Module): def __init__(self,num_classes): super(Widar_RNN,self).__init__() self.rnn = nn.RNN(400,64,num_layers=1) self.fc = nn.Linear(64,num_classes) def forward(self,x): x = x.view(-1,22,400) x = x.permute(1,0,2) _, ht = self.rnn(x) outputs = self.fc(ht[-1]) return outputs class Widar_GRU(nn.Module): def __init__(self,num_classes): super(Widar_GRU,self).__init__() self.gru = nn.GRU(400,64,num_layers=1) self.fc = nn.Linear(64,num_classes) def forward(self,x): x = x.view(-1,22,400) x = x.permute(1,0,2) _, ht = self.gru(x) outputs = self.fc(ht[-1]) return outputs class Widar_LSTM(nn.Module): def __init__(self,num_classes): super(Widar_LSTM,self).__init__() self.lstm = nn.LSTM(400,64,num_layers=1) self.fc = nn.Linear(64,num_classes) def forward(self,x): x = x.view(-1,22,400) x = x.permute(1,0,2) _, (ht,ct) = self.lstm(x) outputs = self.fc(ht[-1]) return outputs class Widar_BiLSTM(nn.Module): def __init__(self,num_classes): super(Widar_BiLSTM,self).__init__() self.lstm = nn.LSTM(400,64,num_layers=1,bidirectional=True) self.fc = nn.Linear(64,num_classes) def forward(self,x): x = x.view(-1,22,400) x = x.permute(1,0,2) _, (ht,ct) = self.lstm(x) outputs = self.fc(ht[-1]) return outputs class Widar_CNN_GRU(nn.Module): def __init__(self,num_classes): super(Widar_CNN_GRU,self).__init__() self.encoder = nn.Sequential( nn.Conv2d(1,8,6,2), nn.ReLU(), nn.Conv2d(8,16,3,1), nn.ReLU(), nn.MaxPool2d(2) ) self.fc = nn.Sequential( nn.Linear(16*3*3,64), nn.ReLU(), nn.Dropout(p=0.5), nn.Linear(64,64), nn.ReLU(), ) self.gru = nn.GRU(64,128,num_layers=1) self.classifier = nn.Sequential( nn.Dropout(0.5), nn.Linear(128,num_classes), nn.Softmax(dim=1) ) def forward(self,x): batch_size = len(x) # batch x 22 x 20 x 20 x = x.view(batch_size*22,1,20,20) # 22*batch x 1 x 20 x 20 x = self.encoder(x) # 22*batch x 16 x 3 x 3 x = x.view(-1,16*3*3) x = self.fc(x) # 22*batch x 64 x = x.view(-1,22,64) x = x.permute(1,0,2) # 22 x batch x 64 _, ht = self.gru(x) outputs = self.classifier(ht[-1]) return outputs class PatchEmbedding(nn.Module): def __init__(self, in_channels = 1, patch_size_w = 2, patch_size_h = 40, emb_size = 2*40, img_size = 22*400): self.patch_size_w = patch_size_w self.patch_size_h = patch_size_h super().__init__() self.projection = nn.Sequential( nn.Conv2d(in_channels, emb_size, kernel_size = (patch_size_w, patch_size_h), stride = (patch_size_w, patch_size_h)), Rearrange('b e (h) (w) -> b (h w) e'), ) self.cls_token = nn.Parameter(torch.randn(1,1,emb_size)) self.position = nn.Parameter(torch.randn(int(img_size/emb_size) + 1, emb_size)) def forward(self, x): x = x.view(-1,1,22,400) b, _, _, _ = x.shape x = self.projection(x) cls_tokens = repeat(self.cls_token, '() n e -> b n e', b=b) x = torch.cat([cls_tokens, x], dim=1) x += self.position return x class MultiHeadAttention(nn.Module): def __init__(self, emb_size = 80, num_heads = 5, dropout = 0.0): super().__init__() self.emb_size = emb_size self.num_heads = num_heads self.qkv = nn.Linear(emb_size, emb_size*3) self.att_drop = nn.Dropout(dropout) self.projection = nn.Linear(emb_size, emb_size) def forward(self, x, mask = None): qkv = rearrange(self.qkv(x), "b n (h d qkv) -> (qkv) b h n d", h=self.num_heads, qkv=3) queries, keys, values = qkv[0], qkv[1], qkv[2] energy = torch.einsum('bhqd, bhkd -> bhqk', queries, keys) if mask is not None: fill_value = torch.finfo(torch.float32).min energy.mask_fill(~mask, fill_value) scaling = self.emb_size ** (1/2) att = F.softmax(energy, dim=-1) / scaling att = self.att_drop(att) # sum up over the third axis out = torch.einsum('bhal, bhlv -> bhav ', att, values) out = rearrange(out, "b h n d -> b n (h d)") out = self.projection(out) return out class ResidualAdd(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x, **kwargs): res = x x = self.fn(x, **kwargs) x += res return x class FeedForwardBlock(nn.Sequential): def __init__(self, emb_size, expansion = 4, drop_p = 0.): super().__init__( nn.Linear(emb_size, expansion * emb_size), nn.GELU(), nn.Dropout(drop_p), nn.Linear(expansion * emb_size, emb_size), ) class TransformerEncoderBlock(nn.Sequential): def __init__(self, emb_size = 80, drop_p = 0.5, forward_expansion = 4, forward_drop_p = 0., ** kwargs): super().__init__( ResidualAdd(nn.Sequential( nn.LayerNorm(emb_size), MultiHeadAttention(emb_size, **kwargs), nn.Dropout(drop_p) )), ResidualAdd(nn.Sequential( nn.LayerNorm(emb_size), FeedForwardBlock( emb_size, expansion=forward_expansion, drop_p=forward_drop_p), nn.Dropout(drop_p) ) )) class TransformerEncoder(nn.Sequential): def __init__(self, depth = 1, **kwargs): super().__init__(*[TransformerEncoderBlock(**kwargs) for _ in range(depth)]) class ClassificationHead(nn.Sequential): def __init__(self, emb_size, num_classes): super().__init__( Reduce('b n e -> b e', reduction='mean'), nn.LayerNorm(emb_size), nn.Linear(emb_size, num_classes)) class Widar_ViT(nn.Sequential): def __init__(self, in_channels = 1, patch_size_w = 2, patch_size_h = 40, emb_size = 80, img_size = 22*400, depth = 1, *, num_classes, **kwargs): super().__init__( PatchEmbedding(in_channels, patch_size_w, patch_size_h, emb_size, img_size), TransformerEncoder(depth, emb_size=emb_size, **kwargs), ClassificationHead(emb_size, num_classes) )
12,936
32.866492
128
py
WiFi-CSI-Sensing-Benchmark
WiFi-CSI-Sensing-Benchmark-main/self_supervised.py
import torch import torch.optim as optim import random import torch.nn as nn from util import load_unsupervised_data_n_model import argparse from torch.autograd import Variable class EntLoss(nn.Module): def __init__(self, args, lam1, lam2, pqueue=None): super(EntLoss, self).__init__() self.lam1 = lam1 self.lam2 = lam2 self.pqueue = pqueue self.args = args def forward(self, feat1, feat2, use_queue=False): probs1 = torch.nn.functional.softmax(feat1, dim=-1) probs2 = torch.nn.functional.softmax(feat2, dim=-1) loss = dict() loss['kl'] = 0.5 * (KL(probs1, probs2, self.args) + KL(probs2, probs1, self.args)) sharpened_probs1 = torch.nn.functional.softmax(feat1/self.args.tau, dim=-1) sharpened_probs2 = torch.nn.functional.softmax(feat2/self.args.tau, dim=-1) loss['eh'] = 0.5 * (EH(sharpened_probs1, self.args) + EH(sharpened_probs2, self.args)) # whether use historical data loss['he'] = 0.5 * (HE(sharpened_probs1, self.args) + HE(sharpened_probs2, self.args)) # TWIST Loss loss['final'] = loss['kl'] + ((1+self.lam1)*loss['eh'] - self.lam2*loss['he']) ######################################################################### # probability distribution (PKT by Kernel Density Estimation) loss['kde'] = cosine_similarity_loss(feat1, feat2) # nuclear-norm loss['n-norm'] = -0.5 * (torch.norm(sharpened_probs1,'nuc')+torch.norm(sharpened_probs2,'nuc')) * 0.001 loss['final-kde'] = loss['kde'] * 100 + loss['final']#+ loss['n-norm'] return loss def KL(probs1, probs2, args): kl = (probs1 * (probs1 + args.EPS).log() - probs1 * (probs2 + args.EPS).log()).sum(dim=1) kl = kl.mean() return kl def CE(probs1, probs2, args): ce = - (probs1 * (probs2 + args.EPS).log()).sum(dim=1) ce = ce.mean() return ce def HE(probs, args): mean = probs.mean(dim=0) ent = - (mean * (mean + args.EPS).log()).sum() return ent def EH(probs, args): ent = - (probs * (probs + args.EPS).log()).sum(dim=1) mean = ent.mean() return mean def cosine_similarity_loss(output_net, target_net, eps=0.0000001): # Normalize each vector by its norm output_net_norm = torch.sqrt(torch.sum(output_net ** 2, dim=1, keepdim=True)) output_net = output_net / (output_net_norm + eps) output_net[output_net != output_net] = 0 target_net_norm = torch.sqrt(torch.sum(target_net ** 2, dim=1, keepdim=True)) target_net = target_net / (target_net_norm + eps) target_net[target_net != target_net] = 0 # Calculate the cosine similarity model_similarity = torch.mm(output_net, output_net.transpose(0, 1)) target_similarity = torch.mm(target_net, target_net.transpose(0, 1)) # Scale cosine similarity to 0..1 model_similarity = (model_similarity + 1.0) / 2.0 target_similarity = (target_similarity + 1.0) / 2.0 # Transform them into probabilities model_similarity = model_similarity / torch.sum(model_similarity, dim=1, keepdim=True) target_similarity = target_similarity / torch.sum(target_similarity, dim=1, keepdim=True) # Calculate the KL-divergence loss = torch.mean(target_similarity * torch.log((target_similarity + eps) / (model_similarity + eps))) return loss def gaussian_noise(csi, epsilon): noise = torch.normal(1, 2, size=(3, 114, 500)).cuda() perturbed_csi = csi + epsilon*noise return perturbed_csi def main(): learning_rate = 1e-3 parser = argparse.ArgumentParser('Self-Supervised') parser.add_argument('--tau', type=float, default=1.0, metavar='LR') parser.add_argument('--EPS', type=float, default=1e-5, help='episillon') parser.add_argument('--weight-decay', type=float, default=1.5e-6, help='weight decay (default: 1e-4)') parser.add_argument('--lam1', type=float, default=0.0, metavar='LR') parser.add_argument('--lam2', type=float, default=1.0, metavar='LR') parser.add_argument('--local_crops_number', type=int, default=12) parser.add_argument('--min1', type=float, default=0.4, metavar='LR') parser.add_argument('--max1', type=float, default=1.0, metavar='LR') parser.add_argument('--min2', type=float, default=0.05, metavar='LR') parser.add_argument('--max2', type=float, default=0.4, metavar='LR') parser.add_argument('--gpu', type=int, default=1, metavar='gpu') parser.add_argument('--eval', type=str, default='no', metavar='gpu') parser.add_argument('--model', choices = ['MLP','LeNet','ResNet18','ResNet50','ResNet101','RNN','GRU','LSTM','BiLSTM','CNN+GRU','ViT']) args = parser.parse_args() args.global_crops_scale = (args.min1, args.max1) args.local_crops_scale = (args.min2, args.max2) criterion = EntLoss(args, 0.0, 0.5) root = "./Data/" unsupervised_train_loader, supervised_train_loader, test_dataloader, model = load_unsupervised_data_n_model(args.model,root) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) ####################################### # self-supervised training print ('Self-supervised encoder training') optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=args.weight_decay) for epoch in range(100): total_loss = 0 kl_loss = 0 eh_loss = 0 he_loss = 0 kde_loss = 0 for data in unsupervised_train_loader: x, y = data x, y = x.to(device), y.to(device) x1 = gaussian_noise(x, random.uniform(0, 2.0)) x2 = gaussian_noise(x, random.uniform(0.1, 2.0)) # ===================forward===================== feat_x1, feat_x2 = model(x1, x2) loss = criterion(feat_x1, feat_x2) loss_kl = loss['kl'] loss_eh = loss['eh'] loss_he = loss['he'] loss_kde = loss['kde'] loss = loss['final-kde'] # ===================backward==================== optimizer.zero_grad() loss.backward() optimizer.step() # ===================log======================== total_loss += loss.data kl_loss += loss_kl.data eh_loss += loss_eh.data he_loss += loss_he.data kde_loss += loss_kde.data print('epoch [{}/{}], total loss:{:.4f},kl loss:{:.4f},eh loss:{:.4f},he loss:{:.4f},kde loss:{:.4f}' .format(epoch+1,100, total_loss, kl_loss, eh_loss, he_loss, kde_loss)) ####################################### ####################################### # test def test(): model.eval() correct_1, correct_2 = 0, 0 total = 0 with torch.no_grad(): for data in test_dataloader: x, y = data x, y = x.to(device), y.to(device) y1, y2 = model(x, x, flag='supervised') _, pred_1 = torch.max(y1.data, 1) _, pred_2 = torch.max(y2.data, 1) total += y.size(0) correct_1 += (pred_1 == y).sum().item() correct_2 += (pred_2 == y).sum().item() print('Test accuracy: {:.2f}%, {:.2f}%'.format(100 * correct_1 / total, 100 * correct_2 / total)) ####################################### ################################## # supervised learning print ('Supervised classifier training') optimizer_supervised = torch.optim.Adam(model.classifier.parameters(), lr=learning_rate, weight_decay=1e-5) ce_criterion = nn.CrossEntropyLoss() for epoch in range(300): model.train() total_loss = 0 for data in supervised_train_loader: x, y = data x = Variable(x).to(device) y = y.type(torch.LongTensor) y = y.to(device) # ===================forward===================== y1, y2 = model(x, x, flag='supervised') loss = ce_criterion(y1, y) + ce_criterion(y2, y) # ===================backward==================== optimizer_supervised.zero_grad() loss.backward() optimizer_supervised.step() # ===================log======================== total_loss += loss.data print('epoch [{}/{}], loss:{:.6f}' .format(epoch+1, 300, total_loss)) # test if epoch > 250: test() ################################## return if __name__ == "__main__": main()
8,839
39.365297
139
py
deficient-efficient
deficient-efficient-master/darts_experiments.py
import json #settings = ['ACDC_%i'%n for n in [6, 12]] +\ # ['SepHashed_%.2f'%s for s in [0.09, 0.20, 0.38]] +\ settings = ['Generic_%.2f'%s for s in [0.03, 0.06, 0.12]] +\ ['Tucker_%.2f'%s for s in [0.24, 0.37, 0.54]] +\ ['TensorTrain_%.2f'%s for s in [0.27, 0.41, 0.59]] +\ ['Shuffle_%i'%n for n in [1, 2, 4]] experiments = [] import datetime now = datetime.datetime.now() monthday = now.strftime("%B")[:3]+"%i"%now.day # use these settings to train WideResNets from scratch for s in settings: experiment = ["python", "main.py", "cifar10", "teacher", "--conv", s, "-t", "darts.%s.%s"%(s.lower(), monthday), "--network", "DARTS"] experiments.append(experiment) # and to train WideResNets with a teacher for s in settings: experiment = ["python", "main.py", "cifar10", "student", "--conv", s, "-t", "darts.teacher", "-s", "darts.%s.student.%s"%(s.lower(), monthday), "--network", "DARTS", "--alpha", "0.", "--beta", "1e3"] experiments.append(experiment) with open("darts_cifar10.json", "w") as f: f.write(json.dumps(experiments))
1,152
37.433333
96
py
deficient-efficient
deficient-efficient-master/main.py
''''Writing everything into one script..''' from __future__ import print_function import os import imp import sys import time import json import argparse import torch import torch.nn as nn import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler import torch.nn.functional as F import torchvision import torchvision.transforms as transforms from torch.autograd import Variable from functools import reduce from tqdm import tqdm from tensorboardX import SummaryWriter from funcs import * from models.wide_resnet import WideResNet, WRN_50_2 from models.darts import DARTS, Cutout, _data_transforms_cifar10 as darts_transforms from models.MobileNetV2 import MobileNetV2 os.mkdir('checkpoints/') if not os.path.isdir('checkpoints/') else None parser = argparse.ArgumentParser(description='Student/teacher training') parser.add_argument('dataset', type=str, choices=['cifar10', 'cifar100', 'imagenet'], help='Choose between Cifar10/100/imagenet.') parser.add_argument('mode', choices=['student','teacher'], type=str, help='Learn a teacher or a student') parser.add_argument('--imagenet_loc', default='/disk/scratch_ssd/imagenet',type=str, help='folder containing imagenet train and val folders') parser.add_argument('--workers', default=2, type=int, help='No. of data loading workers. Make this high for imagenet') parser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint') parser.add_argument('--GPU', default=None, type=str, help='GPU to use') parser.add_argument('--student_checkpoint', '-s', default='wrn_40_2_student_KT',type=str, help='checkpoint to save/load student') parser.add_argument('--teacher_checkpoint', '-t', default='wrn_40_2_T',type=str, help='checkpoint to load in teacher') #network stuff parser.add_argument('--network', default='WideResNet', type=str, help='network to use') parser.add_argument('--wrn_depth', default=40, type=int, help='depth for WRN') parser.add_argument('--wrn_width', default=2, type=float, help='width for WRN') parser.add_argument('--module', default=None, type=str, help='path to file containing custom Conv and maybe Block module definitions') parser.add_argument('--blocktype', default='Basic',type=str, help='blocktype used if specify a --conv') parser.add_argument('--conv', default=None, type=str, help='Conv type') parser.add_argument('--AT_split', default=1, type=int, help='group splitting for AT loss') parser.add_argument('--budget', default=None, type=float, help='budget of parameters to use for the network') #learning stuff parser.add_argument('--lr', default=0.1, type=float, help='learning rate') parser.add_argument('--momentum', default=0.9, type=float, help='momentum') parser.add_argument('--lr_decay_ratio', default=0.2, type=float, help='learning rate decay') parser.add_argument('--temperature', default=4, type=float, help='temp for KD') parser.add_argument('--alpha', default=0.0, type=float, help='alpha for KD') parser.add_argument('--aux_loss', default='AT', type=str, help='AT or SE loss') parser.add_argument('--beta', default=1e3, type=float, help='beta for AT') parser.add_argument('--epoch_step', default='[60,120,160]', type=str, help='json list with epochs to drop lr on') parser.add_argument('--epochs', default=200, type=int, metavar='N', help='number of total epochs to run') parser.add_argument('--print_freq', default=10, type=int, help="print stats frequency") parser.add_argument('--batch_size', default=128, type=int, help='minibatch size') parser.add_argument('--weight_decay', default=0.0005, type=float) parser.add_argument('--nocrswd', action='store_true', help='Disable compression ratio scaled weight decay.') parser.add_argument('--clip_grad', default=None, type=float) args = parser.parse_args() if args.mode == 'teacher': logdir = "runs/%s"%args.teacher_checkpoint elif args.mode == 'student': logdir = "runs/%s.%s"%(args.teacher_checkpoint, args.student_checkpoint) append = 0 while os.path.isdir(logdir+".%i"%append): append += 1 if append > 0: logdir = logdir+".%i"%append writer = SummaryWriter(logdir) def record_oom(train_func): def wrapper(*args): try: _ = train_func(*args) result = (True, "Success") except RuntimeError as e: result = (False, str(e)) except AssertionError as e: result = (True, "Success") except Exception as e: # something else that's not a memory error going wrong result = (False, str(e)) logfile = "oom_checks.json" if os.path.exists(logfile): with open(logfile, 'r') as f: logs = json.load(f) else: logs = [] logs.append((sys.argv, result)) with open(logfile, 'w') as f: f.write(json.dumps(logs)) assert False, "recorded" return wrapper def train_teacher(net): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() net.train() end = time.time() for batch_idx, (inputs, targets) in enumerate(trainloader): # measure data loading time data_time.update(time.time() - end) if use_cuda: inputs, targets = inputs.cuda(non_blocking=True), targets.cuda(non_blocking=True) if isinstance(net, DARTS): outputs, _, aux = net(inputs) outputs = torch.cat([outputs, aux], 0) targets = torch.cat([targets, targets], 0) else: outputs, _ = net(inputs) loss = criterion(outputs, targets) # measure accuracy and record loss prec1, prec5 = accuracy(outputs.data, targets.data, topk=(1, 5)) err1 = 100. - prec1 err5 = 100. - prec5 losses.update(loss.item(), inputs.size(0)) top1.update(err1[0], inputs.size(0)) top5.update(err5[0], inputs.size(0)) # compute gradient and do SGD step optimizer.zero_grad() loss.backward() optimizer.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() if batch_idx % args.print_freq == 0: print('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Error@1 {top1.val:.3f} ({top1.avg:.3f})\t' 'Error@5 {top5.val:.3f} ({top5.avg:.3f})'.format( epoch, batch_idx, len(trainloader), batch_time=batch_time, data_time=data_time, loss=losses, top1=top1, top5=top5)) writer.add_scalar('train_loss', losses.avg, epoch) writer.add_scalar('train_top1', top1.avg, epoch) writer.add_scalar('train_top5', top5.avg, epoch) train_losses.append(losses.avg) train_errors.append(top1.avg) def train_student(net, teach): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() net.train() teach.eval() end = time.time() for batch_idx, (inputs, targets) in enumerate(trainloader): inputs = inputs.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) if isinstance(net, DARTS): outputs, student_AMs, aux = net(inputs) if aux is not None: outputs_student = torch.cat([outputs, aux], 0) targets_plus_aux = torch.cat([targets, targets], 0) else: outputs_student = outputs targets_plus_aux = targets with torch.no_grad(): outputs_teacher, teacher_AMs, _ = teach(inputs) if aux is not None: outputs_teacher = torch.cat([outputs_teacher, outputs_teacher], 0) else: outputs_student, student_AMs = net(inputs) outputs = outputs_student targets_plus_aux = targets with torch.no_grad(): outputs_teacher, teacher_AMs = teach(inputs) # If alpha is 0 then this loss is just a cross entropy. loss = distillation(outputs_student, outputs_teacher, targets_plus_aux, args.temperature, args.alpha) #Add an attention tranfer loss for each intermediate. Let's assume the default is three (as in the original #paper) and adjust the beta term accordingly. adjusted_beta = (args.beta*3)/len(student_AMs) for i in range(len(student_AMs)): loss += adjusted_beta * F.mse_loss(student_AMs[i], teacher_AMs[i]) # measure accuracy and record loss prec1, prec5 = accuracy(outputs.data, targets.data, topk=(1, 5)) err1 = 100. - prec1 err5 = 100. - prec5 losses.update(loss.item(), inputs.size(0)) top1.update(err1[0], inputs.size(0)) top5.update(err5[0], inputs.size(0)) # compute gradient and do SGD step optimizer.zero_grad() loss.backward() if args.clip_grad is not None: max_grad = 0. for p in net.parameters(): g = p.grad.max().item() if g > max_grad: max_grad = g nn.utils.clip_grad_norm(net.parameters(), args.clip_grad) print("Max grad: ", max_grad) optimizer.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() if batch_idx % args.print_freq == 0: print('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Error@1 {top1.val:.3f} ({top1.avg:.3f})\t' 'Error@5 {top5.val:.3f} ({top5.avg:.3f})'.format( epoch, batch_idx, len(trainloader), batch_time=batch_time, data_time=data_time, loss=losses, top1=top1, top5=top5)) writer.add_scalar('train_loss', losses.avg, epoch) writer.add_scalar('train_top1', top1.avg, epoch) writer.add_scalar('train_top5', top5.avg, epoch) train_losses.append(losses.avg) train_errors.append(top1.avg) def validate(net, checkpoint=None): batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() net.eval() end = time.time() for batch_idx, (inputs, targets) in enumerate(valloader): inputs, targets = inputs.cuda(), targets.cuda() with torch.no_grad(): inputs, targets = Variable(inputs), Variable(targets) if isinstance(net, DARTS): outputs, _, _ = net(inputs) else: outputs, _ = net(inputs) if isinstance(outputs,tuple): outputs = outputs[0] loss = criterion(outputs, targets) # measure accuracy and record loss prec1, prec5 = accuracy(outputs.data, targets.data, topk=(1, 5)) err1 = 100. - prec1 err5 = 100. - prec5 losses.update(loss.item(), inputs.size(0)) top1.update(err1[0], inputs.size(0)) top5.update(err5[0], inputs.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if batch_idx % args.print_freq == 0: print('validate: [{0}/{1}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Error@1 {top1.val:.3f} ({top1.avg:.3f})\t' 'Error@5 {top5.val:.3f} ({top5.avg:.3f})'.format( batch_idx, len(valloader), batch_time=batch_time, loss=losses, top1=top1, top5=top5)) print(' * Error@1 {top1.avg:.3f} Error@5 {top5.avg:.3f}' .format(top1=top1, top5=top5)) if checkpoint: writer.add_scalar('val_loss', losses.avg, epoch) writer.add_scalar('val_top1', top1.avg, epoch) writer.add_scalar('val_top5', top5.avg, epoch) val_losses.append(losses.avg) val_errors.append(top1.avg) if isinstance(net, torch.nn.DataParallel): state_dict = net.module.state_dict() else: state_dict = net.state_dict() print('Saving..') state = { 'net': state_dict, 'epoch': epoch, 'args': sys.argv, 'width': args.wrn_width, 'depth': args.wrn_depth, 'conv': args.conv, 'blocktype': args.blocktype, 'module': args.module, 'train_losses': train_losses, 'train_errors': train_errors, 'val_losses': val_losses, 'val_errors': val_errors, } print('SAVED!') torch.save(state, 'checkpoints/%s.t7' % checkpoint) def set_for_budget(eval_network_size, conv_type, budget): assert False, "Deprecated this because I don't trust it 100%" # set bounds using knowledge of conv_type hyperparam domain if 'ACDC' == conv_type: bounds = (2, 128) post_process = lambda x: int(round(x)) elif 'Hashed' == conv_type: bounds = (0.001,0.9) post_process = lambda x: x # do nothing elif 'SepHashed' == conv_type: bounds = (0.001,0.9) post_process = lambda x: x # do nothing elif 'Generic' == conv_type: bounds = (0.1,0.9) post_process = lambda x: x # do nothing elif 'TensorTrain' == conv_type: bounds = (0.1,0.9) post_process = lambda x: x # do nothing elif 'Tucker' == conv_type: bounds = (0.1,0.9) post_process = lambda x: x # do nothing elif 'CP' == conv_type: bounds = (0.1,0.9) post_process = lambda x: x # do nothing else: raise ValueError("Don't know: "+conv_type) def obj(h): return abs(budget-eval_network_size(h)) from scipy.optimize import minimize_scalar minimizer = minimize_scalar(obj, bounds=bounds, method='bounded') return post_process(minimizer.x) def n_params(net): return sum([reduce(lambda x,y:x*y, p.size()) for p in net.parameters()]) def darts_defaults(args): args.batch_size = 96 args.lr = 0.025 args.momentum = 0.9 args.weight_decay = 3e-4 args.epochs = 600 return args def imagenet_defaults(args): args.batch_size=256 args.epochs = 90 args.lr_decay_ratio = 0.1 args.weight_decay = 1e-4 args.epoch_step = '[30,60]' args.workers = 16 return args def mobilenetv2_defaults(args): args.batch_size=256 args.epochs = 150 args.lr = 0.05 args.weight_decay = 4e-5 args.workers = 16 return args def get_scheduler(optimizer, epoch_step, args): if args.network == 'WideResNet' or args.network == 'WRN_50_2': scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=epoch_step, gamma=args.lr_decay_ratio) elif args.network == 'DARTS' or args.network == 'MobileNetV2': scheduler = lr_scheduler.CosineAnnealingLR(optimizer, float(args.epochs)) return scheduler if __name__ == '__main__': if args.aux_loss == 'AT': aux_loss = at_loss elif args.aux_loss == 'SE': aux_loss = se_loss if args.network == 'DARTS': args = darts_defaults(args) # different training hyperparameters elif args.network == 'WRN_50_2': args = imagenet_defaults(args) elif args.network == 'MobileNetV2': args = mobilenetv2_defaults(args) print(vars(args)) parallelise = None if args.GPU is not None: if args.GPU[0] != '[': args.GPU = '[' + args.GPU + ']' args.GPU = [i for i, _ in enumerate(json.loads(args.GPU))] if len(args.GPU) > 1: def parallelise(model): model = torch.nn.DataParallel(model, device_ids=args.GPU) model.grouped_parameters = model.module.grouped_parameters return model else: os.environ["CUDA_VISIBLE_DEVICES"] = "%i"%args.GPU[0] use_cuda = torch.cuda.is_available() assert use_cuda, 'Error: No CUDA!' val_losses = [] train_losses = [] val_errors = [] train_errors = [] best_acc = 0 start_epoch = 0 epoch_step = json.loads(args.epoch_step) # Data and loaders print('==> Preparing data..') if args.dataset == 'cifar10': num_classes = 10 if args.network == 'DARTS': transforms_train, transforms_validate = darts_transforms() else: transforms_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), Cutout(16)]) transforms_validate = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),]) trainset = torchvision.datasets.CIFAR10(root='/disk/scratch/datasets/cifar', train=True, download=False, transform=transforms_train) valset = torchvision.datasets.CIFAR10(root='/disk/scratch/datasets/cifar', train=False, download=False, transform=transforms_validate) elif args.dataset == 'cifar100': num_classes = 100 if args.network == 'DARTS': raise NotImplementedError("Could use transforms for CIFAR-10, but not ported yet.") transforms_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.5071, 0.4866, 0.4409), (0.2009, 0.1984, 0.2023)), ]) transforms_validate = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5071, 0.4866, 0.4409), (0.2009, 0.1984, 0.2023)), ]) trainset = torchvision.datasets.CIFAR100(root='/disk/scratch/datasets/cifar100', train=True, download=True, transform=transforms_train) validateset = torchvision.datasets.CIFAR100(root='/disk/scratch/datasets/cifar100', train=False, download=True, transform=transforms_validate) elif args.dataset == 'imagenet': num_classes = 1000 traindir = os.path.join(args.imagenet_loc, 'train') valdir = os.path.join(args.imagenet_loc, 'val') normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transform_train = transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ]) transform_validate = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize, ]) trainset = torchvision.datasets.ImageFolder(traindir, transform_train) valset = torchvision.datasets.ImageFolder(valdir, transform_validate) trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, pin_memory = True if args.dataset == 'imagenet' else False) valloader = torch.utils.data.DataLoader(valset, batch_size=min(100,args.batch_size), shuffle=False, num_workers=args.workers, pin_memory=True if args.dataset == 'imagenet' else False) criterion = nn.CrossEntropyLoss() # a function for building networks def build_network(Conv, Block): if args.network == 'WideResNet': return WideResNet(args.wrn_depth, args.wrn_width, Conv, Block, num_classes=num_classes, dropRate=0, s=args.AT_split) elif args.network == 'WRN_50_2': return WRN_50_2(Conv) elif args.network == 'MobileNetV2': return MobileNetV2(Conv) elif args.network == 'DARTS': return DARTS(Conv, num_classes=num_classes) # if a budget is specified, figure out what we have to set the # hyperparameter to if args.budget is not None: def eval_network_size(hyperparam): net = build_network(*what_conv_block(args.conv+"_%s"%hyperparam, args.blocktype, args.module)) return n_params(net) hyperparam = set_for_budget(eval_network_size, args.conv, args.budget) args.conv = args.conv + "_%s"%hyperparam # get the classes implementing the Conv and Blocks we're going to use in # the network Conv, Block = what_conv_block(args.conv, args.blocktype, args.module) def load_network(loc): net_checkpoint = torch.load(loc) start_epoch = net_checkpoint['epoch'] SavedConv, SavedBlock = what_conv_block(net_checkpoint['conv'], net_checkpoint['blocktype'], net_checkpoint['module']) net = build_network(SavedConv, SavedBlock).cuda() torch.save(net.state_dict(), "checkpoints/darts.template.t7") net.load_state_dict(net_checkpoint['net']) return net, start_epoch if args.mode == 'teacher': if args.resume: print('Mode Teacher: Loading teacher and continuing training...') teach, start_epoch = load_network('checkpoints/%s.t7' % args.teacher_checkpoint) else: print('Mode Teacher: Making a teacher network from scratch and training it...') teach = build_network(Conv, Block).cuda() if parallelise is not None: teach = parallelise(teach) parameters = teach.grouped_parameters(args.weight_decay) if not args.nocrswd else teach.parameters() optimizer = optim.SGD(parameters, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) scheduler = get_scheduler(optimizer, epoch_step, args) def schedule_drop_path(epoch, net): net.drop_path_prob = 0.2 * epoch / (start_epoch+args.epochs) # Decay the learning rate depending on the epoch for e in range(0,start_epoch): scheduler.step() for epoch in tqdm(range(start_epoch, args.epochs)): scheduler.step() if args.network == 'DARTS': schedule_drop_path(epoch, teach) print('Teacher Epoch %d:' % epoch) print('Learning rate is %s' % [v['lr'] for v in optimizer.param_groups][0]) writer.add_scalar('learning_rate', [v['lr'] for v in optimizer.param_groups][0], epoch) train_teacher(teach) validate(teach, args.teacher_checkpoint) elif args.mode == 'student': print('Mode Student: First, load a teacher network and convert for (optional) attention transfer') teach, _ = load_network('checkpoints/%s.t7' % args.teacher_checkpoint) if parallelise is not None: teach = parallelise(teach) # Very important to explicitly say we require no gradients for the teacher network for param in teach.parameters(): param.requires_grad = False validate(teach) val_losses, val_errors = [], [] # or we'd save the teacher's error as the first entry if args.resume: print('Mode Student: Loading student and continuing training...') student, start_epoch = load_network('checkpoints/%s.t7' % args.student_checkpoint) else: print('Mode Student: Making a student network from scratch and training it...') student = build_network(Conv, Block).cuda() if parallelise is not None: student = parallelise(student) parameters = student.grouped_parameters(args.weight_decay) if not args.nocrswd else student.parameters() optimizer = optim.SGD(parameters, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) scheduler = get_scheduler(optimizer, epoch_step, args) def schedule_drop_path(epoch, net): net.drop_path_prob = 0.2 * epoch / (start_epoch+args.epochs) # Decay the learning rate depending on the epoch for e in range(0, start_epoch): scheduler.step() for epoch in tqdm(range(start_epoch, args.epochs)): scheduler.step() if args.network == 'DARTS': schedule_drop_path(epoch, student) print('Student Epoch %d:' % epoch) print('Learning rate is %s' % [v['lr'] for v in optimizer.param_groups][0]) writer.add_scalar('learning_rate', [v['lr'] for v in optimizer.param_groups][0], epoch) train_student(student, teach) validate(student, args.student_checkpoint)
25,508
39.426307
141
py
deficient-efficient
deficient-efficient-master/count.py
'''Count parameters or mult-adds in models.''' from __future__ import print_function import math import torch import argparse from torch.autograd import Variable from models.wide_resnet import WideResNet, WRN_50_2 from models.darts import DARTS from models.MobileNetV2 import MobileNetV2 from funcs import what_conv_block ignored_modules = [] def get_layer_info(layer): layer_str = str(layer) type_name = layer_str[:layer_str.find('(')].strip() return type_name def get_layer_param(model): return sum([p.numel() for p in model.parameters()]) class OpCounter(object): def __init__(self): self.count_ops = 0 self.count_params = 0 def measure_layer(self, layer, x): delta_ops = 0 delta_params = 0 multi_add = 1 type_name = get_layer_info(layer) x = x[0] ### ops_conv if type_name in ['Conv2d']: out = layer.old_forward(x) out_h = out.size(2) out_w = out.size(3) delta_ops = layer.in_channels * layer.out_channels * layer.kernel_size[0] * \ layer.kernel_size[1] * out_h * out_w / layer.groups * multi_add delta_params = get_layer_param(layer) ### ops_nonlinearity elif type_name in ['ReLU']: delta_ops = x.numel() delta_params = get_layer_param(layer) ### ops_pooling elif type_name in ['AvgPool2d','MaxPool2d']: in_w = x.size()[2] if type(layer.kernel_size) is tuple: k = layer.kernel_size[0] else: k = layer.kernel_size kernel_ops = k * k out_w = int((in_w + 2 * layer.padding - k) / layer.stride + 1) out_h = int((in_w + 2 * layer.padding - k) / layer.stride + 1) out = layer.old_forward(x) assert out_h == out.size(2) assert out_w == out.size(3) delta_ops = x.size()[0] * x.size()[1] * out_w * out_h * kernel_ops delta_params = get_layer_param(layer) ### ops_linear elif type_name in ['Linear']: weight_ops = layer.weight.numel() * multi_add bias_ops = layer.bias.numel() delta_ops = x.size()[0] * (weight_ops + bias_ops) delta_params = get_layer_param(layer) ### ops_nothing elif type_name in ['BatchNorm2d', 'Dropout2d', 'DropChannel', 'Dropout']: delta_params = get_layer_param(layer) ### sequential takes no extra time elif type_name in ['Sequential']: pass ### riffle shuffle elif type_name in ['Riffle']: # technically no floating point operations pass ### channel expansion elif type_name in ['ChannelExpand']: # assume concatentation doesn't take extra FLOPs pass ### channel contraction elif type_name in ['ChannelCollapse']: # do as many additions as we have channels delta_ops += x.size(1) ### ACDC Convolution elif type_name in ['FastStackedConvACDC']: out_h = int((x.size()[2] + 2 * layer.padding[0] - layer.kernel_size[0]) / layer.stride[0] + 1) out_w = int((x.size()[3] + 2 * layer.padding[1] - layer.kernel_size[1]) / layer.stride[1] + 1) assert layer.groups == 1 # pretend we're actually passing through the ACDC layers within N = max(layer.out_channels, layer.in_channels) # size of ACDC layers acdc_ops = 0 for l in layer.layers: acdc_ops += 4*N + 5*N*math.log(N,2) delta_params += 2*N delta_ops += acdc_ops*out_h*out_w ### Grouped ACDC Convolution elif type_name in ['GroupedConvACDC']: assert False out_h = int((x.size()[2] + 2 * layer.padding[0] - layer.kernel_size[0]) / layer.stride[0] + 1) out_w = int((x.size()[3] + 2 * layer.padding[1] - layer.kernel_size[1]) / layer.stride[1] + 1) # pretend we're actually passing through the ACDC layers within N = layer.kernel_size[0] acdc_ops = layer.groups*(4*N + 5*N*math.log(N,2)) conv_ops = layer.in_channels * layer.out_channels * layer.kernel_size[0] * \ layer.kernel_size[1] / layer.groups ops = min(acdc_ops, conv_ops) delta_ops += ops*out_h*out_w delta_params += 2*N ### HashedNet Convolution elif type_name in ['HashedConv2d']: # same number of ops as convolution out_h = int((x.size()[2] + 2 * layer.padding[0] - layer.kernel_size[0]) / layer.stride[0] + 1) out_w = int((x.size()[3] + 2 * layer.padding[1] - layer.kernel_size[1]) / layer.stride[1] + 1) delta_ops = layer.in_channels * layer.out_channels * layer.kernel_size[0] * \ layer.kernel_size[1] * out_h * out_w / layer.groups * multi_add delta_params = get_layer_param(layer) elif type_name in ['DepthwiseSep']: # wrapper for Conv2Ds, that are counted above pass elif type_name in ['TensorTrain', 'Tucker']: if hasattr(layer, 'grouped'): out = layer.grouped.old_forward(x) out_h = out.size(2) out_w = out.size(3) else: out = layer.old_forward(x) out_h = out.size(2) out_w = out.size(3) delta_ops = layer.in_channels * layer.out_channels * layer.kernel_size[0] * \ layer.kernel_size[1] * out_h * out_w / layer.groups * multi_add delta_params = sum([p.numel() for k,p in layer._parameters.items() if p is not None]) elif type_name in ['LinearShuffleNet', 'ShuffleBlock']: # all operations implemented by internal conv2d, so this can be ignored pass elif type_name in ['GenericLowRank']: # all operations implemented by internal conv2d pass elif type_name in ['LowRank']: if hasattr(layer, 'grouped'): x = layer.grouped.old_forward(x) if layer.upsample > 1: x = x.repeat(1,layer.upsample,1,1) out = layer.lowrank.old_forward(x) out_h = out.size(2) out_w = out.size(3) delta_ops = 2 * layer.lowrank.in_channels * \ layer.lowrank.out_channels * layer.lowrank.kernel_size[0] * \ layer.lowrank.kernel_size[1] * out_h * out_w / layer.lowrank.groups \ * multi_add delta_params = get_layer_param(layer.lowrank) #elif type_name in ['TensorTrain']: elif False: # number of cores d = 0 while hasattr(layer, 'weight_core_%i'%d): core = getattr(layer, 'weight_core_%i'%d) d += 1 d += 1 # max dimension m = max(layer.tn_weight.torch().size()) # maximal rank r = max(layer.tn_weight.ranks_tt) # max dim of kernel matrix maxMN = max(layer.in_channels, layer.out_channels) # complexity c = d*r*r*m*maxMN + d*r*r*r*m print(layer.in_channels*layer.out_channels, c) import ipdb ipdb.set_trace() # number of Us n_us = 0 while hasattr(layer, 'weight_u_%i'%n_us): u = getattr(layer, 'weight_u_%i'%n_us) n_us += 1 if type_name == 'TensorTrain': # From "Tensorizing Neural Networks" # For the case of the TT-matrix-by-explicit-vector product c = Wb, # the computational complexity is O(d r^2 m max(M,N)), where d is # the number of cores of the TT-matrix W, m is the max_k m_k, r is # the maximal rank and N = \prod_k=1^d n_k is the length of the # vector b. # # Seems like, naively, the mult-adds can be estimated as those used # by an independent matrix multiply for each core, with the result # then summed. Reading this from Section 4. d = n_cores r = layer.rank N = x.size(1) # plus the ops of the grouped convolution? or does that get caught anyway? #assert False # this would double count the grouped #delta_params = get_layer_param(layer) ### unknown layer type else: if type_name not in ignored_modules: ignored_modules.append(type_name) #raise TypeError('unknown layer type: %s' % type_name) self.count_ops += delta_ops self.count_params += delta_params return None def measure_model(model, H, W): opcount = OpCounter() data = Variable(torch.zeros(1, 3, H, W)) def modify_forward(model): for child in model.modules(): def new_forward(m): def lambda_forward(*x): opcount.measure_layer(m, x) try: return m.old_forward(*x) except NotImplementedError as e: print(m) raise e return lambda_forward child.old_forward = child.forward child.forward = new_forward(child) # recursive function def restore_forward(model): for child in model.children(): # leaf node if is_leaf(child) and hasattr(child, 'old_forward'): child.forward = child.old_forward child.old_forward = None else: restore_forward(child) modify_forward(model) model.forward(data) #restore_forward(model) return opcount.count_ops, opcount.count_params if __name__ == '__main__': parser = argparse.ArgumentParser(description='WRN parameter/flop usage') parser.add_argument('dataset', type=str, choices=['cifar10', 'cifar100', 'imagenet'], help='Choose between Cifar10/100/imagenet.') #network stuff parser.add_argument('--network', default='WideResNet', type=str, help='network to use') parser.add_argument('--wrn_depth', default=40, type=int, help='depth for WRN') parser.add_argument('--wrn_width', default=2, type=float, help='width for WRN') parser.add_argument('--module', default=None, type=str, help='path to file containing custom Conv and maybe Block module definitions') parser.add_argument('--blocktype', default='Basic',type=str, help='blocktype used if specify a --conv') parser.add_argument('--conv', default=None, type=str, help='Conv type') args = parser.parse_args() # Stuff happens from here: Conv, Block = what_conv_block(args.conv, args.blocktype, args.module) if args.dataset == 'cifar10': h,w = 32,32 num_classes = 10 elif args.dataset == 'cifar100': h,w = 32, 32 num_classes = 100 elif args.dataset == 'imagenet': h,w = 224, 224 num_classes = 1000 else: raise ValueError(args.dataset) # instance the model def build_network(Conv, Block): if args.network == 'WideResNet': return WideResNet(args.wrn_depth, args.wrn_width, Conv, Block, num_classes=num_classes, dropRate=0) elif args.network == 'WRN_50_2': return WRN_50_2(Conv) elif args.network == 'DARTS': assert not args.conv == 'Conv', 'The base network here used' \ ' separable convolutions, so you probably did not mean to set this' \ ' option.' return DARTS(Conv, num_classes=num_classes, drop_path_prob=0., auxiliary=False) elif args.network == 'MobileNetV2': return MobileNetV2(Conv) model = build_network(Conv, Block) # count how many parameters are in it flops, params = measure_model(model, h, w) print("Mult-Adds: %.5E"%flops) print("Params: %.5E"%params) sanity = sum([p.numel() for p in model.parameters()]) assert sanity == params, "Sanity check, parameters: %.5E =/= %.5E \n %s"%(sanity, params, str(ignored_modules)) print(ignored_modules) #import time #for m in model.modules(): # time.sleep(0.2) # print(get_layer_info(m), sum([p.numel() for p in m.parameters()]))
12,725
38.156923
138
py
deficient-efficient
deficient-efficient-master/funcs.py
import torch import torch.nn.functional as F from models import * from models.wide_resnet import parse_options def distillation(y, teacher_scores, labels, T, alpha): return F.kl_div(F.log_softmax(y/T, dim=1), F.softmax(teacher_scores/T, dim=1)) * (T*T * 2. * alpha)\ + F.cross_entropy(y, labels) * (1. - alpha) def at(x): return F.normalize(x.pow(2).mean(1).view(x.size(0), -1)) def at_loss(x, y): return F.mse_loss(at(x), at(y)) def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res def get_no_params(net, verbose=True): params = net.state_dict() tot= 0 conv_tot = 0 for p in params: no = params[p].view(-1).__len__() tot += no if 'bn' not in p: if verbose: print('%s has %d params' % (p,no)) if 'conv' in p: conv_tot += no if verbose: print('Net has %d conv params' % conv_tot) print('Net has %d params in total' % tot) return tot class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def what_conv_block(conv, blocktype, module): if conv is not None: Conv, Block = parse_options(conv, blocktype) elif module is not None: conv_module = imp.new_module('conv') with open(module, 'r') as f: exec(f.read(), conv_module.__dict__) Conv = conv_module.Conv try: Block = conv_module.Block except AttributeError: # if the module doesn't implement a custom block, # use default option _, Block = parse_options('Conv', args.blocktype) else: raise ValueError("You must specify either an existing conv option, or supply your own module to import") return Conv, Block
2,477
26.533333
112
py
deficient-efficient
deficient-efficient-master/wrn_experiments.py
import json #settings = ['ACDC_%i'%n for n in [15, 48, 64]] +\ # ['SepHashed_%.2f'%s for s in [0.05, 0.2, 0.5]] +\ settings = ['Generic_%.2f'%s for s in [0.03, 0.1, 0.24]] +\ ['Tucker_%.2f'%s for s in [0.21, 0.41, 0.67]] +\ ['TensorTrain_%.2f'%s for s in [0.23, 0.44, 0.7]] +\ ['Shuffle_%i'%n for n in [1, 3, 7]] experiments = [] import datetime now = datetime.datetime.now() monthday = now.strftime("%B")[:3]+"%i"%now.day # use these settings to train WideResNets from scratch for s in settings: experiment = ["python", "main.py", "cifar10", "teacher", "--conv", s, "-t", "wrn_28_10.%s.%s"%(s.lower(), monthday), "--wrn_depth", "28", "--wrn_width", "10"] experiments.append(experiment) # and to train WideResNets with a teacher for s in settings: experiment = ["python", "main.py", "cifar10", "student", "--conv", s, "-t", "wrn_28_10.patch", "-s", "wrn_28_10.%s.student.%s"%(s.lower(), monthday), "--wrn_depth", "28", "--wrn_width", "10", "--alpha", "0.", "--beta", "1e3"] experiments.append(experiment) with open("wrn_cifar10.json", "w") as f: f.write(json.dumps(experiments))
1,201
39.066667
114
py