python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
"""Script to plot example augmentations generated by the ImageAugmenter.""" from __future__ import print_function # make sure that ImageAugmenter can be imported from parent directory if __name__ == '__main__' and __package__ is None: from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) import numpy as np from ImageAugmenter import ImageAugmenter from scipy import misc from skimage import data def main(): """Plot example augmentations for Lena and an image loaded from a file.""" # try on a lena image image = data.lena() augmenter = ImageAugmenter(image.shape[0], image.shape[1], hflip=True, vflip=True, scale_to_percent=1.3, scale_axis_equally=False, rotation_deg=25, shear_deg=10, translation_x_px=5, translation_y_px=5) augmenter.plot_image(image, 100) # check loading of images from file and augmenting them image = misc.imread("chameleon.png") augmenter = ImageAugmenter(image.shape[1], image.shape[0], hflip=True, vflip=True, scale_to_percent=1.3, scale_axis_equally=False, rotation_deg=25, shear_deg=10, translation_x_px=5, translation_y_px=5) augmenter.plot_image(image, 50) # move the channel from index 2 (3rd position) to index 0 (1st position) # so (y, x, rgb) becomes (rgb, y, x) # try if it still works image = np.rollaxis(image, 2, 0) augmenter = ImageAugmenter(image.shape[2], image.shape[1], hflip=True, vflip=True, scale_to_percent=1.3, scale_axis_equally=False, rotation_deg=25, shear_deg=10, translation_x_px=5, translation_y_px=5, channel_is_first_axis=True) augmenter.plot_image(image, 50) if __name__ == "__main__": main()
imgaug-master
old_version/tests/CheckPlotImages.py
"""Rough measurements of the performance of the ImageAugmenter.""" from __future__ import print_function # make sure that ImageAugmenter can be imported from parent directory if __name__ == '__main__' and __package__ is None: from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) import numpy as np from ImageAugmenter import ImageAugmenter, create_aug_matrices from scipy import misc from skimage import data from skimage import transform as tf import time def main(): """Measure time required to generate augmentations matrices and to apply them. """ batch_size = 64 nb_runs = 20 # Measure time required to generate 100k augmentation matrices """ print("Generating 100 times 1000 augmentation matrices of size 64x64...") start = time.time() for _ in range(100): create_aug_matrices(1000, 64, 64, scale_to_percent=1.5, scale_axis_equally=False, rotation_deg=20, shear_deg=20, translation_x_px=5, translation_y_px=5) print("Done in %.8f" % (time.time() - start,)) """ # Test Performance on 64 images of size 512x512 pixels image = data.lena() images = np.resize(image, (batch_size, image.shape[0], image.shape[1], image.shape[2])) augmenter = ImageAugmenter(image.shape[0], image.shape[1], hflip=True, vflip=True, scale_to_percent=1.3, scale_axis_equally=False, rotation_deg=25, shear_deg=10, translation_x_px=5, translation_y_px=5) print("Running tests on %d images of shape %s" % (batch_size, str(image.shape))) run_tests(augmenter, images, nb_runs) print("") print("Running tests on %d images of shape %s" % (batch_size, str(image.shape))) print("(With 1000 pregenerated matrices)") augmenter.pregenerate_matrices(1000) run_tests(augmenter, images, nb_runs) print("") # Test Performance on 64 images of size 64x64 pixels image = data.lena() image = misc.imresize(image, (64, 64)) images = np.resize(image, (batch_size, image.shape[0], image.shape[1], image.shape[2])) augmenter = ImageAugmenter(image.shape[0], image.shape[1], hflip=True, vflip=True, scale_to_percent=1.3, scale_axis_equally=False, rotation_deg=25, shear_deg=10, translation_x_px=5, translation_y_px=5) print("Running tests on %d images of shape %s" % (batch_size, str(image.shape))) run_tests(augmenter, images, nb_runs) print("Running tests on %d images of shape %s" % (batch_size, str(image.shape))) print("(With 1000 pregenerated matrices)") augmenter.pregenerate_matrices(1000) run_tests(augmenter, images, nb_runs) print("") # Time required to augment 1,000,000 images of size 32x32 print("Augmenting 1000 batches of 1000 lena images (1 million total)" \ ", each of size 32x32...") image = data.lena() image = misc.imresize(image, (32, 32)) batch_size = 1000 images = np.resize(image, (batch_size, image.shape[0], image.shape[1], image.shape[2])) augmenter = ImageAugmenter(image.shape[1], image.shape[0], hflip=True, vflip=True, scale_to_percent=1.3, scale_axis_equally=False, rotation_deg=25, shear_deg=10, translation_x_px=5, translation_y_px=5) augmenter.pregenerate_matrices(1000) start = time.time() for _ in range(1000): augmenter.augment_batch(images) print("Done in %.8fs" % (time.time() - start,)) print("") # Time required to augment 1,000,000 images of size 32x32 # but using only one matrix without the class (no library overhead from # ImageAugmenter) # Notice that this does not include horizontal and vertical flipping, # which is done via numpy in the ImageAugmenter class. print("Augmenting 1000 batches of 1000 lena images (1 million total)" \ ", each of size 32x32, using one matrix directly (no ImageAugmenter " \ "class)...") matrices = create_aug_matrices(1, image.shape[1], image.shape[0], scale_to_percent=1.3, scale_axis_equally=False, rotation_deg=25, shear_deg=10, translation_x_px=5, translation_y_px=5) matrix = matrices[0] start = time.time() for _ in range(1000): for image in images: augmented_image = tf.warp(image, matrix) print("Done in %.8fs" % (time.time() - start,)) def run_tests(augmenter, images, nb_runs): """Perform nb_runs augmentations of the provided images and measure the required time for that. """ results = np.zeros((nb_runs,)) for i in range(nb_runs): start = time.time() augmenter.augment_batch(images) results[i] = time.time() - start print("Run %d: %.8fs" % (i, results[i])) print("Mean: %.8fs" % (results.mean(),)) print("Sum: %.8fs" % (results.sum(),)) if __name__ == "__main__": main()
imgaug-master
old_version/tests/CheckPerformance.py
from __future__ import absolute_import from .imgaug import * from . import augmenters from . import parameters __version__ = '0.1'
imgaug-master
imgaug/__init__.py
from __future__ import print_function, division, absolute_import from abc import ABCMeta, abstractmethod import random import numpy as np import copy import numbers import cv2 import math from scipy import misc import six import six.moves as sm """ try: xrange except NameError: # python3 xrange = range """ ALL = "ALL" # We instantiate a current/global random state here once. # One can also call np.random, but that is (in contrast to np.random.RandomState) # a module and hence cannot be copied via deepcopy. That's why we use RandomState # here (and in all augmenters) instead of np.random. CURRENT_RANDOM_STATE = np.random.RandomState(42) def is_np_array(val): return isinstance(val, (np.ndarray, np.generic)) def is_single_integer(val): return isinstance(val, numbers.Integral) def is_single_float(val): return isinstance(val, numbers.Real) and not is_single_integer(val) def is_single_number(val): return is_single_integer(val) or is_single_float(val) def is_iterable(val): return isinstance(val, (tuple, list)) def is_string(val): return isinstance(val, str) or isinstance(val, unicode) def is_integer_array(val): return issubclass(val.dtype.type, np.integer) def current_random_state(): return CURRENT_RANDOM_STATE def new_random_state(seed=None, fully_random=False): if seed is None: if not fully_random: # sample manually a seed instead of just RandomState(), # because the latter one # is way slower. seed = CURRENT_RANDOM_STATE.randint(0, 10**6, 1)[0] return np.random.RandomState(seed) def dummy_random_state(): return np.random.RandomState(1) def copy_random_state(random_state, force_copy=False): if random_state == np.random and not force_copy: return random_state else: rs_copy = dummy_random_state() orig_state = random_state.get_state() rs_copy.set_state(orig_state) return rs_copy # TODO # def from_json(json_str): # pass def imresize_many_images(images, sizes=None, interpolation=None): s = images.shape assert len(s) == 4, s nb_images = s[0] im_height, im_width = s[1], s[2] nb_channels = s[3] height, width = sizes[0], sizes[1] if height == im_height and width == im_width: return np.copy(images) ip = interpolation assert ip is None or ip in ["nearest", "linear", "area", "cubic", cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_AREA, cv2.INTER_CUBIC] if ip is None: if height > im_height or width > im_width: ip = cv2.INTER_AREA else: ip = cv2.INTER_LINEAR elif ip in ["nearest", cv2.INTER_NEAREST]: ip = cv2.INTER_NEAREST elif ip in ["linear", cv2.INTER_LINEAR]: ip = cv2.INTER_LINEAR elif ip in ["area", cv2.INTER_AREA]: ip = cv2.INTER_AREA elif ip in ["cubic", cv2.INTER_CUBIC]: ip = cv2.INTER_CUBIC else: raise Exception("Invalid interpolation order") result = np.zeros((nb_images, height, width, nb_channels), dtype=np.uint8) for img_idx in sm.xrange(nb_images): result_img = cv2.resize(images[img_idx], (width, height), interpolation=ip) if len(result_img.shape) == 2: result_img = result_img[:, :, np.newaxis] result[img_idx] = result_img return result def imresize_single_image(image, sizes, interpolation=None): grayscale = False if image.shape == 2: grayscale = True image = image[:, :, np.newaxis] assert len(image.shape) == 3, image.shape rs = imresize_many_images(image[np.newaxis, :, :, :], sizes, interpolation=interpolation) if grayscale: return np.squeeze(rs[0, :, :, 0]) else: return rs[0, ...] def draw_grid(images, rows=None, cols=None): if is_np_array(images): assert len(images.shape) == 4 else: assert is_iterable(images) nb_images = len(images) cell_height = max([image.shape[0] for image in images]) cell_width = max([image.shape[1] for image in images]) channels = set([image.shape[2] for image in images]) assert len(channels) == 1 nb_channels = list(channels)[0] if rows is None and cols is None: rows = cols = int(math.ceil(math.sqrt(nb_images))) elif rows is not None: cols = int(math.ceil(nb_images / rows)) elif cols is not None: rows = int(math.ceil(nb_images / cols)) assert rows * cols >= nb_images width = cell_width * cols height = cell_height * rows grid = np.zeros((height, width, nb_channels)) cell_idx = 0 for row_idx in sm.xrange(rows): for col_idx in sm.xrange(cols): if cell_idx < nb_images: image = images[cell_idx] cell_y1 = cell_height * row_idx cell_y2 = cell_y1 + image.shape[0] cell_x1 = cell_width * col_idx cell_x2 = cell_x1 + image.shape[1] grid[cell_y1:cell_y2, cell_x1:cell_x2, :] = image cell_idx += 1 return grid def show_grid(images, rows=None, cols=None): grid = draw_grid(images, rows=rows, cols=cols) misc.imshow(grid) class HooksImages(object): """ # TODO """ def __init__(self, activator=None, propagator=None, preprocessor=None, postprocessor=None): self.activator = activator self.propagator = propagator self.preprocessor = preprocessor self.postprocessor = postprocessor def is_activated(self, images, augmenter, parents, default): if self.activator is None: return default else: return self.activator(images, augmenter, parents, default) # TODO is a propagating hook necessary? seems to be covered by activated # hook already def is_propagating(self, images, augmenter, parents, default): if self.propagator is None: return default else: return self.propagator(images, augmenter, parents, default) def preprocess(self, images, augmenter, parents): if self.preprocessor is None: return images else: return self.preprocessor(images, augmenter, parents) def postprocess(self, images, augmenter, parents): if self.postprocessor is None: return images else: return self.postprocessor(images, augmenter, parents) class HooksKeypoints(HooksImages): pass class Keypoint(object): """ # TODO """ def __init__(self, x, y): # these checks are currently removed because they are very slow for some # reason #assert is_single_integer(x), type(x) #assert is_single_integer(y), type(y) self.x = x self.y = y def project(self, from_shape, to_shape): if from_shape[0:2] == to_shape[0:2]: return Keypoint(x=self.x, y=self.y) else: from_height, from_width = from_shape[0:2] to_height, to_width = to_shape[0:2] x = int(round((self.x / from_width) * to_width)) y = int(round((self.y / from_height) * to_height)) return Keypoint(x=x, y=y) def shift(self, x, y): return Keypoint(self.x + x, self.y + y) def __repr__(self): return self.__str__() def __str__(self): return "Keypoint(x=%d, y=%d)" % (self.x, self.y) class KeypointsOnImage(object): def __init__(self, keypoints, shape): self.keypoints = keypoints if is_np_array(shape): self.shape = shape.shape else: assert isinstance(shape, (tuple, list)) self.shape = tuple(shape) @property def height(self): return self.shape[0] @property def width(self): return self.shape[1] def on(self, image): if is_np_array(image): shape = image.shape else: shape = image if shape[0:2] == self.shape[0:2]: return self.deepcopy() else: keypoints = [kp.project(self.shape, shape) for kp in self.keypoints] return KeypointsOnImage(keypoints, shape) def draw_on_image(self, image, color=[0, 255, 0], size=3, copy=True, raise_if_out_of_image=False): if copy: image = np.copy(image) height, width = image.shape[0:2] for keypoint in self.keypoints: y, x = keypoint.y, keypoint.x if 0 <= y < height and 0 <= x < width: x1 = max(x - size//2, 0) x2 = min(x + 1 + size//2, width - 1) y1 = max(y - size//2, 0) y2 = min(y + 1 + size//2, height - 1) image[y1:y2, x1:x2] = color else: if raise_if_out_of_image: raise Exception("Cannot draw keypoint x=%d, y=%d on image with shape %s." % (y, x, image.shape)) return image def shift(self, x, y): keypoints = [keypoint.shift(x=x, y=y) for keypoint in self.keypoints] return KeypointsOnImage(keypoints, self.shape) def get_coords_array(self): result = np.zeros((len(self.keypoints), 2), np.int32) for i, keypoint in enumerate(self.keypoints): result[i, 0] = keypoint.x result[i, 1] = keypoint.y return result @staticmethod def from_coords_array(coords, shape): assert is_integer_array(coords), coords.dtype keypoints = [Keypoint(x=coords[i, 0], y=coords[i, 1]) for i in sm.xrange(coords.shape[0])] return KeypointsOnImage(keypoints, shape) def to_keypoint_image(self): assert len(self.keypoints) > 0 height, width = self.shape[0:2] image = np.zeros((height, width, len(self.keypoints)), dtype=np.uint8) for i, keypoint in enumerate(self.keypoints): y = keypoint.y x = keypoint.x if 0 <= y < height and 0 <= x < width: image[y, x, i] = 255 return image @staticmethod def from_keypoint_image(image, if_not_found_coords={"x": -1, "y": -1}, threshold=1): assert len(image.shape) == 3 height, width, nb_keypoints = image.shape drop_if_not_found = False if if_not_found_coords is None: drop_if_not_found = True if_not_found_x = -1 if_not_found_y = -1 elif isinstance(if_not_found_coords, (tuple, list)): assert len(if_not_found_coords) == 2 if_not_found_x = if_not_found_coords[0] if_not_found_y = if_not_found_coords[1] elif isinstance(if_not_found_coords, dict): if_not_found_x = if_not_found_coords["x"] if_not_found_y = if_not_found_coords["y"] else: raise Exception("Expected if_not_found_coords to be None or tuple or list or dict, got %s." % (type(if_not_found_coords),)) keypoints = [] for i in sm.xrange(nb_keypoints): maxidx_flat = np.argmax(image[..., i]) maxidx_ndim = np.unravel_index(maxidx_flat, (height, width)) found = (image[maxidx_ndim[0], maxidx_ndim[1], i] >= threshold) if found: keypoints.append(Keypoint(x=maxidx_ndim[1], y=maxidx_ndim[0])) else: if drop_if_not_found: pass # dont add the keypoint to the result list, i.e. drop it else: keypoints.append(Keypoint(x=if_not_found_x, y=if_not_found_y)) return KeypointsOnImage(keypoints, shape=(height, width)) def copy(self): return copy.copy(self) def deepcopy(self): # for some reason deepcopy is way slower here than manual copy #return copy.deepcopy(self) kps = [Keypoint(x=kp.x, y=kp.y) for kp in self.keypoints] return KeypointsOnImage(kps, tuple(self.shape)) def __repr__(self): return self.__str__() def __str__(self): #print(type(self.keypoints), type(self.shape)) return "KeypointOnImage(%s, shape=%s)" % (str(self.keypoints), self.shape) # TODO """ class BackgroundAugmenter(object): def __init__(self, image_source, augmenter, maxlen, nb_workers=1): self.augmenter = augmenter self.maxlen = maxlen self.result_queue = multiprocessing.Queue(maxlen) self.batch_workers = [] for i in range(nb_workers): worker = multiprocessing.Process(target=self._augment, args=(image_source, augmenter, self.result_queue)) worker.daemon = True worker.start() self.batch_workers.append(worker) def join(self): for worker in self.batch_workers: worker.join() def get_batch(self): return self.result_queue.get() def _augment(self, image_source, augmenter, result_queue): batch = next(image_source) self.result_queue.put(augmenter.transform(batch)) """
imgaug-master
imgaug/imgaug.py
from __future__ import print_function, division, absolute_import from . import imgaug as ia from .parameters import StochasticParameter, Deterministic, Binomial, Choice, DiscreteUniform, Normal, Uniform from abc import ABCMeta, abstractmethod import random import numpy as np import copy as copy_module import re import math from scipy import misc, ndimage from skimage import transform as tf import itertools import cv2 import six import six.moves as sm @six.add_metaclass(ABCMeta) class Augmenter(object): """Base class for Augmenter objects Parameters ---------- name : string, optional Name given to an Augmenter object deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, name=None, deterministic=False, random_state=None): super(Augmenter, self).__init__() if name is None: self.name = "Unnamed%s" % (self.__class__.__name__,) else: self.name = name self.deterministic = deterministic if random_state is None: if self.deterministic: self.random_state = ia.new_random_state() else: self.random_state = ia.current_random_state() elif isinstance(random_state, np.random.RandomState): self.random_state = random_state else: self.random_state = np.random.RandomState(random_state) self.activated = True def augment_batches(self, batches, hooks=None): """Augment images, batch-wise Parameters ---------- batches : array-like, shape = (num_samples, height, width, channels) image batch to augment hooks : optional(default=None) HooksImages object to dynamically interfere with the Augmentation process Returns ------- augmented_batch : array-like, shape = (num_samples, height, width, channels) corresponding batch of augmented images """ assert isinstance(batches, list) return [self.augment_images(batch, hooks=hooks) for batch in batches] def augment_image(self, image, hooks=None): """Augment a single image Parameters ---------- image : array-like, shape = (height, width, channels) The image to augment hooks : optional(default=None) HooksImages object to dynamically interfere with the Augmentation process Returns ------- img : array-like, shape = (height, width, channels) The corresponding augmented image """ assert len(image.shape) == 3, "Expected image to have shape (height, width, channels), got shape %s." % (image.shape,) return self.augment_images([image], hooks=hooks)[0] def augment_images(self, images, parents=None, hooks=None): """Augment multiple images Parameters ---------- images : array-like, shape = (num_samples, height, width, channels) or a list of images (particularly useful for images of various dimensions) images to augment parents : optional(default=None) # TODO hooks : optional(default=None) HooksImages object to dynamically interfere with the Augmentation process Returns ------- images_result : array-like, shape = (num_samples, height, width, channels) corresponding augmented images """ if self.deterministic: state_orig = self.random_state.get_state() if parents is None: parents = [] if hooks is None: hooks = ia.HooksImages() if ia.is_np_array(images): assert len(images.shape) == 4, "Expected 4d array of form (N, height, width, channels), got shape %s." % (str(images.shape),) assert images.dtype == np.uint8, "Expected dtype uint8 (with value range 0 to 255), got dtype %s." % (str(images.dtype),) images_tf = images elif ia.is_iterable(images): if len(images) > 0: assert all([len(image.shape) == 3 for image in images]), "Expected list of images with each image having shape (height, width, channels), got shapes %s." % ([image.shape for image in images],) assert all([image.dtype == np.uint8 for image in images]), "Expected dtype uint8 (with value range 0 to 255), got dtypes %s." % ([str(image.dtype) for image in images],) images_tf = list(images) else: raise Exception("Expected list/tuple of numpy arrays or one numpy array, got %s." % (type(images),)) if isinstance(images_tf, list): images_copy = [np.copy(image) for image in images] else: images_copy = np.copy(images) images_copy = hooks.preprocess(images_copy, augmenter=self, parents=parents) if hooks.is_activated(images_copy, augmenter=self, parents=parents, default=self.activated): if len(images) > 0: images_result = self._augment_images( images_copy, random_state=ia.copy_random_state(self.random_state), parents=parents, hooks=hooks ) self.random_state.uniform() else: images_result = images_copy else: images_result = images_copy images_result = hooks.postprocess(images_result, augmenter=self, parents=parents) if self.deterministic: self.random_state.set_state(state_orig) if isinstance(images_result, list): assert all([image.dtype == np.uint8 for image in images_result]), "Expected list of dtype uint8 as augmenter result, got %s." % ([image.dtype for image in images_result],) else: assert images_result.dtype == np.uint8, "Expected dtype uint8 as augmenter result, got %s." % (images_result.dtype,) return images_result @abstractmethod def _augment_images(self, images, random_state, parents, hooks): raise NotImplementedError() def augment_keypoints(self, keypoints_on_images, parents=None, hooks=None): """Augment image keypoints Parameters ---------- keypoints_on_images : # TODO parents : optional(default=None) # TODO hooks : optional(default=None) HooksImages object to dynamically interfere with the Augmentation process Returns ------- keypoints_on_images_result : # TODO """ if self.deterministic: state_orig = self.random_state.get_state() if parents is None: parents = [] if hooks is None: hooks = ia.HooksKeypoints() assert ia.is_iterable(keypoints_on_images) assert all([isinstance(keypoints_on_image, ia.KeypointsOnImage) for keypoints_on_image in keypoints_on_images]) keypoints_on_images_copy = [keypoints_on_image.deepcopy() for keypoints_on_image in keypoints_on_images] keypoints_on_images_copy = hooks.preprocess(keypoints_on_images_copy, augmenter=self, parents=parents) if hooks.is_activated(keypoints_on_images_copy, augmenter=self, parents=parents, default=self.activated): if len(keypoints_on_images_copy) > 0: keypoints_on_images_result = self._augment_keypoints( keypoints_on_images_copy, random_state=ia.copy_random_state(self.random_state), parents=parents, hooks=hooks ) self.random_state.uniform() else: keypoints_on_images_result = keypoints_on_images_copy else: keypoints_on_images_result = keypoints_on_images_copy keypoints_on_images_result = hooks.postprocess(keypoints_on_images_result, augmenter=self, parents=parents) if self.deterministic: self.random_state.set_state(state_orig) return keypoints_on_images_result @abstractmethod def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): raise NotImplementedError() # TODO most of the code of this function could be replaced with ia.draw_grid() def draw_grid(self, images, rows, cols): if ia.is_np_array(images): if len(images.shape) == 4: images = [images[i] for i in range(images.shape[0])] elif len(images.shape) == 3: images = [images] elif len(images.shape) == 2: images = [images[:, :, np.newaxis]] else: raise Exception("Unexpected images shape, expected 2-, 3- or 4-dimensional array, got shape %s." % (images.shape,)) assert isinstance(images, list) det = self if self.deterministic else self.to_deterministic() augs = [] for image in images: augs.append(det.augment_images([image] * (rows * cols))) augs_flat = list(itertools.chain(*augs)) cell_height = max([image.shape[0] for image in images] + [image.shape[0] for image in augs_flat]) cell_width = max([image.shape[1] for image in images] + [image.shape[1] for image in augs_flat]) width = cell_width * cols height = cell_height * (rows * len(images)) grid = np.zeros((height, width, 3)) for row_idx in range(rows): for img_idx, image in enumerate(images): for col_idx in range(cols): image_aug = augs[img_idx][(row_idx * cols) + col_idx] cell_y1 = cell_height * (row_idx * len(images) + img_idx) cell_y2 = cell_y1 + image_aug.shape[0] cell_x1 = cell_width * col_idx cell_x2 = cell_x1 + image_aug.shape[1] grid[cell_y1:cell_y2, cell_x1:cell_x2, :] = image_aug return grid def show_grid(self, images, rows, cols): """Quickly show examples results of the applied augmentation Parameters ---------- images : array-like, shape = (num_samples, height, width, channels) or a list of images (particularly useful for images of various dimensions) images to augment rows : integer. number of rows in the grid cols : integer number of columns in the grid """ grid = self.draw_grid(images, rows, cols) misc.imshow(grid) def to_deterministic(self, n=None): """ # TODO """ if n is None: return self.to_deterministic(1)[0] else: return [self._to_deterministic() for _ in sm.xrange(n)] def _to_deterministic(self): """ # TODO """ aug = self.copy() aug.random_state = ia.new_random_state() aug.deterministic = True return aug def reseed(self, deterministic_too=False, random_state=None): """For reseeding the internal random_state Parameters ---------- deterministic_too : boolean, optional(default=False) # TODO random_state : np.random.RandomState instance, optional(default=None) random seed generator """ if random_state is None: random_state = ia.current_random_state() elif isinstance(random_state, np.random.RandomState): pass # just use the provided random state without change else: random_state = ia.new_random_state(random_state) if not self.deterministic or deterministic_too: seed = random_state.randint(0, 10**6, 1)[0] self.random_state = ia.new_random_state(seed) for lst in self.get_children_lists(): for aug in lst: aug.reseed(deterministic_too=deterministic_too, random_state=random_state) @abstractmethod def get_parameters(self): raise NotImplementedError() def get_children_lists(self): return [] def find_augmenters(self, func, parents=None, flat=True): """ # TODO """ if parents is None: parents = [] result = [] if func(self, parents): result.append(self) subparents = parents + [self] for lst in self.get_children_lists(): for aug in lst: found = aug.find_augmenters(func, parents=subparents, flat=flat) if len(found) > 0: if flat: result.extend(found) else: result.append(found) return result def find_augmenters_by_name(self, name, regex=False, flat=True): """Find augmenter(s) by name Parameters ---------- name : string name of the augmenter to find regex : regular Expression, optional(default=False) Regular Expression for searching the augmenter flat : boolean, optional(default=True) # TODO Returns ------- found augmenter instance """ return self.find_augmenters_by_names([name], regex=regex, flat=flat) def find_augmenters_by_names(self, names, regex=False, flat=True): """Find augmenters by names Parameters ---------- names : list of strings names of the augmenter to find regex : regular Expression, optional(default=False) Regular Expression for searching the augmenter flat : boolean, optional(default=True) # TODO Returns ------- found augmenter instance(s) """ if regex: def comparer(aug, parents): for pattern in names: if re.match(pattern, aug.name): return True return False return self.find_augmenters(comparer, flat=flat) else: return self.find_augmenters(lambda aug, parents: aug.name in names, flat=flat) def remove_augmenters(self, func, copy=True, noop_if_topmost=True): """Remove Augmenters from the list of augmenters Parameters ---------- func : # TODO copy : boolean, optional(default=True) removing the augmenter or it's copy noop_if_topmost : boolean, optional(default=True) if func is provided and noop_if_topmost is True an object of Noop class is returned Returns ------- aug : removed augmenter object """ if func(self, []): if not copy: raise Exception("Inplace removal of topmost augmenter requested, which is currently not possible.") if noop_if_topmost: return Noop() else: return None else: aug = self if not copy else self.deepcopy() aug.remove_augmenters_inplace(func, parents=[]) return aug def remove_augmenters_inplace(self, func, parents): """Inplace removal of augmenters Parameters ---------- func : # TODO parents : # TODO """ subparents = parents + [self] for lst in self.get_children_lists(): to_remove = [] for i, aug in enumerate(lst): if func(aug, subparents): to_remove.append((i, aug)) for count_removed, (i, aug) in enumerate(to_remove): # self._remove_augmenters_inplace_from_list(lst, aug, i, i - count_removed) del lst[i - count_removed] for aug in lst: aug.remove_augmenters_inplace(func, subparents) # TODO # def to_json(self): # pass def copy(self): """Obtain a copy""" return copy_module.copy(self) def deepcopy(self): """Obtain a deep copy""" return copy_module.deepcopy(self) def __repr__(self): return self.__str__() def __str__(self): params = self.get_parameters() params_str = ", ".join([param.__str__() for param in params]) return "%s(name=%s, parameters=[%s], deterministic=%s)" % (self.__class__.__name__, self.name, params_str, self.deterministic) class Sequential(Augmenter, list): """Sequential class is used to apply a number of transformations in an ordered / random sequence It is essentially an Augmenter comprising of multiple Augmenters Parameters ---------- children : optional(default=None) random_order : boolean, optional(default=False) whether to apply the listed transformations in a random order name : string, optional(default=None) name of the object deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, children=None, random_order=False, name=None, deterministic=False, random_state=None): Augmenter.__init__(self, name=name, deterministic=deterministic, random_state=random_state) list.__init__(self, children if children is not None else []) self.random_order = random_order def _augment_images(self, images, random_state, parents, hooks): if hooks.is_propagating(images, augmenter=self, parents=parents, default=True): if self.random_order: # for augmenter in self.children: for index in random_state.permutation(len(self)): images = self[index].augment_images( images=images, parents=parents + [self], hooks=hooks ) else: # for augmenter in self.children: for augmenter in self: images = augmenter.augment_images( images=images, parents=parents + [self], hooks=hooks ) return images def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): if hooks.is_propagating(keypoints_on_images, augmenter=self, parents=parents, default=True): if self.random_order: for index in random_state.permutation(len(self)): keypoints_on_images = self[index].augment_keypoints( keypoints_on_images=keypoints_on_images, parents=parents + [self], hooks=hooks ) else: for augmenter in self: keypoints_on_images = augmenter.augment_keypoints( keypoints_on_images=keypoints_on_images, parents=parents + [self], hooks=hooks ) return keypoints_on_images def _to_deterministic(self): augs = [aug.to_deterministic() for aug in self] seq = self.copy() seq[:] = augs seq.random_state = ia.new_random_state() seq.deterministic = True return seq def get_parameters(self): return [] def add(self, augmenter): """Add an additional augmenter""" self.append(augmenter) def get_children_lists(self): """Return all the children augmenters""" return [self] def __str__(self): # augs_str = ", ".join([aug.__str__() for aug in self.children]) augs_str = ", ".join([aug.__str__() for aug in self]) return "Sequential(name=%s, augmenters=[%s], deterministic=%s)" % (self.name, augs_str, self.deterministic) class Sometimes(Augmenter): """Sometimes is an Augmenter that augments according to some probability Given the probability "p", only certain number of images will be transformed Parameters ---------- p : float, optional(default=0.5) determines the probability with which the associated Augmentation will be applied. eg. value of 0.5 Augments roughly 50% of the image samples that are up for Augmentation then_list : optional(default=None) # TODO else_list : optional(default=None) # TODO name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, p=0.5, then_list=None, else_list=None, name=None, deterministic=False, random_state=None): super(Sometimes, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_float(p) or ia.is_single_integer(p): assert 0 <= p <= 1 self.p = Binomial(p) elif isinstance(p, StochasticParameter): self.p = p else: raise Exception("Expected float/int in range [0, 1] or StochasticParameter as p, got %s." % (type(p),)) if then_list is None: self.then_list = Sequential([], name="%s-then" % (self.name,)) elif ia.is_iterable(then_list): self.then_list = Sequential(then_list, name="%s-then" % (self.name,)) elif isinstance(then_list, Augmenter): self.then_list = Sequential([then_list], name="%s-then" % (self.name,)) else: raise Exception("Expected None, Augmenter or list/tuple as then_list, got %s." % (type(then_list),)) if else_list is None: self.else_list = Sequential([], name="%s-else" % (self.name,)) elif ia.is_iterable(else_list): self.else_list = Sequential(else_list, name="%s-else" % (self.name,)) elif isinstance(else_list, Augmenter): self.else_list = Sequential([else_list], name="%s-else" % (self.name,)) else: raise Exception("Expected None, Augmenter or list/tuple as else_list, got %s." % (type(else_list),)) def _augment_images(self, images, random_state, parents, hooks): result = images if hooks.is_propagating(images, augmenter=self, parents=parents, default=True): nb_images = len(images) samples = self.p.draw_samples((nb_images,), random_state=random_state) # create lists/arrays of images for if and else lists (one for each) indices_then_list = np.where(samples == 1)[0] # np.where returns tuple(array([0, 5, 9, ...])) or tuple(array([])) indices_else_list = np.where(samples == 0)[0] if isinstance(images, list): images_then_list = [images[i] for i in indices_then_list] images_else_list = [images[i] for i in indices_else_list] else: images_then_list = images[indices_then_list] images_else_list = images[indices_else_list] # augment according to if and else list result_then_list = self.then_list.augment_images( images=images_then_list, parents=parents + [self], hooks=hooks ) result_else_list = self.else_list.augment_images( images=images_else_list, parents=parents + [self], hooks=hooks ) # map results of if/else lists back to their initial positions (in "images" variable) result = [None] * len(images) for idx_result_then_list, idx_images in enumerate(indices_then_list): result[idx_images] = result_then_list[idx_result_then_list] for idx_result_else_list, idx_images in enumerate(indices_else_list): result[idx_images] = result_else_list[idx_result_else_list] # if input was a list, keep the output as a list too, # otherwise it was a numpy array, so make the output a numpy array too if not isinstance(images, list): result = np.array(result, dtype=np.uint8) return result def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): # TODO this is mostly copy pasted from _augment_images, make dry result = keypoints_on_images if hooks.is_propagating(keypoints_on_images, augmenter=self, parents=parents, default=True): nb_images = len(keypoints_on_images) samples = self.p.draw_samples((nb_images,), random_state=random_state) # create lists/arrays of images for if and else lists (one for each) indices_then_list = np.where(samples == 1)[0] # np.where returns tuple(array([0, 5, 9, ...])) or tuple(array([])) indices_else_list = np.where(samples == 0)[0] images_then_list = [keypoints_on_images[i] for i in indices_then_list] images_else_list = [keypoints_on_images[i] for i in indices_else_list] # augment according to if and else list result_then_list = self.then_list.augment_keypoints( keypoints_on_images=images_then_list, parents=parents + [self], hooks=hooks ) result_else_list = self.else_list.augment_keypoints( keypoints_on_images=images_else_list, parents=parents + [self], hooks=hooks ) # map results of if/else lists back to their initial positions (in "images" variable) result = [None] * len(keypoints_on_images) for idx_result_then_list, idx_images in enumerate(indices_then_list): result[idx_images] = result_then_list[idx_result_then_list] for idx_result_else_list, idx_images in enumerate(indices_else_list): result[idx_images] = result_else_list[idx_result_else_list] return result def _to_deterministic(self): aug = self.copy() aug.then_list = aug.then_list.to_deterministic() aug.else_list = aug.else_list.to_deterministic() aug.deterministic = True aug.random_state = ia.new_random_state() return aug def get_parameters(self): return [self.p] def get_children_lists(self): return [self.then_list, self.else_list] def __str__(self): return "Sometimes(p=%s, name=%s, then_list=[%s], else_list=[%s], deterministic=%s)" % (self.p, self.name, self.then_list, self.else_list, self.deterministic) class Noop(Augmenter): """Noop is an Augmenter that does nothing Parameters ---------- name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, name=None, deterministic=False, random_state=None): #Augmenter.__init__(self, name=name, deterministic=deterministic, random_state=random_state) super(Noop, self).__init__(name=name, deterministic=deterministic, random_state=random_state) def _augment_images(self, images, random_state, parents, hooks): return images def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): return keypoints_on_images def get_parameters(self): return [] class Lambda(Augmenter): """ # TODO """ def __init__(self, func_images, func_keypoints, name=None, deterministic=False, random_state=None): #Augmenter.__init__(self, name=name, deterministic=deterministic, random_state=random_state) super(Lambda, self).__init__(name=name, deterministic=deterministic, random_state=random_state) self.func_images = func_images self.func_keypoints = func_keypoints def _augment_images(self, images, random_state, parents, hooks): return self.func_images(images, random_state, parents=parents, hooks=hooks) def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): result = self.func_keypoints(keypoints_on_images, random_state, parents=parents, hooks=hooks) assert isinstance(result, list) assert all([isinstance(el, ia.KeypointsOnImage) for el in result]) return result def get_parameters(self): return [] def AssertLambda(func_images, func_keypoints, name=None, deterministic=False, random_state=None): def func_images_assert(images, random_state, parents, hooks): assert func_images(images, random_state, parents=parents, hooks=hooks) return images def func_keypoints_assert(keypoints_on_images, random_state, parents, hooks): assert func_keypoints(keypoints_on_images, random_state, parents=parents, hooks=hooks) return keypoints_on_images if name is None: name = "UnnamedAssertLambda" return Lambda(func_images_assert, func_keypoints_assert, name=name, deterministic=deterministic, random_state=random_state) def AssertShape(shape, check_images=True, check_keypoints=True, name=None, deterministic=False, random_state=None): assert len(shape) == 4, "Expected shape to have length 4, got %d with shape: %s." % (len(shape), str(shape)) def compare(observed, expected, dimension, image_index): if expected is not None: if ia.is_single_integer(expected): assert observed == expected, "Expected dim %d (entry index: %s) to have value %d, got %d." % (dimension, image_index, expected, observed) elif isinstance(expected, tuple): assert len(expected) == 2 assert expected[0] <= observed < expected[1], "Expected dim %d (entry index: %s) to have value in range [%d, %d), got %d." % (dimension, image_index, expected[0], expected[1], observed) elif isinstance(expected, list): assert any([observed == val for val in expected]), "Expected dim %d (entry index: %s) to have any value of %s, got %d." % (dimension, image_index, str(expected), observed) else: raise Exception("Invalid datatype for shape entry %d, expected each entry to be an integer, a tuple (with two entries) or a list, got %s." % (dimension, type(expected),)) def func_images(images, random_state, parents, hooks): if check_images: #assert is_np_array(images), "AssertShape can currently only handle numpy arrays, got " if isinstance(images, list): if shape[0] is not None: compare(len(images), shape[0], 0, "ALL") for i in sm.xrange(len(images)): image = images[i] assert len(image.shape) == 3, "Expected image number %d to have a shape of length 3, got %d (shape: %s)." % (i, len(image.shape), str(image.shape)) for j in sm.xrange(len(shape)-1): expected = shape[j+1] observed = image.shape[j] compare(observed, expected, j, i) else: assert len(images.shape) == 4, "Expected image's shape to have length 4, got %d (shape: %s)." % (len(images.shape), str(images.shape)) for i in range(4): expected = shape[i] observed = images.shape[i] compare(observed, expected, i, "ALL") return images def func_keypoints(keypoints_on_images, random_state, parents, hooks): if check_keypoints: #assert is_np_array(images), "AssertShape can currently only handle numpy arrays, got " if shape[0] is not None: compare(len(keypoints_on_images), shape[0], 0, "ALL") for i in sm.xrange(len(keypoints_on_images)): keypoints_on_image = keypoints_on_images[i] for j in sm.xrange(len(shape[0:2])): expected = shape[j+1] observed = keypoints_on_image.shape[j] compare(observed, expected, j, i) return keypoints_on_images if name is None: name = "UnnamedAssertShape" return Lambda(func_images, func_keypoints, name=name, deterministic=deterministic, random_state=random_state) class Crop(Augmenter): """Crop Augmenter object that crops input image(s) Parameters ---------- px : # TODO percent : tuple, optional(default=None) percent crop on each of the axis keep_size : boolean, optional(default=True) # TODO name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, px=None, percent=None, keep_size=True, name=None, deterministic=False, random_state=None): super(Crop, self).__init__(name=name, deterministic=deterministic, random_state=random_state) self.keep_size = keep_size self.all_sides = None self.top = None self.right = None self.bottom = None self.left = None if px is None and percent is None: self.mode = "noop" elif px is not None and percent is not None: raise Exception("Can only crop by pixels or percent, not both.") elif px is not None: self.mode = "px" if ia.is_single_integer(px): assert px >= 0 #self.top = self.right = self.bottom = self.left = Deterministic(px) self.all_sides = Deterministic(px) elif isinstance(px, tuple): assert len(px) in [2, 4] def handle_param(p): if ia.is_single_integer(p): assert p >= 0 return Deterministic(p) elif isinstance(p, tuple): assert len(p) == 2 assert ia.is_single_integer(p[0]) assert ia.is_single_integer(p[1]) assert p[0] >= 0 assert p[1] >= 0 return DiscreteUniform(p[0], p[1]) elif isinstance(p, list): assert len(p) > 0 assert all([ia.is_single_integer(val) for val in p]) assert all([val >= 0 for val in p]) return Choice(p) elif isinstance(p, StochasticParameter): return p else: raise Exception("Expected int, tuple of two ints, list of ints or StochasticParameter, got type %s." % (type(p),)) if len(px) == 2: #self.top = self.right = self.bottom = self.left = handle_param(px) self.all_sides = handle_param(px) else: # len == 4 self.top = handle_param(px[0]) self.right = handle_param(px[1]) self.bottom = handle_param(px[2]) self.left = handle_param(px[3]) elif isinstance(px, StochasticParameter): self.top = self.right = self.bottom = self.left = px else: raise Exception("Expected int, tuple of 4 ints/lists/StochasticParameters or StochasticParameter, git type %s." % (type(px),)) else: # = elif percent is not None: self.mode = "percent" if ia.is_single_number(percent): assert 0 <= percent < 1.0 #self.top = self.right = self.bottom = self.left = Deterministic(percent) self.all_sides = Deterministic(percent) elif isinstance(percent, tuple): assert len(percent) in [2, 4] def handle_param(p): if ia.is_single_number(p): return Deterministic(p) elif isinstance(p, tuple): assert len(p) == 2 assert ia.is_single_number(p[0]) assert ia.is_single_number(p[1]) assert 0 <= p[0] < 1.0 assert 0 <= p[1] < 1.0 return Uniform(p[0], p[1]) elif isinstance(p, list): assert len(p) > 0 assert all([ia.is_single_number(val) for val in p]) assert all([0 <= val < 1.0 for val in p]) return Choice(p) elif isinstance(p, StochasticParameter): return p else: raise Exception("Expected int, tuple of two ints, list of ints or StochasticParameter, got type %s." % (type(p),)) if len(percent) == 2: #self.top = self.right = self.bottom = self.left = handle_param(percent) self.all_sides = handle_param(percent) else: # len == 4 self.top = handle_param(percent[0]) self.right = handle_param(percent[1]) self.bottom = handle_param(percent[2]) self.left = handle_param(percent[3]) elif isinstance(percent, StochasticParameter): self.top = self.right = self.bottom = self.left = percent else: raise Exception("Expected number, tuple of 4 numbers/lists/StochasticParameters or StochasticParameter, got type %s." % (type(percent),)) def _augment_images(self, images, random_state, parents, hooks): result = [] nb_images = len(images) seeds = random_state.randint(0, 10**6, (nb_images,)) for i in sm.xrange(nb_images): seed = seeds[i] height, width = images[i].shape[0:2] top, right, bottom, left = self._draw_samples_image(seed, height, width) image_cropped = images[i][top:height-bottom, left:width-right, :] if self.keep_size: image_cropped = ia.imresize_single_image(image_cropped, (height, width)) result.append(image_cropped) if not isinstance(images, list): if self.keep_size: result = np.array(result, dtype=np.uint8) return result def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): result = [] nb_images = len(keypoints_on_images) seeds = random_state.randint(0, 10**6, (nb_images,)) for i, keypoints_on_image in enumerate(keypoints_on_images): seed = seeds[i] height, width = keypoints_on_image.shape[0:2] top, right, bottom, left = self._draw_samples_image(seed, height, width) shifted = keypoints_on_image.shift(x=-left, y=-top) shifted.shape = (height - top - bottom, width - left - right) if self.keep_size: result.append(shifted.on(keypoints_on_image.shape)) else: result.append(shifted) return result def _draw_samples_image(self, seed, height, width): random_state = ia.new_random_state(seed) if self.all_sides is not None: samples = self.all_sides.draw_samples((4,), random_state=random_state) top, right, bottom, left = samples else: rs_top = random_state rs_right = rs_top rs_bottom = rs_top rs_left = rs_top top = self.top.draw_sample(random_state=rs_top) right = self.right.draw_sample(random_state=rs_right) bottom = self.bottom.draw_sample(random_state=rs_bottom) left = self.left.draw_sample(random_state=rs_left) if self.mode == "px": # no change necessary for pixel values pass elif self.mode == "percent": # percentage values have to be transformed to pixel values top = int(height * top) right = int(width * right) bottom = int(height * bottom) left = int(width * left) else: raise Exception("Invalid mode") remaining_height = height - (top + bottom) remaining_width = width - (left + right) if remaining_height < 1: regain = abs(remaining_height) + 1 regain_top = regain // 2 regain_bottom = regain // 2 if regain_top + regain_bottom < regain: regain_top += 1 if regain_top > top: diff = regain_top - top regain_top = top regain_bottom += diff elif regain_bottom > bottom: diff = regain_bottom - bottom regain_bottom = bottom regain_top += diff assert regain_top <= top assert regain_bottom <= bottom top = top - regain_top bottom = bottom - regain_bottom if remaining_width < 1: regain = abs(remaining_width) + 1 regain_right = regain // 2 regain_left = regain // 2 if regain_right + regain_left < regain: regain_right += 1 if regain_right > right: diff = regain_right - right regain_right = right regain_left += diff elif regain_left > left: diff = regain_left - left regain_left = left regain_right += diff assert regain_right <= right assert regain_left <= left right = right - regain_right left = left - regain_left assert top >= 0 and right >= 0 and bottom >= 0 and left >= 0 assert top + bottom < height assert right + left < width return top, right, bottom, left def get_parameters(self): return [self.top, self.right, self.bottom, self.left] class Fliplr(Augmenter): """Flip the input images horizontally Parameters ---------- p : int, float or StochasticParameter number or percentage of samples to Flip name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, p=0, name=None, deterministic=False, random_state=None): super(Fliplr, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_number(p): self.p = Binomial(p) elif isinstance(p, StochasticParameter): self.p = p else: raise Exception("Expected p to be int or float or StochasticParameter, got %s." % (type(p),)) def _augment_images(self, images, random_state, parents, hooks): nb_images = len(images) samples = self.p.draw_samples((nb_images,), random_state=random_state) for i in sm.xrange(nb_images): if samples[i] == 1: images[i] = np.fliplr(images[i]) return images def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): nb_images = len(keypoints_on_images) samples = self.p.draw_samples((nb_images,), random_state=random_state) for i, keypoints_on_image in enumerate(keypoints_on_images): if samples[i] == 1: width = keypoints_on_image.shape[1] for keypoint in keypoints_on_image.keypoints: keypoint.x = (width - 1) - keypoint.x return keypoints_on_images def get_parameters(self): return [self.p] class Flipud(Augmenter): """Flip the input images vertically Parameters ---------- p : int, float or StochasticParameter number or percentage of samples to Flip name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, p=0, name=None, deterministic=False, random_state=None): super(Flipud, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_number(p): self.p = Binomial(p) elif isinstance(p, StochasticParameter): self.p = p else: raise Exception("Expected p to be int or float or StochasticParameter, got %s." % (type(p),)) def _augment_images(self, images, random_state, parents, hooks): nb_images = len(images) samples = self.p.draw_samples((nb_images,), random_state=random_state) for i in sm.xrange(nb_images): if samples[i] == 1: images[i] = np.flipud(images[i]) return images def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): nb_images = len(keypoints_on_images) samples = self.p.draw_samples((nb_images,), random_state=random_state) for i, keypoints_on_image in enumerate(keypoints_on_images): if samples[i] == 1: height = keypoints_on_image.shape[0] for keypoint in keypoints_on_image.keypoints: keypoint.y = (height - 1) - keypoint.y return keypoints_on_images def get_parameters(self): return [self.p] # TODO tests # Note: Not clear whether this class will be kept (for anything aside from grayscale) # other colorspaces dont really make sense and they also might not work correctly # due to having no clearly limited range (like 0-255 or 0-1) class ChangeColorspace(Augmenter): RGB = "RGB" BGR = "BGR" GRAY = "GRAY" CIE = "CIE" YCrCb = "YCrCb" HSV = "HSV" HLS = "HLS" Lab = "Lab" Luv = "Luv" COLORSPACES = set([ RGB, BGR, GRAY, CIE, YCrCb, HSV, HLS, Lab, Luv ]) CV_VARS = { # RGB #"RGB2RGB": cv2.COLOR_RGB2RGB, "RGB2BGR": cv2.COLOR_RGB2BGR, "RGB2GRAY": cv2.COLOR_RGB2GRAY, "RGB2CIE": cv2.COLOR_RGB2XYZ, "RGB2YCrCb": cv2.COLOR_RGB2YCR_CB, "RGB2HSV": cv2.COLOR_RGB2HSV, "RGB2HLS": cv2.COLOR_RGB2HLS, "RGB2LAB": cv2.COLOR_RGB2LAB, "RGB2LUV": cv2.COLOR_RGB2LUV, # BGR "BGR2RGB": cv2.COLOR_BGR2RGB, #"BGR2BGR": cv2.COLOR_BGR2BGR, "BGR2GRAY": cv2.COLOR_BGR2GRAY, "BGR2CIE": cv2.COLOR_BGR2XYZ, "BGR2YCrCb": cv2.COLOR_BGR2YCR_CB, "BGR2HSV": cv2.COLOR_BGR2HSV, "BGR2HLS": cv2.COLOR_BGR2HLS, "BGR2LAB": cv2.COLOR_BGR2LAB, "BGR2LUV": cv2.COLOR_BGR2LUV } def __init__(self, to_colorspace, alpha, from_colorspace="RGB", name=None, deterministic=False, random_state=None): super(ChangeColorspace, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_number(alpha): self.alpha = Deterministic(alpha) elif ia.is_iterable(alpha): assert len(alpha) == 2, "Expected tuple/list with 2 entries, got %d entries." % (str(len(alpha)),) self.alpha = Uniform(alpha[0], alpha[1]) elif isinstance(p, StochasticParameter): self.alpha = alpha else: raise Exception("Expected alpha to be int or float or tuple/list of ints/floats or StochasticParameter, got %s." % (type(alpha),)) if ia.is_string(to_colorspace): assert to_colorspace in ChangeColorspace.COLORSPACES self.to_colorspace = Deterministic(to_colorspace) elif ia.is_iterable(to_colorspace): assert all([ia.is_string(colorspace) for colorspace in to_colorspace]) assert all([(colorspace in ChangeColorspace.COLORSPACES) for colorspace in to_colorspace]) self.to_colorspace = Choice(to_colorspace) elif isinstance(to_colorspace, StochasticParameter): self.to_colorspace = to_colorspace else: raise Exception("Expected to_colorspace to be string, list of strings or StochasticParameter, got %s." % (type(to_colorspace),)) self.from_colorspace = from_colorspace assert self.from_colorspace in ChangeColorspace.COLORSPACES assert from_colorspace != ChangeColorspace.GRAY def _augment_images(self, images, random_state, parents, hooks): result = images nb_images = len(images) alphas = self.alpha.draw_samples((nb_images,), random_state=ia.copy_random_state(random_state)) to_colorspaces = self.to_colorspace.draw_samples((nb_images,), random_state=ia.copy_random_state(random_state)) for i in sm.xrange(nb_images): alpha = alphas[i] to_colorspace = to_colorspaces[i] image = images[i] assert 0.0 <= alpha <= 1.0 assert to_colorspace in ChangeColorspace.COLORSPACES if alpha == 0 or self.from_colorspace == to_colorspace: pass # no change necessary else: # some colorspaces here should use image/255.0 according to the docs, # but at least for conversion to grayscale that results in errors, # ie uint8 is expected if self.from_colorspace in [ChangeColorspace.RGB, ChangeColorspace.BGR]: from_to_var_name = "%s2%s" % (self.from_colorspace, to_colorspace) from_to_var = ChangeColorspace.CV_VARS[from_to_var_name] img_to_cs = cv2.cvtColor(image, from_to_var) else: # convert to RGB from_to_var_name = "%s2%s" % (self.from_colorspace, ChangeColorspace.RGB) from_to_var = ChangeColorspace.CV_VARS[from_to_var_name] img_rgb = cv2.cvtColor(image, from_to_var) # convert from RGB to desired target colorspace from_to_var_name = "%s2%s" % (ChangeColorspace.RGB, to_colorspace) from_to_var = ChangeColorspace.CV_VARS[from_to_var_name] img_to_cs = cv2.cvtColor(img_rgb, from_to_var) # this will break colorspaces that have values outside 0-255 or 0.0-1.0 if ia.is_integer_array(img_to_cs): img_to_cs = np.clip(img_to_cs, 0, 255).astype(np.uint8) else: img_to_cs = np.clip(img_to_cs * 255, 0, 255).astype(np.uint8) if len(img_to_cs.shape) == 2: img_to_cs = img_to_cs[:, :, np.newaxis] img_to_cs = np.tile(img_to_cs, (1, 1, 3)) if alpha == 1: result[i] = img_to_cs else: result[i] = (alpha * img_to_cs + (1 - alpha) * image).astype(np.uint8) return images def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): return keypoints_on_images def get_parameters(self): return [self.alpha, self.to_colorspace] # TODO tests def Grayscale(alpha=0, from_colorspace="RGB", name=None, deterministic=False, random_state=None): return ChangeColorspace(to_colorspace=ChangeColorspace.GRAY, alpha=alpha, from_colorspace=from_colorspace, name=name, deterministic=deterministic, random_state=random_state) class GaussianBlur(Augmenter): """Apply GaussianBlur to input images Parameters ---------- sigma : float, list/iterable of length 2 of floats or StochasticParameter variance parameter. name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, sigma=0, name=None, deterministic=False, random_state=None): super(GaussianBlur, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_number(sigma): self.sigma = Deterministic(sigma) elif ia.is_iterable(sigma): assert len(sigma) == 2, "Expected tuple/list with 2 entries, got %d entries." % (str(len(sigma)),) self.sigma = Uniform(sigma[0], sigma[1]) elif isinstance(sigma, StochasticParameter): self.sigma = sigma else: raise Exception("Expected float, int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(sigma),)) def _augment_images(self, images, random_state, parents, hooks): result = images nb_images = len(images) samples = self.sigma.draw_samples((nb_images,), random_state=random_state) for i in sm.xrange(nb_images): nb_channels = images[i].shape[2] sig = samples[i] if sig > 0: for channel in sm.xrange(nb_channels): result[i][:, :, channel] = ndimage.gaussian_filter(result[i][:, :, channel], sig) return result def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): return keypoints_on_images def get_parameters(self): return [self.sigma] def AdditiveGaussianNoise(loc=0, scale=0, per_channel=False, name=None, deterministic=False, random_state=None): """Add Random Gaussian Noise to images Parameters ---------- loc : integer/ optional(default=0) # TODO scale : integer/optional(default=0) # TODO per_channel : boolean, optional(default=False) Apply transformation in a per channel manner name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ if ia.is_single_number(loc): loc2 = Deterministic(loc) elif ia.is_iterable(loc): assert len(loc) == 2, "Expected tuple/list with 2 entries for argument 'loc', got %d entries." % (str(len(scale)),) loc2 = Uniform(loc[0], loc[1]) elif isinstance(loc, StochasticParameter): loc2 = loc else: raise Exception("Expected float, int, tuple/list with 2 entries or StochasticParameter for argument 'loc'. Got %s." % (type(loc),)) if ia.is_single_number(scale): scale2 = Deterministic(scale) elif ia.is_iterable(scale): assert len(scale) == 2, "Expected tuple/list with 2 entries for argument 'scale', got %d entries." % (str(len(scale)),) scale2 = Uniform(scale[0], scale[1]) elif isinstance(scale, StochasticParameter): scale2 = scale else: raise Exception("Expected float, int, tuple/list with 2 entries or StochasticParameter for argument 'scale'. Got %s." % (type(scale),)) return AddElementwise(Normal(loc=loc2, scale=scale2), per_channel=per_channel, name=name, deterministic=deterministic, random_state=random_state) # TODO #class MultiplicativeGaussianNoise(Augmenter): # pass # TODO #class ReplacingGaussianNoise(Augmenter): # pass def Dropout(p=0, per_channel=False, name=None, deterministic=False, random_state=None): """Dropout (Blacken) certain fraction of pixels Parameters ---------- p : float, iterable of len 2, StochasticParameter optional(default=0) per_channel : boolean, optional(default=False) apply transform in a per channel manner name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Returns ------- # TODO """ if ia.is_single_number(p): p2 = Binomial(1 - p) elif ia.is_iterable(p): assert len(p) == 2 assert p[0] < p[1] assert 0 <= p[0] <= 1.0 assert 0 <= p[1] <= 1.0 p2 = Binomial(Uniform(1- p[1], 1 - p[0])) elif isinstance(p, StochasticParameter): p2 = p else: raise Exception("Expected p to be float or int or StochasticParameter, got %s." % (type(p),)) return MultiplyElementwise(p2, per_channel=per_channel, name=name, deterministic=deterministic, random_state=random_state) # TODO tests class Add(Augmenter): """Augmenter that Adds a value elementwise to the pixels of the image Parameters ---------- value : integer, iterable of len 2, StochasticParameter value to be added to the pixels/elements per_channel : boolean, optional(default=False) apply transform in a per channel manner name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, value=0, per_channel=False, name=None, deterministic=False, random_state=None): super(Add, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_integer(value): assert -255 <= value <= 255, "Expected value to have range [-255, 255], got value %d." % (value,) self.value = Deterministic(value) elif ia.is_iterable(value): assert len(value) == 2, "Expected tuple/list with 2 entries, got %d entries." % (len(value),) self.value = DiscreteUniform(value[0], value[1]) elif isinstance(value, StochasticParameter): self.value = value else: raise Exception("Expected float or int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(value),)) if per_channel in [True, False, 0, 1, 0.0, 1.0]: self.per_channel = Deterministic(int(per_channel)) elif ia.is_single_number(per_channel): assert 0 <= per_channel <= 1.0 self.per_channel = Binomial(per_channel) else: raise Exception("Expected per_channel to be boolean or number or StochasticParameter") def _augment_images(self, images, random_state, parents, hooks): result = images nb_images = len(images) seeds = random_state.randint(0, 10**6, (nb_images,)) for i in sm.xrange(nb_images): image = images[i].astype(np.int32) rs_image = ia.new_random_state(seeds[i]) per_channel = self.per_channel.draw_sample(random_state=rs_image) if per_channel == 1: nb_channels = image.shape[2] samples = self.value.draw_samples((nb_channels,), random_state=rs_image) for c, sample in enumerate(samples): assert -255 <= sample <= 255 image[..., c] += sample np.clip(image, 0, 255, out=image) result[i] = image.astype(np.uint8) else: sample = self.value.draw_sample(random_state=rs_image) assert -255 <= sample <= 255 image += sample np.clip(image, 0, 255, out=image) result[i] = image.astype(np.uint8) return result def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): return keypoints_on_images def get_parameters(self): return [self.value] # TODO tests class AddElementwise(Augmenter): # TODO def __init__(self, value=0, per_channel=False, name=None, deterministic=False, random_state=None): super(AddElementwise, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_integer(value): assert -255 <= value <= 255, "Expected value to have range [-255, 255], got value %d." % (value,) self.value = Deterministic(value) elif ia.is_iterable(value): assert len(value) == 2, "Expected tuple/list with 2 entries, got %d entries." % (len(value),) self.value = DiscreteUniform(value[0], value[1]) elif isinstance(value, StochasticParameter): self.value = value else: raise Exception("Expected float or int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(value),)) if per_channel in [True, False, 0, 1, 0.0, 1.0]: self.per_channel = Deterministic(int(per_channel)) elif ia.is_single_number(per_channel): assert 0 <= per_channel <= 1.0 self.per_channel = Binomial(per_channel) else: raise Exception("Expected per_channel to be boolean or number or StochasticParameter") def _augment_images(self, images, random_state, parents, hooks): result = images nb_images = len(images) seeds = random_state.randint(0, 10**6, (nb_images,)) for i in sm.xrange(nb_images): seed = seeds[i] image = images[i].astype(np.int32) height, width, nb_channels = image.shape rs_image = ia.new_random_state(seed) per_channel = self.per_channel.draw_sample(random_state=rs_image) if per_channel == 1: samples = self.value.draw_samples((height, width, nb_channels), random_state=rs_image) else: samples = self.value.draw_samples((height, width, 1), random_state=rs_image) samples = np.tile(samples, (1, 1, nb_channels)) after_add = image + samples np.clip(after_add, 0, 255, out=after_add) result[i] = after_add.astype(np.uint8) return result def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): return keypoints_on_images def get_parameters(self): return [self.value] class Multiply(Augmenter): """Augmenter that Multiplies a value elementwise to the pixels of the image Parameters ---------- value : integer, iterable of len 2, StochasticParameter value to be added to the pixels/elements per_channel : boolean, optional(default=False) apply transform in a per channel manner name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, mul=1.0, per_channel=False, name=None, deterministic=False, random_state=None): super(Multiply, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_number(mul): assert mul >= 0.0, "Expected multiplier to have range [0, inf), got value %.4f." % (mul,) self.mul = Deterministic(mul) elif ia.is_iterable(mul): assert len(mul) == 2, "Expected tuple/list with 2 entries, got %d entries." % (len(mul),) self.mul = Uniform(mul[0], mul[1]) elif isinstance(mul, StochasticParameter): self.mul = mul else: raise Exception("Expected float or int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(mul),)) if per_channel in [True, False, 0, 1, 0.0, 1.0]: self.per_channel = Deterministic(int(per_channel)) elif ia.is_single_number(per_channel): assert 0 <= per_channel <= 1.0 self.per_channel = Binomial(per_channel) else: raise Exception("Expected per_channel to be boolean or number or StochasticParameter") def _augment_images(self, images, random_state, parents, hooks): result = images nb_images = len(images) seeds = random_state.randint(0, 10**6, (nb_images,)) for i in sm.xrange(nb_images): image = images[i].astype(np.float32) rs_image = ia.new_random_state(seeds[i]) per_channel = self.per_channel.draw_sample(random_state=rs_image) if per_channel == 1: nb_channels = image.shape[2] samples = self.mul.draw_samples((nb_channels,), random_state=rs_image) for c, sample in enumerate(samples): assert sample >= 0 image[..., c] *= sample np.clip(image, 0, 255, out=image) result[i] = image.astype(np.uint8) else: sample = self.mul.draw_sample(random_state=rs_image) assert sample >= 0 image *= sample np.clip(image, 0, 255, out=image) result[i] = image.astype(np.uint8) return result def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): return keypoints_on_images def get_parameters(self): return [self.mul] # TODO tests class MultiplyElementwise(Augmenter): # TODO def __init__(self, mul=1.0, per_channel=False, name=None, deterministic=False, random_state=None): super(MultiplyElementwise, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_number(mul): assert mul >= 0.0, "Expected multiplier to have range [0, inf), got value %.4f." % (mul,) self.mul = Deterministic(mul) elif ia.is_iterable(mul): assert len(mul) == 2, "Expected tuple/list with 2 entries, got %d entries." % (str(len(mul)),) self.mul = Uniform(mul[0], mul[1]) elif isinstance(mul, StochasticParameter): self.mul = mul else: raise Exception("Expected float or int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(mul),)) if per_channel in [True, False, 0, 1, 0.0, 1.0]: self.per_channel = Deterministic(int(per_channel)) elif ia.is_single_number(per_channel): assert 0 <= per_channel <= 1.0 self.per_channel = Binomial(per_channel) else: raise Exception("Expected per_channel to be boolean or number or StochasticParameter") def _augment_images(self, images, random_state, parents, hooks): result = images nb_images = len(images) seeds = random_state.randint(0, 10**6, (nb_images,)) for i in sm.xrange(nb_images): seed = seeds[i] image = images[i].astype(np.float32) height, width, nb_channels = image.shape rs_image = ia.new_random_state(seed) per_channel = self.per_channel.draw_sample(random_state=rs_image) if per_channel == 1: samples = self.mul.draw_samples((height, width, nb_channels), random_state=rs_image) else: samples = self.mul.draw_samples((height, width, 1), random_state=rs_image) samples = np.tile(samples, (1, 1, nb_channels)) after_multiply = image * samples np.clip(after_multiply, 0, 255, out=after_multiply) result[i] = after_multiply.astype(np.uint8) return result def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): return keypoints_on_images def get_parameters(self): return [self.mul] # TODO tests class ContrastNormalization(Augmenter): """Augmenter class for ContrastNormalization Parameters ---------- alpha : float, iterable of len 2, StochasticParameter Normalization parameter that governs the contrast ratio of the resulting image per_channel : boolean, optional(default=False) apply transform in a per channel manner name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, alpha=1.0, per_channel=False, name=None, deterministic=False, random_state=None): super(ContrastNormalization, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_number(alpha): assert alpha >= 0.0, "Expected alpha to have range (0, inf), got value %.4f." % (alpha,) self.alpha = Deterministic(alpha) elif ia.is_iterable(alpha): assert len(alpha) == 2, "Expected tuple/list with 2 entries, got %d entries." % (str(len(alpha)),) self.alpha = Uniform(alpha[0], alpha[1]) elif isinstance(alpha, StochasticParameter): self.alpha = alpha else: raise Exception("Expected float or int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(alpha),)) if per_channel in [True, False, 0, 1, 0.0, 1.0]: self.per_channel = Deterministic(int(per_channel)) elif ia.is_single_number(per_channel): assert 0 <= per_channel <= 1.0 self.per_channel = Binomial(per_channel) else: raise Exception("Expected per_channel to be boolean or number or StochasticParameter") def _augment_images(self, images, random_state, parents, hooks): result = images nb_images = len(images) seeds = random_state.randint(0, 10**6, (nb_images,)) for i in sm.xrange(nb_images): image = images[i].astype(np.float32) rs_image = ia.new_random_state(seeds[i]) per_channel = self.per_channel.draw_sample(random_state=rs_image) if per_channel: nb_channels = images[i].shape[2] alphas = self.alpha.draw_samples((nb_channels,), random_state=rs_image) for c, alpha in enumerate(alphas): image[..., c] = alpha * (image[..., c] - 128) + 128 else: alpha = self.alpha.draw_sample(random_state=rs_image) image = alpha * (image - 128) + 128 np.clip(image, 0, 255, out=image) result[i] = image.astype(np.uint8) return result def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): return keypoints_on_images def get_parameters(self): return [self.alpha] class Affine(Augmenter): """Augmenter for Affine Transformations An Affine Transformation is a linear mapping that preserves points, straight lines and planes Parameters ---------- scale : # TODO translate_percent : # TODO translate_px : # TODO rotate : # TODO shear : # TODO order : # TODO cval : # TODO mode : # TODO per_channel : boolean, optional(default=False) apply transform in a per channel manner name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, scale=1.0, translate_percent=None, translate_px=None, rotate=0.0, shear=0.0, order=1, cval=0.0, mode="constant", name=None, deterministic=False, random_state=None): super(Affine, self).__init__(name=name, deterministic=deterministic, random_state=random_state) # Peformance: # 1.0x order 0 # 1.5x order 1 # 3.0x order 3 # 30.0x order 4 # 60.0x order 5 # measurement based on 256x256x3 batches, difference is smaller # on smaller images (seems to grow more like exponentially with image # size) if order == ia.ALL: # self.order = DiscreteUniform(0, 5) self.order = Choice([0, 1, 3, 4, 5]) # dont use order=2 (bi-quadratic) because that is apparently currently not recommended (and throws a warning) elif ia.is_single_integer(order): assert 0 <= order <= 5, "Expected order's integer value to be in range 0 <= x <= 5, got %d." % (order,) self.order = Deterministic(order) elif isinstance(order, list): assert all([ia.is_single_integer(val) for val in order]), "Expected order list to only contain integers, got types %s." % (str([type(val) for val in order]),) assert all([0 <= val <= 5 for val in order]), "Expected all of order's integer values to be in range 0 <= x <= 5, got %s." % (str(order),) self.order = Choice(order) elif isinstance(order, StochasticParameter): self.order = order else: raise Exception("Expected order to be imgaug.ALL, int or StochasticParameter, got %s." % (type(order),)) if cval == ia.ALL: self.cval = Uniform(0, 1.0) elif ia.is_single_number(cval): assert 0 <= cval <= 1.0 self.cval = Deterministic(cval) elif ia.is_iterable(cval): assert len(cval) == 2 assert 0 <= cval[0] <= 1.0 assert 0 <= cval[1] <= 1.0 self.cval = Uniform(cval[0], cval[1]) elif isinstance(cval, StochasticParameter): self.cval = cval else: raise Exception("Expected cval to be imgaug.ALL, int, float or StochasticParameter, got %s." % (type(cval),)) # constant, edge, symmetric, reflect, wrap if mode == ia.ALL: self.mode = Choice(["constant", "edge", "symmetric", "reflect", "wrap"]) elif ia.is_string(mode): self.mode = Deterministic(mode) elif isinstance(mode, list): assert all([ia.is_string(val) for val in mode]) self.mode = Choice(mode) elif isinstance(mode, StochasticParameter): self.mode = mode else: raise Exception("Expected mode to be imgaug.ALL, a string, a list of strings or StochasticParameter, got %s." % (type(mode),)) # scale # float | (float, float) | [float, float] | StochasticParameter def scale_handle_param(param, allow_dict): if isinstance(param, StochasticParameter): return param elif ia.is_single_number(param): assert param > 0.0, "Expected scale to have range (0, inf), got value %.4f. Note: The value to _not_ change the scale of images is 1.0, not 0.0." % (param,) return Deterministic(param) elif ia.is_iterable(param) and not isinstance(param, dict): assert len(param) == 2, "Expected scale tuple/list with 2 entries, got %d entries." % (str(len(param)),) assert param[0] > 0.0 and param[1] > 0.0, "Expected scale tuple/list to have values in range (0, inf), got values %.4f and %.4f. Note: The value to _not_ change the scale of images is 1.0, not 0.0." % (param[0], param[1]) return Uniform(param[0], param[1]) elif allow_dict and isinstance(param, dict): assert "x" in param or "y" in param x = param.get("x") y = param.get("y") x = x if x is not None else 1.0 y = y if y is not None else 1.0 return (scale_handle_param(x, False), scale_handle_param(y, False)) else: raise Exception("Expected float, int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(param),)) self.scale = scale_handle_param(scale, True) # translate if translate_percent is None and translate_px is None: translate_px = 0 assert translate_percent is None or translate_px is None if translate_percent is not None: # translate by percent def translate_handle_param(param, allow_dict): if ia.is_single_number(param): return Deterministic(float(param)) elif ia.is_iterable(param) and not isinstance(param, dict): assert len(param) == 2, "Expected translate_percent tuple/list with 2 entries, got %d entries." % (str(len(param)),) all_numbers = all([ia.is_single_number(p) for p in param]) assert all_numbers, "Expected translate_percent tuple/list to contain only numbers, got types %s." % (str([type(p) for p in param]),) #assert param[0] > 0.0 and param[1] > 0.0, "Expected translate_percent tuple/list to have values in range (0, inf), got values %.4f and %.4f." % (param[0], param[1]) return Uniform(param[0], param[1]) elif allow_dict and isinstance(param, dict): assert "x" in param or "y" in param x = param.get("x") y = param.get("y") x = x if x is not None else 0 y = y if y is not None else 0 return (translate_handle_param(x, False), translate_handle_param(y, False)) elif isinstance(param, StochasticParameter): return param else: raise Exception("Expected float, int or tuple/list with 2 entries of both floats or ints or StochasticParameter. Got %s." % (type(param),)) self.translate = translate_handle_param(translate_percent, True) else: # translate by pixels def translate_handle_param(param, allow_dict): if ia.is_single_integer(param): return Deterministic(param) elif ia.is_iterable(param) and not isinstance(param, dict): assert len(param) == 2, "Expected translate_px tuple/list with 2 entries, got %d entries." % (str(len(param)),) all_integer = all([ia.is_single_integer(p) for p in param]) assert all_integer, "Expected translate_px tuple/list to contain only integers, got types %s." % (str([type(p) for p in param]),) return DiscreteUniform(param[0], param[1]) elif allow_dict and isinstance(param, dict): assert "x" in param or "y" in param x = param.get("x") y = param.get("y") x = x if x is not None else 0 y = y if y is not None else 0 return (translate_handle_param(x, False), translate_handle_param(y, False)) elif isinstance(param, StochasticParameter): return param else: raise Exception("Expected int or tuple/list with 2 ints or StochasticParameter. Got %s." % (type(param),)) self.translate = translate_handle_param(translate_px, True) # rotate # StochasticParameter | float | int | (float or int, float or int) | [float or int, float or int] if isinstance(rotate, StochasticParameter): self.rotate = rotate elif ia.is_single_number(rotate): self.rotate = Deterministic(rotate) elif ia.is_iterable(rotate): assert len(rotate) == 2, "Expected rotate tuple/list with 2 entries, got %d entries." % (str(len(rotate)),) assert all([ia.is_single_number(val) for val in rotate]), "Expected floats/ints in rotate tuple/list" self.rotate = Uniform(rotate[0], rotate[1]) else: raise Exception("Expected float, int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(rotate),)) # shear # StochasticParameter | float | int | (float or int, float or int) | [float or int, float or int] if isinstance(shear, StochasticParameter): self.shear = shear elif ia.is_single_number(shear): self.shear = Deterministic(shear) elif ia.is_iterable(shear): assert len(shear) == 2, "Expected rotate tuple/list with 2 entries, got %d entries." % (str(len(shear)),) assert all([ia.is_single_number(val) for val in shear]), "Expected floats/ints in shear tuple/list." self.shear = Uniform(shear[0], shear[1]) else: raise Exception("Expected float, int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(shear),)) def _augment_images(self, images, random_state, parents, hooks): # skimage's warp() converts to 0-1 range, so we use float here and then convert # at the end # float images are expected by skimage's warp() to be in range 0-1, so we divide by 255 if isinstance(images, list): result = [image.astype(np.float32, copy=False) for image in images] result = [image / 255.0 for image in images] else: result = images.astype(np.float32, copy=False) result = result / 255.0 nb_images = len(images) scale_samples, translate_samples, rotate_samples, shear_samples, cval_samples, mode_samples, order_samples = self._draw_samples(nb_images, random_state) for i in sm.xrange(nb_images): height, width = result[i].shape[0], result[i].shape[1] shift_x = int(width / 2.0) shift_y = int(height / 2.0) scale_x, scale_y = scale_samples[0][i], scale_samples[1][i] translate_x, translate_y = translate_samples[0][i], translate_samples[1][i] #assert isinstance(translate_x, (float, int)) #assert isinstance(translate_y, (float, int)) if ia.is_single_float(translate_y): translate_y_px = int(round(translate_y * images[i].shape[0])) else: translate_y_px = translate_y if ia.is_single_float(translate_x): translate_x_px = int(round(translate_x * images[i].shape[1])) else: translate_x_px = translate_x rotate = rotate_samples[i] shear = shear_samples[i] cval = cval_samples[i] mode = mode_samples[i] order = order_samples[i] if scale_x != 1.0 or scale_y != 1.0 or translate_x_px != 0 or translate_y_px != 0 or rotate != 0 or shear != 0: matrix_to_topleft = tf.SimilarityTransform(translation=[-shift_x, -shift_y]) matrix_transforms = tf.AffineTransform( scale=(scale_x, scale_y), translation=(translate_x_px, translate_y_px), rotation=math.radians(rotate), shear=math.radians(shear) ) matrix_to_center = tf.SimilarityTransform(translation=[shift_x, shift_y]) matrix = (matrix_to_topleft + matrix_transforms + matrix_to_center) result[i] = tf.warp( result[i], matrix.inverse, order=order, mode=mode, cval=cval ) result[i] *= 255.0 np.clip(result[i], 0, 255, out=result[i]) if isinstance(images, list): result = [image.astype(np.uint8, copy=False) for image in result] else: result = result.astype(np.uint8, copy=False) return result def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): result = [] nb_images = len(keypoints_on_images) scale_samples, translate_samples, rotate_samples, shear_samples, cval_samples, mode_samples, order_samples = self._draw_samples(nb_images, random_state) for i, keypoints_on_image in enumerate(keypoints_on_images): height, width = keypoints_on_image.height, keypoints_on_image.width shift_x = int(width / 2.0) shift_y = int(height / 2.0) scale_x, scale_y = scale_samples[0][i], scale_samples[1][i] translate_x, translate_y = translate_samples[0][i], translate_samples[1][i] #assert isinstance(translate_x, (float, int)) #assert isinstance(translate_y, (float, int)) if ia.is_single_float(translate_y): translate_y_px = int(round(translate_y * keypoints_on_image.shape[0])) else: translate_y_px = translate_y if ia.is_single_float(translate_x): translate_x_px = int(round(translate_x * keypoints_on_image.shape[1])) else: translate_x_px = translate_x rotate = rotate_samples[i] shear = shear_samples[i] #cval = cval_samples[i] #mode = mode_samples[i] #order = order_samples[i] if scale_x != 1.0 or scale_y != 1.0 or translate_x_px != 0 or translate_y_px != 0 or rotate != 0 or shear != 0: matrix_to_topleft = tf.SimilarityTransform(translation=[-shift_x, -shift_y]) matrix_transforms = tf.AffineTransform( scale=(scale_x, scale_y), translation=(translate_x_px, translate_y_px), rotation=math.radians(rotate), shear=math.radians(shear) ) matrix_to_center = tf.SimilarityTransform(translation=[shift_x, shift_y]) matrix = (matrix_to_topleft + matrix_transforms + matrix_to_center) coords = keypoints_on_image.get_coords_array() #print("coords", coords) #print("matrix", matrix.params) coords_aug = tf.matrix_transform(coords, matrix.params) #print("coords before", coords) #print("coordsa ftre", coords_aug, np.around(coords_aug).astype(np.int32)) result.append(ia.KeypointsOnImage.from_coords_array(np.around(coords_aug).astype(np.int32), shape=keypoints_on_image.shape)) else: result.append(keypoints_on_image) return result def get_parameters(self): return [self.scale, self.translate, self.rotate, self.shear] def _draw_samples(self, nb_samples, random_state): seed = random_state.randint(0, 10**6, 1)[0] if isinstance(self.scale, tuple): scale_samples = ( self.scale[0].draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 10)), self.scale[1].draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 20)), ) else: scale_samples = self.scale.draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 30)) scale_samples = (scale_samples, scale_samples) if isinstance(self.translate, tuple): translate_samples = ( self.translate[0].draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 40)), self.translate[1].draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 50)), ) else: translate_samples = self.translate.draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 60)) translate_samples = (translate_samples, translate_samples) assert translate_samples[0].dtype in [np.int32, np.int64, np.float32, np.float64] assert translate_samples[1].dtype in [np.int32, np.int64, np.float32, np.float64] rotate_samples = self.rotate.draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 70)) shear_samples = self.shear.draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 80)) cval_samples = self.cval.draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 90)) mode_samples = self.mode.draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 100)) order_samples = self.order.draw_samples((nb_samples,), random_state=ia.new_random_state(seed + 110)) return scale_samples, translate_samples, rotate_samples, shear_samples, cval_samples, mode_samples, order_samples # code partially from # https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a class ElasticTransformation(Augmenter): """Augmenter class for ElasticTransformations Elastic Transformations are transformations that allow non-rigid transformations of images. In a sense, Elastic Transformations are opposite of Affine Transforms, since Elastic Transformations can effect the lines, planes and points of an image. Elastic Transformations can be used to create new, unseen images from given images, and are used extensively in Machine Learning/Pattern Recognition. Parameters ---------- alpha : float, iterable of len 2, StochasticParameter # TODO sigma : float, iterable of len 2, StochasticParameter # TODO per_channel : boolean, optional(default=False) apply transform in a per channel manner name : string, optional(default=None) name of the instance deterministic : boolean, optional (default=False) Whether random state will be saved before augmenting images and then will be reset to the saved value post augmentation use this parameter to obtain transformations in the EXACT order everytime random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ def __init__(self, alpha=0, sigma=0, name=None, deterministic=False, random_state=None): super(ElasticTransformation, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if ia.is_single_number(alpha): assert alpha >= 0.0, "Expected alpha to have range [0, inf), got value %.4f." % (alpha,) self.alpha = Deterministic(alpha) elif ia.is_iterable(alpha): assert len(alpha) == 2, "Expected tuple/list with 2 entries, got %d entries." % (str(len(alpha)),) self.alpha = Uniform(alpha[0], alpha[1]) elif isinstance(alpha, StochasticParameter): self.alpha = alpha else: raise Exception("Expected float or int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(alpha),)) if ia.is_single_number(sigma): assert sigma >= 0.0, "Expected sigma to have range [0, inf), got value %.4f." % (sigma,) self.sigma = Deterministic(sigma) elif ia.is_iterable(sigma): assert len(sigma) == 2, "Expected tuple/list with 2 entries, got %d entries." % (str(len(sigma)),) self.sigma = Uniform(sigma[0], sigma[1]) elif isinstance(sigma, StochasticParameter): self.sigma = sigma else: raise Exception("Expected float or int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(sigma),)) def _augment_images(self, images, random_state, parents, hooks): result = images nb_images = len(images) seeds = ia.copy_random_state(random_state).randint(0, 10**6, (nb_images,)) alphas = self.alpha.draw_samples((nb_images,), random_state=ia.copy_random_state(random_state)) sigmas = self.sigma.draw_samples((nb_images,), random_state=ia.copy_random_state(random_state)) for i in sm.xrange(nb_images): image = images[i] image_first_channel = np.squeeze(image[..., 0]) indices_x, indices_y = ElasticTransformation.generate_indices(image_first_channel.shape, alpha=alphas[i], sigma=sigmas[i], random_state=ia.new_random_state(seeds[i])) result[i] = ElasticTransformation.map_coordinates(images[i], indices_x, indices_y) return result """ def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): # TODO do keypoints even have to be augmented for elastic transformations? # TODO this transforms keypoints to images, augments the images, then transforms # back to keypoints - inefficient and keypoints that get outside of the images # cannot be recovered result = [] nb_images = len(keypoints_on_images) seeds = ia.copy_random_state(random_state).randint(0, 10**6, (nb_images,)) alphas = self.alpha.draw_samples((nb_images,), random_state=ia.copy_random_state(random_state)) sigmas = self.sigma.draw_samples((nb_images,), random_state=ia.copy_random_state(random_state)) for i, keypoints_on_image in enumerate(keypoints_on_images): indices_x, indices_y = ElasticTransformation.generate_indices(keypoints_on_image.shape[0:2], alpha=alphas[i], sigma=sigmas[i], random_state=ia.new_random_state(seeds[i])) keypoint_image = keypoints_on_image.to_keypoint_image() keypoint_image_aug = ElasticTransformation.map_coordinates(keypoint_image, indices_x, indices_y) keypoints_aug = ia.KeypointsOnImage.from_keypoint_image(keypoint_image_aug) result.append(keypoints_aug) return result """ # no transformation of keypoints for this currently, # it seems like this is the more appropiate choice overall for this augmentation # technique def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): return keypoints_on_images def get_parameters(self): return [self.alpha, self.sigma] @staticmethod def generate_indices(shape, alpha, sigma, random_state): """Elastic deformation of images as described in [Simard2003]_. .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Conference on Document Analysis and Recognition, 2003. """ assert len(shape) == 2 dx = ndimage.gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha dy = ndimage.gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha x, y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij') return np.reshape(x+dx, (-1, 1)), np.reshape(y+dy, (-1, 1)) @staticmethod def map_coordinates(image, indices_x, indices_y): assert len(image.shape) == 3 result = np.copy(image) height, width = image.shape[0:2] for c in sm.xrange(image.shape[2]): remapped_flat = ndimage.interpolation.map_coordinates(image[..., c], (indices_x, indices_y), order=1) remapped = remapped_flat.reshape((height, width)) result[..., c] = remapped return result
imgaug-master
imgaug/augmenters.py
from __future__ import print_function, division, absolute_import from . import imgaug as ia from abc import ABCMeta, abstractmethod import numpy as np import copy as copy_module import six @six.add_metaclass(ABCMeta) class StochasticParameter(object): def __init__(self): super(StochasticParameter, self).__init__() def draw_sample(self, random_state=None): return self.draw_samples(1, random_state=random_state)[0] def draw_samples(self, size, random_state=None): random_state = random_state if random_state is not None else ia.current_random_state() return self._draw_samples(size, random_state) @abstractmethod def _draw_samples(self, size, random_state): raise NotImplementedError() def copy(self): return copy_module.copy(self) def deepcopy(self): return copy_module.deepcopy(self) class Binomial(StochasticParameter): def __init__(self, p): super(Binomial, self).__init__() if isinstance(p, StochasticParameter): self.p = p elif ia.is_single_number(p): assert 0 <= p <= 1.0, "Expected probability p to be in range [0.0, 1.0], got %s." % (p,) self.p = Deterministic(float(p)) else: raise Exception("Expected StochasticParameter or float/int value, got %s." % (type(p),)) def _draw_samples(self, size, random_state): p = self.p.draw_sample(random_state=random_state) assert 0 <= p <= 1.0, "Expected probability p to be in range [0.0, 1.0], got %s." % (p,) return random_state.binomial(1, p, size) def __repr__(self): return self.__str__() def __str__(self): if isinstance(self.p, float): return "Binomial(%.4f)" % (self.p,) else: return "Binomial(%s)" % (self.p,) class Choice(StochasticParameter): def __init__(self, a, replace=True, p=None): super(Choice, self).__init__() self.a = a self.replace = replace self.p = p def _draw_samples(self, size, random_state): return random_state.choice(self.a, size, replace=self.replace, p=self.p) def __repr__(self): return self.__str__() def __str__(self): return "Choice(a=%s, replace=%s, p=%s)" % (str(self.a), str(self.replace), str(self.p),) class DiscreteUniform(StochasticParameter): def __init__(self, a, b): StochasticParameter.__init__(self) # for two ints the samples will be from range a <= x <= b assert isinstance(a, (int, StochasticParameter)), "Expected a to be int or StochasticParameter, got %s" % (type(a),) assert isinstance(b, (int, StochasticParameter)), "Expected b to be int or StochasticParameter, got %s" % (type(b),) if ia.is_single_integer(a): self.a = Deterministic(a) else: self.a = a if ia.is_single_integer(b): self.b = Deterministic(b) else: self.b = b def _draw_samples(self, size, random_state): a = self.a.draw_sample(random_state=random_state) b = self.b.draw_sample(random_state=random_state) if a > b: a, b = b, a elif a == b: return np.tile(np.array([a]), size) return random_state.randint(a, b + 1, size) def __repr__(self): return self.__str__() def __str__(self): return "DiscreteUniform(%s, %s)" % (self.a, self.b) class Normal(StochasticParameter): def __init__(self, loc, scale): super(Normal, self).__init__() if isinstance(loc, StochasticParameter): self.loc = loc elif ia.is_single_number(loc): self.loc = Deterministic(loc) else: raise Exception("Expected float, int or StochasticParameter as loc, got %s, %s." % (type(loc),)) if isinstance(scale, StochasticParameter): self.scale = scale elif ia.is_single_number(scale): assert scale >= 0, "Expected scale to be in range [0, inf) got %s (type %s)." % (scale, type(scale)) self.scale = Deterministic(scale) else: raise Exception("Expected float, int or StochasticParameter as scale, got %s, %s." % (type(scale),)) def _draw_samples(self, size, random_state): loc = self.loc.draw_sample(random_state=random_state) scale = self.scale.draw_sample(random_state=random_state) assert scale >= 0, "Expected scale to be in rnage [0, inf), got %s." % (scale,) if scale == 0: return np.tile(loc, size) else: return random_state.normal(loc, scale, size=size) def __repr__(self): return self.__str__() def __str__(self): return "Normal(loc=%s, scale=%s)" % (self.loc, self.scale) class Uniform(StochasticParameter): def __init__(self, a, b): super(Uniform, self).__init__() assert isinstance(a, (int, float, StochasticParameter)), "Expected a to be int, float or StochasticParameter, got %s" % (type(a),) assert isinstance(b, (int, float, StochasticParameter)), "Expected b to be int, float or StochasticParameter, got %s" % (type(b),) if ia.is_single_number(a): self.a = Deterministic(a) else: self.a = a if ia.is_single_number(b): self.b = Deterministic(b) else: self.b = b def _draw_samples(self, size, random_state): a = self.a.draw_sample(random_state=random_state) b = self.b.draw_sample(random_state=random_state) if a > b: a, b = b, a elif a == b: return np.tile(np.array([a]), size) return random_state.uniform(a, b, size) def __repr__(self): return self.__str__() def __str__(self): return "Uniform(%s, %s)" % (self.a, self.b) class Deterministic(StochasticParameter): def __init__(self, value): super(Deterministic, self).__init__() if isinstance(value, StochasticParameter): self.value = value.draw_sample() elif ia.is_single_number(value) or ia.is_string(value): self.value = value else: raise Exception("Expected StochasticParameter object or number or string, got %s." % (type(value),)) def _draw_samples(self, size, random_state): return np.tile(np.array([self.value]), size) def __repr__(self): return self.__str__() def __str__(self): if isinstance(self.value, int): return "Deterministic(int %d)" % (self.value,) else: return "Deterministic(float %.8f)" % (self.value,) class FromLowerResolution(StochasticParameter): def __init__(self, other_param, size_percent=None, size_px=None, method="nearest", min_size=1): super(StochasticParameter, self).__init__() assert size_percent is not None or size_px is not None if size_percent is not None: self.size_method = "percent" self.size_px = None if ia.is_single_number(size_percent): self.size_percent = Deterministic(size_percent) elif ia.is_iterable(size_percent): assert len(size_percent) == 2 self.size_percent = Uniform(size_percent[0], size_percent[1]) elif isinstance(size_percent, StochasticParameter): self.size_percent = size_percent else: raise Exception("Expected int, float, tuple of two ints/floats or StochasticParameter for size_percent, got %s." % (type(size_percent),)) else: # = elif size_px is not None: self.size_method = "px" self.size_percent = None if ia.is_single_integer(size_px): self.size_px = Deterministic(size_px) elif ia.is_iterable(size_px): assert len(size_px) == 2 self.size_px = DiscreteUniform(size_px[0], size_px[1]) elif isinstance(size_px, StochasticParameter): self.size_px = size_px else: raise Exception("Expected int, float, tuple of two ints/floats or StochasticParameter for size_px, got %s." % (type(size_px),)) self.other_param = other_param if ia.is_string(method): self.method = Deterministic(method) elif isinstance(method, StochasticParameter): self.method = method else: raise Exception("Expected string or StochasticParameter, got %s." % (type(method),)) self.min_size = min_size def _draw_samples(self, size, random_state): if len(size) == 3: n = 1 h, w, c = size elif len(size) == 4: n, h, w, c = size else: raise Exception("FromLowerResolution can only generate samples of shape (H, W, C) or (N, H, W, C), requested was %s." % (str(size),)) if self.size_method == "percent": hw_percents = self.size_percent.draw_samples((n, 2), random_state=random_state) hw_pxs = (hw_percents * np.array([h, w])).astype(np.int32) else: hw_pxs = self.size_px.draw_samples((n, 2), random_state=random_state) methods = self.method.draw_samples((n,), random_state=random_state) result = None #for i, (size_factor, method) in enumerate(zip(size_factors, methods)): for i, (hw_px, method) in enumerate(zip(hw_pxs, methods)): #h_small = max(int(h * size_factor), self.min_size) #w_small = max(int(w * size_factor), self.min_size) h_small = max(hw_px[0], self.min_size) w_small = max(hw_px[1], self.min_size) samples = self.other_param.draw_samples((1, h_small, w_small, c)) samples_upscaled = ia.imresize_many_images(samples, (h, w), interpolation=method) if result is None: result = np.zeros((n, h, w, c), dtype=samples.dtype) result[i] = samples_upscaled if len(size) == 3: return result[0] else: return result def __repr__(self): return self.__str__() def __str__(self): if self.size_method == "percent": return "FromLowerResolution(size_percent=%s, method=%s, other_param=%s)" % (self.size_percent, self.method, self.other_param) else: return "FromLowerResolution(size_px=%s, method=%s, other_param=%s)" % (self.size_px, self.method, self.other_param) class Clip(StochasticParameter): def __init__(self, other_param, minval=None, maxval=None): super(Clip, self).__init__() assert isinstance(other_param, StochasticParameter) assert minval is None or ia.is_single_number(minval) assert maxval is None or ia.is_single_number(maxval) self.other_param = other_param self.minval = minval self.maxval = maxval def _draw_samples(self, size, random_state): samples = self.other_param.draw_samples(size, random_state=random_state) if self.minval is not None and self.maxval is not None: np.clip(samples, self.minval, self.maxval, out=samples) elif self.minval is not None: np.clip(samples, self.minval, np.max(samples), out=samples) elif self.maxval is not None: np.clip(samples, np.min(samples), self.maxval, out=samples) else: pass return samples def __repr__(self): return self.__str__() def __str__(self): opstr = str(self.other_param) if self.minval is not None and self.maxval is not None: return "Clip(%s, %.6f, %.6f)" % (opstr, float(self.minval), float(self.maxval)) elif self.minval is not None: return "Clip(%s, %.6f, None)" % (opstr, float(self.minval)) elif self.maxval is not None: return "Clip(%s, None, %.6f)" % (opstr, float(self.maxval)) else: return "Clip(%s, None, None)" % (opstr,)
imgaug-master
imgaug/parameters.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import os from scripts.download_data import ContactPoseDownloader osp = os.path def startup(data_dir=None, default_dir=osp.join('data', 'contactpose_data')): # check that the provided data_dir is OK if data_dir is not None: assert data_dir!=default_dir, \ "If you provide --data_dir, it must not be {:s}".format(default_dir) assert osp.isdir(data_dir), "If you provide --data_dir, it must exist" else: data_dir = default_dir if not osp.isdir(data_dir): if osp.isfile(data_dir) or osp.islink(data_dir): os.remove(data_dir) print('Removed file {:s}'.format(data_dir)) os.mkdir(data_dir) # symlink for easy access if data_dir != default_dir: if osp.islink(default_dir): os.remove(default_dir) print('Removed symlink {:s}'.format(default_dir)) os.symlink(data_dir, default_dir) print('Symlinked to {:s} for easy access'.format(default_dir)) downloader = ContactPoseDownloader() # download 3D models and marker locations downloader.download_3d_models() downloader.download_markers() # download all 3D joint, object pose, camera calibration data downloader.download_grasps() # download contact maps for participant 28, 'use' grasps downloader.download_contact_maps(28, 'use') # download RGB-D images for participant 28, bowl 'use' grasp downloader.download_images(28, 'use', data_dir, include_objects=('bowl',)) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--data_dir', default=None, help='Base data dir for the ContactPose dataset') args = parser.parse_args() startup(args.data_dir)
ContactPose-main
startup.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt
ContactPose-main
__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import numpy as np import logging import math import transforms3d.euler as txe import transforms3d.quaternions as txq import argparse import cv2 import matplotlib.pyplot as plt try: from thirdparty.mano.webuser.smpl_handpca_wrapper_HAND_only \ import load_model as load_mano_model MANO_PRESENT = True except ImportError: load_mano_model = None MANO_PRESENT = False if MANO_PRESENT: # hacks needed for MANO Python2 code import os.path as osp import _pickle as cPickle import sys sys.modules['cPickle'] = cPickle sys.path.append(osp.join('thirdparty', 'mano')) sys.path.append(osp.join('thirdparty', 'mano', 'webuser')) def texture_proc(colors, a=0.05, invert=False): idx = colors > 0 ci = colors[idx] if len(ci) == 0: return colors if invert: ci = 1 - ci # fit a sigmoid x1 = min(ci); y1 = a x2 = max(ci); y2 = 1-a lna = np.log((1 - y1) / y1) lnb = np.log((1 - y2) / y2) k = (lnb - lna) / (x1 - x2) mu = (x2*lna - x1*lnb) / (lna - lnb) # apply the sigmoid ci = np.exp(k * (ci-mu)) / (1 + np.exp(k * (ci-mu))) colors[idx] = ci return colors class MovingAverage: def __init__(self): self.count = 0 self.val = 0 def append(self, v): self.val = self.val*self.count + v self.count += 1 self.val /= self.count def linesegment_from_points(p1, p2): n = p2 - p1 return np.hstack((p1, n)) def get_hand_line_ids(): line_ids = [] for finger in range(5): base = 4*finger + 1 line_ids.append([0, base]) for j in range(3): line_ids.append([base+j, base+j+1]) line_ids = np.asarray(line_ids, dtype=int) return line_ids def rotmat_from_vecs(v1, v2=np.asarray([0, 0, 1])): """ Returns a rotation matrix R_1_2 :param v1: vector in frame 1 :param v2: vector in frame 2 :return: """ v1 = v1 / np.linalg.norm(v1) v2 = v2 / np.linalg.norm(v2) v = np.cross(v2, v1) vx = np.asarray([ [0, -v[2], +v[1], 0], [+v[2], 0, -v[0], 0], [-v[1], +v[0], 0, 0], [0, 0, 0, 0]]) dotp = np.dot(v1, v2) if np.abs(dotp + 1) < 1e-3: R = np.eye(4) x = np.cross(v2, [1, 0, 0]) R[:3, :3] = txe.axangle2mat(x, np.pi) else: R = np.eye(4) + vx + np.dot(vx, vx)/(1+dotp) return R def p_dist_linesegment(p, ls): """ Distance from point p to line segment ls p: Nx3 ls: Mx6 (2 3-dim endpoints of M line segments) """ # NxMx3 ap = p[:, np.newaxis, :] - ls[np.newaxis, :, :3] # 1xMx3 u = ls[np.newaxis, :, 3:] # 1xMx3 u_norm = u / np.linalg.norm(u, axis=2, keepdims=True) # NxM proj = np.sum(ap * u_norm, axis=2) # point to line distance # NxM d_line = np.linalg.norm(np.cross(ap, u_norm, axis=2), axis=2) # point to endpoint distance # NxM d_a = np.linalg.norm(ap, axis=2) d_b = np.linalg.norm(ap-u, axis=2) d_endp = np.minimum(d_a, d_b) within_ls = (proj > 0) * (proj < np.linalg.norm(u, axis=2)) * (d_endp < 0.03) d_ls = within_ls*d_line + (1-within_ls)*d_endp return d_ls def closest_linesegment_point(l0, l1, p): """ For each point in p, finds the closest point on the list of line segments whose endpoints are l0 and l1 p: N x 3 l0, l1: M x 3 out: N x M x 3 """ p = np.broadcast_to(p[:, np.newaxis, :], (len(p), len(l0), 3)) l0 = np.broadcast_to(l0[np.newaxis, :, :], (len(p), len(l0), 3)) l1 = np.broadcast_to(l1[np.newaxis, :, :], (len(p), len(l1), 3)) llen = np.linalg.norm(l1 - l0, axis=-1, keepdims=True) lu = (l1 - l0) / llen v = p - l0 d = np.sum(v * lu, axis=-1, keepdims=True) d = np.clip(d, a_min=0, a_max=llen) out = l0 + d*lu return out def pose_matrix(pose): T = np.eye(4) T[:3, 3] = pose['translation'] T[:3, :3] = txq.quat2mat(pose['rotation']) return T def tform_points(T, X): """ X: Nx3 T: 4x4 homogeneous """ X = np.vstack((X.T, np.ones(len(X)))) X = T @ X X = X[:3].T return X def project(P, X): """ X: Nx3 P: 3x4 projection matrix, ContactPose.P or K @ cTo returns Nx2 perspective projections """ X = np.vstack((X.T, np.ones(len(X)))) x = P @ X x = x[:2] / x[2] return x.T def get_A(camera_name, W=960, H=540): """ Get the affine transformation matrix applied after 3D->2D projection """ def flipud(H): return np.asarray([[1, 0, 0], [0, -1, H], [0, 0, 1]]) def fliplr(W): return np.asarray([[-1, 0, W], [0, 1, 0], [0, 0, 1]]) def transpose(): return np.asarray([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) if camera_name == 'kinect2_left': return np.dot(fliplr(H), transpose()) elif camera_name == 'kinect2_right': return np.dot(flipud(W), transpose()) elif camera_name == 'kinect2_middle': return np.dot(fliplr(W), flipud(H)) else: raise NotImplementedError def setup_logging(filename=None): logging.basicConfig(level=logging.DEBUG) root = logging.getLogger() if filename is not None: root.addHandler(logging.FileHandler(filename, 'w')) root.info('Logging to {:s}'.format(filename)) def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True): EPS = np.finfo(float).eps * 4.0 q0 = np.asarray(quat0) / np.linalg.norm(quat0) q1 = np.asarray(quat1) / np.linalg.norm(quat1) if fraction == 0.0: return q0 elif fraction == 1.0: return q1 d = np.dot(q0, q1) if abs(abs(d) - 1.0) < EPS: return q0 if shortestpath and d < 0.0: # invert rotation d = -d q1 *= -1.0 angle = math.acos(d) + spin * math.pi if abs(angle) < EPS: return q0 isin = 1.0 / math.sin(angle) q0 *= math.sin((1.0 - fraction) * angle) * isin q1 *= math.sin(fraction * angle) * isin q0 += q1 return q0 def average_quaternions(qs, ws=None): """ From https://qr.ae/TcwOci """ if ws is None: ws = np.ones(len(qs)) / len(qs) else: assert sum(ws) == 1 for idx in range(1, len(qs)): if np.dot(qs[0], qs[idx]) < 0: qs[idx] *= -1 for i in range(1, len(qs)): frac = ws[i] / (ws[i-1] + ws[i]) # weight of qs[i] qs[i] = quaternion_slerp(qs[i-1], qs[i], fraction=frac) ws[i] = 1 - sum(ws[i+1:]) return qs[-1] def default_argparse(require_p_num=True, require_intent=True, require_object_name=True): parser = argparse.ArgumentParser() parser.add_argument('--p_num', type=int, help='Participant number (1-50)', required=require_p_num) parser.add_argument('--intent', choices=('use', 'handoff'), help='Grasp intent', required=require_intent) parser.add_argument('--object_name', help="Name of object", required=require_object_name) return parser def default_multiargparse(): parser = argparse.ArgumentParser() parser.add_argument('--p_num', help='Participant numbers, comma or - separated.' 'Skipping means all participants', default=None) parser.add_argument('--intent', choices=('use', 'handoff', 'use,handoff'), help='Grasp intents, comma separated', default='use,handoff') parser.add_argument('--object_name', help="Object names, comma separated, ignore for all objects", default=None) return parser def parse_multiargs(args): """ parses the p_num, intent, and object_name arguments from a parser created with default_multiargparse """ from utilities.dataset import get_p_nums p_nums = args.p_num if p_nums is None: p_nums = list(range(1, 51)) elif '-' in p_nums: first, last = p_nums.split('-') p_nums = list(range(int(first), int(last)+1)) else: p_nums = [int(p) for p in p_nums.split(',')] intents = args.intent.split(',') object_names = args.object_name if object_names is not None: object_names = object_names.split(',') all_p_nums = [] for intent in intents: for object_name in object_names: all_p_nums.extend([pn for pn in p_nums if pn in get_p_nums(object_name, intent)]) p_nums = list(set(all_p_nums)) delattr(args, 'p_num') delattr(args, 'intent') delattr(args, 'object_name') return p_nums, intents, object_names, args def colorcode_depth_image(im): assert(im.ndim == 2) im = im.astype(float) im /= im.max() j, i = np.nonzero(im) c = im[j, i] im = np.zeros((im.shape[0], im.shape[1], 3)) im[j, i, :] = plt.cm.viridis(c)[:, :3] im = (im * 255.0).astype(np.uint8) return im def draw_hands(im, joints, colors=((0, 255, 0), (0, 0, 255)), circle_radius=3, line_thickness=2, offset=np.zeros(2, dtype=np.int)): if im is None: print('Invalid image') return im if im.ndim == 2: # depth image im = colorcode_depth_image(im) for hand_idx, (js, c) in enumerate(zip(joints, colors)): if js is None: continue else: js = np.round(js-offset[np.newaxis, :]).astype(np.int) for j in js: im = cv2.circle(im, tuple(j), circle_radius, c, -1, cv2.LINE_AA) for finger in range(5): base = 4*finger + 1 im = cv2.line(im, tuple(js[0]), tuple(js[base]), (0, 0, 0), line_thickness, cv2.LINE_AA) for j in range(3): im = cv2.line(im, tuple(js[base+j]), tuple(js[base+j+1]), (0, 0, 0), line_thickness, cv2.LINE_AA) return im def draw_object_markers(im, ms, color=(0, 255, 255), circle_radius=3, offset=np.zeros(2, dtype=np.int)): if im.ndim == 2: # depth image im = colorcode_depth_image(im) for m in np.round(ms).astype(np.int): im = cv2.circle(im, tuple(m-offset), circle_radius, color, -1, cv2.LINE_AA) return im def crop_image(im, joints, crop_size, fillvalue=[0]): """ joints: list of 21x2 2D joint locations per each hand crops the im into a crop_size square centered at the mean of all joint locations returns cropped image and top-left pixel position of the crop in the full image """ if im.ndim < 3: im = im[:, :, np.newaxis] if isinstance(fillvalue, list) or isinstance(fillvalue, np.ndarray): fillvalue = np.asarray(fillvalue).astype(im.dtype) else: fillvalue = np.asarray([fillvalue for _ in im.shape[2]]).astype(im.dtype) joints = np.vstack([j for j in joints if j is not None]) bbcenter = np.round(np.mean(joints, axis=0)).astype(np.int) im_crop = np.zeros((crop_size, crop_size, im.shape[2]), dtype=im.dtype) tl = bbcenter - crop_size//2 br = bbcenter + crop_size//2 tl_crop = np.asarray([0, 0], dtype=np.int) br_crop = np.asarray([crop_size, crop_size], dtype=np.int) tl_spill = np.minimum(0, tl) tl -= tl_spill tl_crop -= tl_spill br_spill = np.maximum(0, br-np.array([im.shape[1], im.shape[0]])) br -= br_spill br_crop -= br_spill im_crop[tl_crop[1]:br_crop[1], tl_crop[0]:br_crop[0], :] = \ im[tl[1]:br[1], tl[0]:br[0], :] return im_crop.squeeze(), tl def openpose2mano(o, n_joints_per_finger=4): """ convert joints from openpose format to MANO format """ finger_o2m = {0: 4, 1: 0, 2: 1, 3: 3, 4: 2} m = np.zeros((5*n_joints_per_finger+1, 3)) m[0] = o[0] for ofidx in range(5): for jidx in range(n_joints_per_finger): oidx = 1 + ofidx*4 + jidx midx = 1 + finger_o2m[ofidx]*n_joints_per_finger + jidx m[midx] = o[oidx] return np.array(m) # m2o # 0->1, 1->2, 2->4, 3->3, 4->0 def mano2openpose(m, n_joints_per_finger=4): """ convert joints from MANO format to openpose format """ finger_o2m = {0: 4, 1: 0, 2: 1, 3: 3, 4: 2} finger_m2o = {v: k for k,v in finger_o2m.items()} o = np.zeros((5*n_joints_per_finger+1, 3)) o[0] = m[0] for mfidx in range(5): for jidx in range(n_joints_per_finger): midx = 1 + mfidx*4 + jidx oidx = 1 + finger_m2o[mfidx]*n_joints_per_finger + jidx o[oidx] = m[midx] return o def mano_joints_with_fingertips(m): """ get joints from MANO model MANO model does not come with fingertip joints, so we have selected vertices that correspond to fingertips """ fingertip_idxs = [333, 444, 672, 555, 745] out = [m.J_transformed[0]] for fidx in range(5): for jidx in range(4): if jidx < 3: idx = 1 + fidx*3 + jidx out.append(m.J_transformed[idx]) else: out.append(m[fingertip_idxs[fidx]]) return out def load_mano_meshes(params, model_dicts, oTh=(np.eye(4), np.eye(4)), flat_hand_mean=False): if not MANO_PRESENT or model_dicts is None: return (None, None) out = [] for hand_idx, mp in enumerate(params): if mp is None: out.append(None) continue ncomps = len(mp['pose']) - 3 m = load_mano_model(model_dicts[hand_idx], ncomps=ncomps, flat_hand_mean=flat_hand_mean) m.betas[:] = mp['betas'] m.pose[:] = mp['pose'] oTm = oTh[hand_idx] @ mp['hTm'] vertices = np.array(m) vertices = tform_points(oTm, vertices) joints = mano2openpose(mano_joints_with_fingertips(m)) joints = tform_points(oTm, joints) out.append({ 'vertices': vertices, 'joints': joints, 'faces': np.asarray(m.f), }) return out def grabcut_mask(src, mask, n_iters=10): """ Refines noisy mask edges using Grabcut on image src """ assert(src.shape[:2] == mask.shape[:2]) y, x = np.where(mask) gmask = np.zeros((src.shape[0], src.shape[1]), dtype=np.uint8) # GC_BGD gmask[y.min():y.max()+1, x.min():x.max()+1] = 2 # GC_PR_BGD gmask[y, x] = 3 # GC_PR_FGD bgdModel = np.zeros((1,65),np.float64) fgdModel = np.zeros((1,65),np.float64) gmask, bgdModel, fgdModel = \ cv2.grabCut(src, gmask, (0, 0, 0, 0), bgdModel, fgdModel, n_iters, mode=cv2.GC_INIT_WITH_MASK) mask = np.logical_or(gmask==1, gmask==3) return mask
ContactPose-main
utilities/misc.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt from utilities.import_open3d import * from open3d import pipelines import utilities.misc as mutils assert(mutils.load_mano_model is not None) import numpy as np import chumpy as ch import os import json import transforms3d.quaternions as txq import pickle osp = os.path o3dr = pipelines.registration def mano_param_dict(n_pose_params, n_betas=10): out = { 'pose': [0.0 for _ in range(n_pose_params+3)], 'betas': [0.0 for _ in range(n_betas)], 'valid': False, 'mTc': { 'translation': [0.0, 0.0, 0.0], 'rotation': [1.0, 0.0, 0.0, 0.0], } } return out def get_palm_joints(p, n_joints_per_finger=4): """ get the 6 palm joints (root + base of all 5 fingers) """ idx = [0] for fidx in range(5): idx.append(1 + fidx*n_joints_per_finger) return p[idx] def register_pcs(src, tgt, verbose=True): """ registers two pointclouds by rigid transformation target_x = target_T_source * source_x """ assert(len(src) == len(tgt)) ps = o3dg.PointCloud() ps.points = o3du.Vector3dVector(src) pt = o3dg.PointCloud() pt.points = o3du.Vector3dVector(tgt) c = [[i, i] for i in range(len(src))] c = o3du.Vector2iVector(c) r = o3dr.TransformationEstimationPointToPoint() r.with_scaling = False if verbose: print('Rigid registration RMSE (before) = {:f}'. format(r.compute_rmse(ps, pt, c))) tTs = r.compute_transformation(ps, pt, c) pst = ps.transform(tTs) if verbose: print('Rigid registration RMSE (after) = {:f}'. format(r.compute_rmse(pst, pt, c))) return tTs class MANOFitter(object): _mano_dicts = None def __init__(self): if MANOFitter._mano_dicts is None: MANOFitter._mano_dicts = [] for hand_name in ('LEFT', 'RIGHT'): filename = osp.join('thirdparty', 'mano', 'models', 'MANO_{:s}.pkl'.format(hand_name)) with open(filename, 'rb') as f: MANOFitter._mano_dicts.append(pickle.load(f, encoding='latin1')) @staticmethod def fit_joints(both_joints, n_pose_params=15, shape_sigma=10.0, save_filename=None): """ Fits the MANO model to hand joint 3D locations both_jonts: tuple of length 2, 21 joints per hand, e.g. output of ContactPose.hand_joints() n_pose_params: number of pose parameters (excluding 3 global rotation params) shape_sigma: reciprocal of shape regularization strength save_filename: file where the fitting output will be saved in JSON format """ mano_params = [] for hand_idx, joints in enumerate(both_joints): if joints is None: # hand is not present mano_params.append(mano_param_dict(n_pose_params)) # dummy continue cp_joints = mutils.openpose2mano(joints) # MANO model m = mutils.load_mano_model(MANOFitter._mano_dicts[hand_idx], ncomps=n_pose_params, flat_hand_mean=False) m.betas[:] = np.zeros(m.betas.size) m.pose[:] = np.zeros(m.pose.size) mano_joints = mutils.mano_joints_with_fingertips(m) mano_joints_np = np.array([[float(mm) for mm in m] for m in mano_joints]) # align palm cp_palm = get_palm_joints(np.asarray(cp_joints)) mano_palm = get_palm_joints(np.asarray(mano_joints_np)) mTc = register_pcs(cp_palm, mano_palm) cp_joints = np.dot(mTc, np.vstack((cp_joints.T, np.ones(len(cp_joints))))) cp_joints = cp_joints[:3].T cp_joints = ch.array(cp_joints) # set up objective objective = [m-c for m,c in zip(mano_joints, cp_joints)] mean_betas = ch.array(np.zeros(m.betas.size)) objective.append((m.betas - mean_betas) / shape_sigma) # optimize ch.minimize(objective, x0=(m.pose, m.betas, m.trans), method='dogleg') p = mano_param_dict(n_pose_params) p['pose'] = np.array(m.pose).tolist() p['betas'] = np.array(m.betas).tolist() p['valid'] = True p['mTc']['translation'] = (mTc[:3, 3] - np.array(m.trans)).tolist() p['mTc']['rotation'] = txq.mat2quat(mTc[:3, :3]).tolist() mano_params.append(p) # # to access hand mesh vertices and faces # vertices = np.array(m.r) # vertices = mutils.tform_points(np.linalg.inv(mTc), vertices) # faces = np.array(m.f) if save_filename is not None: with open(save_filename, 'w') as f: json.dump(mano_params, f, indent=4, separators=(',', ':')) print('{:s} written'.format(save_filename)) return mano_params
ContactPose-main
utilities/mano_fitting.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import sys sys.path.append('.')
ContactPose-main
utilities/init_paths.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import os os.environ["PYOPENGL_PLATFORM"] = "osmesa" import trimesh import pyrender import numpy as np import transforms3d.euler as txe import utilities.misc as mutils import cv2 osp = os.path class DepthRenderer(object): """ Renders object or hand mesh into a depth map """ def __init__(self, object_name_or_mesh, K, camera_name, mesh_scale=1.0): """ object_name_or_mesh: either object name string (for objects), or {'vertices': ..., 'faces': ...} (for hand mesh) K: 3x3 intrinsics matrix mesh_scale: scale factor applied to the mesh (1.0 for hand, 1e-3 for object) """ self.K = K self.camera_name = camera_name if camera_name == 'kinect2_middle': self.flip_fn = lambda x: cv2.flip(cv2.flip(x, 0), 1) self.out_imsize = (960, 540) elif camera_name == 'kinect2_left': self.flip_fn = lambda x: cv2.flip(cv2.transpose(x), 1) self.out_imsize = (540, 960) elif camera_name == 'kinect2_right': self.flip_fn = lambda x: cv2.flip(cv2.transpose(x), 0) self.out_imsize = (540, 960) else: raise NotImplementedError # mesh if isinstance(object_name_or_mesh, str): filename = osp.join('data', 'object_models', '{:s}.ply'.format(object_name_or_mesh)) mesh_t = trimesh.load_mesh(filename) elif isinstance(object_name_or_mesh, dict): mesh_t = trimesh.Trimesh(vertices=object_name_or_mesh['vertices'], faces=object_name_or_mesh['faces']) else: raise NotImplementedError mesh_t.apply_transform(np.diag([mesh_scale, mesh_scale, mesh_scale, 1])) self.oX = mesh_t.vertices mesh = pyrender.Mesh.from_trimesh(mesh_t) self.scene = pyrender.Scene() self.scene.add(mesh, pose=np.eye(4)) # camera camera = pyrender.IntrinsicsCamera(K[0, 0], K[1, 1], K[0, 2], K[1, 2], znear=0.1, zfar=2.0) self.camera_node = pyrender.Node(camera=camera, matrix=np.eye(4)) self.scene.add_node(self.camera_node) self.cTopengl = np.eye(4) self.cTopengl[:3, :3] = txe.euler2mat(np.pi, 0, 0) # renderer object self.renderer = pyrender.OffscreenRenderer(960, 540) def render(self, object_pose): """ returns depth map produced by rendering the mesh object_pose: 4x4 pose of object w.r.t. camera, from ContactPose.object_pose() object_pose = cTo in the naming convention """ oTc = np.linalg.inv(object_pose) oTopengl = oTc @ self.cTopengl self.scene.set_pose(self.camera_node, oTopengl) # TODO: figure out DEPTH_ONLY rendering mode with OSMesa backend # DEPTH_ONLY + OSMesa does not work currently # so we have to render color also :( _, depth = self.renderer.render(self.scene) return self.flip_fn(depth) def object_visibility_and_projections(self, object_pose, depth_thresh=5e-3): """ returns projection locations of object mesh vertices (Nx2) and their binary visibility from the object_pose object_pose = cTo 4x4 pose of object w.r.t. camera This is cheap Z-buffering. We use rendered depth maps because they are cleaner than Kinect depth maps """ # render depth image depth_im = self.render(object_pose) # project all vertices cX = mutils.tform_points(object_pose, self.oX) P = mutils.get_A(self.camera_name) @ self.K @ np.eye(4)[:3] cx = mutils.project(P, cX) # determine visibility visible = cX[:, 2] > 0 visible = np.logical_and(visible, cx[:, 0] >= 0) visible = np.logical_and(visible, cx[:, 1] >= 0) visible = np.logical_and(visible, cx[:, 0] < self.out_imsize[0]-1) visible = np.logical_and(visible, cx[:, 1] < self.out_imsize[1]-1) u = np.round(cx[:, 0]).astype(np.int) v = np.round(cx[:, 1]).astype(np.int) d_sensor = -np.ones(len(u)) d_sensor[visible] = depth_im[v[visible], u[visible]] visible = np.logical_and(visible, np.abs(d_sensor-cX[:, 2]) < depth_thresh) return cx, visible
ContactPose-main
utilities/rendering.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt from open3d import io as o3dio from open3d import visualization as o3dv from open3d import utility as o3du from open3d import geometry as o3dg
ContactPose-main
utilities/import_open3d.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt
ContactPose-main
utilities/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt """ ContactPose dataset loading utilities """ import os import json import numpy as np import pickle from . import misc as mutils osp = os.path def get_object_names(p_num, intent, ignore_hp=True): """ returns list of objects grasped by this participant with this intent """ sess_dir = 'full{:d}_{:s}'.format(p_num, intent) sess_dir = osp.join(osp.dirname(__file__), '..', 'data', 'contactpose_data', sess_dir) ignored_objects = ('hands', 'palm_print') if ignore_hp else () return [o for o in next(os.walk(sess_dir))[1] if o not in ignored_objects] def get_intents(p_num, object_name): """ returns list of intents with which this participant grasped object """ out = [] for ins in ('use', 'handoff'): sess_dir = 'full{:d}_{:s}'.format(p_num, ins) sess_dir = osp.join(osp.dirname(__file__), '..', 'data', 'contactpose_data', sess_dir, object_name) if osp.isdir(sess_dir): out.append(ins) return out def get_p_nums(object_name, intent): """ returns list of participants who grasped this object with this intent """ out = [] for p_num in range(1, 51): sess_dir = 'full{:d}_{:s}'.format(p_num, intent) sess_dir = osp.join(osp.dirname(__file__), '..', 'data', 'contactpose_data', sess_dir, object_name) if osp.isdir(sess_dir): out.append(p_num) return out class ContactPose(object): """ Base class for accessing the ContactPose dataset """ _mano_dicts = None # class variable so that large data is not loaded repeatedly def __init__(self, p_num, intent, object_name, mano_pose_params=15, load_mano=True): """ load_mano: Flag can be used to prevent loading MANO hand models, which is time consuming """ if (object_name == 'palm_print') or (object_name == 'hands'): print('This class is not meant to be used with palm_print or hands') raise ValueError self.p_num = p_num self.intent = intent self.object_name = object_name self._mano_pose_params = mano_pose_params p_id = 'full{:d}_{:s}'.format(p_num, intent) self.data_dir = osp.join(osp.dirname(__file__), '..', 'data', 'contactpose_data', p_id, object_name) assert(osp.isdir(self.data_dir)) # read grasp data with open(self.annotation_filename, 'r') as f: ann = json.load(f) self._n_frames = len(ann['frames']) self._valid_cameras = [cn for cn,cv in ann['cameras'].items() if cv['valid']] self._is_object_pose_optimized = [f['object_pose_optimized'] for f in ann['frames']] self._valid_hands = [hand_idx for hand_idx, hand in enumerate(ann['hands']) if hand['valid']] im_filenames = {} for camera_name in self.valid_cameras: im_dir = osp.join(self.data_dir, 'images_full', camera_name, '{:s}') im_filenames[camera_name] = [ osp.join(im_dir, 'frame{:03d}.png'.format(i)) for i in range(len(self))] self._im_filenames = [{k: v for k,v in zip(im_filenames.keys(), vv)} for vv in zip(*im_filenames.values())] oX = [] # 3D joints w.r.t. object all_oTh = [] for hand_idx, hand in enumerate(ann['hands']): if hand['valid']: hX = np.asarray(hand['joints']) # hand joints w.r.t. hand root if hand['moving']: # object pose w.r.t. hand oThs = [np.linalg.inv(mutils.pose_matrix(f['hTo'][hand_idx])) for f in ann['frames']] all_oTh.append(oThs) oX.append([mutils.tform_points(oTh, hX) for oTh in oThs]) else: oX.append([hX for _ in range(len(self))]) all_oTh.append([np.eye(4) for _ in range(len(self))]) else: oX.append([None for _ in range(len(self))]) all_oTh.append([np.eye(4) for _ in range(len(self))]) self._oX = list(map(tuple, zip(*oX))) self._oTh = list(map(tuple, zip(*all_oTh))) # world pose w.r.t. object oTws = [mutils.pose_matrix(f['oTw']) for f in ann['frames']] self._cTo = {} # object pose w.r.t. camera self._K = {} # camera intrinsics for camera_name in self.valid_cameras: cam = ann['cameras'][camera_name] self._K[camera_name] = np.array([[cam['K']['fx'], 0, cam['K']['cx']], [0, cam['K']['fy'], cam['K']['cy']], [0, 0, 1]]) # camera pose w.r.t. world wTc = mutils.pose_matrix(cam['wTc']) self._cTo[camera_name] = [np.linalg.inv(oTw @ wTc) for oTw in oTws] # projections self._ox = [] # joint projections self._om = [] # marker projections # 3D marker locations w.r.t. object oM = np.loadtxt(osp.join(osp.dirname(__file__), '..', 'data', 'object_marker_locations', '{:s}_final_marker_locations.txt'. format(object_name)))[:, :3] for frame_idx in range(len(self)): this_ox = {} this_om = {} for camera_name in self.valid_cameras: this_om[camera_name] = mutils.project(self.P(camera_name, frame_idx), oM) x = [] for hand_idx in range(2): if hand_idx not in self._valid_hands: x.append(None) else: x.append(mutils.project(self.P(camera_name, frame_idx), self._oX[frame_idx][hand_idx])) this_ox[camera_name] = tuple(x) self._ox.append(this_ox) self._om.append(this_om) # check if MANO code and models are present if mutils.MANO_PRESENT and load_mano: # load MANO data for the class if ContactPose._mano_dicts is not None: return ContactPose._mano_dicts = [] for hand_name in ('LEFT', 'RIGHT'): filename = osp.join(osp.dirname(__file__), '..', 'thirdparty', 'mano', 'models', 'MANO_{:s}.pkl'.format(hand_name)) with open(filename, 'rb') as f: ContactPose._mano_dicts.append(pickle.load(f, encoding='latin1')) elif load_mano: print('MANO code was not detected, please follow steps in README.md. ' 'mano_meshes() will return (None, None)') def __len__(self): """ Number of RGB-D time frames """ return self._n_frames def __repr__(self): hand_names = ['left', 'right'] hand_str = ' '.join([hand_names[i] for i in self._valid_hands]) return 'Participant {:d}, intent {:s}, object {:s}\n'.format(self.p_num, self.intent, self.object_name) +\ '{:d} frames\n'.format(len(self)) +\ 'Cameras present: {:s}\n'.format(' '.join(self.valid_cameras)) +\ 'Hands present: {:s}'.format(hand_str) @property def contactmap_filename(self): return osp.join(self.data_dir, '{:s}.ply'.format(self.object_name)) @property def annotation_filename(self): return osp.join(self.data_dir, 'annotations.json') @property def mano_filename(self): """ return name of file containing MANO fit params """ return osp.join(self.data_dir, 'mano_fits_{:d}.json'.format(self._mano_pose_params)) @property def valid_cameras(self): """ return list of cameras valid for this grasp """ return self._valid_cameras @property def mano_params(self): """ List of 2 [left, right]. Each element is None or a dict containing 'pose' (PCA pose space of dim self._mano_pose_params), 'betas' (PCA shape space), and root transform 'hTm' """ with open(self.mano_filename, 'r') as f: params = json.load(f) out = [] for p in params: if not p['valid']: out.append(None) continue # MANO root pose w.r.t. hand hTm = np.linalg.inv(mutils.pose_matrix(p['mTc'])) out.append({ 'pose': p['pose'], 'betas': p['betas'], 'hTm': hTm, }) return out def im_size(self, camera_name): """ (width, height) in pixels """ return (960, 540) if camera_name == 'kinect2_middle' else (540, 960) def image_filenames(self, mode, frame_idx): """ return dict with full image filenames for all valid cameras mode = color or depth """ return {k: v.format(mode) for k,v in self._im_filenames[frame_idx].items()} def hand_joints(self, frame_idx=None): """ 3D hand joints w.r.t. object randomly sampled time frame if frame_idx is None tuple of length 2, 21 joints per hand, None if hand is not present """ if frame_idx is None: frame_idx = np.random.choice(len(self)) return self._oX[frame_idx] def K(self, camera_name): """ Camera intrinsics 3x3 You will almost never need this. Use self.P() for projection """ return self._K[camera_name] def A(self, camera_name): """ Affine transform to be applied to 2D points after projection Included in self.P """ return mutils.get_A(camera_name, 960, 540) def P(self, camera_name, frame_idx): """ 3x4 3D -> 2D projection matrix Use this for all projection operations, not self.K """ P = self.K(camera_name) @ self.object_pose(camera_name, frame_idx)[:3] P = self.A(camera_name) @ P return P def object_pose(self, camera_name, frame_idx): """ Pose of object w.r.t. camera at frame frame_idx 4x4 homogeneous matrix """ return self._cTo[camera_name][frame_idx] def projected_hand_joints(self, camera_name, frame_idx): """ hand joints projected into camera image tuple of length 2 21x2 or None based on if hand is present in this grasp """ return self._ox[frame_idx][camera_name] def projected_object_markers(self, camera_name, frame_idx): """ object markers projected into camera image Nx2 where N in [5, 10] """ return self._om[frame_idx][camera_name] def mano_meshes(self, frame_idx=None): """ return list of 2 dicts. Element is None if that hand is absent, or contains 'vertices', 'faces', and 'joints' """ if frame_idx is None: frame_idx = np.random.choice(len(self)) return mutils.load_mano_meshes(self.mano_params, ContactPose._mano_dicts, self._oTh[frame_idx])
ContactPose-main
utilities/dataset.py
import datetime try: import dropbox DROPBOX_FOUND = True except ImportError: DROPBOX_FOUND = False import json import math import os import random import requests from requests.exceptions import ConnectionError import time from tqdm.autonotebook import tqdm osp = os.path if DROPBOX_FOUND: dropbox_app_key = os.environ.get('DROPBOX_APP_KEY') with open(osp.join('data', 'proxies.json'), 'r') as f: proxies = json.load(f) if ('https' not in proxies) or (proxies['https'] is None): proxies = None def exponential_backoff(n, max_backoff=64.0): t = math.pow(2.0, n) t += (random.randint(0, 1000)) / 1000.0 t = min(t, max_backoff) return t def upload_dropbox(lfilename, dfilename, max_tries=7): """ Upload local file lfilename to dropbox location dfilename Implements exponential backoff """ if not DROPBOX_FOUND: print('Dropbox API not found') return False dbx = dropbox.Dropbox(dropbox_app_key) ddir, _ = osp.split(dfilename) ddir_exists = True try: dbx.files_get_metadata(ddir) except dropbox.exceptions.ApiError as err: ddir_exists = False if not ddir_exists: try: dbx.files_create_folder(ddir) except dropbox.exceptions.ApiError as err: print('*** API error', err) dbx.close() return False mtime = osp.getmtime(lfilename) with open(lfilename, 'rb') as f: ldata = f.read() upload_tries = 0 while upload_tries < max_tries: try: res = dbx.files_upload( ldata, dfilename, dropbox.files.WriteMode.overwrite, client_modified=datetime.datetime(*time.gmtime(mtime)[:6]), mute=True) print('uploaded as', res.name.encode('utf8')) dbx.close() return True except dropbox.exceptions.ApiError as err: print('*** API error', err) dbx.close() return False except ConnectionError as err: t = exponential_backoff(upload_tries) print('*** Requests Connection error, sleeping for {:f} s'.format(t), err) time.sleep(t) upload_tries += 1 print('*** Max upload tries exceeded') dbx.close() return False def download_url(url, filename, progress=True, max_tries=7): """ Download file from a URL to filename, optionally displaying progress bar with tqdm Implements exponential backoff """ tries = 0 while tries < max_tries: done = download_url_once(url, filename, progress) if done: return True else: t = exponential_backoff(tries) print('*** Sleeping for {:f} s'.format(t)) time.sleep(t) tries += 1 print('*** Max download tries exceeded') return False def download_url_once(url, filename, progress=True): """ Download file from a URL to filename, optionally displaying progress bar with tqdm taken from https://stackoverflow.com/a/37573701 """ # Streaming, so we can iterate over the response. try: r = requests.get(url, stream=True, proxies=proxies) except ConnectionError as err: print(err) return False # Total size in bytes. total_size = int(r.headers.get('content-length', 0)) block_size = 1024 #1 Kibibyte if progress: t=tqdm(total=total_size, unit='iB', unit_scale=True) done = True datalen = 0 with open(filename, 'wb') as f: itr = r.iter_content(block_size) while True: try: try: data = next(itr) except StopIteration: break if progress: t.update(len(data)) datalen += len(data) f.write(data) except KeyboardInterrupt: done = False print('Cancelled') except ConnectionError as err: done = False print(err) if progress: t.close() if (not done) or (total_size != 0 and datalen != total_size): print("ERROR, something went wrong") try: os.remove(filename) except OSError as e: print(e) return False else: return True
ContactPose-main
utilities/networking.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import sys sys.path.append('.')
ContactPose-main
scripts/init_paths.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import matplotlib.pyplot as plt import numpy as np import init_paths from utilities.import_open3d import * from utilities.dataset import ContactPose import utilities.misc as mutils def apply_colormap_to_mesh(mesh, sigmoid_a=0.05, invert=False): colors = np.asarray(mesh.vertex_colors)[:, 0] colors = mutils.texture_proc(colors, a=sigmoid_a, invert=invert) colors = plt.cm.inferno(colors)[:, :3] mesh.vertex_colors = o3du.Vector3dVector(colors) return mesh def apply_semantic_colormap_to_mesh(mesh, semantic_idx, sigmoid_a=0.05, invert=False): colors = np.asarray(mesh.vertex_colors)[:, 0] colors = mutils.texture_proc(colors, a=sigmoid_a, invert=invert) # apply different colormaps based on finger mesh_colors = np.zeros((len(colors), 3)) cmaps = ['Greys', 'Purples', 'Oranges', 'Greens', 'Blues', 'Reds'] cmaps = [plt.cm.get_cmap(c) for c in cmaps] for semantic_id in np.unique(semantic_idx): if (len(cmaps) <= semantic_id): print('Not enough colormaps, ignoring semantic id {:d}'.format( semantic_id)) continue idx = semantic_idx == semantic_id mesh_colors[idx] = cmaps[semantic_id](colors[idx])[:, :3] mesh.vertex_colors = o3du.Vector3dVector(mesh_colors) return mesh def show_contactmap(p_num, intent, object_name, mode='simple', joint_sphere_radius_mm=4.0, bone_cylinder_radius_mm=2.5, bone_color=np.asarray([224.0, 172.0, 105.0])/255, show_axes=False): """ mode = simple: just contact map simple_hands: skeleton + contact map semantic_hands_fingers: skeleton + contact map colored by finger proximity semantic_hands_phalanges: skeleton + contact map colored by phalange proximity show_axes: visualize coordinate axes if True """ cp = ContactPose(p_num, intent, object_name) # read contactmap mesh = o3dio.read_triangle_mesh(cp.contactmap_filename) mesh.compute_vertex_normals() geoms = [] # apply simple colormap to the mesh if 'simple' in mode: mesh = apply_colormap_to_mesh(mesh) geoms.append(mesh) if 'hands' in mode: # read hands line_ids = mutils.get_hand_line_ids() joint_locs = cp.hand_joints() # show hands hand_colors = [[0, 1, 0], [1, 0, 0]] for hand_idx, hand_joints in enumerate(joint_locs): if hand_joints is None: continue # joint locations for j in hand_joints: m = o3dg.TriangleMesh.create_sphere(radius=joint_sphere_radius_mm*1e-3, resolution=10) T = np.eye(4) T[:3, 3] = j m.transform(T) m.paint_uniform_color(hand_colors[hand_idx]) m.compute_vertex_normals() geoms.append(m) # connecting lines for line_idx, (idx0, idx1) in enumerate(line_ids): bone = hand_joints[idx0] - hand_joints[idx1] h = np.linalg.norm(bone) l = o3dg.TriangleMesh.create_cylinder(radius=bone_cylinder_radius_mm*1e-3, height=h, resolution=10) T = np.eye(4) T[2, 3] = -h/2.0 l.transform(T) T = mutils.rotmat_from_vecs(bone, [0, 0, 1]) T[:3, 3] = hand_joints[idx0] l.transform(T) l.paint_uniform_color(bone_color) l.compute_vertex_normals() geoms.append(l) if 'semantic' in mode: n_lines_per_hand = len(line_ids) n_parts_per_finger = 4 # find line equations for hand parts lines = [] for hand_joints in joint_locs: if hand_joints is None: continue for line_id in line_ids: a = hand_joints[line_id[0]] n = hand_joints[line_id[1]] - hand_joints[line_id[0]] n /= np.linalg.norm(n) lines.append(np.hstack((a, n))) lines = np.asarray(lines) ops = np.asarray(mesh.vertices) d_lines = mutils.p_dist_linesegment(ops, lines) line_idx = np.argmin(d_lines, axis=1) % n_lines_per_hand finger_idx, part_idx = divmod(line_idx, n_parts_per_finger) if 'phalanges' in mode: mesh = apply_semantic_colormap_to_mesh(mesh, part_idx) elif 'fingers' in mode: mesh = apply_semantic_colormap_to_mesh(mesh, finger_idx) geoms.append(mesh) elif 'mano' in mode: for hand in cp.mano_meshes(): if hand is None: continue mesh = o3dg.TriangleMesh() mesh.vertices = o3du.Vector3dVector(hand['vertices']) mesh.triangles = o3du.Vector3iVector(hand['faces']) mesh.paint_uniform_color(bone_color) mesh.compute_vertex_normals() geoms.append(mesh) if show_axes: geoms.append(o3dg.TriangleMesh.create_coordinate_frame(size=0.2)) o3dv.draw_geometries(geoms) if __name__ == '__main__': import sys parser = mutils.default_argparse() parser.add_argument('--mode', help='Contact Map mode', default='simple_hands', choices=('simple', 'simple_mano', 'simple_hands', 'semantic_hands_fingers', 'semantic_hands_phalanges')) parser.add_argument('--show_axes', action='store_true', help='Show coordinate axes') args = parser.parse_args() if args.object_name == 'hands': print('hands do not have a contact map') sys.exit(0) elif args.object_name == 'palm_print': print('Forcing mode to simple since palm_print does not have hand pose') args.mode = 'simple' show_contactmap(args.p_num, args.intent, args.object_name, args.mode, show_axes=args.show_axes)
ContactPose-main
scripts/show_contactmap.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt """ Preprocesses images for ML training by cropping (RGB and depth), and randomizing background (RGB only) NOTE: Requites rendering setup, see docs/rendering.py """ import init_paths from utilities.dataset import ContactPose, get_object_names from utilities.rendering import DepthRenderer import utilities.misc as mutils import numpy as np import cv2 import os from tqdm import tqdm osp = os.path def inspect_dir(dirname): assert(osp.isdir(dirname)) print('Inspecting {:s}...'.format(dirname)) filenames = next(os.walk(dirname))[-1] filenames = [osp.join(dirname, f) for f in filenames] print('Found {:d} images'.format(len(filenames))) return filenames def preprocess(p_num, intent, object_name, rim_filenames_or_dir, crop_size, do_rgb=True, do_depth=True, do_grabcut=True, depth_percentile_thresh=30, mask_dilation=5): if isinstance(rim_filenames_or_dir, list): rim_filenames = rim_filenames_or_dir[:] else: rim_filenames = inspect_dir(rim_filenames_or_dir) cp = ContactPose(p_num, intent, object_name, load_mano=False) for camera_name in cp.valid_cameras: K = cp.K(camera_name) renderer = DepthRenderer(object_name, K, camera_name, 1e-3) output_dir = osp.join(cp.data_dir, 'images', camera_name) for d in ('color', 'depth', 'projections'): dd = osp.join(output_dir, d) if not osp.isdir(dd): os.makedirs(dd) A = mutils.get_A(camera_name) print('{:d}:{:s}:{:s}:{:s}'.format(p_num, intent, object_name, camera_name)) print('Writing to {:s}'.format(output_dir)) for frame_idx in tqdm(range(len(cp))): # read images filename = cp.image_filenames('color', frame_idx)[camera_name] rgb_im = cv2.imread(filename) if rgb_im is None: print('Could not read {:s}, skipping frame'.format(filename)) continue filename = cp.image_filenames('depth', frame_idx)[camera_name] _, out_filename = osp.split(filename) depth_im = cv2.imread(filename, -1) if depth_im is None: print('Could not read {:s}, skipping frame'.format(filename)) continue # crop images joints = cp.projected_hand_joints(camera_name, frame_idx) rgb_im, _ = mutils.crop_image(rgb_im, joints, crop_size) depth_im, crop_tl = mutils.crop_image(depth_im, joints, crop_size) this_A = np.copy(A) A = np.asarray([[1, 0, -crop_tl[0]], [0, 1, -crop_tl[1]], [0, 0, 1]]) @ A cTo = cp.object_pose(camera_name, frame_idx) P = this_A @ K @ cTo[:3] if do_depth: # save preprocessed depth image filename = osp.join(output_dir, 'depth', out_filename) cv2.imwrite(filename, depth_im) # save projection matrix filename = osp.join(output_dir, 'projections', out_filename.replace('.png', '_P.txt')) np.savetxt(filename, P) # foreground mask cxx, visible = renderer.object_visibility_and_projections(cTo) cxx -= crop_tl cx = np.round(cxx).astype(np.int) visible = np.logical_and(visible, cx[:, 0]>=0) visible = np.logical_and(visible, cx[:, 1]>=0) visible = np.logical_and(visible, cx[:, 0] < rgb_im.shape[1]) visible = np.logical_and(visible, cx[:, 1] < rgb_im.shape[0]) cx = cx[visible] # save projection information filename = osp.join(output_dir, 'projections', out_filename.replace('.png', '_verts.npy')) idx = np.where(visible)[0] projs = np.vstack((cxx[idx].T, idx)).T np.save(filename, projs) if not do_rgb: continue obj_depths = depth_im[cx[:, 1], cx[:, 0]] obj_depths = obj_depths[obj_depths > 0] all_depths = depth_im[depth_im > 0] if (len(obj_depths) > 0) and (len(all_depths) > 0): mthresh = np.median(obj_depths) + 150.0 pthresh = np.percentile(depth_im[depth_im>0], depth_percentile_thresh) else: print('Depth image {:s} all 0s, skipping frame'.format(filename)) continue thresh = min(pthresh, mthresh) # mask derived from depth dmask = 255 * np.logical_and(depth_im > 0, depth_im <= thresh) dmask = cv2.dilate(dmask.astype(np.uint8), np.ones( (mask_dilation, mask_dilation), dtype=np.uint8)) # mask derived from color cmask_green = np.logical_and(rgb_im[:, :, 1] > rgb_im[:, :, 0], rgb_im[:, :, 1] > rgb_im[:, :, 2]) cmask_white = np.mean(rgb_im, axis=2) > 225 cmask = np.logical_not(np.logical_or(cmask_green, cmask_white)) mask = np.logical_and(dmask>0, cmask) if do_grabcut: mask = mutils.grabcut_mask(rgb_im, mask) # randomize background count = 0 while count < len(rim_filenames): random_idx = np.random.choice(len(rim_filenames)) random_im = cv2.imread(rim_filenames[random_idx], cv2.IMREAD_COLOR) if np.any(np.asarray(random_im.shape[:2]) <= np.asarray(rgb_im.shape[:2])): count += 1 continue x = np.random.choice(random_im.shape[1] - rgb_im.shape[1]) y = np.random.choice(random_im.shape[0] - rgb_im.shape[0]) random_im = random_im[y:y+rgb_im.shape[0], x:x+rgb_im.shape[1], :] break else: print('ERROR: All random images are smaller than {:d}x{:d}!'. format(crop_size, crop_size)) break mask = mask[:, :, np.newaxis] im = mask*rgb_im + (1-mask)*random_im filename = osp.join(output_dir, 'color', out_filename) cv2.imwrite(filename, im) def preprocess_all(p_nums, intents, object_names, background_images_dir, *args, **kwargs): rim_filenames = inspect_dir(background_images_dir) for p_num in p_nums: for intent in intents: if object_names is None: object_names = get_object_names(p_num, intent) for object_name in object_names: preprocess(p_num, intent, object_name, rim_filenames_or_dir=rim_filenames, *args, **kwargs) if __name__ == '__main__': parser = mutils.default_multiargparse() parser.add_argument('--no_rgb', action='store_false', dest='do_rgb') parser.add_argument('--no_depth', action='store_false', dest='do_depth') parser.add_argument('--background_images_dir', required=True, help='Directory containing background images e.g. COCO') parser.add_argument('--crop_size', default=256, type=int) parser.add_argument('--no_mask_refinement', action='store_false', dest='do_grabcut', help='No refinement of masks with GrabCut') args = parser.parse_args() p_nums, intents, object_names, args = mutils.parse_multiargs(args) preprocess_all(p_nums, intents, object_names, **vars(args))
ContactPose-main
scripts/preprocess_images.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt
ContactPose-main
scripts/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt """ script to download ContactPose data from Dropbox URLs in data/urls.json """ import init_paths import cv2 import os import json import shutil from tqdm.autonotebook import tqdm import utilities.networking as nutils from zipfile import ZipFile osp = os.path def is_nonempty_dir(dir): if osp.isdir(dir): return next(os.scandir(dir), None) is not None else: return False class ContactPoseDownloader(object): def __init__(self): self.data_dir = osp.join('data', 'contactpose_data') if not osp.isdir(self.data_dir): os.makedirs(self.data_dir) print('Created {:s}'.format(self.data_dir)) with open(osp.join('data', 'urls.json'), 'r') as f: self.urls = json.load(f) @staticmethod def _unzip_and_del(filename, dst_dir=None, progress=True, filter_fn=None): if dst_dir is None: dst_dir, _ = osp.split(filename) if len(dst_dir) == 0: dst_dir = '.' with ZipFile(filename) as f: # members = None means everything members = None if filter_fn is None else \ list(filter(filter_fn, f.namelist())) f.extractall(dst_dir, members=members) os.remove(filename) def download_grasps(self): filename = osp.join(self.data_dir, 'grasps.zip') print('Downloading grasps...') if not nutils.download_url(self.urls['grasps'], filename): print('Download unsuccessful') return print('Extracting...') self._unzip_and_del(filename, self.data_dir) p_ids = next(os.walk(self.data_dir))[1] for p_id in tqdm(p_ids): if 'full' not in p_id: continue sess_dir = osp.join(self.data_dir, p_id) for filename in next(os.walk(sess_dir))[-1]: if '.zip' not in filename: continue self._unzip_and_del(osp.join(sess_dir, filename), progress=False) def download_contact_maps(self, p_num, intent): p_id = 'full{:d}_{:s}'.format(p_num, intent) filename = osp.join(self.data_dir, '{:s}_contact_maps.zip'.format(p_id)) print('Downloading {:d} {:s} contact maps...'.format(p_num, intent)) if not nutils.download_url(self.urls['contact_maps'][p_id], filename): print('Download unsuccessful') return print('Extracting...') self._unzip_and_del(filename, self.data_dir) def download_markers(self): filename = osp.join('data', 'markers.zip') print('Downloading 3D model marker locations...') if not nutils.download_url(self.urls['object_marker_locations'], filename): print('Download unsuccessful') return print('Extracting...') self._unzip_and_del(filename, osp.join('data', 'object_marker_locations')) def download_3d_models(self): filename = osp.join('data', '3Dmodels.zip') print('Downloading 3D models...') if not nutils.download_url(self.urls['object_models'], filename): print('Download unsuccessful') return print('Extracting...') self._unzip_and_del(filename, osp.join('data', 'object_models')) def download_depth_images(self, p_num, intent, dload_dir, include_objects=None): self.download_images(p_num, intent, dload_dir, include_objects, download_color=False, download_depth=True) def download_color_images(self, p_num, intent, dload_dir, include_objects=None): self.download_images(p_num, intent, dload_dir, include_objects, download_color=True, download_depth=False) def download_images(self, p_num, intent, dload_dir, include_objects=None, download_color=True, download_depth=True): assert osp.isdir(dload_dir),\ 'Image download dir {:s} does not exist'.format(dload_dir) p_id = 'full{:d}_{:s}'.format(p_num, intent) if download_color and (not download_depth): urls = self.urls['videos']['color'] else: urls = self.urls['images'] # check if already extracted dirs_to_check = [] if download_color: dirs_to_check.append('color') if download_depth: dirs_to_check.append('depth') ok = True if osp.isdir(osp.join(self.data_dir, p_id)): sess_dir = osp.join(self.data_dir, p_id) for object_name in next(os.walk(sess_dir))[1]: if include_objects is not None and object_name not in include_objects: continue images_dir = osp.join(sess_dir, object_name, 'images_full') if not osp.isdir(images_dir): continue for cam_name in next(os.walk(images_dir))[1]: for check_name in dirs_to_check: check_dir = osp.join(images_dir, cam_name, check_name) if is_nonempty_dir(check_dir): print('{:s} {:s} already has extracted images, please delete {:s}'. format(p_id, object_name, check_dir)) ok = False if not ok: return # download and extract sess_dir = osp.join(dload_dir, p_id) if not osp.isdir(sess_dir): print('Creating {:s}'.format(sess_dir)) os.makedirs(sess_dir, exist_ok=True) print('Downloading {:s} images...'.format(p_id)) object_names = list(urls[p_id].keys()) if include_objects is None: include_objects = object_names[:] filenames_to_extract = {} for object_name in tqdm(include_objects): if object_name not in object_names: print('{:d} {:s} does not have {:s}'.format(p_num, intent, object_name)) continue filename = osp.join(sess_dir, '{:s}_images.zip'.format(object_name)) url = urls[p_id][object_name] print(object_name) if nutils.download_url(url, filename): filenames_to_extract[object_name] = filename else: print('{:s} {:s} Download unsuccessful'.format(p_id, object_name)) return print('Extracting...') for object_name, filename in tqdm(filenames_to_extract.items()): obj_dir = osp.join(sess_dir, object_name) os.makedirs(obj_dir, exist_ok=True) self._unzip_and_del(filename, obj_dir) for filename in next(os.walk(obj_dir))[-1]: if download_color and (not download_depth): if '.mp4' not in filename: continue camera_name = filename.replace('.mp4', '') video_filename = osp.join(obj_dir, filename) im_dir = osp.join(obj_dir, 'images_full', camera_name, 'color') os.makedirs(im_dir, exist_ok=True) cap = cv2.VideoCapture(video_filename) if not cap.isOpened(): print('Could not read {:s}'.format(video_filename)) return count = 0 while True: ok, im = cap.read() if not ok: break filename = osp.join(im_dir, 'frame{:03d}.png'.format(count)) cv2.imwrite(filename, im) count += 1 os.remove(video_filename) else: if '.zip' not in filename: continue filter_fn = (lambda x: 'color' not in x) if (not download_color) \ else None self._unzip_and_del(osp.join(obj_dir, filename), progress=False, filter_fn=filter_fn) # symlink if osp.realpath(dload_dir) != osp.realpath(self.data_dir): src = osp.join(obj_dir, 'images_full') dst_dir = osp.join(self.data_dir, p_id, object_name) if not osp.isdir(dst_dir): os.makedirs(dst_dir) dst = osp.join(dst_dir, 'images_full') os.symlink(src, dst) if __name__ == '__main__': import argparse import sys from itertools import product parser = argparse.ArgumentParser() parser.add_argument('--type', choices=('grasps', 'markers', '3Dmodels', 'color_images', 'depth_images', 'images', 'contact_maps'), required=True) parser.add_argument('--p_nums', default=None, help='Participant numbers E.g. 1, 1,2, or 1-5') parser.add_argument('--intents', default='use,handoff', help='use, handoff, or use,handoff') parser.add_argument('--object_names', default=None, help='Comma separated object names. Used only for image '+\ 'download. All other types download data for all '+\ 'objects in that particular p_num, intent combo') parser.add_argument('--images_dload_dir', default=osp.join('data', 'contactpose_data'), help='Directory where images will be downloaded. ' 'They will be symlinked to the appropriate location') args = parser.parse_args() downloader = ContactPoseDownloader() if args.type == 'grasps': downloader.download_grasps() sys.exit(0) elif args.type == 'markers': downloader.download_markers() sys.exit(0) elif args.type == '3Dmodels': downloader.download_3d_models() sys.exit(0) assert(args.p_nums is not None) if '-' in args.p_nums: start, finish = args.p_nums.split('-') nums = list(range(int(start), int(finish)+1)) elif ',' in args.p_nums: nums = [int(n) for n in args.p_nums.split(',')] else: nums = [int(args.p_nums)] intents = args.intents.split(',') include_objects = args.object_names if include_objects is not None: include_objects = include_objects.split(',') include_objects = list(set(include_objects)) # remove duplicates for p_num, intent in product(nums, intents): p_id = 'full{:d}_{:s}'.format(p_num, intent) print('####### {:s} #######'.format(p_id)) if args.type == 'contact_maps': downloader.download_contact_maps(p_num, intent) elif args.type == 'color_images': downloader.download_color_images(p_num, intent, osp.expanduser(args.images_dload_dir), include_objects=include_objects) elif args.type == 'depth_images': downloader.download_depth_images(p_num, intent, osp.expanduser(args.images_dload_dir), include_objects=include_objects) elif args.type == 'images': downloader.download_images(p_num, intent, osp.expanduser(args.images_dload_dir), include_objects=include_objects) else: raise NotImplementedError
ContactPose-main
scripts/download_data.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt """ Discovers 'active areas' i.e. areas on the object surface most frequently touched by a certain part of the hand. See Figure 7 in the paper https://arxiv.org/pdf/2007.09545.pdf. """ import init_paths from utilities.import_open3d import * # need to import open3d before others import json from matplotlib import cm import numpy as np import os from random import shuffle from utilities.dataset import get_p_nums import utilities.misc as mutils osp = os.path def discover_active_areas(finger_idx, part_idx, object_name, intent, p_nums=None, color_thresh=0.4): """ finger_idx: 0->4 : thumb->little part_idx: 0->3 : proximal to distal phalanges, 3 = finger tip """ p_nums = p_nums or get_p_nums(object_name, intent) shuffle(p_nums) data_dir = osp.join('data', 'contactpose_data') # read object mesh vertices = None for p_num in p_nums: filename = osp.join(data_dir, f'full{p_num}_{intent}', object_name, f'{object_name}.ply') if osp.isfile(filename): mesh = o3dio.read_triangle_mesh(filename) else: print('{:s} does not exist'.format(filename)) continue vertices = np.asarray(mesh.vertices) break if vertices is None: print("no object model found") return line_ids = mutils.get_hand_line_ids() n_lines_per_hand = len(line_ids) n_parts_per_finger = 4 touched_by_part = np.zeros(len(vertices)) count = 0 for p_num in p_nums: print(f'Processing full{p_num}_{intent} {object_name}') # read contact from the mesh filename = osp.join(data_dir, f'full{p_num}_{intent}', object_name, f'{object_name}.ply') if osp.isfile(filename): mesh = o3dio.read_triangle_mesh(filename) else: print('{:s} does not exist'.format(filename)) continue tex = np.asarray(mesh.vertex_colors)[:, 0] tex = mutils.texture_proc(tex) # read joints filename = osp.join(data_dir, f'full{p_num}_{intent}', object_name, 'annotations.json') try: with open(filename, 'r') as f: annotations = json.load(f) except FileNotFoundError: print('{:s} does not exist'.format(filename)) continue ds = [] for hand_idx, hand in enumerate(annotations['hands']): if hand['valid']: joints = np.asarray(hand['joints']) l0 = joints[line_ids[:, 0]] l1 = joints[line_ids[:, 1]] pl = mutils.closest_linesegment_point(l0, l1, vertices) d = pl - vertices[:, np.newaxis, :] d = np.linalg.norm(d, axis=2) else: d = np.inf * np.ones((len(vertices), n_lines_per_hand)) ds.append(d) ds = np.hstack(ds) hand_idxs, line_idxs = divmod(np.argmin(ds, axis=1), n_lines_per_hand) finger_idxs, part_idxs = divmod(line_idxs, n_parts_per_finger) this_touched_by_part = np.logical_and( tex > color_thresh, np.logical_and(hand_idxs >= 0, np.logical_and(finger_idxs == finger_idx, part_idxs == part_idx))) touched_by_part += this_touched_by_part count += 1 touched_by_part /= count touched_by_part /= touched_by_part.max() filename = osp.join('data', f'{object_name}_{intent}_{finger_idx}_{part_idx}_active_areas.npy') np.save(filename, touched_by_part) print('{:s} saved'.format(filename)) def show_active_areas(finger_idx, part_idx, object_name, intent): filename = osp.join('data', 'object_models', f'{object_name}.ply') mesh = o3dio.read_triangle_mesh(filename) mesh.compute_vertex_normals() filename = osp.join('data', f'{object_name}_{intent}_{finger_idx}_{part_idx}_active_areas.npy') c = np.load(filename) mesh.vertex_colors = o3du.Vector3dVector(cm.bwr(c)[:, :3]) o3dv.draw_geometries([mesh]) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--finger_idx', type=int, required=True, help='0->4 : thumb->little', choices=(0, 1, 2, 3, 4)) parser.add_argument('--part_idx', type=int, required=True, choices=(0, 1, 2, 3), help='0->3 : proximal to distal phalanges, 3 = finger tip') parser.add_argument('--object_name', required=True) parser.add_argument('--intent', required=True, choices=('use', 'handoff')) parser.add_argument('--p_nums', default='1-50', help='Participant numbers, comma or - separated.' 'Skipping means all participants') parser.add_argument('--show', action='store_true') args = parser.parse_args() p_nums = args.p_nums if '-' in p_nums: first, last = p_nums.split('-') p_nums = list(range(int(first), int(last)+1)) else: p_nums = [int(p) for p in p_nums.split(',')] if args.show: show_active_areas(args.finger_idx, args.part_idx, args.object_name, args.intent) else: discover_active_areas(args.finger_idx, args.part_idx, args.object_name, args.intent, p_nums)
ContactPose-main
scripts/data_analysis/active_areas.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import sys sys.path.append('.')
ContactPose-main
scripts/data_analysis/init_paths.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt """ Calculates and shows the contact probability for hand points Figure 5(a) in the paper """ import os import matplotlib.pyplot as plt import numpy as np import init_paths from utilities.import_open3d import * from utilities.dataset import ContactPose, get_object_names import utilities.misc as mutils osp = os.path def calc_hand_contact_prob(p_nums, intents, object_names, contact_thresh=0.4, search_r=15e-3, hand_idx=1): """ hand_idx: 0 for left, 1 for right """ contact_probs = [] for p_num in p_nums: for intent in intents: if object_names is None: object_names = get_object_names(p_num, intent) for object_name in object_names: print('{:d} : {:s} : {:s}'.format(p_num, intent, object_name)) cp = ContactPose(p_num, intent, object_name) object_mesh = o3dio.read_triangle_mesh(cp.contactmap_filename) v = np.array(object_mesh.vertices) c = np.array(object_mesh.vertex_colors)[:, 0] c = mutils.texture_proc(c) idx = c >= contact_thresh v = v[idx] # read mano hand = cp.mano_meshes()[hand_idx] if hand is None: continue h_pc = o3dg.PointCloud() h_pc.points = o3du.Vector3dVector(hand['vertices']) tree = o3dg.KDTreeFlann(h_pc) contact_prob = np.zeros(len(hand['vertices'])) for vv in v: k, idx, dist2 = tree.search_hybrid_vector_3d(vv, search_r, 10) for i in range(k): # contact_prob[idx[i]] += (1.0/np.sqrt(dist2[i])) contact_prob[idx[i]] = 1 contact_probs.append(contact_prob) contact_probs = np.mean(contact_probs, axis=0) return contact_probs def show_hand_contact_prob(contact_prob, hand_idx=1): # dummy params mp = { 'pose': np.zeros(15+3), 'betas': np.zeros(10), 'hTm': np.eye(4) } hand = mutils.load_mano_meshes([mp, mp], ContactPose._mano_dicts, flat_hand_mean=True)[hand_idx] contact_prob -= contact_prob.min() contact_prob /= contact_prob.max() contact_prob = plt.cm.bwr(contact_prob)[:, :3] h = o3dg.TriangleMesh() h.vertices = o3du.Vector3dVector(hand['vertices']) h.triangles = o3du.Vector3iVector(hand['faces']) h.vertex_colors = o3du.Vector3dVector(contact_prob) h.compute_vertex_normals() o3dv.draw_geometries([h]) if __name__ == '__main__': parser = mutils.default_multiargparse() args = parser.parse_args() p_nums, intents, object_names, args = mutils.parse_multiargs(args) hand_idx = 1 p = calc_hand_contact_prob(p_nums, intents, object_names, hand_idx=hand_idx) show_hand_contact_prob(p, hand_idx=hand_idx)
ContactPose-main
scripts/data_analysis/hand_contact_prob.py
ContactPose-main
scripts/data_analysis/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import init_paths import dropbox import json from requests.exceptions import ConnectionError import os from utilities.dataset import get_object_names osp = os.path dbx = dropbox.Dropbox(os.environ['DROPBOX_APP_KEY']) def move(p_num, intent, object_name): p_id = 'full{:d}_{:s}'.format(p_num, intent) opath = osp.join('/', 'contactpose', 'videos_full', p_id, object_name) dpath = osp.join(opath, 'color') try: dbx.files_create_folder(dpath) except dropbox.exceptions.ApiError as err: print('*** API error', err) dbx.close() return print('{:s} created'.format(dpath)) for camera_name in ('kinect2_left', 'kinect2_right', 'kinect2_middle'): src = osp.join(opath, '{:s}_color.mp4'.format(camera_name)) file_exists = True try: dbx.files_get_metadata(src) except dropbox.exceptions.ApiError as err: file_exists = False print('{:s} does not exist'.format(src)) if not file_exists: continue dst = osp.join(dpath, '{:s}.mp4'.format(camera_name)) try: dbx.files_move(src, dst) except dropbox.exceptions.ApiError as err: print('*** API error moving {:s} -> {:s}'.format(src, dst), err) print('Moved {:s} -> {:s}'.format(src, dst)) if __name__ == '__main__': p_num = 5 for intent in ('use', 'handoff'): p_id = 'full{:d}_{:s}'.format(p_num, intent) with open(osp.join('data', 'object_names.txt'), 'r') as f: object_names = [o.strip() for o in f] with open(osp.join('data', 'urls.json'), 'r') as f: urls = json.load(f) object_names = [o for o in object_names if o in urls['images'][p_id]] for object_name in object_names: move(p_num, intent, object_name)
ContactPose-main
scripts/maintenance/move_videos_dropbox.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import sys sys.path.append('.')
ContactPose-main
scripts/maintenance/init_paths.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import requests import json from copy import deepcopy import os osp = os.path data_template = { 'path': '/contactpose/videos_full/{:s}/{:s}/color', 'settings': { 'requested_visibility': 'public', 'audience': 'public', 'access': 'viewer' } } def get_url(p_id, object_name): headers = { 'Authorization': 'Bearer {:s}'.format(os.environ['DROPBOX_APP_KEY']), 'Content-Type': 'application/json', } d = deepcopy(data_template) d['path'] = d['path'].format(p_id, object_name) filename = '/tmp/tmpurl.json' with open(filename, 'w') as f: json.dump(d, f) r = requests.post('https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings', data=open(filename), headers=headers) if r.status_code != 200: print('Unsuccessful, return status = {:d}'.format(r.status_code)) return url = r.json()['url'] url = url.replace('dl=0', 'dl=1') filename = osp.join('data', 'urls.json') with open(filename, 'r') as f: d = json.load(f) if p_id not in d['videos']['color']: d['videos']['color'][p_id] = {} d['videos']['color'][p_id][object_name] = url with open(filename, 'w') as f: json.dump(d, f, indent=4, separators=(', ', ': ')) # print('{:s} updated'.format(filename)) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--p_id', required=True) args = parser.parse_args() with open(osp.join('data', 'urls.json'), 'r') as f: d = json.load(f) object_names = d['images'][args.p_id] print('#########', args.p_id) for object_name in object_names: print(object_name) get_url(args.p_id, object_name)
ContactPose-main
scripts/maintenance/get_urls.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import os import shutil import sys osp = os.path def remove(p_num): for ins in ('use', 'handoff'): p_id = 'full{:s}_{:s}'.format(p_num, ins) sess_dir = osp.join('..', '..', 'data', 'contactpose_data', p_id) for object_name in next(os.walk(sess_dir))[1]: obj_dir = osp.join(sess_dir, object_name) for filename in next(os.walk(obj_dir))[-1]: if '.zip' not in filename: continue filename = osp.join(obj_dir, filename) os.remove(filename) print(filename) obj_dir = osp.join(obj_dir, 'images_full') # if osp.isdir(obj_dir): # shutil.rmtree(obj_dir) # print(obj_dir) for camera_name in ('kinect2_left', 'kinect2_right', 'kinect2_middle'): cam_dir = osp.join(obj_dir, camera_name) filename = osp.join(cam_dir, 'color.mp4') if osp.isfile(filename): os.remove(filename) print(filename) for filename in next(os.walk(sess_dir))[-1]: filename = osp.join(sess_dir, filename) os.remove(filename) print(filename) if __name__ == '__main__': remove(sys.argv[1])
ContactPose-main
scripts/maintenance/remove_videos.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt
ContactPose-main
scripts/maintenance/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt import init_paths from scripts.download_data import ContactPoseDownloader import ffmpeg import os import shutil import json import itertools from multiprocessing import Pool import argparse from functools import partial import utilities.networking as nutils osp = os.path intents = ('use', 'handoff') with open(osp.join('data', 'object_names.txt'), 'r') as f: object_names = [l.strip() for l in f] # object_names = ('bowl', ) with open(osp.join('data', 'urls.json'), 'r') as f: urls = json.load(f) urls = urls['images'] video_params = { 'color': { 'ffmpeg_kwargs': dict(pix_fmt='yuv420p', vcodec='libx264', crf=0), 'ext': 'mp4', 'valid': True, }, 'depth': { 'ffmpeg_kwargs': dict(pix_fmt='gray16le', vcodec='ffv1'), 'ext': 'mkv', 'valid': False, # compression not working losslessly right now, so skip }, } def produce_worker(task, ffmpeg_path): try: p_num, intent, object_name = task p_id = 'full{:d}_{:s}'.format(p_num, intent) dload_dir=osp.join('data', 'contactpose_data') data_dir = osp.join(dload_dir, p_id, object_name, 'images_full') # download downloader = ContactPoseDownloader() if osp.isdir(data_dir): shutil.rmtree(data_dir) print('Deleted {:s}'.format(data_dir)) downloader.download_images(p_num, intent, dload_dir, include_objects=(object_name,)) if not osp.isdir(data_dir): print('Could not download {:s} {:s}'.format(p_id, object_name)) # check if the data actually exists if object_name in urls[p_id]: return False else: print('But that is OK because underlying data does not exist') return True # process for camera_position in ('left', 'right', 'middle'): camera_name = 'kinect2_{:s}'.format(camera_position) this_data_dir = osp.join(data_dir, camera_name) if not osp.isdir(this_data_dir): print('{:s} does not have {:s} camera'.format(this_data_dir, camera_position)) continue for mode, params in video_params.items(): if not params['valid']: shutil.rmtree(osp.join(this_data_dir, mode)) continue # video encoding output_filename = osp.join(this_data_dir, '{:s}.{:s}'.format(mode, params['ext'])) ( ffmpeg .input(osp.join(this_data_dir, mode, 'frame%03d.png'), framerate=30) .output(output_filename, **params['ffmpeg_kwargs']) .overwrite_output() .run(cmd=ffmpeg_path) ) print('{:s} written'.format(output_filename), flush=True) shutil.rmtree(osp.join(this_data_dir, mode)) # upload dropbox_path = osp.join('/', 'contactpose', 'videos_full', p_id, object_name, mode, '{:s}.mp4'.format(camera_name)) if not nutils.upload_dropbox(output_filename, dropbox_path): return False return True except Exception as e: print('Error somewhere in ', task) print(str(e)) return False def produce(p_nums, cleanup=False, parallel=True, ffmpeg_path='ffmpeg', tasks=None): if tasks is not None: pass elif cleanup: print('#### Cleanup mode ####') filename = osp.join('status.json') with open(filename, 'r') as f: status = json.load(f) tasks = [] for task,done in status.items(): if done: continue task = task.split('_') p_num = int(task[0][4:]) intent = task[1] object_name = '_'.join(task[2:]) tasks.append((p_num, intent, object_name)) print('Found {:d} cleanup items'.format(len(tasks))) else: tasks = list(itertools.product(p_nums, intents, object_names)) worker = partial(produce_worker, ffmpeg_path=ffmpeg_path) if parallel: p = Pool(len(object_names)) dones = p.map(worker, tasks) p.close() p.join() else: dones = map(worker, tasks) filename = osp.join('status.json') d = {} if osp.isfile(filename): with open(filename, 'r') as f: d = json.load(f) for task, done in zip(tasks, dones): d['full{:d}_{:s}_{:s}'.format(*task)] = done with open(filename, 'w') as f: json.dump(d, f, indent=4, separators=(', ', ': ')) print('{:s} updated'.format(filename)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-p', type=int, default=-1) parser.add_argument('--tasks', default=None, help='e.g. 1-use-pan,34-use-mug') parser.add_argument('--cleanup', action='store_true') parser.add_argument('--no_parallel', action='store_false', dest='parallel') parser.add_argument('--ffmpeg_path', default='ffmpeg') args = parser.parse_args() if args.tasks is not None: # parse tasks tasks = args.tasks.split(',') tasks = [t.split('-') for t in tasks] tasks = [(int(t[0]), t[1], t[2]) for t in tasks] else: tasks = args.tasks assert (args.p > 0) produce((args.p, ), cleanup=args.cleanup, parallel=args.parallel, tasks=tasks)
ContactPose-main
scripts/maintenance/produce_videos.py
# Copyright (c) Facebook, Inc. and its affiliates. # Code by Samarth Brahmbhatt
ContactPose-main
thirdparty/__init__.py
#!/usr/bin/env python3 """ Copyright (c) Meta Platforms, Inc. and affiliates. Calculate cumulative distribution functions for standard Brownian motions. Running as a script tests assertions that closed-form, analytical expressions for the means match numerical evaluations of the means for the cumulative distribution functions, prints values of the cumulative distribution functions at some interesting values for their arguments, saves to disk plots in pdf of the complementary cumulative distribution functions, and saves to disk plots in both pdf and jpg of calibration curves for synthetic data sets drawn from perfectly calibrated distributions. The script saves plots in the current directory, in files named "gauss.pdf", "gauss_log.pdf", "kuiper.pdf", "kuiper_log.pdf", "kolmogorov_smirnov.pdf", and "kolmogorov_smirnov_log.pdf". The files whose names end with "_log.pdf" use log scales for the vertical axes. The plots for the metrics of Kuiper and of Kolmogorov and Smirnov include vertical dotted lines at the means associated with the corresponding distribution. The script saves twelve other plots in the current directory, too, as detailed in the docstring for function plotnull below. An article detailing the functions named after mathematicians and statisticians (Kolmogorov, Smirnov, Kuiper, Gauss, and Chebyshev) is Mark Tygert's "Calibration of P-values for calibration and for deviation of a subpopulation from the full population." Functions --------- kolmogorov_smirnov Evaluates the cumulative distribution function for the maximum of the absolute value of the standard Brownian motion on [0, 1] kuiper Evaluates the cumulative distribution function for the range (maximum minus minimum) of the standard Brownian motion on [0, 1] gauss Evaluates the cumulative distribution function for the distribution N(0, 1) (the standard normal distribution, involving a Gaussian) chebyshev Integrates the function f(x) from x=a to x=b using n Chebyshev nodes testmeans Verifies that the means of the cumulative distribution functions are right printvals Evaluates the cumulative distribution functions at some points of interest and prints them saveplots Plots and saves to disk the complementary cumulative distribution functions plotnull Plots the P-values for data generated from a perfectly calibrated model This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import math import numpy as np from numpy.random import default_rng import subprocess import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt def kolmogorov_smirnov(x): """ Evaluates the cumulative distribution function for the maximum of the absolute value of the standard Brownian motion on [0, 1] Parameters ---------- x : float argument at which to evaluate the cumulative distribution function (must be positive) Returns ------- float cumulative distribution function evaluated at x """ assert x > 0 # Compute the machine precision assuming binary numerical representations. eps = 7 / 3 - 4 / 3 - 1 # Determine how many terms to use to attain accuracy eps. fact = 4 / math.pi kmax = math.ceil( 1 / 2 + x * math.sqrt(2) / math.pi * math.sqrt(math.log(fact / eps))) # Sum the series. c = 0 for k in range(kmax): kplus = k + 1 / 2 c += (-1)**k / kplus * math.exp(-kplus**2 * math.pi**2 / (2 * x**2)) c *= 2 / math.pi return c def kuiper(x): """ Evaluates the cumulative distribution function for the range (maximum minus minimum) of the standard Brownian motion on [0, 1] Parameters ---------- x : float argument at which to evaluate the cumulative distribution function (must be positive) Returns ------- float cumulative distribution function evaluated at x """ assert x > 0 # Compute the machine precision assuming binary numerical representations. eps = 7 / 3 - 4 / 3 - 1 # Determine how many terms to use to attain accuracy eps. fact = 4 / math.sqrt(2 * math.pi) * (1 / x + x / math.pi**2) kmax = math.ceil( 1 / 2 + x / math.pi / math.sqrt(2) * math.sqrt(math.log(fact / eps))) # Sum the series. c = 0 for k in range(kmax): kplus = k + 1 / 2 c += (8 / x**2 + 2 / kplus**2 / math.pi**2) * math.exp( -2 * kplus**2 * math.pi**2 / x**2) return c def gauss(x): """ Evaluates the cumulative distribution function for the distribution N(0, 1) (the standard normal distribution, involving a Gaussian) Parameters ---------- x : float argument at which to evaluate the cumulative distribution function Returns ------- float cumulative distribution function evaluated at x """ return (1 + math.erf(x / math.sqrt(2))) / 2 def chebyshev(a, b, n, f): """ Integrates the function f(x) from x=a to x=b using n Chebyshev nodes Parameters ---------- a : float lower limit of integration b : float upper limit of integration n : int number of Chebyshev nodes in the Gauss-Chebyshev quadrature f : callable real-valued function of a real argument to be integrated Returns ------- float integral from x=a to x=b of f(x) (dx) """ sum = 0 for k in range(n): c = math.cos((2 * k + 1) * math.pi / (2 * n)) x = a + (b - a) * (1 + c) / 2 sum += f(x) * math.sqrt(1 - c**2) sum *= (b - a) * math.pi / (2 * n) return sum def testmeans(): """ Verifies that the means of the cumulative distribution functions are right Returns ------- float mean of the Kolmogorov-Smirnov statistic under the null hypothesis that the subpopulation arises from the full population's distribution (and that the scores are dense in their domain) float mean of the Kuiper statistic under the null hypothesis that the subpopulation arises from the full population's distribution (and that the scores are dense in their domain) References ---------- William Feller, "The asymptotic distribution of the range of sums of independent random variables," Ann. Math. Statist., 22 (1951): 427-432. Jaume Masoliver, "Extreme values and the level-crossing problem: an application to the Feller process," Phys. Rev. E., 89 (2014): 042106. """ # Compute the means of the Kolmogorov-Smirnov and Kuiper statistics # using closed-form analytic expressions (see Formula 1.4 of the reference # to Feller given in the docstring, as well as Formula 46 of the reference # to Masoliver). ks_mean = math.sqrt(math.pi / 2) ku_mean = 2 * math.sqrt(2 / math.pi) # Compute the means from the associated cumulative distribution functions # evaluated numerically. ks_mean2 = chebyshev(1e-8, 8, 100000, lambda x: 1 - kolmogorov_smirnov(x)) ku_mean2 = chebyshev(1e-8, 8, 100000, lambda x: 1 - kuiper(x)) # Check that the calculated values agree with each other. tolerance = 1e-8 assert (ks_mean - ks_mean2) / ks_mean < tolerance assert (ku_mean - ku_mean2) / ku_mean < tolerance return ks_mean, ku_mean def printvals(ks_mean, ku_mean): """ Evaluates the cumulative distribution functions at some points of interest and prints them Parameters ---------- ks_mean : float mean of the Kolmogorov-Smirnov statistic under the null hypothesis that the subpopulation arises from the full population's distribution (and that the scores are dense in their domain) ku_mean : float mean of the Kuiper statistic under the null hypothesis that the subpopulation arises from the full population's distribution (and that the scores are dense in their domain) """ print(f'1 - kolmogorov_smirnov(0.001) = {1 - kolmogorov_smirnov(0.001)}') print('1 - kolmogorov_smirnov(ks_mean) = {}' .format(1 - kolmogorov_smirnov(ks_mean))) print('1 - kolmogorov_smirnov(7.319) = {}' .format(1 - kolmogorov_smirnov(7.319))) print('1 - kolmogorov_smirnov(6.818) = {}' .format(1 - kolmogorov_smirnov(6.818))) print('1 - kolmogorov_smirnov(4.307) = {}' .format(1 - kolmogorov_smirnov(4.307))) print('1 - kolmogorov_smirnov(4.624) = {}' .format(1 - kolmogorov_smirnov(4.624))) print('1 - kolmogorov_smirnov(2.205) = {}' .format(1 - kolmogorov_smirnov(2.205))) print('1 - kolmogorov_smirnov(2.043) = {}' .format(1 - kolmogorov_smirnov(2.043))) print(f'1 - kolmogorov_smirnov(1000) = {1 - kolmogorov_smirnov(1000)}') print() print(f'1 - kuiper(0.001) = {1 - kuiper(0.001)}') print(f'1 - kuiper(ku_mean) = {1 - kuiper(ku_mean)}') print(f'1 - kuiper(7.521) = {1 - kuiper(7.521)}') print(f'1 - kuiper(7.213) = {1 - kuiper(7.213)}') print(f'1 - kuiper(4.373) = {1 - kuiper(4.373)}') print(f'1 - kuiper(4.710) = {1 - kuiper(4.710)}') print(f'1 - kuiper(2.259) = {1 - kuiper(2.259)}') print(f'1 - kuiper(2.110) = {1 - kuiper(2.110)}') print(f'1 - kuiper(1000) = {1 - kuiper(1000)}') print() print('switch the mean values and see that the P-values deviate ' + 'far from 0.5:') print('1 - kolmogorov_smirnov(ku_mean) = {}' .format(1 - kolmogorov_smirnov(ku_mean))) print(f'1 - kuiper(ks_mean) = {1 - kuiper(ks_mean)}') def saveplots(ks_mean, ku_mean): """ Plots and saves to disk the complementary cumulative distribution functions The plots, saved in the current directory, are "gauss.pdf", "gauss_log.pdf", "kuiper.pdf", "kuiper_log.pdf", "kolmogorov_smirnov.pdf", and "kolmogorov_smirnov_log.pdf". The files whose names end with "_log.pdf" use logarithmic scales for the vertical axes. The plots for Kuiper and for Kolmogorov and Smirnov include vertical dotted lines at the means of the corresponding distribution, assuming that the input parameters are correct. Parameters ---------- ks_mean : float mean of the Kolmogorov-Smirnov statistic under the null hypothesis that the subpopulation arises from the full population's distribution (and that the scores are dense in their domain) ku_mean : float mean of the Kuiper statistic under the null hypothesis that the subpopulation arises from the full population's distribution (and that the scores are dense in their domain) """ for func in ['gauss', 'kuiper', 'kolmogorov_smirnov']: for logscale in [True, False]: # Create a plot. plt.figure(figsize=[4.8, 3.6]) # Create abscissae and ordinates. xmax = 8 x = np.arange(1e-3, xmax, 1e-3) y = 1 - np.vectorize(globals()[func])(x) # Plot y versus x. plt.plot(x, y, 'k') # Plot a vertical line at the mean. if func == 'kuiper': mean = ku_mean elif func == 'kolmogorov_smirnov': mean = ks_mean else: mean = 0 if mean > 0: plt.vlines(mean, 1 - globals()[func](xmax), 1, 'k', 'dotted') plt.text( mean, 1 - globals()[func](xmax), 'mean ', ha='center', va='top') # Set the vertical axis to use a logscale if logscale is True. if logscale: plt.yscale('log') # Title the axes. plt.xlabel('$x$') if func == 'kuiper': plt.ylabel('$1 - F(x)$') elif func == 'kolmogorov_smirnov': plt.ylabel('$1 - D(x)$') else: plt.ylabel('$1 - \\Phi(x)$') # Clean up the whitespace in the plot. plt.tight_layout() # Save the plot. filename = func if logscale: filename += '_log' filename += '.pdf' plt.savefig(filename, bbox_inches='tight') plt.close() def plotnull(ns, points, transform=None, suffix=''): """ Plots the P-values for data generated from a perfectly calibrated model The plots, saved in the current directory are "kuiper_ecdf[suffix].pdf", "kuiper_ecdf[suffix].jpg", "kolmogorov_smirnov_ecdf[suffix].pdf", and "kolmogorov_smirnov_ecdf[suffix].jpg". The JPEG versions are conversions from the PDF at a resolution of 1200 pixels per inch. The plots display the empirical cumulative distribution functions of the P-values associated with the Kuiper and Kolmogorov-Smirnov statistics, for points data sets, each with the number of scores and corresponding Bernoulli responses given by the given entry in ns (running everything again for each entry in ns). The Bernoulli responses are independent, and the probability of success for each is equal to the corresponding score (ensuring perfect calibration of the underlying data distribution). The transform gets applied to each score, with the scores being equispaced before application of transform (and remaining equispaced if transform is None). Parameters ---------- ns : list of int sample sizes for each generated data set points : int number of data sets to generate per calibration curve (that is, per empirical cumulative distribution function of P-values) transform : callable, optional numpy function to apply to the otherwise equispaced scores (set to None -- the default -- to use the original equispaced scores) suffix : string, optional suffix to append to the filename (defaults to the empty string) """ # Store processes for converting from pdf to jpeg in procs. procs = [] # Store the calibration curves for both Kolmogorov-Smirnov and Kuiper # statistics (these are empirical cumulative distribution functions), # in ksc and kuc, respectively. ksc = np.zeros((len(ns), points)) kuc = np.zeros((len(ns), points)) for j, n in enumerate(ns): rng = default_rng(seed=543216789) # Run simulations points times. pks = np.zeros((points)) pku = np.zeros((points)) for k in range(points): # Generate predicted probabilities (the "scores"). s = np.arange(0, 1, 1 / n)[:n] if transform is not None: s = transform(s) # Generate a sample of classifications (the "responses") # into two classes, correct (class 1) and incorrect (class 0), # avoiding numpy's random number generators that are based # on random bits -- they yield strange results for many seeds. uniform = rng.uniform(size=(n)) r = (uniform <= s).astype(float) # Calculate the cumulative differences. c = (np.cumsum(r) - np.cumsum(s)) / n # Calculate the estimate of sigma. sigma = np.sqrt(np.sum(s * (1 - s))) / n # Compute the normalized Kolmogorov-Smirnov and Kuiper statistics. ks = np.abs(c).max() / sigma c = np.insert(c, 0, [0]) ku = (c.max() - c.min()) / sigma # Evaluate the P-values. pks[k] = 1 - kolmogorov_smirnov(ks) pku[k] = 1 - kuiper(ku) # Calculate the empirical cumulative distributions of the P-values. ksc[j, :] = np.sort(pks) kuc[j, :] = np.sort(pku) for stat in ['kolmogorov_smirnov', 'kuiper']: # Create a plot. plt.figure(figsize=[4.8, 3.6]) # Title the axes. plt.xlabel('$x$') plt.ylabel('fraction of P-values $\\leq x$') # Plot the empirical cumulative distribution functions. frac = np.arange(1 / points, 1 + 1 / points, 1 / points)[:points] for j in range(len(ns)): if stat == 'kolmogorov_smirnov': plt.plot(ksc[j, :], frac, color='k') elif stat == 'kuiper': plt.plot(kuc[j, :], frac, color='k') # Add a diagonal line from (0, 0) to (1, 1). zeroone = np.asarray((0, 1)) plt.plot(zeroone, zeroone, 'k', linestyle='dashed') # Save the plot. filepdf = stat + '_ecdf' + suffix + '.pdf' plt.savefig(filepdf, bbox_inches='tight') plt.close() # Convert the pdf to jpg. filejpg = filepdf[:-4] + '.jpg' args = ['convert', '-density', '1200', filepdf, filejpg] procs.append(subprocess.Popen(args)) print('waiting for conversion from pdf to jpg to finish....') for iproc, proc in enumerate(procs): proc.wait() print(f'{iproc + 1} of {len(procs)} conversions are done....') if __name__ == '__main__': # Test if the cumulative distribution functions yield the known values # for their means. print('testing means...') ks_mean, ku_mean = testmeans() # Print values of the cumulative distribution functions at some interesting # values for their arguments. print() print('evaluating for particular values of the arguments...') print() printvals(ks_mean, ku_mean) # Save plots of the complementary cumulative distribution functions. print() print('plotting the complementary cumulative distribution functions...') saveplots(ks_mean, ku_mean) # Plot the calibration curves ("calibration curves" are the empirical # cumulative distribution functions of P-values under the null hypothesis # of perfect calibration). ns = [100, 1000, 10000] points = 100000 print('plotting calibration with equispaced scores...') plotnull(ns, points) print('plotting calibration with square-rooted scores...') plotnull(ns, points, np.sqrt, suffix='_sqrt') print('plotting calibration with squared scores...') plotnull(ns, points, np.square, suffix='_square')
cdeets-main
codes/dists.py
#!/usr/bin/env python3 """ Copyright (c) Meta Platforms, Inc. and affiliates. Plot the subpopulation deviations for the American Community Survey of USCB. This script creates a directory, "weighted," in the working directory if the directory does not already exist, then creates subdirectories there for each of the counties in California specified by the list "exs" defined below, and fills each subdirectory with eight files: 1. metrics.txt -- metrics about the plots 2. cumulative.pdf -- plot of cumulative differences between the county & state 3. equiscores10.pdf -- reliability diagram of the county & state with 10 bins (equispaced in scores) 4. equiscores20.pdf -- reliability diagram of the county & state with 20 bins (equispaced in scores) 5. equiscores100.pdf -- reliability diagram of the county & state with 100 bins (equispaced in scores) 6. equierrs10.pdf -- reliability diagram of the county & state with 10 bins (the error bar is about the same for every bin) 7. equierrs20.pdf -- reliability diagram of the county & state with 20 bins (the error bar is about the same for every bin) 8. equierrs100.pdf -- reliability diagram of the county & state with 100 bins (the error bar is about the same for every bin) The data comes from the American Community Survey of the U.S. Census Bureau, specifically the household data from the state of California and its counties. The scores are log_10 of the adjusted household personal incomes. The results/responses are given by the variates specified in the list "exs" defined below (together with the value of the variate to be considered "success" in the sense of Bernoulli trials, or else the nonnegative integer count for the variate, counting people, for instance). This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import math import numpy as np import os from subpop_weighted import equiscores, equierrs, cumulative # Specify which counties and variates to process, as well as the coded value # of interest for each variate (or None if the values of interest are # nonnegative integer counts). exs = [ {'county': 'Humboldt', 'var': 'LNGI', 'val': 2}, {'county': 'Los Angeles', 'var': 'NP', 'val': None}, {'county': 'Napa', 'var': 'SATELLITE', 'val': 1}, {'county': 'Orange', 'var': 'HISPEED', 'val': 1}, {'county': 'San Joaquin', 'var': 'NRC', 'val': None}, {'county': 'Stanislaus', 'var': 'NRC', 'val': None}, ] # Specify the name of the file of comma-separated values # for the household data in the American Community Survey. filename = 'psam_h06.csv' # Count the number of lines in the file for filename. lines = 0 with open(filename, 'r') as f: for line in f: lines += 1 print(f'reading and filtering all {lines} lines from {filename}....') # Determine the number of columns in the file for filename. with open(filename, 'r') as f: line = f.readline() num_cols = line.count(',') + 1 # Read and store all but the first two columns in the file for filename. raw = np.zeros((lines, num_cols - 2)) with open(filename, 'r') as f: for line_num, line in enumerate(f): parsed = line.split(',')[2:] if line_num == 0: # The initial line is a header ... save its column labels. header = parsed.copy() # Eliminate the newline character at the end of the line. header[-1] = header[-1][:-1] else: # All but the initial line consist of data ... extract the ints. raw[line_num - 1, :] = np.array( [int(s if s != '' else -1) for s in parsed]) # Filter out undesirable observations -- keep only strictly positive weights, # strictly positive household personal incomes, and strictly positive factors # for adjusting the income. keep = np.logical_and.reduce([ raw[:, header.index('WGTP')] > 0, raw[:, header.index('HINCP')] > 0, raw[:, header.index('ADJINC')] > 0]) raw = raw[keep, :] print(f'm = raw.shape[0] = {raw.shape[0]}') # Form a dictionary of the lower- and upper-bounds on the ranges of numbers # of the public-use microdata areas (PUMAs) for the counties in California. puma = { 'Alameda': (101, 110), 'Alpine, Amador, Calaveras, Inyo, Mariposa, Mono and Tuolumne': (300, 300), 'Butte': (701, 702), 'Colusa, Glenn, Tehama and Trinity': (1100, 1100), 'Contra Costa': (1301, 1309), 'Del Norte, Lassen, Modoc, Plumas and Siskiyou': (1500, 1500), 'El Dorado': (1700, 1700), 'Fresno': (1901, 1907), 'Humboldt': (2300, 2300), 'Imperial': (2500, 2500), 'Kern': (2901, 2905), 'Kings': (3100, 3100), 'Lake and Mendocino': (3300, 3300), 'Los Angeles': (3701, 3769), 'Madera': (3900, 3900), 'Marin': (4101, 4102), 'Merced': (4701, 4702), 'Monterey': (5301, 5303), 'Napa': (5500, 5500), 'Nevada and Sierra': (5700, 5700), 'Orange': (5901, 5918), 'Placer': (6101, 6103), 'Riverside': (6501, 6515), 'Sacramento': (6701, 6712), 'San Bernardino': (7101, 7115), 'San Diego': (7301, 7322), 'San Francisco': (7501, 7507), 'San Joaquin': (7701, 7704), 'San Luis Obispo': (7901, 7902), 'San Mateo': (8101, 8106), 'Santa Barbara': (8301, 8303), 'Santa Clara': (8501, 8514), 'Santa Cruz': (8701, 8702), 'Shasta': (8900, 8900), 'Solano': (9501, 9503), 'Sonoma': (9701, 9703), 'Stanislaus': (9901, 9904), 'Sutter and Yuba': (10100, 10100), 'Tulare': (10701, 10703), 'Ventura': (11101, 11106), 'Yolo': (11300, 11300), } # Process the examples. for ex in exs: for dither in [True, False]: # Form the scores, results, and weights. np.random.seed(seed=3820497) # Adjust the household personal income by the relevant factor. s = raw[:, header.index('HINCP')] * raw[:, header.index('ADJINC')] s /= 1e6 # Convert the adjusted incomes to a log (base-10) scale. s = np.log(s) / math.log(10) # Dither in order to ensure the uniqueness of the scores (if dither # is True). if dither: s = s * (np.ones(s.shape) + np.random.normal(size=s.shape) * 1e-8) # Read the result (raw integer count if the specified value is None, # Bernoulli indicator of success otherwise). if ex['val'] is None: r = raw[:, header.index(ex['var'])] else: r = raw[:, header.index(ex['var'])] == ex['val'] # Read the weight. w = raw[:, header.index('WGTP')] # Sort the scores. perm = np.argsort(s) s = s[perm] r = r[perm] w = w[perm] # Set a directory for the county (creating the directory if necessary). dir = 'weighted' try: os.mkdir(dir) except FileExistsError: pass dir = 'weighted/County_of_' dir += ex['county'].replace(' ', '_').replace(',', '') dir += '-' dir += ex['var'] dir += '-' if dither: dir += 'dithered' else: dir += 'averaged' try: os.mkdir(dir) except FileExistsError: pass dir += '/' print(f'./{dir} is under construction....') # Identify the indices of the subset corresponding to the county. slice = raw[perm, header.index('PUMA')] inds = slice >= (puma[ex['county']][0] * np.ones(raw.shape[0])) inds = inds & ( slice <= (puma[ex['county']][1] * np.ones(raw.shape[0]))) inds = np.nonzero(inds)[0] inds = np.unique(inds) # Plot reliability diagrams and the cumulative graph. nin = [10, 20, 100] nout = {} for nbins in nin: filename = dir + 'equiscores' + str(nbins) + '.pdf' equiscores(r, s, inds, nbins, filename, weights=w, left=0) filename = dir + 'equierrs' + str(nbins) + '.pdf' nout[str(nbins)] = equierrs(r, s, inds, nbins, filename, weights=w) if nbins < 100: assert abs(nout[str(nbins)][0] - nbins) <= 3 assert abs(nout[str(nbins)][1] - nbins) <= 3 majorticks = 10 minorticks = 300 filename = dir + 'cumulative.pdf' kuiper, kolmogorov_smirnov, lenscale = cumulative( r, s, inds, majorticks, minorticks, ex['val'] is not None, filename=filename, weights=w) # Save metrics in a text file. filename = dir + 'metrics.txt' with open(filename, 'w') as f: f.write('m:\n') f.write(f'{len(s)}\n') f.write('n:\n') f.write(f'{len(inds)}\n') f.write('number of unique scores in the subset:\n') f.write(f'{len(np.unique(s[inds]))}\n') f.write('lenscale:\n') f.write(f'{lenscale}\n') for nbins in nin: f.write("nout['" + str(nbins) + "']:\n") f.write(f'{nout[str(nbins)][0]}\n') f.write(f'{nout[str(nbins)][1]}\n') f.write('Kuiper:\n') f.write(f'{kuiper:.4}\n') f.write('Kolmogorov-Smirnov:\n') f.write(f'{kolmogorov_smirnov:.4}\n') f.write('Kuiper / lenscale:\n') f.write(f'{(kuiper / lenscale):.4}\n') f.write('Kolmogorov-Smirnov / lenscale:\n') f.write(f'{(kolmogorov_smirnov / lenscale):.4}\n')
cdeets-main
codes/acs.py
#!/usr/bin/env python3 """ Copyright (c) Meta Platforms, Inc. and affiliates. Plots of deviation of a subpop. from the full pop., with weighted sampling * This implementation considers responses r that can take arbitrary values, not necesssarily restricted to taking values 0 or 1. * Functions --------- cumulative Cumulative difference between observations from a subpop. & the full pop. equiscores Reliability diagram with roughly equispaced average scores over bins equierrs Reliability diagram with similar ratio L2-norm / L1-norm of weights by bin exactplot Reliability diagram with exact values plotted This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import math import os import subprocess import random import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt from matplotlib.ticker import FixedFormatter def cumulative(r, s, inds, majorticks, minorticks, bernoulli=True, filename='cumulative.pdf', title='subpop. deviation is the slope as a function of $A_k$', fraction=1, weights=None): """ Cumulative difference between observations from a subpop. & the full pop. Saves a plot of the difference between the normalized cumulative weighted sums of r for the subpopulation indices inds and the normalized cumulative weighted sums of r from the full population interpolated to the subpop. indices, with majorticks major ticks and minorticks minor ticks on the lower axis, labeling the major ticks with the corresponding values from s. Parameters ---------- r : array_like random outcomes s : array_like scores (must be in non-decreasing order) inds : array_like indices of the subset within s that defines the subpopulation (must be unique and in strictly increasing order) majorticks : int number of major ticks on each of the horizontal axes minorticks : int number of minor ticks on the lower axis bernoulli : bool, optional set to True (the default) for Bernoulli variates; set to False to use empirical estimates of the variance rather than the formula p(1-p) for a Bernoulli variate whose mean is p filename : string, optional name of the file in which to save the plot title : string, optional title of the plot fraction : float, optional proportion of the full horizontal axis to display weights : array_like, optional weights of the observations (the default None results in equal weighting) Returns ------- float Kuiper statistic float Kolmogorov-Smirnov statistic float quarter of the full height of the isosceles triangle at the origin in the plot """ def histcounts(nbins, a): # Counts the number of entries of a # falling into each of nbins equispaced bins. j = 0 nbin = np.zeros(nbins, dtype=np.int64) for k in range(len(a)): if a[k] > a[-1] * (j + 1) / nbins: j += 1 if j == nbins: break nbin[j] += 1 return nbin def aggregate(r, s, ss, w): # Determines the weighted mean and variance of the entries of r # in a bin around each entry of s corresponding to the subset ss of s. # The bin ranges from halfway to the nearest entry of s in ss # on the left to halfway to the nearest entry of s in ss on the right. q = np.insert(np.append(ss, [1e20]), 0, [-1e20]) t = np.asarray([(q[k] + q[k + 1]) / 2 for k in range(len(q) - 1)]) rc = np.zeros((len(ss))) rc2 = np.zeros((len(ss))) sc = np.zeros((len(ss))) sc2 = np.zeros((len(ss))) j = 0 for k in range(len(s)): if s[k] > t[j + 1]: j += 1 if j == len(ss): break if s[k] >= t[0]: sc[j] += w[k] sc2[j] += w[k]**2 rc[j] += w[k] * r[k] rc2[j] += w[k] * r[k]**2 means = rc / sc # Calculate an adjustment factor for the estimate of the variance # that will make the estimate unbiased. unbias = sc**2 unbias[np.where(sc**2 == sc2)] = 0 unbias[np.where(sc**2 != sc2)] /= (sc**2 - sc2)[np.where(sc**2 != sc2)] return means, unbias * (rc2 / sc - means**2) assert all(s[k] <= s[k + 1] for k in range(len(s) - 1)) assert all(inds[k] < inds[k + 1] for k in range(len(inds) - 1)) # Determine the weighting scheme. if weights is None: w = np.ones((len(s))) else: w = weights.copy() assert np.all(w > 0) w /= w.sum() # Create the figure. plt.figure() ax = plt.axes() # Subsample s, r, and w. ss = s[inds] rs = r[inds] ws = w[inds] # Average the results and weights for repeated scores, while subsampling # the scores and indices for the subpopulation. Also calculate factors # for adjusting the variances of responses to account for the responses # being averages of other responses (when the scores need not be unique). sslist = [] rslist = [] wslist = [] fslist = [] rssum = 0 wssum = 0 wssos = 0 for k in range(len(ss)): rssum += rs[k] * ws[k] wssum += ws[k] wssos += ws[k]**2 if k == len(ss) - 1 or not math.isclose( ss[k], ss[k + 1], rel_tol=1e-14): sslist.append(ss[k]) rslist.append(rssum / wssum) wslist.append(wssum) fslist.append(wssos / wssum**2) rssum = 0 wssum = 0 wssos = 0 ss = np.asarray(sslist) rs = np.asarray(rslist) ws = np.asarray(wslist) fs = np.asarray(fslist) # Normalize the weights. ws /= ws[:int(len(ws) * fraction)].sum() # Aggregate r according to s, ss, and w. rt, rtvar = aggregate(r, s, ss, w) # Accumulate the weighted rs and rt, as well as ws. f = np.insert(np.cumsum(ws * rs), 0, [0]) ft = np.insert(np.cumsum(ws * rt), 0, [0]) x = np.insert(np.cumsum(ws), 0, [0]) # Plot the difference. plt.plot( x[:int(len(x) * fraction)], (f - ft)[:int(len(f) * fraction)], 'k') # Make sure the plot includes the origin. plt.plot(0, 'k') # Add an indicator of the scale of 1/sqrt(n) to the vertical axis. rtsub = np.insert(rt, 0, [0])[:(int(len(rt) * fraction) + 1)] if bernoulli: lenscale = np.sqrt(np.sum(ws**2 * rtsub[1:] * (1 - rtsub[1:]) * fs)) else: lenscale = np.sqrt(np.sum(ws**2 * rtvar * fs)) plt.plot(2 * lenscale, 'k') plt.plot(-2 * lenscale, 'k') kwargs = { 'head_length': 2 * lenscale, 'head_width': fraction / 20, 'width': 0, 'linewidth': 0, 'length_includes_head': True, 'color': 'k'} plt.arrow(.1e-100, -2 * lenscale, 0, 4 * lenscale, shape='left', **kwargs) plt.arrow(.1e-100, 2 * lenscale, 0, -4 * lenscale, shape='right', **kwargs) plt.margins(x=0, y=.1) # Label the major ticks of the lower axis with the values of ss. lenxf = int(len(x) * fraction) sl = ['{:.2f}'.format(a) for a in np.insert(ss, 0, [0])[:lenxf:(lenxf // majorticks)].tolist()] plt.xticks(x[:lenxf:(lenxf // majorticks)], sl) if len(rtsub) >= 300 and minorticks >= 50: # Indicate the distribution of s via unlabeled minor ticks. plt.minorticks_on() ax.tick_params(which='minor', axis='x') ax.tick_params(which='minor', axis='y', left=False) ax.set_xticks(x[np.cumsum(histcounts(minorticks, ss[:int((len(x) - 1) * fraction)]))], minor=True) # Label the axes. plt.xlabel('$S_k$') plt.ylabel('$B_k$') ax2 = plt.twiny() plt.xlabel( '$k/n$ (together with minor ticks at equispaced values of $A_k$)') ax2.tick_params(which='minor', axis='x', top=True, direction='in', pad=-17) ax2.set_xticks(np.arange(0, 1 + 1 / majorticks, 1 / majorticks), minor=True) ks = ['{:.2f}'.format(a) for a in np.arange(0, 1 + 1 / majorticks, 1 / majorticks).tolist()] alist = (lenxf - 1) * np.arange(0, 1 + 1 / majorticks, 1 / majorticks) alist = alist.tolist() # Jitter minor ticks that overlap with major ticks lest Pyplot omit them. alabs = [] for a in alist: multiple = x[int(a)] * majorticks if abs(multiple - round(multiple)) > 1e-4: alabs.append(x[int(a)]) else: alabs.append(x[int(a)] * (1 - 1e-4)) plt.xticks(alabs, ks) ax2.xaxis.set_minor_formatter(FixedFormatter( [r'$A_k\!=\!{:.2f}$'.format(1 / majorticks)] + [r'${:.2f}$'.format(k / majorticks) for k in range(2, majorticks)])) # Title the plot. plt.title(title) # Clean up the whitespace in the plot. plt.tight_layout() # Save the plot. plt.savefig(filename, bbox_inches='tight') plt.close() # Calculate summary statistics. fft = (f - ft)[:int(len(f) * fraction)] kuiper = np.max(fft) - np.min(fft) kolmogorov_smirnov = np.max(np.abs(fft)) return kuiper, kolmogorov_smirnov, lenscale def equiscores(r, s, inds, nbins, filename='equiscore.pdf', weights=None, top=None, left=None, right=None): """ Reliability diagram with roughly equispaced average scores over bins Plots a reliability diagram with roughly equispaced average scores for the bins, for both the full population and the subpopulation specified by the indices inds. Parameters ---------- r : array_like random outcomes s : array_like scores (must be in non-decreasing order) inds : array_like indices of the subset within s that defines the subpopulation (must be unique and in strictly increasing order) nbins : int number of bins filename : string, optional name of the file in which to save the plot weights : array_like, optional weights of all observations (the default None results in equal weighting) top : float, optional top of the range of the vertical axis (the default None is adaptive) left : float, optional leftmost value of the horizontal axis (the default None is adaptive) right : float, optional rightmost value of the horizontal axis (the default None is adaptive) Returns ------- None """ def bintwo(nbins, a, b, q, qmax, w): # Determines the total weight of entries of q falling into each # of nbins equispaced bins, and calculates the weighted average per bin # of the arrays a and b, returning np.nan as the "average" # for any bin that is empty. j = 0 bina = np.zeros(nbins) binb = np.zeros(nbins) wbin = np.zeros(nbins) for k in range(len(q)): if q[k] > qmax * (j + 1) / nbins: j += 1 if j == nbins: break bina[j] += w[k] * a[k] binb[j] += w[k] * b[k] wbin[j] += w[k] # Normalize the sum for each bin to compute the arithmetic average. bina = np.divide(bina, wbin, where=wbin != 0) bina[np.where(wbin == 0)] = np.nan binb = np.divide(binb, wbin, where=wbin != 0) binb[np.where(wbin == 0)] = np.nan return wbin, bina, binb assert all(s[k] <= s[k + 1] for k in range(len(s) - 1)) assert all(inds[k] < inds[k + 1] for k in range(len(inds) - 1)) # Determine the weighting scheme. if weights is None: w = np.ones((len(s))) else: w = weights.copy() assert np.all(w > 0) w /= w.sum() ws = w[inds] ws /= ws.sum() # Create the figure. plt.figure() _, binr, binst = bintwo(nbins, r, s, s, s[inds[-1]], w) _, binrs, binss = bintwo(nbins, r[inds], s[inds], s[inds], s[inds[-1]], ws) plt.plot(binst, binr, '*:', color='gray') plt.plot(binss, binrs, '*:', color='black') xmin = min(binst[0], binss[0]) if left is None else left xmax = max(binst[-1], binss[-1]) if right is None else right plt.xlim((xmin, xmax)) plt.ylim(bottom=0) plt.ylim(top=top) plt.xlabel('weighted average of $S_k$ for $k$ in the bin') plt.ylabel('weighted average of $R_k$ for $k$ in the bin') plt.title('reliability diagram') plt.tight_layout() plt.savefig(filename, bbox_inches='tight') plt.close() def equierrs(r, s, inds, nbins, filename='equibins.pdf', weights=None, top=None, left=None, right=None): """ Reliability diagram with similar ratio L2-norm / L1-norm of weights by bin Plots a reliability diagram with the ratio of the L2 norm of the weights to the L1 norm of the weights being roughly the same for every bin. The L2 norm is the square root of the sum of the squares, while the L1 norm is the sum of the absolute values. The plot includes a graph both for the full population and for the subpopulation specified by the indices inds. Parameters ---------- r : array_like random outcomes s : array_like scores (must be in non-decreasing order) inds : array_like indices of the subset within s that defines the subpopulation (must be unique and in strictly increasing order) nbins : int rough number of bins to construct filename : string, optional name of the file in which to save the plot weights : array_like, optional weights of all observations (the default None results in equal weighting) top : float, optional top of the range of the vertical axis (the default None is adaptive) left : float, optional leftmost value of the horizontal axis (the default None is adaptive) right : float, optional rightmost value of the horizontal axis (the default None is adaptive) Returns ------- int number of bins constructed for the subpopulation int number of bins constructed for the full population """ def inbintwo(a, b, inbin, w): # Determines the total weight falling into the bins given by inbin, # and calculates the weighted average per bin of the arrays a and b, # returning np.nan as the "average" for any bin that is empty. wbin = [w[inbin[k]:inbin[k + 1]].sum() for k in range(len(inbin) - 1)] bina = [(w[inbin[k]:inbin[k + 1]] * a[inbin[k]:inbin[k + 1]]).sum() for k in range(len(inbin) - 1)] binb = [(w[inbin[k]:inbin[k + 1]] * b[inbin[k]:inbin[k + 1]]).sum() for k in range(len(inbin) - 1)] # Normalize the sum for each bin to compute the weighted average. bina = np.divide(bina, wbin, where=wbin != 0) bina[np.where(wbin == 0)] = np.nan binb = np.divide(binb, wbin, where=wbin != 0) binb[np.where(wbin == 0)] = np.nan return wbin, bina, binb def binbounds(nbins, w): # Partitions w into around nbins bins, each with roughly equal ratio # of the L2 norm of w in the bin to the L1 norm of w in the bin, # returning the indices defining the bins in the list inbin. proxy = len(w) // nbins v = w[np.sort(np.random.permutation(len(w))[:proxy])] # t is a heuristic threshold. t = np.square(v).sum() / v.sum()**2 inbin = [] k = 0 while k < len(w) - 1: inbin.append(k) k += 1 s = w[k] ss = w[k]**2 while ss / s**2 > t and k < len(w) - 1: k += 1 s += w[k] ss += w[k]**2 if len(w) - inbin[-1] < (inbin[-1] - inbin[-2]) / 2: inbin[-1] = len(w) else: inbin.append(len(w)) return inbin assert all(s[k] <= s[k + 1] for k in range(len(s) - 1)) assert all(inds[k] < inds[k + 1] for k in range(len(inds) - 1)) # Determine the weighting scheme. if weights is None: w = np.ones((len(s))) else: w = weights.copy() assert np.all(w > 0) w /= w.sum() inbin = binbounds(nbins, w) ws = w[inds] ws /= ws.sum() inbins = binbounds(nbins, ws) # Create the figure. plt.figure() _, binr, binst = inbintwo(r, s, inbin, w) _, binrs, binss = inbintwo(r[inds], s[inds], inbins, ws) plt.plot(binst, binr, '*:', color='gray') plt.plot(binss, binrs, '*:', color='black') xmin = min(binst[0], binss[0]) if left is None else left xmax = max(binst[-1], binss[-1]) if right is None else right plt.xlim((xmin, xmax)) plt.ylim(bottom=0) plt.ylim(top=top) plt.xlabel('weighted average of $S_k$ for $k$ in the bin') plt.ylabel('weighted average of $R_k$ for $k$ in the bin') title = r'reliability diagram' title += r' ($\Vert W \Vert_2 / \Vert W \Vert_1$ is similar for every bin)' plt.title(title) plt.tight_layout() plt.savefig(filename, bbox_inches='tight') plt.close() return len(inbins) - 1, len(inbin) - 1 def exactplot(r, s, inds, filename='exact.pdf', title='exact expectations', top=None, left=None, right=None): """ Reliability diagram with exact values plotted Plots a reliability diagram at full resolution with fractional numbers, for both the full population and the subpop. specified by indices inds. The entries of r should be the expected values of outcomes, even if the outcomes are integer-valued counts or just 0s and 1s. Parameters ---------- r : array_like expected value of outcomes s : array_like scores (must be in non-decreasing order) inds : array_like indices of the subset within s that defines the subpopulation (must be unique and in strictly increasing order) filename : string, optional name of the file in which to save the plot title : string, optional title of the plot top : float, optional top of the range of the vertical axis (the default None is adaptive) left : float, optional leftmost value of the horizontal axis (the default None is adaptive) right : float, optional rightmost value of the horizontal axis (the default None is adaptive) Returns ------- None """ assert all(s[k] <= s[k + 1] for k in range(len(s) - 1)) assert all(inds[k] < inds[k + 1] for k in range(len(inds) - 1)) plt.figure() plt.plot(s, r, '*', color='gray') rs = r[inds] ss = s[inds] plt.plot(ss, rs, '*', color='black') plt.xlim((left, right)) plt.ylim(bottom=0) plt.ylim(top=top) plt.xlabel('score $S_k$') plt.ylabel('expected value ($P_k$) of outcome $R_k$') plt.title(title) plt.tight_layout() plt.savefig(filename, bbox_inches='tight') plt.close() if __name__ == '__main__': # # Generate directories with plots as specified via the code below, # with each directory named m_len(inds)_nbins_iex-dithered or # m_len(inds)_nbins_iex-averaged (where m, inds, nbins, and iex # are defined in the code below, and "dithered" uses scores dithered # to become distinct, while "averaged" uses responses averaged together # at the same score). # # Set parameters. # minorticks is the number of minor ticks on the lower axis. minorticks = 100 # majorticks is the number of major ticks on the lower axis. majorticks = 10 # m is the number of members from the full population. m = 50000 # n determines the number of observations for the subpopulation. n = 2500 # Store processes for converting from pdf to jpeg in procs. procs = [] # Consider 4 examples. for iex in range(4): for dither in [True, False]: # nbins is the number of bins for the reliability diagrams. for nbins in [10, 50]: # nbins must divide n evenly. assert n % nbins == 0 if iex == 0: # Define the indices of the subset for the subpopulation. inds = np.arange(0, m, m // n) + m // n // 2 inds1 = np.arange(0, m // 4, m // n // 4) + m // 2 - m // 8 inds2 = np.arange(0, m // 2, m // n // 2) + m // 2 - m // 4 inds3 = np.arange(0, m, m // n) inds = np.concatenate((inds1, inds1 + 1, inds2, inds3)) # Indices must be sorted and unique. inds = np.unique(inds) inds = inds[0:(m // (m // len(inds)))] # Construct scores. sl = np.arange(0, 1, 4 / m) + 2 / m s = np.square(sl) s = np.concatenate([s] * 4) if dither: ss = s.shape s *= np.ones(ss) + np.random.normal(size=ss) * 1e-8 # The scores must be in non-decreasing order. s = np.sort(s) # Construct perturbations to the scores for sampling rates. d = .25 tl = -np.arange(-d, d, 2 * d / m) - d / m t = d - 1.1 * np.square(np.square(tl)) / d**3 e = .7 ul = -np.arange(-e, e, 2 * e / m) - e / m u = e - np.abs(ul) ins = np.arange(m // 2 - m // 50, m // 2 + m // 50) u[ins] = t[ins] u2 = 2 * t - u t += np.sin(np.arange((m))) * (u - t) # Construct the exact sampling probabilities. exact = s + t exact[inds] = s[inds] + u[inds] exact[inds + 1] = s[inds] + u2[inds] # Construct weights. weights = 4 - np.cos(9 * np.arange(m) / m) if iex == 1: # Define the indices of the subset for the subpopulation. np.random.seed(987654321) inds = np.sort(np.random.permutation((m))[:n]) # Construct scores. s = np.arange(0, 1, 2 / m) + 1 / m s = np.sqrt(s) s = np.concatenate((s, s)) if dither: ss = s.shape s *= np.ones(ss) + np.random.normal(size=ss) * 1e-8 # The scores must be in non-decreasing order. s = np.sort(s) # Construct perturbations to the scores for sampling rates. d = math.sqrt(1 / 2) tl = np.arange(-d, d, 2 * d / m) - d / m t = (1 + np.sin(np.arange((m)))) / 2 t *= np.square(tl) - d**2 u = np.square(tl) - d**2 u *= .75 * np.round(1 + np.sin(10 * np.arange((m)) / m)) u /= 2 # Construct the exact sampling probabilities. exact = s + t exact[inds] = s[inds] + u[inds] # Construct weights. weights = 4 - np.cos(9 * np.arange(m) / m) if iex == 2: # Define the indices of the subset for the subpopulation. np.random.seed(987654321) inds = np.arange(0, m ** (3 / 4), 1) inds = np.unique(np.round(np.power(inds, 4 / 3))) inds = inds.astype(int) inds = inds[0:(50 * (len(inds) // 50))] # Construct scores. s = np.arange(0, 1, 10 / m) + 5 / m s = np.concatenate([s] * 10) if dither: ss = s.shape s *= np.ones(ss) + np.random.normal(size=ss) * 1e-8 # The scores must be in non-decreasing order. s = np.sort(s) # Construct perturbations to the scores for sampling rates. tl = np.arange(0, 1, 1 / m) + 1 / (2 * m) t = np.power(tl, 1 / 4) - tl t *= (1 + np.sin(np.arange((m)))) / 2 u = np.power(tl, 1 / 4) - tl u *= .5 * (1 + np.sin( 50 * np.power(np.arange(0, m**4, m**3), 1 / 4) / m)) # Construct the exact sampling probabilities. exact = s + t exact[inds] = s[inds] + u[inds] # Construct weights. weights = 4 - np.cos(9 * np.arange(m) / m) if iex == 3: # Define the indices of the subset for the subpopulation. np.random.seed(987654321) inds = np.sort(np.random.permutation((m))[:n]) # Construct scores. s = np.arange(0, 1, 4 / m) + 2 / m s = np.concatenate([s] * 4) if dither: ss = s.shape s *= np.ones(ss) + np.random.normal(size=ss) * 1e-8 # The scores must be in non-decreasing order. s = np.sort(s) # Construct the exact sampling probabilities. exact = np.sin(np.arange(m)) exact *= np.sin(50 * np.arange(-3 * m / 4, m / 4) / m) exact = np.square(exact) exact /= 5 exact[inds] = 0 # Construct weights. weights = np.ones((m)) ind = 3 * m // 4 - 1 # Identify an index near the middle that belongs # to the subpop. for which the two adjacent indices do not. while( np.any(inds == (ind - 1)) or not np.any(inds == ind) or np.any(inds == (ind + 1))): ind += 1 weights[ind] = n / 50 weights[ind - 1] = m / 500 weights[ind + 1] = m / 500 # Alter the exact sampling probabilities for the 3 indices # selected in the preceding "while" loop. exact[ind] = 1 exact[ind - 1] = 1 exact[ind + 1] = 0 # Set a unique directory for each collection of experiments # (creating the directory if necessary). dir = 'weighted' try: os.mkdir(dir) except FileExistsError: pass dir = 'weighted/' + str(m) + '_' + str(len(inds)) dir = dir + '_' + str(nbins) dir = dir + '_' + str(iex) dir += '-' if dither: dir += 'dithered' else: dir += 'averaged' try: os.mkdir(dir) except FileExistsError: pass dir = dir + '/' print(f'./{dir} is under construction....') # Generate a sample of classifications into two classes, # correct (class 1) and incorrect (class 0), # avoiding numpy's random number generators # that are based on random bits -- # they yield strange results for many seeds. random.seed(987654321) uniform = np.asarray([random.random() for _ in range(m)]) r = (uniform <= exact).astype(float) # Generate five plots and a text file reporting metrics. filename = dir + 'cumulative.pdf' kuiper, kolmogorov_smirnov, lenscale = cumulative( r, s, inds, majorticks, minorticks, True, filename, weights=weights) filename = dir + 'metrics.txt' with open(filename, 'w') as f: f.write('n:\n') f.write(f'{len(inds)}\n') f.write('number of unique scores in the subset:\n') f.write(f'{len(np.unique(s[inds]))}\n') f.write('lenscale:\n') f.write(f'{lenscale}\n') f.write('Kuiper:\n') f.write(f'{kuiper:.4}\n') f.write('Kolmogorov-Smirnov:\n') f.write(f'{kolmogorov_smirnov:.4}\n') f.write('Kuiper / lenscale:\n') f.write(f'{(kuiper / lenscale):.4}\n') f.write('Kolmogorov-Smirnov / lenscale:\n') f.write(f'{(kolmogorov_smirnov / lenscale):.4}\n') filename = dir + 'cumulative_exact.pdf' _, _, _ = cumulative( exact, s, inds, majorticks, minorticks, True, filename, title='exact expectations', weights=weights) filename = dir + 'equiscores.pdf' equiscores(r, s, inds, nbins, filename, weights, top=1, left=0, right=1) filename = dir + 'equierrs.pdf' equierrs(r, s, inds, nbins + 3, filename, weights, top=1, left=0, right=1) filepdf = dir + 'exact.pdf' filejpg = dir + 'exact.jpg' exactplot(exact, s, inds, filepdf, top=1, left=0, right=1) args = ['convert', '-density', '1200', filepdf, filejpg] procs.append(subprocess.Popen(args)) print('waiting for conversion from pdf to jpg to finish....') for iproc, proc in enumerate(procs): proc.wait() print(f'{iproc + 1} of {len(procs)} conversions are done....')
cdeets-main
codes/subpop_weighted.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved #Common imports import sys import os import argparse import random import copy import torch import torch.utils.data as data_utils from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable import numpy as np import matplotlib.pyplot as plt from scipy import stats from sklearn.decomposition import FastICA from algorithms.base_auto_encoder import AE from algorithms.poly_auto_encoder import AE_Poly from algorithms.ioss_auto_encoder import AE_IOSS from algorithms.image_auto_encoder import AE_Image from utils.metrics import * from utils.helper import * # Input Parsing parser = argparse.ArgumentParser() parser.add_argument('--method_type', type=str, default='ae_poly', help= 'ae, ae_poly') parser.add_argument('--latent_case', type=str, default='uniform', help='laplace; uniform') parser.add_argument('--data_dim', type=int, default= 200, help='') parser.add_argument('--latent_dim', type=int, default= 6, help='') parser.add_argument('--poly_degree', type=int, default= 2, help='') parser.add_argument('--batch_size', type=int, default= 16, help='') parser.add_argument('--lr', type=float, default= 1e-3, help='') parser.add_argument('--weight_decay', type=float, default= 5e-4, help='') parser.add_argument('--num_seeds', type=int, default=5, help='') parser.add_argument('--intervention_case', type= int, default= 0, help= '') parser.add_argument('--eval_ioss_transformation', type=int, default=0, help='Evaluate the IOSS transformation from the base model representation') parser.add_argument('--eval_intervene_transformation', type=int, default=0, help='Evaluate the Intervention transformation from the base model representation') parser.add_argument('--eval_dgp', type=int, default= 0, help= 'Evaluate the function from z -> x and x -> z in the true DGP') parser.add_argument('--wandb_log', type=int, default=0, help='') parser.add_argument('--cuda_device', type=int, default=-1, help='Select the cuda device by id among the avaliable devices' ) args = parser.parse_args() method_type= args.method_type latent_case= args.latent_case data_dim= args.data_dim latent_dim= args.latent_dim poly_degree= args.poly_degree batch_size= args.batch_size lr= args.lr weight_decay= args.weight_decay num_seeds= args.num_seeds intervention_case= args.intervention_case eval_dgp= args.eval_dgp eval_ioss_transformation= args.eval_ioss_transformation eval_intervene_transformation= args.eval_intervene_transformation wandb_log= args.wandb_log cuda_device= args.cuda_device if 'balls' in latent_case: save_dir= latent_case + '/' else: save_dir= 'polynomial' + '_latent_' + latent_case + '_poly_degree_' + str(poly_degree) + '_data_dim_' + str(data_dim) + '_latent_dim_' + str(latent_dim) + '/' args.save_dir= save_dir #GPU #GPU if cuda_device == -1: device= "cpu" else: device= torch.device("cuda:" + str(cuda_device)) if device: kwargs = {'num_workers': 0, 'pin_memory': False} else: kwargs= {} res={} for seed in range(num_seeds): #Seed values random.seed(seed*10) np.random.seed(seed*10) torch.manual_seed(seed*10) # Load Dataset train_dataset, val_dataset, test_dataset= sample_base_data_loaders(save_dir, batch_size, seed= seed, observation_case=1, intervention_case= intervention_case, latent_case= latent_case, kwargs=kwargs) #Load Algorithm if method_type == 'ae': method= AE(args, train_dataset, val_dataset, test_dataset, seed=seed) elif method_type == 'ae_poly': method= AE_Poly(args, train_dataset, val_dataset, test_dataset, seed=seed) elif method_type == 'ae_image': method= AE_Image(args, train_dataset, val_dataset, test_dataset, seed=seed, device= device) # Evaluate the models learnt on true latent variables if eval_dgp: # X->Z prediction R2 x, z= get_predictions_check(train_dataset, test_dataset) rmse, r2= get_indirect_prediction_error(x, z) key= 'oracle_pred_rmse' if key not in res.keys(): res[key]= [] res[key].append(rmse) key= 'oracle_pred_r2' if key not in res.keys(): res[key]= [] res[key].append(r2) # Z->X prediction R2 x, z= get_predictions_check(train_dataset, test_dataset) rmse, r2= get_indirect_prediction_error(z, x) key= 'debug_pred_rmse' if key not in res.keys(): res[key]= [] res[key].append(rmse) key= 'debug_pred_r2' if key not in res.keys(): res[key]= [] res[key].append(r2) # Evaluate the base model method.load_model() # method.load_intermediate_model(epoch=10) #Latent Prediction Error rmse,r2= method.eval_identification() key= 'latent_pred_rmse' if key not in res.keys(): res[key]=[] res[key].append(rmse) key= 'latent_pred_r2' if key not in res.keys(): res[key]=[] res[key].append(r2) # Evaluating MCC on the observational data with representations from Step 1 #Sample data from only the observational distribution train_dataset, val_dataset, test_dataset= sample_base_data_loaders(save_dir, batch_size, seed= seed, observation_case=1, intervention_case= 0, latent_case= latent_case, kwargs=kwargs) #Obtain Predictions and Reconstruction Loss logs= get_predictions(method.encoder, method.decoder, train_dataset, val_dataset, test_dataset, device=method.device, plot= False) #Prediction RMSE key= 'recon_rmse' if key not in res.keys(): res[key]= [] res[key].append(logs['recon_loss']['val']) print('RMSE Val: ', logs['recon_loss']['val']) #MCC if 'balls' not in latent_case: mcc= get_cross_correlation(copy.deepcopy(logs['pred_z']), copy.deepcopy(logs['true_z'])) key= 'mcc' if key not in res.keys(): res[key]= [] for item in mcc: res[key].append(item) if eval_intervene_transformation: #Sample only from interventional distribution train_dataset, val_dataset, test_dataset= sample_base_data_loaders(save_dir, batch_size, seed= seed, latent_case= latent_case, observation_case=0, intervention_case= 1, kwargs=kwargs) #Obtain Predictions and Reconstruction Loss logs= get_predictions(method.encoder, method.decoder, train_dataset, val_dataset, test_dataset, device=method.device, plot= False) # Intervention Specific Metric if 'balls' not in latent_case: reg_models= intervene_metric(copy.deepcopy(logs['pred_z']), copy.deepcopy(logs['true_z']), model_train=1) else: reg_models= intervene_metric_image(copy.deepcopy(logs['pred_z']), copy.deepcopy(logs['true_z']), copy.deepcopy(logs['true_y']), model_train=1, model= 'mlp') #Sample data from only the observational distribution train_dataset, val_dataset, test_dataset= sample_base_data_loaders(save_dir, batch_size, seed= seed, latent_case= latent_case, observation_case=1, intervention_case= 0, kwargs=kwargs) #Obtain Predictions and Reconstruction Loss logs= get_predictions(method.encoder, method.decoder, train_dataset, val_dataset, test_dataset, device=method.device, plot= False) # Intervention Specific Metric if 'balls' not in latent_case: logs['pred_z']= intervene_metric(copy.deepcopy(logs['pred_z']), copy.deepcopy(logs['true_z']), model_train=0, list_models=reg_models) else: logs['pred_z'], logs['true_z']= intervene_metric_image(copy.deepcopy(logs['pred_z']), copy.deepcopy(logs['true_z']), copy.deepcopy(logs['true_y']), model_train=0, list_models= reg_models, model= 'mlp') #Sample dataloaders for finetuning the representations if eval_ioss_transformation: #Sample data from only the observational distribution train_dataset, val_dataset, test_dataset= sample_base_data_loaders(save_dir, batch_size, seed= seed, latent_case= latent_case, observation_case=1, intervention_case= 0, kwargs=kwargs) #Obtain Predictions and Reconstruction Loss logs= get_predictions(method.encoder, method.decoder, train_dataset, val_dataset, test_dataset, device=method.device, plot= False) #Train with IOSS Loss train_dataset, val_dataset, test_dataset= sample_finetune_data_loaders(logs['pred_z'], logs['true_z'], save_dir, batch_size, kwargs= kwargs) ioss_method= AE_IOSS(args, train_dataset, val_dataset, test_dataset, seed=seed, device=device, base_algo= method_type) ioss_method.load_model() #Obtain Predictions and Reconstruction Loss logs= get_predictions(ioss_method.encoder, ioss_method.decoder, ioss_method.train_dataset, ioss_method.val_dataset, ioss_method.test_dataset, device=ioss_method.device, plot= False) #MCC if eval_ioss_transformation or eval_intervene_transformation: mcc= get_cross_correlation(logs['pred_z'], logs['true_z']) print('MCC: ', mcc) key= 'mcc_tune' if key not in res.keys(): res[key]= [] for item in mcc: res[key].append(item) print('Final Results') print(res.keys()) for key in res.keys(): res[key]= np.array(res[key]) print('Metric: ', key, np.mean(res[key]), np.std(res[key])/np.sqrt(num_seeds))
CausalRepID-main
test.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved #Common imports import sys import os import argparse import random import copy import torch from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable import numpy as np import matplotlib.pyplot as plt from scipy import stats from sklearn.decomposition import FastICA from algorithms.base_auto_encoder import AE from algorithms.poly_auto_encoder import AE_Poly from algorithms.ioss_auto_encoder import AE_IOSS from algorithms.image_auto_encoder import AE_Image from utils.metrics import * from utils.helper import * # Input Parsing parser = argparse.ArgumentParser() parser.add_argument('--method_type', type=str, default='ae_poly', help= 'ae; ae_poly; ae_image') parser.add_argument('--latent_case', type=str, default='uniform', help='laplace; uniform') parser.add_argument('--data_dim', type=int, default= 200, help='') parser.add_argument('--latent_dim', type=int, default= 10, help='') parser.add_argument('--poly_degree', type=int, default= 2, help='') parser.add_argument('--batch_size', type=int, default= 16, help='') parser.add_argument('--lr', type=float, default= 1e-3, help='') parser.add_argument('--weight_decay', type=float, default= 5e-4, help='') parser.add_argument('--num_epochs', type=int, default= 200, help='') parser.add_argument('--seed', type=int, default=0, help='') parser.add_argument('--intervention_case', type= int, default= 0, help= '') parser.add_argument('--train_base_model', type=int, default=1, help='Train the base auto encoder') parser.add_argument('--train_ioss_transformation', type=int, default=0, help='Learn the IOSS transformation from the base model representations') parser.add_argument('--wandb_log', type=int, default=0, help='') parser.add_argument('--cuda_device', type=int, default=-1, help='Select the cuda device by id among the avaliable devices' ) args = parser.parse_args() method_type= args.method_type latent_case= args.latent_case data_dim= args.data_dim latent_dim= args.latent_dim poly_degree= args.poly_degree batch_size= args.batch_size lr= args.lr weight_decay= args.weight_decay num_epochs= args.num_epochs seed= args.seed intervention_case= args.intervention_case train_base_model= args.train_base_model train_ioss_transformation= args.train_ioss_transformation wandb_log= args.wandb_log cuda_device= args.cuda_device if 'balls' in latent_case: save_dir= latent_case + '/' else: save_dir= 'polynomial' + '_latent_' + latent_case + '_poly_degree_' + str(poly_degree) + '_data_dim_' + str(data_dim) + '_latent_dim_' + str(latent_dim) + '/' args.save_dir= save_dir #GPU if cuda_device == -1: device= torch.device("cpu") else: device= torch.device("cuda:" + str(cuda_device)) if device: kwargs = {'num_workers': 0, 'pin_memory': False} else: kwargs= {} #Seed values random.seed(seed*10) np.random.seed(seed*10) torch.manual_seed(seed*10) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed*10) # Load Dataset train_dataset, val_dataset, test_dataset= sample_base_data_loaders(save_dir, batch_size, observation_case=1, intervention_case= intervention_case, latent_case= latent_case, seed= seed, kwargs=kwargs) #Load Algorithm if method_type == 'ae': method= AE(args, train_dataset, val_dataset, test_dataset, seed=seed, device= device) elif method_type == 'ae_poly': method= AE_Poly(args, train_dataset, val_dataset, test_dataset, seed=seed, device= device) elif method_type == 'ae_image': method= AE_Image(args, train_dataset, val_dataset, test_dataset, seed=seed, device= device) else: print('Error: Incorrect method type') sys.exit(-1) # Training if train_base_model: method.train() #Train with IOSS Loss if train_ioss_transformation: method.load_model() #Sample data from only the observational distribution train_dataset, val_dataset, test_dataset= sample_base_data_loaders(save_dir, batch_size, seed= seed, observation_case=1, intervention_case= 0, kwargs=kwargs) #Obtain Predictions and Reconstruction Loss res= get_predictions(method.encoder, method.decoder, train_dataset, val_dataset, test_dataset, device=method.device) #Sample dataloaders for finetuning the representations train_dataset, val_dataset, test_dataset= sample_finetune_data_loaders(res['pred_z'], res['true_z'], save_dir, batch_size, kwargs= kwargs) ioss_method= AE_IOSS(args, train_dataset, val_dataset, test_dataset, seed=seed, device=device, base_algo= method_type) ioss_method.train()
CausalRepID-main
train.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import math import torch import torch.utils.data as data_utils from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable from sklearn.decomposition import FastICA from sklearn.decomposition import PCA from utils.metrics import * from models.encoder import Encoder from models.poly_decoder import PolyDecoder #Base Class from algorithms.base_auto_encoder import AE path= os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(path) from utils.helper import ValidationHelper from utils.metrics import * import wandb class AE_Poly(AE): def __init__(self, args, train_dataset, val_dataset, test_dataset, seed=0, device= None): super().__init__(args, train_dataset, val_dataset, test_dataset, seed, device) self.encoder= Encoder(self.args.data_dim, self.args.latent_dim).to(self.device) self.decoder= PolyDecoder(self.args.data_dim, self.args.latent_dim, self.args.poly_degree, self.device).to(self.device) self.opt, self.scheduler= self.get_optimizer() if self.args.intervention_case: self.res_dir= 'results/ae-poly/intervention/' + str(self.args.save_dir) + 'seed_' + str(seed) + '/' else: self.res_dir= 'results/ae-poly/observation/' + str(self.args.save_dir) + 'seed_' + str(seed) + '/' self.save_path= self.res_dir if self.args.wandb_log: wandb.init(project="polynomial-identification", reinit=True) wandb.run.name= 'ae-poly/' + self.args.save_dir + 'seed_' + str(seed) + '/'
CausalRepID-main
algorithms/poly_auto_encoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import math import torch import torch.utils.data as data_utils from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable from sklearn.decomposition import FastICA from sklearn.decomposition import PCA from utils.metrics import * from models.encoder import Encoder from models.decoder import Decoder path= os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(path) from utils.helper import ValidationHelper from utils.metrics import * import wandb wandb.init(project="polynomial-identification", reinit=True) class AE(): def __init__(self, args, train_dataset, val_dataset, test_dataset, seed=0, device= None): self.args= args self.seed= seed self.device= device self.train_dataset= train_dataset self.val_dataset= val_dataset self.test_dataset= test_dataset self.encoder= Encoder(self.args.data_dim, self.args.latent_dim).to(self.device) self.decoder= Decoder(self.args.data_dim, self.args.latent_dim).to(self.device) self.opt, self.scheduler= self.get_optimizer() self.validation_helper= ValidationHelper() if self.args.intervention_case: self.res_dir= 'results/ae/intervention/' + str(self.args.save_dir) + 'seed_' + str(seed) + '/' else: self.res_dir= 'results/ae/observation/' + str(self.args.save_dir) + 'seed_' + str(seed) + '/' self.save_path= self.res_dir if self.args.wandb_log: wandb.init(project="polynomial-identification", reinit=True) wandb.run.name= 'ae/' + self.args.save_dir + 'seed_' + str(seed) + '/' def get_optimizer(self): opt= optim.Adam([ {'params': filter(lambda p: p.requires_grad, list(self.encoder.parameters()) + list(self.decoder.parameters()) )}, ], lr= self.args.lr, weight_decay= self.args.weight_decay ) scheduler = optim.lr_scheduler.StepLR(opt, step_size=500, gamma=0.5) return opt, scheduler def save_model(self): if not os.path.exists(self.res_dir): os.makedirs(self.res_dir) torch.save(self.encoder.state_dict(), self.save_path + 'lr_' + str(self.args.lr) + '_weight_decay_' + str(self.args.weight_decay) + '_batch_size_' + str(self.args.batch_size) + '_encoder.pth') torch.save(self.decoder.state_dict(), self.save_path + 'lr_' + str(self.args.lr) + '_weight_decay_' + str(self.args.weight_decay) + '_batch_size_' + str(self.args.batch_size) + '_decoder.pth') return def load_model(self): self.encoder.load_state_dict(torch.load(self.save_path + 'lr_' + str(self.args.lr) + '_weight_decay_' + str(self.args.weight_decay) + '_batch_size_' + str(self.args.batch_size) + '_encoder.pth', map_location=torch.device('cpu'))) self.encoder.eval() self.decoder.load_state_dict(torch.load(self.save_path + 'lr_' + str(self.args.lr) + '_weight_decay_' + str(self.args.weight_decay) + '_batch_size_' + str(self.args.batch_size) + '_decoder.pth', map_location=torch.device('cpu'))) self.decoder.eval() return def validation(self): self.encoder.eval() self.decoder.eval() val_loss=0.0 count=0 for batch_idx, (x, _, _) in enumerate(self.val_dataset): with torch.no_grad(): x= x.to(self.device) z_pred= self.encoder(x) out= self.decoder(z_pred) loss= torch.mean(((out-x)**2)) val_loss+= loss.item() count+=1 if self.args.wandb_log: wandb.log({'val_loss': val_loss/count}) return val_loss/count def train(self): for epoch in range(self.args.num_epochs): train_loss=0.0 count=0 #LR Scheduler self.scheduler.step() print(self.scheduler.get_last_lr()) #Training self.encoder.train() self.decoder.train() #Compute identification metrics if epoch % 10 == 0: self.eval_identification(epoch= epoch) if 'balls' in self.args.latent_case and ( epoch==0 or epoch==10 ): self.save_intermediate_model(epoch= epoch) for batch_idx, (x, _, _) in enumerate(self.train_dataset): self.opt.zero_grad() #Forward Pass x= x.to(self.device) z_pred= self.encoder(x) x_pred= self.decoder(z_pred) #Compute Reconstruction Loss loss= self.compute_loss(z_pred, x_pred, x) #Backward Pass loss.backward() # grad_norm= 0.0 # for p in self.coff_matrix.parameters(): # param_norm = p.grad.detach().data.norm(2) # grad_norm += param_norm.item() ** 2 # grad_norm = grad_norm ** 0.5 # wandb.log({'grad_norm': grad_norm}) self.opt.step() train_loss+= loss.item() count+=1 val_score= self.validation() print('\n') print('Done Training for Epoch: ', epoch) print('Training Loss: ', train_loss/count) print('Validation Loss: ', val_score) print('Best Epoch: ', self.validation_helper.best_epoch) if self.args.wandb_log: wandb.log({'train_loss': train_loss/count}) if self.validation_helper.save_model(val_score, epoch): print('Saving model') self.save_model() elif self.validation_helper.early_stop(val_score): print('Early Stopping') break return def compute_loss(self, z_pred, x_pred, x): loss= torch.mean(((x-x_pred)**2)) return loss def eval_identification(self, epoch= -1): self.encoder.eval() self.decoder.eval() save_dir= 'results/plots/'+ self.args.save_dir + 'epoch_' + str(epoch) + '/' if not os.path.exists(save_dir): os.makedirs(save_dir) #Obtain Predictions and Reconstruction Loss if 'balls' in self.args.latent_case: plot_case=True else: plot_case=False res= get_predictions(self.encoder, self.decoder, self.train_dataset, self.val_dataset, self.test_dataset, device= self.device, save_dir= save_dir, plot=plot_case) true_z= res['true_z'] pred_z= res['pred_z'] recon_err= res['recon_loss'] print(true_z['tr'].shape, pred_z['tr'].shape) #Latent Prediction Error rmse, r2= get_indirect_prediction_error(pred_z, true_z) print('latent prediction r2: ', r2) if 'balls' in self.args.latent_case: _, r2_mlp= get_indirect_prediction_error(pred_z, true_z, model= 'mlp') print('latent prediction r2 MLP: ', r2_mlp) else: r2_mlp= 0 # MCC Score if 'balls' not in self.args.latent_case: mcc= get_cross_correlation(pred_z, true_z) print('MCC: ', mcc) else: mcc=0 if self.args.wandb_log: wandb.log({'test_loss': recon_err['te']}) wandb.log({'latent_pred_rmse': rmse}) wandb.log({'latent_pred_r2': r2}) # wandb.log({'max/min singular values': np.max(sig_values)/np.min(sig_values)}) wandb.log({'mcc': mcc}) wandb.log({'latent_pred_r2_mlp': r2_mlp}) # #DCI # imp_matrix= compute_importance_matrix(pred_z['te'], true_z['te'], case='disentanglement') # score= disentanglement(imp_matrix) # wandb.log({'dci-disentanglement': score}) # imp_matrix= compute_importance_matrix(pred_z['te'], true_z['te'], case='completeness') # score= completeness(imp_matrix) # wandb.log({'dci-completeness': score}) # #MCC # mcc= get_cross_correlation(pred_z, true_z) # wandb.log({'mcc': mcc}) return rmse, r2 def get_final_layer_weights(self): self.load_model() for p in self.model.fc_net.parameters(): print(p.data)
CausalRepID-main
algorithms/base_auto_encoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import math import torch import torch.utils.data as data_utils from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable from sklearn.decomposition import FastICA from sklearn.decomposition import PCA from utils.metrics import * from models.image_encoder import ImageEncoder as Encoder from models.image_decoder import ImageDecoder as Decoder # from models.image_resnet_decoder import ImageDecoder as Decoder #Base Class from algorithms.base_auto_encoder import AE path= os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(path) from utils.helper import ValidationHelper from utils.metrics import * import wandb class AE_Image(AE): def __init__(self, args, train_dataset, val_dataset, test_dataset, seed=0, device= None): super().__init__(args, train_dataset, val_dataset, test_dataset, seed, device) self.encoder= Encoder(self.args.latent_dim).to(self.device) self.decoder= Decoder(self.args.latent_dim).to(self.device) self.opt, self.scheduler= self.get_optimizer() self.validation_helper= ValidationHelper(patience=100) if self.args.intervention_case: self.res_dir= 'results/ae-image/intervention/' + str(self.args.save_dir) + 'seed_' + str(seed) + '/' else: self.res_dir= 'results/ae-image/observation/' + str(self.args.save_dir) + 'seed_' + str(seed) + '/' self.save_path= self.res_dir if self.args.wandb_log: wandb.init(project="image-dataset-identification", reinit=True) wandb.run.name= 'ae-image/' + self.args.save_dir + 'seed_' + str(seed) + '/' def save_intermediate_model(self, epoch= -1): if not os.path.exists(self.res_dir): os.makedirs(self.res_dir) torch.save(self.encoder.state_dict(), self.save_path + 'lr_' + str(self.args.lr) + '_weight_decay_' + str(self.args.weight_decay) + '_batch_size_' + str(self.args.batch_size) + '_epoch_' + str(epoch) + '_encoder.pth') torch.save(self.decoder.state_dict(), self.save_path + 'lr_' + str(self.args.lr) + '_weight_decay_' + str(self.args.weight_decay) + '_batch_size_' + str(self.args.batch_size) + '_epoch_' + str(epoch) + '_decoder.pth') return def load_intermediate_model(self, epoch): self.encoder.load_state_dict(torch.load(self.save_path + 'lr_' + str(self.args.lr) + '_weight_decay_' + str(self.args.weight_decay) + '_batch_size_' + str(self.args.batch_size) + '_epoch_' + str(epoch) + '_encoder.pth')) self.encoder.eval() self.decoder.load_state_dict(torch.load(self.save_path + 'lr_' + str(self.args.lr) + '_weight_decay_' + str(self.args.weight_decay) + '_batch_size_' + str(self.args.batch_size) + '_epoch_' + str(epoch) + '_decoder.pth')) self.decoder.eval() return
CausalRepID-main
algorithms/image_auto_encoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import math import torch import torch.utils.data as data_utils from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable from sklearn.decomposition import FastICA from sklearn.decomposition import PCA from utils.metrics import * from models.linear_auto_encoder import LinearAutoEncoder #Base Class from algorithms.base_auto_encoder import AE path= os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(path) from utils.helper import ValidationHelper from utils.metrics import * def IOSS(mu, n_draws=10000, robust_k_prop = 0.01, device= None): stdmu = (mu - torch.min(mu,dim=0)[0])/ (torch.max(mu,dim=0)[0]-torch.min(mu,dim=0)[0]) K = np.int(robust_k_prop * mu.shape[0]) + 1 maxs = torch.topk(stdmu, K, dim=0)[0][-1,:] mins = -(torch.topk(-stdmu, K, dim=0)[0][-1,:]) smps = (torch.stack([torch.rand(n_draws).to(device) * (maxs[i]-mins[i]) + mins[i] for i in range(stdmu.shape[1])], dim=1)) min_dist = (torch.min(torch.cdist(smps, stdmu.to(device)), dim=1)[0]) # ortho = (torch.mean(min_dist,dim=0)) ortho = (torch.topk(min_dist, np.int(robust_k_prop*n_draws)+1, dim=0))[0][-1] # ortho = torch.max(min_dist,dim=0)[0] return ortho class AE_IOSS(AE): def __init__(self, args, train_dataset, val_dataset, test_dataset, seed=0, device= None, base_algo= 'ae_poly'): super().__init__(args, train_dataset, val_dataset, test_dataset, seed, device) self.encoder= LinearAutoEncoder(self.args.latent_dim, self.args.latent_dim, batch_norm= 0).to(self.device) self.decoder= LinearAutoEncoder(self.args.latent_dim, self.args.latent_dim, batch_norm= 0).to(self.device) self.opt, self.scheduler= self.get_optimizer() self.base_algo = base_algo if self.args.intervention_case: self.res_dir= 'results/ae-ioss/intervention/' + self.base_algo + '/' + str(self.args.save_dir) + 'seed_' + str(seed) + '/' else: self.res_dir= 'results/ae-ioss/observation/' + self.base_algo + '/' + str(self.args.save_dir) + 'seed_' + str(seed) + '/' self.save_path= self.res_dir def compute_loss(self, z_pred, x_pred, x): loss= torch.mean(((x-x_pred)**2)) total_pairs= 3 lambda_reg= 10.0 ioss_penalty= torch.tensor(0.0).to(self.device) for idx in range(total_pairs): perm= torch.randperm(z_pred.shape[1]) ioss_penalty+= torch.mean(IOSS( z_pred[:, perm[:2]], device= self.device)) loss+= lambda_reg * ioss_penalty return loss
CausalRepID-main
algorithms/ioss_auto_encoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import sys import copy import torch import torchvision import numpy as np from sklearn.metrics import r2_score from sklearn.linear_model import LinearRegression, Lasso, Ridge, LassoCV, RidgeCV from sklearn.linear_model import LogisticRegression from sklearn.neural_network import MLPRegressor from scipy.optimize import linear_sum_assignment from sklearn.feature_selection import mutual_info_regression import scipy import matplotlib.pyplot as plt from torchvision import transforms def get_pca_sources(pred_z, pca_transform): return { 'tr': pca_transform.transform(pred_z['tr']), 'te': pca_transform.transform(pred_z['te']) } def get_ica_sources(pred_z, ica_transform): return { 'tr': ica_transform.transform(pred_z['tr']), 'te': ica_transform.transform(pred_z['te']) } def regression_approx(x, y, model, fit_intercept=False): if model == 'lr': reg= LinearRegression(fit_intercept= fit_intercept).fit(x, y) elif model == 'lasso': # reg= Lasso(alpha=0.001, fit_intercept= True).fit(x, y) reg= LassoCV(fit_intercept=True, cv=3).fit(x, y) elif model == 'ridge': # reg= Ridge(alpha=0.001, fit_intercept= True).fit(x, y) alphas_list = np.linspace(1e-2, 1e0, num=10).tolist() alphas_list += np.linspace(1e0, 1e1, num=10).tolist() reg= RidgeCV(fit_intercept= True, cv=3, alphas=alphas_list).fit(x, y) elif model == 'mlp': reg= MLPRegressor(random_state=1, max_iter= 1000).fit(x, y) return reg def get_predictions_check(train_dataset, test_dataset): true_x={'tr':[], 'te':[]} true_z= {'tr':[], 'te':[]} data_case_list= ['train', 'test'] for data_case in data_case_list: if data_case == 'train': dataset= train_dataset key='tr' elif data_case == 'test': dataset= test_dataset key='te' for batch_idx, (x, z, _) in enumerate(dataset): with torch.no_grad(): true_x[key].append(x) true_z[key].append(z) true_x[key]= torch.cat(true_x[key]).detach().numpy() true_z[key]= torch.cat(true_z[key]).detach().numpy() return true_x, true_z def get_predictions(encoder, decoder, train_dataset, val_dataset, test_dataset, device= None, save_dir='plots/', plot=True): true_z= {'tr':[], 'val':[], 'te':[]} pred_z= {'tr':[], 'val':[], 'te':[]} true_y= {'tr':[], 'val':[], 'te':[]} recon_loss= {'tr':0.0, 'val':0.0, 'te':0.0} data_case_list= ['train', 'val', 'test'] for data_case in data_case_list: if data_case == 'train': dataset= train_dataset key='tr' elif data_case == 'val': dataset= val_dataset key='val' elif data_case == 'test': dataset= test_dataset key='te' count=0 for batch_idx, (x, z, y) in enumerate(dataset): with torch.no_grad(): x= x.to(device) pred= encoder(x) x_pred= decoder(pred) loss= torch.mean((x-x_pred)**2) true_y[key].append(y) true_z[key].append(z) pred_z[key].append(pred) recon_loss[key]+= loss.item() count+=1 if plot and batch_idx == 0: for idx in range(5): transform = transforms.Compose( [ transforms.ToPILImage(), ] ) data= x[idx].cpu() data= (data - data.min()) / (data.max() - data.min()) data= transform(data) data.save( save_dir + 'real_image_' + str(idx) + '.jpg') data= x_pred[idx].cpu() data= (data - data.min()) / (data.max() - data.min()) data= transform(data) data.save( save_dir + 'fake_image_' + str(idx) + '.jpg') true_y[key]= torch.cat(true_y[key]).detach().numpy() true_z[key]= torch.cat(true_z[key]).detach().numpy() pred_z[key]= torch.cat(pred_z[key]).cpu().detach().numpy() recon_loss[key]= recon_loss[key]/count # print('Sanity Check: ') # print( true_y['tr'].shape, pred_y['tr'].shape, true_z['tr'].shape, pred_z['tr'].shape ) # print( true_y['te'].shape, pred_y['te'].shape, true_z['te'].shape, pred_z['te'].shape ) return {'true_z': true_z, 'pred_z': pred_z, 'true_y': true_y, 'recon_loss': recon_loss} def get_indirect_prediction_error(pred_latent, true_score, case='test', model='lr'): if case == 'train': key= 'tr' elif case == 'test': key= 'te' reg= regression_approx(pred_latent['tr'], true_score['tr'], model, fit_intercept=True) pred_score= reg.predict(pred_latent[key]) if len(pred_score.shape) == 1: pred_score= np.reshape(pred_score, (pred_score.shape[0], 1)) rmse= np.sqrt(np.mean((true_score[key] - pred_score)**2)) r2= r2_score(true_score[key], pred_score) # mat= reg.coef_ # _, sig_values ,_ = np.linalg.svd(mat) # print(mat) # print(np.mean(pred_latent['tr']), np.var(pred_latent['tr'])) # sys.exit() return rmse, r2 def get_mi_score(pred_latent, true_latent, case='test'): if case == 'train': key= 'tr' elif case == 'test': key= 'te' n= pred_latent[key].shape[0] dim= pred_latent[key].shape[1] mutual_info= 0.0 for i in range(dim): for j in range(dim): if i != j: mutual_info+= mutual_info_regression( np.reshape( pred_latent[key][:, i], (n, 1) ), true_latent[key][:, j] ) print('Mutual Information') print(mutual_info/(dim**2 - dim)) return def get_independence_score(pred_latent, true_latent, case='test'): if case == 'train': key= 'tr' elif case == 'test': key= 'te' dim= pred_latent[key].shape[1] cross_corr= np.zeros((dim, dim)) for i in range(dim): for j in range(dim): cross_corr[i,j]= (np.cov( pred_latent[key][:,i], true_latent[key][:,j] )[0,1]) / ( np.std(pred_latent[key][:,i])*np.std(true_latent[key][:,j]) ) print('Independence Score') print(cross_corr) print(np.linalg.norm( cross_corr - np.eye(dim), ord='fro')) return def get_cross_correlation(pred_latent, true_latent, case='test', batch_size= 5000): if case == 'train': key= 'tr' elif case == 'test': key= 'te' num_samples= pred_latent[key].shape[0] dim= pred_latent[key].shape[1] total_batches= int( num_samples / batch_size ) mcc_arr= [] for batch_idx in range(total_batches): z_hat= copy.deepcopy( pred_latent[key][ (batch_idx)*batch_size : (batch_idx+1)*batch_size ] ) z= copy.deepcopy( true_latent[key][ (batch_idx)*batch_size : (batch_idx+1)*batch_size ] ) batch_idx += 1 cross_corr= np.zeros((dim, dim)) for i in range(dim): for j in range(dim): cross_corr[i,j]= (np.cov( z_hat[:,i], z[:,j] )[0,1]) / ( np.std(z_hat[:,i])*np.std(z[:,j]) ) # cross_corr= np.corrcoef(pred_latent[key], true_latent[key], rowvar=False)[dim:, :dim] cost= -1*np.abs(cross_corr) row_ind, col_ind= linear_sum_assignment(cost) score= 100*( -1*cost[row_ind, col_ind].sum() )/(dim) print(-100*cost[row_ind, col_ind]) # score= 100*np.sum( -1*cost[row_ind, col_ind] > 0.80 )/(dim) mcc_arr.append(score) return mcc_arr def intervene_metric(pred_latent, true_latent, model='lr', model_train=1, list_models=None, hard_intervention_val= 2.0): ''' pred_latent: Output representation from stage 1 true_score: intervened latent true value ''' latent_dim= true_latent['tr'].shape[1] if model_train: res={} for intervene_idx in range(latent_dim): indices= true_latent['tr'][:, intervene_idx] == hard_intervention_val curr_pred_latent_subset= pred_latent['tr'][indices] intervene_targets= 10* np.ones( curr_pred_latent_subset.shape[0] ) reg= regression_approx(curr_pred_latent_subset, intervene_targets, model, fit_intercept=False) res[intervene_idx]= reg return res else: num_samples= true_latent['te'].shape[0] res= np.zeros((num_samples, latent_dim)) for intervene_idx in range(latent_dim): res[:, intervene_idx]= list_models[intervene_idx].predict(pred_latent['te']) return {'te': res} def intervene_metric_image(pred_latent, true_latent, intervention_meta_data, model='lr', model_train=1, list_models=None): ''' pred_latent: Output representation from stage 1 true_score: intervened latent true value ''' if model_train: res={} intervened_latents_set= np.unique( intervention_meta_data['tr'][:, 0] ) print(intervened_latents_set) for intervene_idx in intervened_latents_set: print(intervene_idx) indices= intervention_meta_data['tr'][:, 0] == intervene_idx curr_pred_latent_subset= pred_latent['tr'][indices] intervene_targets= 10* intervention_meta_data['tr'][indices, 1] print(np.unique(intervene_targets)) reg= regression_approx(curr_pred_latent_subset, intervene_targets, model, fit_intercept=False) res[intervene_idx]= reg return res else: intervened_latents_set= list(list_models.keys()) num_samples= true_latent['te'].shape[0] eff_latent_dim= len(intervened_latents_set) z= np.zeros((num_samples, eff_latent_dim)) z_hat= np.zeros((num_samples, eff_latent_dim)) for idx in range(eff_latent_dim): intervene_idx= intervened_latents_set[idx] z[:, idx]= true_latent['te'][:, int(intervene_idx)] z_hat[:, idx]= list_models[intervene_idx].predict(pred_latent['te']) print('Transformed Latents using Itv Dataset', z_hat.shape, z.shape) return {'te':z_hat}, {'te': z} # DCI Score def compute_importance_matrix(z_pred, z, case= 'disentanglement', fit_intercept= True): true_latent_dim= z.shape[1] pred_latent_dim= z_pred.shape[1] imp_matrix= np.zeros((pred_latent_dim, true_latent_dim)) for idx in range(true_latent_dim): model= LinearRegression(fit_intercept= fit_intercept).fit(z_pred, z[:, idx]) # model= LassoCV(fit_intercept=True, cv=3).fit(z_pred, z[:, idx]) imp_matrix[:, idx]= model.coef_ # Taking the absolute value for weights to encode relative importance properly imp_matrix= np.abs(imp_matrix) if case == 'disetanglement': imp_matrix= imp_matrix / np.reshape( np.sum(imp_matrix, axis=1), (pred_latent_dim, 1) ) elif case == 'completeness': imp_matrix= imp_matrix / np.reshape( np.sum(imp_matrix, axis=0), (1, true_latent_dim) ) return imp_matrix def disentanglement_per_code(importance_matrix): """Compute disentanglement score of each code.""" # importance_matrix is of shape [num_codes, num_factors]. return 1. - scipy.stats.entropy(importance_matrix.T + 1e-11, base=importance_matrix.shape[1]) def disentanglement(importance_matrix): """Compute the disentanglement score of the representation.""" per_code = disentanglement_per_code(importance_matrix) if importance_matrix.sum() == 0.: importance_matrix = np.ones_like(importance_matrix) code_importance = importance_matrix.sum(axis=1) / importance_matrix.sum() return np.sum(per_code*code_importance) def completeness_per_factor(importance_matrix): """Compute completeness of each factor.""" # importance_matrix is of shape [num_codes, num_factors]. return 1. - scipy.stats.entropy(importance_matrix + 1e-11, base=importance_matrix.shape[0]) def completeness(importance_matrix): """"Compute completeness of the representation.""" per_factor = completeness_per_factor(importance_matrix) if importance_matrix.sum() == 0.: importance_matrix = np.ones_like(importance_matrix) factor_importance = importance_matrix.sum(axis=0) / importance_matrix.sum() return np.sum(per_factor*factor_importance)
CausalRepID-main
utils/metrics.py
CausalRepID-main
utils/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import numpy as np import torch import torch.utils.data as data_utils path= os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(path) from data.data_loader import BaseDataLoader from data.fine_tune_loader import FineTuneDataLoader from data.balls_dataset_loader import BallsDataLoader class ValidationHelper: def __init__(self, patience=10, min_delta=1e-4): self.patience = patience self.min_delta = min_delta self.counter = 0 self.min_validation_loss = np.inf self.best_epoch = -1 def save_model(self, validation_loss, epoch): if validation_loss < (self.min_validation_loss + self.min_delta): self.min_validation_loss = validation_loss self.best_epoch = epoch self.counter= 0 return True return False def early_stop(self, validation_loss): if validation_loss > (self.min_validation_loss + self.min_delta): self.counter += 1 if self.counter >= self.patience: return True return False def sample_base_data_loaders(data_dir, batch_size, observation_case= 1, intervention_case= 0, latent_case='', seed=0, kwargs={}): if 'balls' in latent_case: data_obj= BallsDataLoader(data_dir= data_dir, data_case='train', observation_case = observation_case, intervention_case= intervention_case) train_dataset= data_utils.DataLoader(data_obj, batch_size=batch_size, shuffle=True, **kwargs ) data_obj= BallsDataLoader(data_dir= data_dir, data_case='val', observation_case = observation_case, intervention_case= intervention_case) val_dataset= data_utils.DataLoader(data_obj, batch_size=batch_size, shuffle=True, **kwargs ) data_obj= BallsDataLoader(data_dir= data_dir, data_case='test', observation_case = observation_case, intervention_case= intervention_case) test_dataset= data_utils.DataLoader(data_obj, batch_size=batch_size, shuffle=True, **kwargs ) else: data_obj= BaseDataLoader(data_dir= data_dir, data_case='train', seed= seed, observation_case = observation_case, intervention_case= intervention_case) train_dataset= data_utils.DataLoader(data_obj, batch_size=batch_size, shuffle=True, **kwargs ) data_obj= BaseDataLoader(data_dir= data_dir, data_case='val', seed= seed, observation_case = observation_case, intervention_case= intervention_case) val_dataset= data_utils.DataLoader(data_obj, batch_size=batch_size, shuffle=True, **kwargs ) data_obj= BaseDataLoader(data_dir= data_dir, data_case='test', seed= seed, observation_case = observation_case, intervention_case= intervention_case) test_dataset= data_utils.DataLoader(data_obj, batch_size=batch_size, shuffle=True, **kwargs ) return train_dataset, val_dataset, test_dataset def sample_finetune_data_loaders(pred_z, true_z, data_dir, batch_size, kwargs= {}): data_obj= FineTuneDataLoader(pred_z, true_z, data_dir= data_dir, data_case='train') train_dataset= data_utils.DataLoader(data_obj, batch_size=batch_size, shuffle=True, **kwargs ) data_obj= FineTuneDataLoader(pred_z, true_z, data_dir= data_dir, data_case='val') val_dataset= data_utils.DataLoader(data_obj, batch_size=batch_size, shuffle=True, **kwargs ) data_obj= FineTuneDataLoader(pred_z, true_z, data_dir= data_dir, data_case='test') test_dataset= data_utils.DataLoader(data_obj, batch_size=batch_size, shuffle=True, **kwargs ) return train_dataset, val_dataset, test_dataset
CausalRepID-main
utils/helper.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from torch import nn class LinearAutoEncoder(torch.nn.Module): def __init__(self, data_dim, latent_dim, batch_norm= False): super(LinearAutoEncoder, self).__init__() self.data_dim = data_dim self.latent_dim = latent_dim if batch_norm: self.net= nn.Sequential( nn.BatchNorm1d(self.data_dim), nn.Linear(self.data_dim, self.latent_dim), ) else: self.net= nn.Sequential( nn.Linear(self.data_dim, self.latent_dim), ) def forward(self, x): return self.net(x)
CausalRepID-main
models/linear_auto_encoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable from torchvision.models.resnet import ResNet, BasicBlock class Decoder(torch.nn.Module): def __init__(self, data_dim, latent_dim): super(Decoder, self).__init__() self.data_dim = data_dim self.latent_dim = latent_dim self.hidden_dim= 200 self.net= nn.Sequential( nn.Linear(self.latent_dim, self.hidden_dim), nn.LeakyReLU(0.5), nn.Linear(self.hidden_dim, self.hidden_dim), nn.LeakyReLU(0.5), nn.Linear(self.hidden_dim, self.data_dim), ) def forward(self, z): return self.net(z)
CausalRepID-main
models/decoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable from torchvision.models.resnet import ResNet, BasicBlock import sys ''' Refernce for DeConv Blocks: https://github.com/julianstastny/VAE-ResNet18-PyTorch/blob/master/model.py ''' class ResizeConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, scale_factor, mode='nearest'): super().__init__() self.scale_factor = scale_factor self.mode = mode self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=1) def forward(self, x): x = F.interpolate(x, scale_factor=self.scale_factor, mode=self.mode) x = self.conv(x) return x class BasicBlockDec(nn.Module): def __init__(self, in_planes, stride=1): super().__init__() planes = int(in_planes/stride) self.conv2 = nn.Conv2d(in_planes, in_planes, kernel_size=3, stride=1, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(in_planes) # self.bn1 could have been placed here, but that messes up the order of the layers when printing the class if stride == 1: self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential() else: self.conv1 = ResizeConv2d(in_planes, planes, kernel_size=3, scale_factor=stride) self.bn1 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential( ResizeConv2d(in_planes, planes, kernel_size=3, scale_factor=stride), nn.BatchNorm2d(planes) ) def forward(self, x): out = torch.relu(self.bn2(self.conv2(x))) out = self.bn1(self.conv1(out)) out += self.shortcut(x) out = torch.relu(out) return out class ImageDecoder(torch.nn.Module): def __init__(self, latent_dim): super(ImageDecoder, self).__init__() self.latent_dim = latent_dim self.width= 128 self.num_Blocks=[2,2,2,2] self.in_planes = 512 self.nc= 3 self.linear = [ nn.Linear(self.latent_dim, self.width), nn.LeakyReLU(), nn.Linear(self.width, 512), ] self.linear= nn.Sequential(*self.linear) self.layer4 = self._make_layer(BasicBlockDec, 256, self.num_Blocks[3], stride=2) self.layer3 = self._make_layer(BasicBlockDec, 128, self.num_Blocks[2], stride=2) self.layer2 = self._make_layer(BasicBlockDec, 64, self.num_Blocks[1], stride=2) self.layer1 = self._make_layer(BasicBlockDec, 64, self.num_Blocks[0], stride=1) self.conv1 = ResizeConv2d(64, self.nc, kernel_size=3, scale_factor=2) def _make_layer(self, BasicBlockDec, planes, num_Blocks, stride): strides = [stride] + [1]*(num_Blocks-1) layers = [] for stride in reversed(strides): layers += [BasicBlockDec(self.in_planes, stride)] self.in_planes = planes return nn.Sequential(*layers) def forward(self, z): x = self.linear(z) x = x.view(z.size(0), 512, 1, 1) x = F.interpolate(x, scale_factor=4) x = self.layer4(x) x = self.layer3(x) x = self.layer2(x) x = self.layer1(x) x = self.conv1(x) return x
CausalRepID-main
models/image_resnet_decoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable from torchvision.models.resnet import ResNet, BasicBlock class PolyDecoder(torch.nn.Module): def __init__(self, data_dim, latent_dim, poly_degree, device): super(PolyDecoder, self).__init__() self.data_dim = data_dim self.latent_dim = latent_dim self.poly_degree = poly_degree self.device = device self.total_poly_terms= self.compute_total_polynomial_terms() self.coff_matrix= nn.Sequential( nn.Linear(self.total_poly_terms, self.data_dim), ) def forward(self, z): x=[] for idx in range(z.shape[0]): x.append( self.compute_decoder_polynomial(z[idx, :])) x= torch.cat(x, dim=0) x= self.coff_matrix(x) return x def compute_total_polynomial_terms(self): count=0 for degree in range(self.poly_degree + 1): count+= pow(self.latent_dim, degree) return count def compute_kronecker_product(self, degree, latent): if degree ==0: out= torch.tensor([1]).to(self.device) else: out=torch.clone(latent) for idx in range(1, degree): out= torch.kron(out, latent) return out def compute_decoder_polynomial(self, latent): out=[] for degree in range(self.poly_degree + 1): # print('Computing polynomial term of degree ', degree) out.append(self.compute_kronecker_product(degree, latent)) out= torch.cat(out) out= out.view((1,out.shape[0])) return out
CausalRepID-main
models/poly_decoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from torch import nn class Encoder(torch.nn.Module): def __init__(self, data_dim, latent_dim): super(Encoder, self).__init__() self.data_dim = data_dim self.latent_dim = latent_dim self.hidden_dim= 100 self.net= nn.Sequential( nn.Linear(self.data_dim, self.hidden_dim), nn.LeakyReLU(0.5), nn.Linear(self.hidden_dim, self.hidden_dim), nn.LeakyReLU(0.5), nn.Linear(self.hidden_dim, self.latent_dim), ) def forward(self, x): return self.net(x)
CausalRepID-main
models/encoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable from torchvision.models.resnet import ResNet, BasicBlock class ImageDecoder(torch.nn.Module): def __init__(self, latent_dim): super(ImageDecoder, self).__init__() self.latent_dim = latent_dim self.width= 128 self.nc= 3 self.linear = [ nn.Linear(self.latent_dim, self.width), nn.LeakyReLU(), nn.Linear(self.width, 1024), nn.LeakyReLU(), ] self.linear= nn.Sequential(*self.linear) self.conv= [ nn.ConvTranspose2d(64, 64, 4, stride=2, padding=1), nn.LeakyReLU(), nn.ConvTranspose2d(64, 32, 4, stride=2, padding=1), nn.LeakyReLU(), nn.ConvTranspose2d(32, 32, 4, stride=2, padding=1), nn.LeakyReLU(), nn.ConvTranspose2d(32, self.nc, 4, stride=2, padding=1), ] self.conv= nn.Sequential(*self.conv) def forward(self, z): x = self.linear(z) x = x.view(z.size(0), 64, 4, 4) x = self.conv(x) return x
CausalRepID-main
models/image_decoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from torch import nn from torchvision import models as vision_models from torchvision.models import resnet18, resnet50 from torchvision import transforms class ImageEncoder(torch.nn.Module): def __init__(self, latent_dim): super(ImageEncoder, self).__init__() self.latent_dim = latent_dim self.base_architecture= 'resnet18' self.width = 128 self.base_model = resnet18(pretrained=True) self.feat_layers= list(self.base_model.children())[:-1] self.feat_net= nn.Sequential(*self.feat_layers) self.fc_layers= [ nn.Linear(512, self.width), nn.LeakyReLU(), nn.Linear(self.width, self.latent_dim), ] self.fc_net = nn.Sequential(*self.fc_layers) def forward(self, x): x= self.feat_net(x) x= x.view(x.shape[0], x.shape[1]) x= self.fc_net(x) return x
CausalRepID-main
models/image_encoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable from torchvision.models.resnet import ResNet, BasicBlock def build_grid(resolution): ranges = [np.linspace(0., 1., num=res) for res in resolution] grid = np.meshgrid(*ranges, sparse=False, indexing="ij") grid = np.stack(grid, axis=-1) grid = np.reshape(grid, [resolution[0], resolution[1], -1]) grid = np.expand_dims(grid, axis=0) grid = grid.astype(np.float32) return torch.from_numpy(np.concatenate([grid, 1.0 - grid], axis=-1)) """Adds soft positional embedding with learnable projection.""" class SoftPositionEmbed(nn.Module): def __init__(self, hidden_size, resolution): """Builds the soft position embedding layer. Args: hidden_size: Size of input feature dimension. resolution: Tuple of integers specifying width and height of grid. """ super().__init__() self.embedding = nn.Linear(4, hidden_size, bias=True) self.grid = build_grid(resolution) def forward(self, inputs): grid = self.embedding(self.grid) return inputs + grid class ImageDecoder(torch.nn.Module): def __init__(self, latent_dim): super(ImageDecoder, self).__init__() self.latent_dim = latent_dim self.width= 128 self.nc= 3 self.linear = [ nn.Linear(self.latent_dim, self.width), nn.LeakyReLU(), nn.Linear(self.width, 1024), nn.LeakyReLU(), ] self.linear= nn.Sequential(*self.linear) self.decoder_initial_size = (8, 8) self.decoder_pos = SoftPositionEmbed(1024, self.decoder_initial_size) self.conv1 = nn.ConvTranspose2d(hid_dim, hid_dim, 5, stride=(2, 2), padding=2, output_padding=1).to(device) self.conv2 = nn.ConvTranspose2d(hid_dim, hid_dim, 5, stride=(2, 2), padding=2, output_padding=1).to(device) self.conv3 = nn.ConvTranspose2d(hid_dim, hid_dim, 5, stride=(2, 2), padding=2, output_padding=1).to(device) self.conv4 = nn.ConvTranspose2d(hid_dim, hid_dim, 5, stride=(2, 2), padding=2, output_padding=1).to(device) self.conv5 = nn.ConvTranspose2d(hid_dim, hid_dim, 5, stride=(1, 1), padding=2).to(device) self.conv6 = nn.ConvTranspose2d(hid_dim, 4, 3, stride=(1, 1), padding=1) self.resolution = resolution def forward(self, z): x = self.linear(z) x = self.decoder_pos(x) x = x.view(z.size(0), 64, 4, 4) return x
CausalRepID-main
models/image_slot_attention_decoder.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import numpy as np import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument('--case', type=str, default='log', help= 'test; log; debug') parser.add_argument('--target_latent', type=str, default='balls_iid_none', help= '') parser.add_argument('--eval_ioss_transformation', type=int, default=0, help='Evaluate the IOSS transformation from the base model representation') parser.add_argument('--eval_intervene_transformation', type=int, default=1, help='Evaluate the Intervention transformation from the base model representation') args = parser.parse_args() case= args.case target_latent= args.target_latent eval_ioss_transformation= args.eval_ioss_transformation eval_intervene_transformation= args.eval_intervene_transformation latent_case_grid= ['balls_iid_none', 'balls_scm_linear', 'balls_scm_non_linear'] interventions_per_latent_grid= [1, 3, 5, 7, 9] method_type= 'ae_image' total_seeds= 5 latent_dim = 25 lr= 5e-4 intervention_case= 0 batch_size= 64 cuda_device= 0 #Test Models if args.case == 'test': for latent_case in latent_case_grid: if latent_case != target_latent: continue for total_interventions in interventions_per_latent_grid: latent= latent_case.split('_')[1] mechanism= latent_case.split('_')[2] if mechanism == 'non': mechanism= 'non_linear' #Data Script script= 'python data/balls_dataset.py --distribution_case intervention ' + ' --latent_case ' + str(latent) + ' --scm_mechanism ' + str(mechanism) + ' --interventions_per_latent ' + str(total_interventions) print('Data Case: ', script) os.system(script) #Eval Script fname= 'latent_case_' + str(latent_case) + '_itv_per_latent_' + str(total_interventions) + '_latent_dim_' + str(latent_dim) + '_lr_' + str(lr) + '_method_type_' + str(method_type) + '.txt' print(fname) script= 'python test.py ' + ' --latent_case ' + str(latent_case) + ' --latent_dim ' + str(latent_dim) + ' --intervention_case ' + str(intervention_case) + ' --lr ' + str(lr) + ' --batch_size ' + str(batch_size) + ' --method_type ' + str(method_type) + ' --num_seeds ' + str(total_seeds) + ' --cuda_device ' + str(cuda_device) + ' --eval_ioss_transformation ' + str(eval_ioss_transformation) + ' --eval_intervene_transformation ' + str(eval_intervene_transformation) + ' > ' + 'results/final_logs/balls/' + fname os.system(script) #Log Results latent_name_map= {'balls_iid_none': 'Uniform', 'balls_scm_linear': 'SCM (linear)', 'balls_scm_non_linear': 'SCM (non-linear)'} if args.case == 'log': meta_res={} for lr in [0.0005]: res={'Latent Case': [], 'Total Interventions': [], 'Recon-RMSE':[], 'R2':[], 'MCC-Tune': []} for latent_case in latent_case_grid: for total_interventions in interventions_per_latent_grid: fname= 'latent_case_' + str(latent_case) + '_itv_per_latent_' + str(total_interventions) + '_latent_dim_' + str(latent_dim) + '_lr_' + str(lr) + '_method_type_' + str(method_type) + '.txt' data= open( 'results/final_logs/balls/' + fname, 'r').readlines() for line in data: line= line.replace('\n','') if 'Metric' in line: if 'recon_rmse' in line: key= 'Recon-RMSE' elif 'latent_pred_r2' in line: key= 'R2' elif 'mcc_tune' in line: key= 'MCC-Tune' else: continue mean= round( float(line.split(" ")[-2]), 2 ) var= round( float(line.split(" ")[-1]), 2 ) val= str(mean) + ' \u00B1 ' + str(var) # val= str(mean) + ' ( ' + str(var) + ' ) ' res[key].append(val) res['Latent Case'].append( latent_name_map[latent_case] ) res['Total Interventions'].append(total_interventions) meta_res[lr]= res final_res={'Latent Case': [], 'Total Interventions': [], 'LR': [], 'Recon-RMSE':[], 'MCC-Tune': []} final_res= meta_res[0.0005] for key in final_res.keys(): print(key, len(final_res[key])) df= pd.DataFrame(final_res) # df= df.drop(columns= ['Recon-RMSE']) print(df.to_latex(index=False))
CausalRepID-main
scripts/main_exps_images.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import numpy as np import scipy import copy from sklearn.linear_model import LinearRegression, Lasso, Ridge, LassoCV, RidgeCV ''' z: True Latent (dataset_size, latent_dim) (.npy file) Pred_z: Inferred Latent (dataset_size, latent_dim) (.npy file) ''' # DCI Score def compute_importance_matrix(z_pred, z, case= 'disentanglement', fit_intercept= True): true_latent_dim= z.shape[1] pred_latent_dim= z_pred.shape[1] imp_matrix= np.zeros((pred_latent_dim, true_latent_dim)) for idx in range(true_latent_dim): model= LinearRegression(fit_intercept= fit_intercept).fit(z_pred, z[:, idx]) # model= LassoCV(fit_intercept=True, cv=3).fit(z_pred, z[:, idx]) imp_matrix[:, idx]= model.coef_ # Taking the absolute value for weights to encode relative importance properly imp_matrix= np.abs(imp_matrix) if case == 'disetanglement': imp_matrix= imp_matrix / np.reshape( np.sum(imp_matrix, axis=1), (pred_latent_dim, 1) ) elif case == 'completeness': imp_matrix= imp_matrix / np.reshape( np.sum(imp_matrix, axis=0), (1, true_latent_dim) ) return imp_matrix def disentanglement_per_code(importance_matrix): """Compute disentanglement score of each code.""" # importance_matrix is of shape [num_codes, num_factors]. return 1. - scipy.stats.entropy(importance_matrix.T + 1e-11, base=importance_matrix.shape[1]) def disentanglement(importance_matrix): """Compute the disentanglement score of the representation.""" per_code = disentanglement_per_code(importance_matrix) if importance_matrix.sum() == 0.: importance_matrix = np.ones_like(importance_matrix) code_importance = importance_matrix.sum(axis=1) / importance_matrix.sum() return np.sum(per_code*code_importance) def completeness_per_factor(importance_matrix): """Compute completeness of each factor.""" # importance_matrix is of shape [num_codes, num_factors]. return 1. - scipy.stats.entropy(importance_matrix + 1e-11, base=importance_matrix.shape[0]) def completeness(importance_matrix): """"Compute completeness of the representation.""" per_factor = completeness_per_factor(importance_matrix) if importance_matrix.sum() == 0.: importance_matrix = np.ones_like(importance_matrix) factor_importance = importance_matrix.sum(axis=0) / importance_matrix.sum() return np.sum(per_factor*factor_importance) # Test Cases # Case 1: True latent same as the predicted latent list_matrices= [ np.eye(10), np.random.random((10, 10)) ] for matrix in list_matrices: true_z= np.random.random((1000, 10)) pred_z= np.matmul(true_z, matrix) imp_matrix= compute_importance_matrix(pred_z, true_z, case='disentanglement') score= disentanglement(imp_matrix) print('Disentanglement', score) imp_matrix= compute_importance_matrix(pred_z, true_z, case='completeness') score= completeness(imp_matrix) print('Completeness', score) # Permutation Case pred_z= copy.deepcopy(true_z) perm= np.random.permutation(10) pred_z= pred_z[:, perm] imp_matrix= compute_importance_matrix(pred_z, true_z, case='disentanglement') score= disentanglement(imp_matrix) print('Disentanglement', score) imp_matrix= compute_importance_matrix(pred_z, true_z, case='completeness') score= completeness(imp_matrix) print('Completeness', score)
CausalRepID-main
scripts/test_metrics.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import numpy as np import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument('--case', type=str, default='log', help= 'train; test; log; debug') parser.add_argument('--intervention_case', type=int, default=0, help='') parser.add_argument('--target_latent', type=str, default='uniform', help= '') parser.add_argument('--target_dim', type=int, default=6, help='') parser.add_argument('--target_degree', type=int, default=2, help='') parser.add_argument('--method_type', type=str, default='ae_poly', help= 'ae, ae_poly') parser.add_argument('--batch_size', type=int, default= 16, help='') parser.add_argument('--lr', type=float, default= 1e-3, help='') parser.add_argument('--train_base_model', type=int, default=1, help='Train the base auto encoder') parser.add_argument('--train_ioss_transformation', type=int, default=0, help='Learn the IOSS transformation from the base model representations') parser.add_argument('--eval_ioss_transformation', type=int, default=0, help='Evaluate the IOSS transformation from the base model representation') parser.add_argument('--eval_intervene_transformation', type=int, default=0, help='Evaluate the Intervention transformation from the base model representation') parser.add_argument('--eval_dgp', type=int, default= 1, help= 'Evaluate the function from z -> x and x -> z in the true DGP') parser.add_argument('--cuda_device', type=int, default=-1, help='Select the cuda device by id among the avaliable devices' ) args = parser.parse_args() intervention_case= args.intervention_case batch_size= args.batch_size lr= args.lr method_type= args.method_type target_latent= args.target_latent target_dim= args.target_dim target_degree= args.target_degree train_base_model= args.train_base_model train_ioss_transformation= args.train_ioss_transformation eval_ioss_transformation= args.eval_ioss_transformation eval_intervene_transformation= args.eval_intervene_transformation eval_dgp= args.eval_dgp cuda_device= args.cuda_device # latent_case_grid= ['uniform', 'uniform_corr'] # latent_case_grid= ['gaussian_mixture', 'scm_sparse', 'scm_dense'] latent_case_grid= ['uniform', 'uniform_corr', 'gaussian_mixture', 'scm_sparse', 'scm_dense'] # latent_case_grid= ['scm_sparse', 'scm_dense'] poly_degree_grid= [2, 3] latent_dim_grid=[6, 10] total_seeds= 5 data_dim = 200 #Sanity Checks if args.case == 'debug': for latent_case in latent_case_grid: for latent_dim in latent_dim_grid: for poly_degree in poly_degree_grid: for seed in range(total_seeds): curr_dir= 'results/ae-ioss/ae_poly/' + 'polynomial' + '_latent_' + latent_case + '_poly_degree_' + str(poly_degree) + '_data_dim_' + str(data_dim) + '_latent_dim_' + str(latent_dim) + '/' + 'seed_' + str(seed) + '/' # curr_dir= 'results/ae-poly/' + 'polynomial' + '_latent_' + latent_case + '_poly_degree_' + str(poly_degree) + '_data_dim_' + str(data_dim) + '_latent_dim_' + str(latent_dim) + '/' + 'seed_' + str(seed) + '/' count=0 for _, _, f_list in os.walk(curr_dir): for fname in f_list: if '.pth' in fname: count+=1 if count!=6: print('Error: ', latent_case, latent_dim, poly_degree, seed, count) #Generate Datasets if args.case == 'data': for latent_case in latent_case_grid: if latent_case != target_latent: continue for latent_dim in latent_dim_grid: for poly_degree in poly_degree_grid: for seed in range(total_seeds): script= 'python data/synthetic_polynomial_dgp.py ' + ' --latent_case ' + str(latent_case) + ' --latent_dim ' + str(latent_dim) + ' --poly_degree ' + str(poly_degree) + ' --seed ' + str(seed) os.system(script) #Train Models if args.case == 'train': train_ioss_transformation= 1 - intervention_case for latent_case in latent_case_grid: if latent_case != target_latent: continue for latent_dim in latent_dim_grid: if latent_dim != target_dim: continue for poly_degree in poly_degree_grid: if poly_degree != target_degree: continue for seed in range(total_seeds): script= 'python train.py ' + ' --latent_case ' + str(latent_case) + ' --latent_dim ' + str(latent_dim) + ' --poly_degree ' + str(poly_degree) + ' --seed ' + str(seed) + ' --intervention_case ' + str(intervention_case) + ' --lr ' + str(lr) + ' --batch_size ' + str(batch_size) + ' --method_type ' + str(method_type) + ' --cuda_device ' + str(cuda_device) + ' --train_base_model ' + str(train_base_model) + ' --train_ioss_transformation ' + str(train_ioss_transformation) os.system(script) #Test Models if args.case == 'test': eval_ioss_transformation= 1 - intervention_case eval_intervene_transformation= intervention_case for latent_case in latent_case_grid: for latent_dim in latent_dim_grid: for poly_degree in poly_degree_grid: fname= 'latent_case_' + str(latent_case) + '_latent_dim_' + str(latent_dim) + '_poly_degree_' + str(poly_degree) + '_intervention_' + str(intervention_case) + '_lr_' + str(lr) + '_method_type_' + str(method_type) + '.txt' print(fname) script= 'python test.py ' + ' --latent_case ' + str(latent_case) + ' --latent_dim ' + str(latent_dim) + ' --poly_degree ' + str(poly_degree) + ' --intervention_case ' + str(intervention_case) + ' --lr ' + str(lr) + ' --batch_size ' + str(batch_size) + ' --method_type ' + str(method_type) + ' --eval_ioss_transformation ' + str(eval_ioss_transformation) + ' --eval_intervene_transformation ' + str(eval_intervene_transformation) + ' --eval_dgp ' + str(eval_dgp) + ' > ' + 'results/final_logs/'+ fname os.system(script) #Log Results latent_name_map= {'uniform': 'Uniform', 'uniform_corr': 'Uniform-C', 'gaussian_mixture': 'Gaussian-Mixture', 'scm_sparse': 'SCM-S', 'scm_dense': 'SCM-D'} if args.case == 'log': meta_res={} for lr in [0.001, 0.0005, 0.0001]: res={'Latent Case': [], 'Latent Dim': [], 'Poly Degree': [], 'Recon Error':[], 'RMSE': [], 'R2': [], 'Debug-R2' : [], 'Oracle-R2': [], 'MCC': [], 'MCC-Tune': []} for latent_case in latent_case_grid: for latent_dim in latent_dim_grid: for poly_degree in poly_degree_grid: fname= 'latent_case_' + str(latent_case) + '_latent_dim_' + str(latent_dim) + '_poly_degree_' + str(poly_degree) + '_intervention_' + str(intervention_case) + '_lr_' + str(lr) + '_method_type_' + str(method_type) + '.txt' data= open( 'results/final_logs/' + fname, 'r').readlines() for line in data: line= line.replace('\n','') if 'Metric' in line: if 'recon_rmse' in line: key= 'Recon Error' elif 'latent_pred_rmse' in line: key= 'RMSE' elif 'latent_pred_r2' in line: key= 'R2' elif 'mcc ' in line: key= 'MCC' elif 'mcc_tune' in line: key= 'MCC-Tune' elif 'debug_pred_r2' in line: key= 'Debug-R2' elif 'oracle_pred_r2' in line: key= 'Oracle-R2' else: continue mean= round( float(line.split(" ")[-2]), 2 ) var= round( float(line.split(" ")[-1]), 2 ) # val= str(mean) + ' ( ' + str(var) + ' ) ' val= str(mean) + ' \u00B1 ' + str(var) res[key].append(val) res['Latent Case'].append( latent_name_map[latent_case] ) res['Latent Dim'].append(latent_dim) res['Poly Degree'].append(poly_degree) meta_res[lr]= res final_res={'Latent Case': [], 'Latent Dim': [], 'Poly Degree': [], 'LR': [], 'Recon Error':[], 'RMSE': [], 'R2': [], 'Debug-R2' : [], 'Oracle-R2': [], 'MCC': [], 'MCC-Tune': []} total_size= len(res['Recon Error']) for idx in range(total_size): opt_val= np.inf opt_lr= -1 for lr in [0.001, 0.0005, 0.0001]: curr_val= float(meta_res[lr]['Recon Error'][idx].split(' ')[0]) if opt_val > curr_val: opt_val = curr_val opt_lr= lr final_res['LR'].append(opt_lr) for key in res.keys(): final_res[key].append( meta_res[opt_lr][key][idx] ) for key in final_res.keys(): print(key, len(final_res[key])) df= pd.DataFrame(final_res) df= df.drop(columns= ['RMSE', 'Debug-R2', 'Oracle-R2', 'LR']) # df= df.drop(columns= ['RMSE', 'Debug-R2', 'Oracle-R2', 'LR', 'R2', 'Recon Error']) print(df.to_latex(index=False))
CausalRepID-main
scripts/main_exps.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import random import numpy as np import networkx as nx import matplotlib.pyplot as plt import os import sys path= os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(path) from data.dag_generator import DagGenerator random.seed(10) np.random.seed(10) dag= DagGenerator('linear', cause='gaussian', nodes=10, expected_density= 0.5, npoints= 5000) print(dir(dag)) df1, obj1= dag.generate() z= df1.values print('Observational Data') print(z) # print(np.cov(np.transpose(z))) # print(z.shape) # print(df1) # print(df1.values.shape) nx.draw_networkx(obj1, arrows=True) plt.savefig('a.jpg') plt.clf() # sys.exit() print('Adjanceny Matrix') print(nx.adjacency_matrix(obj1)) print('Degree Values') print(type(obj1.degree())) # ''' # Calling dag.generate second time does not reinitialise the DAG structure but samples new points; so simply call dag.generate() with different seed values should give the train/val/test split. # ''' # df2, obj2= dag.generate() # print(df2) # # nx.draw_networkx(obj2, arrows=True) # # plt.savefig('b.jpg') # # plt.clf() #Checking for intervention df3, obj3= dag.intervene(intervention_nodes= [9], target_distribution= 'hard_intervention') print('Interventional Matrix') print(df3) # nx.draw_networkx(obj3, arrows=True) # plt.savefig('c.jpg') # plt.clf()
CausalRepID-main
scripts/dag_gen_debug.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import math import argparse import numpy as np import time ## Imports for plotting import matplotlib.pyplot as plt from IPython.display import set_matplotlib_formats set_matplotlib_formats('svg', 'pdf') # For export from matplotlib.colors import to_rgba import seaborn as sns sns.set() from tqdm.notebook import tqdm import torch import torch.nn as nn import torch.nn.functional as F from sklearn.linear_model import LogisticRegression import torch.utils.data as data from scipy.stats import ortho_group from utils.metrics import get_cross_correlation from scipy.stats import bernoulli def get_predictions(model, train_dataset, device= None): true_z= [] pred_z= [] count= 0 for batch_idx, (data_inputs, data_latents), in enumerate(train_dataset): with torch.no_grad(): data_inputs = data_inputs.to(device) preds = model(data_inputs) true_z.append(data_latents) pred_z.append(preds) count+=1 true_z= torch.cat(true_z).detach().numpy() pred_z= torch.cat(pred_z).cpu().detach().numpy() return true_z, pred_z class LinearEncoder(nn.Module): def __init__(self, num_inputs, num_outputs): super().__init__() self.linear = nn.Linear(num_inputs, num_outputs) def forward(self, x): x = self.linear(x) return x class data_class_loader(data.Dataset): def __init__(self, dataset): super().__init__() self.dataset_generate(dataset) self.size = dataset[0].size()[0] def dataset_generate(self, dataset): self.data = dataset[0] self.latent = dataset[1] self.label = dataset[2].T[0].to(int) def __len__(self): return self.size def __getitem__(self, idx): data_point = self.data[idx] data_latent = self.latent[idx] data_label = self.label[idx] return data_point, data_latent def IOSS(mu, n_draws=10000, robust_k_prop = 0.01): stdmu = (mu - torch.min(mu,dim=0)[0])/ (torch.max(mu,dim=0)[0]-torch.min(mu,dim=0)[0]) K = np.int(robust_k_prop * mu.shape[0]) + 1 maxs = torch.topk(stdmu, K, dim=0)[0][-1,:] mins = -(torch.topk(-stdmu, K, dim=0)[0][-1,:]) smps = (torch.stack([torch.rand(n_draws).cuda() * (maxs[i]-mins[i]) + mins[i] for i in range(stdmu.shape[1])], dim=1)) min_dist = (torch.min(torch.cdist(smps, stdmu.cuda()), dim=1)[0]) # ortho = (torch.mean(min_dist,dim=0)) ortho = (torch.topk(min_dist, np.int(robust_k_prop*n_draws)+1, dim=0))[0][-1] # ortho = torch.max(min_dist,dim=0)[0] return ortho def loss_intervention(decoder, preds, inputs, ioss_penalty=0.1, device=[]): # constraint= torch.mean( IOSS(preds) ) constraint= torch.tensor(0.0).to(device) total_pairs= 3 for idx in range(total_pairs): perm= torch.randperm(preds.shape[1]) constraint+= torch.mean(IOSS( preds[:, perm[:2]] )) #Reconstruction Loss criterion = nn.MSELoss() preds= decoder(preds) loss = criterion(preds,inputs) #Final Loss theta = ioss_penalty loss = loss + theta*constraint return loss def train_model(encoder, decoder, optimizer, data_loader, num_epochs, ioss_penalty= 0.1): # Set model to train mode encoder.train() decoder.train() # Training loop for epoch in tqdm(range(num_epochs)): #MCC z, z_pred= get_predictions(encoder, data_loader, device= device) mcc= get_cross_correlation({'te':z}, {'te':z_pred}) print('MCC: ', mcc) print('Epoch: ', epoch) train_loss= 0.0 batch_count= 0 for data_inputs, data_latents, in data_loader: data_inputs = data_inputs.to(device) preds = encoder(data_inputs) # preds = preds.squeeze(dim=1) # loss = loss_intervention(preds, data_inputs) loss = loss_intervention(decoder, preds, data_inputs, ioss_penalty= ioss_penalty, device= device) train_loss+= loss.item() batch_count+=1 optimizer.zero_grad() loss.backward() optimizer.step() print('Loss: ', train_loss/batch_count) # Input Parsing parser = argparse.ArgumentParser() parser.add_argument('--total_samples', type=int, default=50000, help='') parser.add_argument('--latent_dim', type=int, default= 10, help='') parser.add_argument('--latent_case', type=str, default='uniform', help='uniform, uniform_corr') parser.add_argument('--ioss_penalty', type=float, default= 10.0, help='') parser.add_argument('--batch_size', type=int, default= 16, help='') parser.add_argument('--lr', type=float, default= 0.001, help='') parser.add_argument('--weight_decay', type=float, default= 5e-4, help='') parser.add_argument('--num_epochs', type=int, default= 300, help='') parser.add_argument('--seed', type=int, default=3, help='') args = parser.parse_args() n = args.total_samples d = args.latent_dim latent_case= args.latent_case ioss_penalty= args.ioss_penalty lr= args.lr weight_decay= args.weight_decay # A = np.random.uniform(size=(d,d)) A = ortho_group.rvs(d) # Observational data if latent_case == 'uniform': Zobs = np.random.uniform(size=(n,d)) elif latent_case == 'uniform_corr': Zobs= np.zeros((n, d)) for d_idx in range(0 , d, 2): print('Latent entries for the pair: ', d_idx, d_idx + 1) p1= bernoulli.rvs(0.5, size=n) p2= bernoulli.rvs(0.9, size=n) z_11= np.random.uniform(low=0, high=5, size=n) z_12= np.random.uniform(low=-5, high=0, size=n) z_21= np.random.uniform(low=0, high=3, size=n) z_22= np.random.uniform(low=-3, high=0, size=n) for idx in range(n): if p1[idx] == 1: Zobs[idx, d_idx + 0]= z_11[idx] if p2[idx] == 1: Zobs[idx, d_idx + 1]= z_21[idx] else: Zobs[idx, d_idx + 1]= z_22[idx] else: Zobs[idx, d_idx + 0]= z_12[idx] if p2[idx] == 1: Zobs[idx, d_idx + 1]= z_22[idx] else: Zobs[idx, d_idx + 1]= z_21[idx] # print(100*np.sum(Zobs[:,0]*Zobs[:,1]<0)/n) Xobs = np.matmul(Zobs,A) Eobs = np.zeros((n,1)) X = Xobs Z = Zobs E = Eobs X = torch.tensor(X, dtype=torch.float32) E = torch.tensor(E, dtype=torch.float32) Data_train = (X, Z, E) # data prep data_train_obj = data_class_loader(Data_train) train_data_loader = data.DataLoader(data_train_obj, batch_size=32, shuffle=True) # device = torch.device("cuda:0") device = torch.device("cuda:0") # model and optimizer init num_inputs= Data_train[0].size()[1] encoder = LinearEncoder(num_inputs=num_inputs, num_outputs=num_inputs) encoder.to(device) decoder = LinearEncoder(num_inputs=num_inputs, num_outputs=num_inputs) decoder.to(device) optimizer= torch.optim.Adam([ {'params': filter(lambda p: p.requires_grad, list(encoder.parameters()) + list(decoder.parameters()) )}, ], lr= lr, weight_decay= weight_decay ) num_epochs = 200 # train model train_model(encoder, decoder, optimizer, train_data_loader, num_epochs, ioss_penalty= ioss_penalty)
CausalRepID-main
scripts/ioss.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import copy import numpy as np import torch import torch.utils.data as data_utils from torchvision import datasets, transforms from sklearn.preprocessing import StandardScaler # Base Class from data.data_loader import BaseDataLoader class BallsDataLoader(): def __init__(self, data_dir='', data_case='train', observation_case= True, intervention_case=False): self.data_case= data_case self.observation_case= observation_case self.intervention_case= intervention_case self.obs_data_dir = 'data/datasets/' + data_dir + 'observation/' self.itv_data_dir = 'data/datasets/' + data_dir + 'intervention/' self.data, self.latents, self.intervention_indices= self.load_data(self.data_case) def __len__(self): return self.latents.shape[0] def __getitem__(self, index): x = self.data[index] z = self.latents[index] y= self.intervention_indices[index] data_transform= transforms.Compose([ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) x= data_transform(x) return x, z, y def load_data(self, data_case): #Note: intervention indices are being sampled as some random values for now; do not need them but for consistency with functions in metrics module x_obs= np.load(self.obs_data_dir + data_case + '_' + 'x' + '.npy') z_obs= np.load(self.obs_data_dir + data_case + '_' + 'z' + '.npy') y_obs= np.load(self.obs_data_dir + data_case + '_' + 'y' + '.npy') x_itv= np.load(self.itv_data_dir + data_case + '_' + 'x' + '.npy') z_itv= np.load(self.itv_data_dir + data_case + '_' + 'z' + '.npy') y_itv= np.load(self.itv_data_dir + data_case + '_' + 'y' + '.npy') if self.observation_case and self.intervention_case: x= np.concatenate((x_obs, x_itv), axis=0) z= np.concatenate((z_obs, z_itv), axis=0) y= np.concatenate((y_obs, y_itv), axis=0) elif self.observation_case: x= x_obs z= z_obs y= y_obs elif self.intervention_case: x= x_itv z= z_itv y= y_itv x= torch.tensor(x).float() z= torch.tensor(z).float() y= torch.tensor(y).float() # Change the dimension from (B, H, W, C) to (B, C, H ,W) x= x.permute(0, 3, 1, 2) return x, z, y
CausalRepID-main
data/balls_dataset_loader.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved #Common imports import sys import os import argparse import random import copy import math import networkx as nx import matplotlib.pyplot as plt import numpy as np from scipy import stats import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from scipy.stats import bernoulli path= os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(path) from data.dag_generator import DagGenerator def sigmoid(x): return 1 / (1 + np.exp(-x)) def compute_total_polynomial_terms(poly_degree, latent_dim): count=0 for degree in range(poly_degree+1): count+= pow(latent_dim, degree) return count def compute_kronecker_product(degree, latent): if degree ==0: out= np.array([1]) else: out=copy.deepcopy(latent) for idx in range(1, degree): out= np.kron(out, latent) # print(out.shape) return out def compute_decoder_polynomial(poly_degree, latent): out=[] for degree in range(poly_degree+1): # print('Computing polynomial term of degree ', degree) out.append(compute_kronecker_product(degree, latent)) out= np.concatenate(out) out= np.reshape(out, (1,out.shape[0])) return out def generate_latent_vector(dataset_size, latent_dim, latent_case, intervention_indices= [], intervention_case= 0, dag=None, base_dir= ''): z= np.zeros((dataset_size, latent_dim)) for i in range(latent_dim): if latent_case == 'laplace': z[:, i]= np.random.laplace(10, 5, dataset_size) elif latent_case == 'uniform': z[:, i]= np.random.uniform(low=-5, high=5, size=dataset_size) elif latent_case == 'uniform_discrete': z[:, i]= np.random.randint(10, size= dataset_size) elif latent_case == 'gaussian': z[:, i]= np.random.normal(0, 1, size= dataset_size) elif latent_case == 'special': support= np.array([0, 1]) p= 1 prob= np.exp( -1*support**p ) prob= prob/np.sum(prob) idx= np.argmax( np.random.multinomial(1, prob, size=dataset_size), axis=1 ) z[:, i]= support[idx] if latent_case == 'gaussian_corr': rho= 0.9 noise_var= np.eye(latent_dim) for i in range(latent_dim): for j in range(i+1, latent_dim): noise_var[i,j]= rho ** (np.abs(i-j)) z= np.random.multivariate_normal(np.zeros(latent_dim), noise_var, dataset_size) if latent_case == 'uniform_corr': for d_idx in range(0 , latent_dim, 2): print('Latent entries for the pair: ', d_idx, d_idx + 1) p1= bernoulli.rvs(0.5, size=dataset_size) p2= bernoulli.rvs(0.9, size=dataset_size) z_11= np.random.uniform(low=0, high=5, size=dataset_size) z_12= np.random.uniform(low=-5, high=0, size=dataset_size) z_21= np.random.uniform(low=0, high=3, size=dataset_size) z_22= np.random.uniform(low=-3, high=0, size=dataset_size) for idx in range(dataset_size): if p1[idx] == 1: z[idx, d_idx + 0]= z_11[idx] if p2[idx] == 1: z[idx, d_idx + 1]= z_21[idx] else: z[idx, d_idx + 1]= z_22[idx] else: z[idx, d_idx + 0]= z_12[idx] if p2[idx] == 1: z[idx, d_idx + 1]= z_22[idx] else: z[idx, d_idx + 1]= z_21[idx] if 'mixture' in latent_case: mix_coff= bernoulli.rvs(0.5, size=dataset_size) mix_coff= np.reshape( mix_coff, (mix_coff.shape[0], 1) ) z1= np.zeros((dataset_size, latent_dim)) z2= np.zeros((dataset_size, latent_dim)) for i in range(latent_dim): if args.latent_case == 'uniform_mixture': z1[:, i]= np.random.uniform(low=-5, high=5, size=dataset_size) z2[:, i]= np.random.uniform(low=-1, high=1, size=dataset_size) elif args.latent_case == 'gaussian_mixture': z1[:, i]= np.random.normal(0, 1, size=dataset_size) z2[:, i]= np.random.normal(1, 2, size= dataset_size) else: print('Error: Not valid latent type for a mixture model') sys.exit() z= mix_coff * z1 + (1-mix_coff) * z2 if intervention_case and 'scm' not in latent_case: for idx, intervene_idx in np.ndenumerate(intervention_indices): z[idx, intervene_idx]= 2.0 if 'scm' in latent_case: if intervention_case: latent_dict = {} for intervene_idx in range(latent_dim): dag_copy= copy.deepcopy(dag) df, obj= dag_copy.intervene(intervention_nodes= [intervene_idx], target_distribution= 'hard_intervention') latent_dict[intervene_idx]= df for idx, intervene_idx in np.ndenumerate(intervention_indices): z[idx, :]= latent_dict[intervene_idx][idx, :] else: df, obj= dag.generate() z= df.values[:dataset_size, :] nx.draw_networkx(obj, arrows=True) plt.savefig( base_dir + latent_case + '.jpg') plt.clf() return z ''' Notations: n: batch size d: latent dimension D: data dimension p: degree of polynomial q: number of terms in polynomial Dimensions: p: 2; q~ 111 z: (n, d): d= 10 x: (n, D): D= 100 -> 25 Poly(z): (n, q) Coefficient Matrix: (D, q) Ideal: D > q ''' #TODO: Throw exception when the latent case if not amongst the valid ones # Input Parsing parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=0, help='') parser.add_argument('--data_dim', type=int, default=200, help='') parser.add_argument('--latent_dim', type=int, default=10, help='') parser.add_argument('--latent_case', type=str, default='uniform', help='uniform; uniform_corr; gaussian_mixture') parser.add_argument('--poly_degree', type=int, default=2, help='') parser.add_argument('--train_size', type=int, default=10000, help='') parser.add_argument('--test_size', type=int, default=20000, help='') args = parser.parse_args() seed= args.seed data_dim= args.data_dim latent_dim= args.latent_dim latent_case= args.latent_case poly_degree= args.poly_degree train_size= args.train_size test_size= args.test_size poly_size= compute_total_polynomial_terms(poly_degree, latent_dim) print('Total Polynomial Terms: ', poly_size) #Random Seed random.seed(seed*10) np.random.seed(seed*10) coff_matrix= np.random.multivariate_normal(np.zeros(poly_size), np.eye(poly_size), size=data_dim).T print('Coeff Matrix', coff_matrix.shape) _, sng_values, _ = np.linalg.svd(coff_matrix) # print('Singular Values for Coeff Matrix: ', sng_values) #DAG #NOTE: For this configuration to work we need to have the same train and test size if latent_case == 'scm_sparse': dag= DagGenerator('linear', cause='gaussian', nodes=latent_dim, npoints= max( args.train_size, args.test_size), expected_density= 0.5) elif latent_case == 'scm_dense': dag= DagGenerator('linear', cause='gaussian', nodes=latent_dim, npoints= max( args.train_size, args.test_size), expected_density= 1.0) else: dag= None for distribution_case in ['observational', 'interventional']: for data_case in ['train', 'val', 'test']: if distribution_case == 'observational': base_dir= 'data/datasets/' + 'seed_' + str(seed) + '/observation/' elif distribution_case == 'interventional': base_dir= 'data/datasets/' + 'seed_' + str(seed) + '/intervention/' base_dir= base_dir + 'polynomial_latent_' + latent_case + '_poly_degree_' + str(poly_degree) + '_data_dim_' + str(data_dim) + '_latent_dim_' + str(latent_dim) + '/' if not os.path.exists(base_dir): os.makedirs(base_dir) print('Data Case: ', data_case) if data_case == 'train': dataset_size= args.train_size if data_case == 'val': dataset_size= int(args.train_size/4) elif data_case == 'test': dataset_size= args.test_size #Generating the latent vector if distribution_case == 'observational': y= -1 * np.ones(dataset_size) z= generate_latent_vector(dataset_size, latent_dim, latent_case, intervention_case= 0, intervention_indices= y, dag= dag, base_dir= base_dir) elif distribution_case == 'interventional': y= np.argmax(np.random.multinomial(1, [1/latent_dim]*latent_dim, dataset_size), axis=1 ) z= generate_latent_vector(dataset_size, latent_dim, latent_case, intervention_case= 1, intervention_indices= y, dag= dag, base_dir= base_dir) print('Latent Z') print(z.shape) print(z[:5]) #Transforming the latent via polynomial decoder print('Data X') x=[] for idx in range(z.shape[0]): x.append( compute_decoder_polynomial(poly_degree, z[idx, :] ) ) x= np.concatenate(x, axis=0) print(x.shape) x1= np.matmul(x[:, :1+latent_dim], coff_matrix[:1+latent_dim, :]) print('X1') print('Min', np.min(np.abs(x1)), 'Max', np.max(np.abs(x1)), 'Mean', np.mean(np.abs(x1))) x2= np.matmul(x[:, 1+latent_dim:], coff_matrix[1+latent_dim:, :]) norm_factor= 0.5 * np.max(np.abs(x2)) / np.max(np.abs(x1)) x2 = x2 / norm_factor print('X2') print('Min', np.min(np.abs(x2)), 'Max', np.max(np.abs(x2)), 'Mean', np.mean(np.abs(x2))) x= (x1+x2) print(x.shape) f= base_dir + data_case + '_' + 'x' + '.npy' np.save(f, x) f= base_dir + data_case + '_' + 'z' + '.npy' np.save(f, z) f= base_dir + data_case + '_' + 'y' + '.npy' np.save(f, y)
CausalRepID-main
data/synthetic_polynomial_dgp.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """Defining a set of classes that represent causal functions/ mechanisms. Author: Diviyan Kalainathan Modified by Philippe Brouillard, July 24th 2019 Modified by Divyat Mahajan, December 30th 2022 .. MIT License .. .. Copyright (c) 2018 Diviyan Kalainathan .. .. 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. """ import random import numpy as np from scipy.stats import bernoulli from sklearn.mixture import GaussianMixture as GMM from sklearn.metrics.pairwise import euclidean_distances from sklearn.gaussian_process import GaussianProcessRegressor import torch as th import copy class LinearMechanism(object): """Linear mechanism, where Effect = alpha*Cause + Noise.""" def __init__(self, ncauses, points, noise_function, d=4, noise_coeff=.4): """Init the mechanism.""" super(LinearMechanism, self).__init__() self.n_causes = ncauses self.points = points self.coefflist = [] self.other_coefflist = [] self.noise_coeff = noise_coeff self.noise_function = noise_function for i in range(ncauses): coeff = np.random.uniform(0.25, 1) if np.random.randint(2) == 0: coeff *= -1 self.coefflist.append(coeff) self.old_coefflist = self.coefflist[:] def parametric_intervention(self): for i,c in enumerate(self.old_coefflist): change = np.random.uniform(0.5, 1) if c > 0: coeff = c + change else: coeff = c - change self.coefflist[i] = coeff def unique_parametric_intervention(self): if len(self.other_coefflist) == 0: for i,c in enumerate(self.old_coefflist): change = np.random.uniform(2, 5) if np.random.randint(2) == 0: change *= -1 if c > 0: coeff = c + change else: coeff = c - change self.other_coefflist.append(coeff) self.coefflist = self.other_coefflist[:] def reinit(self): self.coefflist = self.old_coefflist[:] def __call__(self, causes): """Run the mechanism.""" # Additive only, for now effect = np.zeros((self.points, 1)) self.noise = self.noise_coeff * self.noise_function(self.points) # Compute each cause's contribution for par in range(causes.shape[1]): effect[:, 0] = effect[:, 0] + self.coefflist[par]*causes[:, par] effect[:, 0] = effect[:, 0] + self.noise[:, 0] return effect class SigmoidMix_Mechanism(object): def __init__(self, ncauses, points, noise_function, d=4, noise_coeff=.4): """Init the mechanism.""" super(SigmoidMix_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.a = np.random.exponential(1/4) + 1 ber = bernoulli.rvs(0.5) self.b = ber * np.random.uniform(-2, -0.5) + (1-ber)*np.random.uniform(0.5, 2) self.c = np.random.uniform(-2, 2) self.noise_coeff = noise_coeff self.noise_function = noise_function self.old_b = self.b self.old_c = self.c self.other_b = None self.other_c = None def parametric_intervention(self): change = np.random.uniform(0.5, 1) if self.b <= -0.5: self.b -= change else: self.b += change change = np.random.uniform(-1, 1) self.c += change def unique_parametric_intervention(self): if self.other_b is None and self.other_c is None: self.parametric_intervention() self.other_b = self.b self.other_c = self.c self.b = self.other_b self.c = self.other_c def reinit(self): self.b = self.old_b self.c = self.old_c def mechanism(self, causes): """Mechanism function.""" self.noise = self.noise_coeff * self.noise_function(self.points) result = np.zeros((self.points, 1)) for i in range(self.points): pre_add_effect = 0 for c in range(causes.shape[1]): pre_add_effect += causes[i, c] pre_add_effect += self.noise[i] result[i, 0] = self.a * self.b * \ (pre_add_effect + self.c)/(1 + abs(self.b*(pre_add_effect + self.c))) return result def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) # Compute each cause's contribution effect[:, 0] = self.mechanism(causes)[:, 0] return effect class SigmoidAM_Mechanism(object): def __init__(self, ncauses, points, noise_function, d=4, noise_coeff=.4): """Init the mechanism.""" super(SigmoidAM_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.a = np.random.exponential(1/4) + 1 ber = bernoulli.rvs(0.5) self.b = ber * np.random.uniform(-2, -0.5) + (1-ber)*np.random.uniform(0.5, 2) self.c = np.random.uniform(-2, 2) self.noise_coeff = noise_coeff self.noise_function = noise_function self.old_b = self.b self.old_c = self.c self.other_b = None self.other_c = None def mechanism(self, x): """Mechanism function.""" result = np.zeros((self.points, 1)) for i in range(self.points): result[i, 0] = self.a * self.b * (x[i] + self.c) / (1 + abs(self.b * (x[i] + self.c))) return result def __call__(self, causes): """Run the mechanism.""" # Additive only self.noise = self.noise_coeff * self.noise_function(self.points) effect = np.zeros((self.points, 1)) # Compute each cause's contribution for par in range(causes.shape[1]): effect[:, 0] = effect[:, 0] + self.mechanism(causes[:, par])[:, 0] effect[:, 0] = effect[:, 0] + self.noise[:, 0] return effect class ANM_Mechanism(object): def __init__(self, ncauses, points, noise_function, noise_coeff=.4): """Init the mechanism.""" super(ANM_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.noise_function = noise_function self.noise_coeff = noise_coeff self.nb_step = 0 def mechanism(self, x): """Mechanism function.""" self.nb_step += 1 x = np.reshape(x, (x.shape[0], x.shape[1])) if(self.nb_step == 1): cov = computeGaussKernel(x) mean = np.zeros((1, self.points))[0, :] y = np.random.multivariate_normal(mean, cov) self.gpr = GaussianProcessRegressor() self.gpr.fit(x, y) else: y = self.gpr.predict(x) return y def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) self.noise = self.noise_coeff * self.noise_function(self.points) # Compute each cause's contribution if(causes.shape[1] > 0): effect[:, 0] = self.mechanism(causes) else: effect[:, 0] = self.mechanism(self.noise) effect[:, 0] = effect[:, 0] + self.noise[:, 0] return effect class NN_Mechanism_Add(object): def __init__(self, ncauses, points, noise_function, nh=10, noise_coeff=.4): """Init the mechanism.""" super(NN_Mechanism_Add, self).__init__() self.n_causes = ncauses self.points = points self.noise_coeff = noise_coeff self.noise_function = noise_function self.nb_step = 0 self.nh = nh self.layers = self.initialize() self.old_layers = copy.deepcopy(self.layers) self.other_layers = None def weight_init(self, model): if isinstance(model, th.nn.modules.Linear): th.nn.init.normal_(model.weight.data, mean=0., std=1) def initialize(self): """Mechanism function.""" layers = [] layers.append(th.nn.modules.Linear(self.n_causes, self.nh)) layers.append(th.nn.PReLU()) layers.append(th.nn.modules.Linear(self.nh, 1)) layers = th.nn.Sequential(*layers) layers.apply(self.weight_init) return layers def parametric_intervention(self): for i,layer in enumerate(self.layers): if isinstance(layer, th.nn.modules.Linear): with th.no_grad(): layer.weight += th.empty_like(layer.weight).normal_(mean=0, std=.1) def unique_parametric_intervention(self): if self.other_layers is None: self.other_layers = copy.deepcopy(self.layers) for i,layer in enumerate(self.other_layers): if isinstance(layer, th.nn.modules.Linear) and i > 0: with th.no_grad(): layer.weight += th.empty_like(layer.weight).normal_(mean=0, std=1) self.layers = copy.deepcopy(self.other_layers) def reinit(self): self.layers = copy.deepcopy(self.old_layers) def apply_nn(self, x): data = x.astype('float32') data = th.from_numpy(data) return np.reshape(self.layers(data).data, (x.shape[0],)) def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) self.noise = self.noise_coeff * self.noise_function(self.points) # Compute each cause's contribution if (causes.shape[1] > 0): effect[:, 0] = self.apply_nn(causes) else: print("abnormal") effect[:, 0] = effect[:, 0] + self.noise[:, 0] return effect class NN_Mechanism(object): def __init__(self, ncauses, points, noise_function, nh=20, noise_coeff=.4): """Init the mechanism.""" super(NN_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.noise_coeff = noise_coeff self.noise_function = noise_function self.nb_step = 0 self.nh = nh self.layers = self.initialize() self.old_layers = copy.deepcopy(self.layers) self.other_layers = None def weight_init(self, model): if isinstance(model, th.nn.modules.Linear): th.nn.init.normal_(model.weight.data, mean=0., std=1) def initialize(self): """Mechanism function.""" layers = [] layers.append(th.nn.modules.Linear(self.n_causes+1, self.nh)) layers.append(th.nn.Tanh()) layers.append(th.nn.modules.Linear(self.nh, 1)) layers = th.nn.Sequential(*layers) layers.apply(self.weight_init) return layers def parametric_intervention(self): for i,layer in enumerate(self.layers): if isinstance(layer, th.nn.modules.Linear): with th.no_grad(): layer.weight += th.empty_like(layer.weight).normal_(mean=0, std=.1) def unique_parametric_intervention(self): if self.other_layers is None: self.other_layers = copy.deepcopy(self.layers) for i,layer in enumerate(self.other_layers): if isinstance(layer, th.nn.modules.Linear) and i > 0: with th.no_grad(): layer.weight += th.empty_like(layer.weight).normal_(mean=0, std=1) self.layers = copy.deepcopy(self.other_layers) def reinit(self): self.layers = copy.deepcopy(self.old_layers) def apply_nn(self, x): data = x.astype('float32') data = th.from_numpy(data) return np.reshape(self.layers(data).data, (x.shape[0],)) def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) self.noise = self.noise_coeff * self.noise_function(self.points) # Compute each cause's contribution if (causes.shape[1] > 0): mix = np.hstack((causes, self.noise)) effect[:, 0] = self.apply_nn(mix) else: effect[:, 0] = self.apply_nn(self.noise) return effect # === Multimodal Mechanisms === class Multimodal_X_Mechanism(object): """Mecanism with multimodal distribution: usually a combination of multiple functions""" def __init__(self, ncauses, points, noise_function, d=4, noise_coeff=.4): """Init the mechanism.""" super(Multimodal_X_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.coefflist = [] self.other_coefflist = [] self.noise_coeff = noise_coeff self.noise_function = noise_function for i in range(ncauses): coeff = np.random.uniform(0.5, 1) if np.random.randint(2) == 0: coeff *= -1 self.coefflist.append(coeff) self.old_coefflist = self.coefflist[:] def parametric_intervention(self): for i,c in enumerate(self.old_coefflist): change = np.random.uniform(0.5, 1) if c > 0: coeff = c + change else: coeff = c - change self.coefflist[i] = coeff def unique_parametric_intervention(self): if len(self.other_coefflist) == 0: for i,c in enumerate(self.old_coefflist): change = np.random.uniform(0.5, 1) if c > 0: coeff = c + change else: coeff = c - change self.other_coefflist.append(coeff) self.coefflist = self.other_coefflist[:] def reinit(self): self.coefflist = self.old_coefflist[:] def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) self.noise = self.noise_coeff * self.noise_function(self.points) selector = np.random.choice([-1,1], size=self.points) # Compute each cause's contribution for par in range(causes.shape[1]): for i, sel in enumerate(selector): effect[i, 0] = effect[i, 0] + sel*self.coefflist[par]*causes[i, par] effect[:, 0] = effect[:, 0] + self.noise[:, 0] return effect class Multimodal_Circle_Mechanism(object): def __init__(self, ncauses, points, noise_function, d=4, noise_coeff=.4): """Init the mechanism.""" super(Multimodal_Circle_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.noise_coeff = noise_coeff self.noise_function = noise_function self.sin_scale = np.random.uniform(0.5, 1.5) #1 self.period = np.random.uniform(0.5, 1.5) #1 self.phase_shift = np.pi/2 # make copy of initial parameters self.old_sin_scale = self.sin_scale self.old_period = self.period self.old_phase_shift = self.phase_shift self.other_sin_scale = None self.other_period = None self.other_phase_shift = None def parametric_intervention(self): change = np.random.uniform(0.5, 1.5) self.sin_scale = self.old_phase_shift self.period = np.random.uniform(0.5, 1.5) #1 self.phase_shift = np.pi/2 def unique_parametric_intervention(self): if self.other_sin_scale is None: self.parametric_intervention() self.other_sin_scale = self.sin_scale self.other_period = self.period self.other_phase_shift = self.phase_shift self.sin_scale = self.other_sin_scale self.period = self.other_period self.phase_shift = self.other_phase_shift def reinit(self): self.sin_scale = self.old_sin_scale self.period = self.old_period self.phase_shift = self.old_phase_shift def mechanism(self, sel, x): if sel: sin_scale = -self.sin_scale else: sin_scale = self.sin_scale return sin_scale * np.sin(self.period * (x + self.phase_shift)) def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) self.noise = self.noise_coeff * self.noise_function(self.points) selector = np.random.choice([0,1], size=self.points) # Compute each cause's contribution for par in range(causes.shape[1]): for i, sel in enumerate(selector): effect[i, 0] = effect[i, 0] + self.mechanism(sel, causes[i, par]) effect[:, 0] = effect[:, 0] + self.noise[:, 0] return effect class Multimodal_ADN_Mechanism(object): def __init__(self, ncauses, points, noise_function, d=4, noise_coeff=.4): """Init the mechanism.""" super(Multimodal_ADN_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.noise_coeff = noise_coeff self.noise_function = noise_function self.sin_scale = np.random.uniform(0.5, 1.5) #1 self.period = np.random.uniform(1, 2) #1 self.phase_shift = np.pi/2 # make copy of initial parameters self.old_sin_scale = self.sin_scale self.old_period = self.period self.old_phase_shift = self.phase_shift self.other_sin_scale = None self.other_period = None self.other_phase_shift = None def parametric_intervention(self): # change = np.random.uniform(1, 2) self.sin_scale = self.old_phase_shift change = np.random.uniform(1, 2) self.period = self.old_period + change self.phase_shift = np.pi/2 def unique_parametric_intervention(self): if self.other_sin_scale is None: self.parametric_intervention() self.other_sin_scale = self.sin_scale self.other_period = self.period self.other_phase_shift = self.phase_shift self.sin_scale = self.other_sin_scale self.period = self.other_period self.phase_shift = self.other_phase_shift def reinit(self): self.sin_scale = self.old_sin_scale self.period = self.old_period self.phase_shift = self.old_phase_shift def mechanism(self, sel, x): if sel: sin_scale = -self.sin_scale else: sin_scale = self.sin_scale return sin_scale * np.sin(self.period * (x + self.phase_shift)) def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) self.noise = self.noise_coeff * self.noise_function(self.points) selector = np.random.choice([0,1], size=self.points) # Compute each cause's contribution for par in range(causes.shape[1]): for i, sel in enumerate(selector): effect[i, 0] = effect[i, 0] + self.mechanism(sel, causes[i, par]) effect[:, 0] = effect[:, 0] + self.noise[:, 0] return effect class Function_Template: def __init__(self, sign, slope, intercept, sin_scale, period, phase_shift): self.sign = sign self.slope = slope self.intercept = intercept self.sin_scale = sin_scale self.period = period self.phase_shift = phase_shift def __call__(self, x): return self.sign*self.slope*x + self.intercept \ + self.sin_scale*np.sin(self.period*(x + self.phase_shift)) # ==================================== class Polynomial_Mechanism(object): def __init__(self, ncauses, points, noise_function, d=2, noise_coeff=.4): """Init the mechanism.""" super(Polynomial_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.d = d self.polycause = [] for c in range(ncauses): self.coefflist = [] for j in range(self.d + 1): self.coefflist.append(random.random()) self.polycause.append(self.coefflist) self.ber = bernoulli.rvs(0.5) self.noise = noise_coeff * noise_function(points) def mechanism(self, x, par): """Mechanism function.""" list_coeff = self.polycause[par] result = np.zeros((self.points, 1)) for i in range(self.points): for j in range(self.d+1): result[i, 0] += list_coeff[j]*np.power(x[i], j) result[i, 0] = min(result[i, 0], 1) result[i, 0] = max(result[i, 0], -1) return result def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) # Compute each cause's contribution for par in range(causes.shape[1]): effect[:, 0] = effect[:, 0] + self.mechanism(causes[:, par], par)[:, 0] if(self.ber > 0 and causes.shape[1] > 0): effect[:, 0] = effect[:, 0] * self.noise[:, 0] else: effect[:, 0] = effect[:, 0] + self.noise[:, 0] return effect def computeGaussKernel(x): """Compute the gaussian kernel on a 1D vector.""" xnorm = np.power(euclidean_distances(x, x), 2) return np.exp(-xnorm / (2.0)) class GaussianProcessAdd_Mechanism(object): def __init__(self, ncauses, points, noise_function, noise_coeff=.4): """Init the mechanism.""" super(GaussianProcessAdd_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.noise = noise_coeff * noise_function(points) self.nb_step = 0 def mechanism(self, x): """Mechanism function.""" self.nb_step += 1 x = np.reshape(x, (x.shape[0], 1)) cov = computeGaussKernel(x) mean = np.zeros((1, self.points))[0, :] y = np.random.multivariate_normal(mean, cov) # if(self.nb_step < 5): # cov = computeGaussKernel(x) # mean = np.zeros((1, self.points))[0, :] # y = np.random.multivariate_normal(mean, cov) # elif(self.nb_step == 5): # cov = computeGaussKernel(x) # mean = np.zeros((1, self.points))[0, :] # y = np.random.multivariate_normal(mean, cov) # self.gpr = GaussianProcessRegressor() # self.gpr.fit(x, y) # y = self.gpr.predict(x) # else: # y = self.gpr.predict(x) return y def __call__(self, causes): """Run the mechanism.""" # Additive only effect = np.zeros((self.points, 1)) # Compute each cause's contribution for par in range(causes.shape[1]): effect[:, 0] = effect[:, 0] + self.mechanism(causes[:, par]) effect[:, 0] = effect[:, 0] + self.noise[:, 0] return effect class GaussianProcessMix_Mechanism(object): def __init__(self, ncauses, points, noise_function, noise_coeff=.4): """Init the mechanism.""" super(GaussianProcessMix_Mechanism, self).__init__() self.n_causes = ncauses self.points = points self.noise = noise_coeff * noise_function(points) self.nb_step = 0 def mechanism(self, x): """Mechanism function.""" self.nb_step += 1 x = np.reshape(x, (x.shape[0], x.shape[1])) if(self.nb_step < 2): cov = computeGaussKernel(x) mean = np.zeros((1, self.points))[0, :] y = np.random.multivariate_normal(mean, cov) elif(self.nb_step == 2): cov = computeGaussKernel(x) mean = np.zeros((1, self.points))[0, :] y = np.random.multivariate_normal(mean, cov) self.gpr = GaussianProcessRegressor() self.gpr.fit(x, y) y = self.gpr.predict(x) else: y = self.gpr.predict(x) return y def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) # Compute each cause's contribution if(causes.shape[1] > 0): mix = np.hstack((causes, self.noise)) effect[:, 0] = self.mechanism(mix) else: effect[:, 0] = self.mechanism(self.noise) return effect class pnl_gp_mechanism(object): """ Post-Nonlinear model using a GP with additive noise. The second non-linearity is a sigmoid """ def __init__(self, ncauses, points, noise_function, noise_coeff=.4): """Init the mechanism.""" super(pnl_gp_mechanism, self).__init__() self.n_causes = ncauses self.points = points self.noise = noise_coeff * noise_function(points) self.nb_step = 0 self.f2 = lambda x: 1 / (1 + np.exp(-x)) def mechanism(self, x): """Mechanism function.""" self.nb_step += 1 x = np.reshape(x, (x.shape[0], x.shape[1])) if(self.nb_step == 1): cov = computeGaussKernel(x) mean = np.zeros((1, self.points))[0, :] y = np.random.multivariate_normal(mean, cov) self.gpr = GaussianProcessRegressor() self.gpr.fit(x, y) y = self.gpr.predict(x) else: y = self.gpr.predict(x) return y def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) # Compute each cause's contribution if(causes.shape[1] > 0): effect[:, 0] = self.mechanism(causes) effect[:, 0] = effect[:, 0] + self.noise[:, 0] else: effect[:, 0] = self.mechanism(self.noise) effect[:, 0] = self.f2(effect[:, 0]) return effect class pnl_mult_mechanism(object): """ Post-Nonlinear model using a exp and log as the non-linearities. This results in a multiplicative model. """ def __init__(self, ncauses, points, noise_function, noise_coeff=.4): """Init the mechanism.""" super(pnl_mult_mechanism, self).__init__() self.n_causes = ncauses self.points = points self.noise_function = noise_function self.noise_coeff = noise_coeff self.f1 = lambda x: np.log(np.sum(x, axis=1)) self.f2 = lambda x: np.exp(x) def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) self.noise = self.noise_coeff * self.noise_function(self.points) # Compute each cause's contribution if(causes.shape[1] > 0): effect[:, 0] = self.f1(causes) #[:, 0] else: effect[:, 0] = self.f1(self.noise) effect[:, 0] = effect[:, 0] + self.noise[:, 0] effect[:, 0] = self.f2(effect[:, 0]) return effect class PostNonLinear_Mechanism: def __init__(self, ncauses, points, noise_function, f1=None, f2=None, noise_coeff=.4): self.gp = GaussianProcessAdd_Mechanism(ncauses, points, noise_function, noise_coeff=0) self.points = points self.noise = noise_coeff * noise_function(points) self.f1 = f1 self.f2 = f2 if f1 is None and f2 is None: raise ValueError("f1 and f2 have to de defined!") elif f1 is None and f2 is not None: self.f1 = self.gp def __call__(self, causes): """Run the mechanism.""" effect = np.zeros((self.points, 1)) # Compute each cause's contribution if(causes.shape[1] > 0): effect[:, 0] = self.f1(causes)[:,0] # mult [:, 0] else: effect[:, 0] = self.f1(self.noise) effect[:, 0] = effect[:, 0] + self.noise[:, 0] effect[:, 0] = self.f2(effect[:, 0]) return effect def gmm_cause(points, k=4, p1=2, p2=2): """Init a root cause with a Gaussian Mixture Model w/ a spherical covariance type.""" g = GMM(k, covariance_type="spherical") g.fit(np.random.randn(300, 1)) g.means_ = p1 * np.random.randn(k, 1) g.covars_ = np.power(abs(p2 * np.random.randn(k, 1) + 1), 2) g.weights_ = abs(np.random.rand(k)) g.weights_ = g.weights_ / sum(g.weights_) return g.sample(points)[0].reshape(-1) def gaussian_cause(points): """Init a root cause with a Gaussian.""" return np.random.randn(points, 1)[:, 0] def variable_gaussian_cause(points): """Init a root cause with a Gaussian. Similar to gaussian_cause but have variable variance. Identical to J.Peters with default value (set noise_coeff=0.2)""" # + np.random.rand(points, 1)[:, 0] - 1 return np.sqrt(np.random.rand(1) + 1) * np.random.randn(points, 1)[:, 0] def uniform_cause(points): """Init a root cause with a uniform.""" return np.random.rand(points, 1)[:, 0] * 2 - 1 def uniform_cause_positive(points): """Init a root cause with a uniform.""" return np.random.rand(points, 1)[:, 0] * 2 def normal_noise(points): """Init a normal noise variable.""" return np.random.rand(1) * np.random.randn(points, 1) \ + random.sample([2, -2], 1) def variable_normal_noise(points): """Init a normal noise variable. Similar to normal_noise but make sure to have at least a std of 1. Identical to J.Peters with default value (set noise_coeff=0.2)""" return np.sqrt(np.random.rand(1) + 1) * np.random.randn(points, 1) def absolute_gaussian_noise(points): """Init an absolute normal noise variable.""" return np.abs(np.random.rand(points, 1) * np.random.rand(1)) def laplace_noise(points): """Init a Laplace noise variable.""" lambda_ = np.random.rand(1) return np.random.laplace(0, lambda_, (points, 1)) def uniform_noise(points): """Init a uniform noise variable.""" return np.random.rand(1) * np.random.uniform(size=(points, 1)) \ + random.sample([2, -2], 1) class NormalCause(object): def __init__(self, mean=0, std=1, std_min=None, std_max=None): self.mean = mean if std_min is None and std_max is None: self.std = std else: self.std = np.random.uniform(std_min, std_max) def __call__(self, points): return np.random.normal(self.mean, self.std, \ size=(points)) class UniformCause(object): def __init__(self, _min=-1, _max=1): self._min = _min self._max = _max def __call__(self, points): return np.random.uniform(self._min, self._max, size=(points)) class HardIntervention(object): def __init__(self, _val): self._val = _val def __call__(self, points): return self._val * np.ones(points) class nn_noise(object): def __init__(self, noise=variable_normal_noise, n_hidden=20): """Init the mechanism.""" super(nn_noise, self).__init__() self.noise = noise self.n_hidden = n_hidden self.initialize_nn() def initialize_nn(self): layers = [] layers.append(th.nn.modules.Linear(1, self.n_hidden)) layers.append(th.nn.Tanh()) layers.append(th.nn.modules.Linear(self.n_hidden, 1)) self.layers = th.nn.Sequential(*layers) # use a normal initialization # self.layers.apply(self.weight_init) def weight_init(self, model): if isinstance(model, th.nn.modules.Linear): th.nn.init.normal_(model.weight.data, mean=0., std=0.5) def __call__(self, points): x = self.noise(points) data = x.astype('float32') data = th.from_numpy(data) data = self.layers(data).data.numpy() return data
CausalRepID-main
data/causal_mechanisms.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import copy import numpy as np import torch import torch.utils.data as data_utils from torchvision import datasets, transforms class BaseDataLoader(data_utils.Dataset): def __init__(self, data_dir='', data_case='train', seed= 0, observation_case= True, intervention_case=False): self.data_case= data_case self.seed= seed self.obs_data_dir = 'data/datasets/' + 'seed_' + str(seed) + '/observation/' + data_dir self.itv_data_dir = 'data/datasets/' + 'seed_' + str(seed) + '/intervention/' + data_dir self.observation_case= observation_case self.intervention_case= intervention_case self.data, self.latents, self.intervention_indices= self.load_data(self.data_case) def __len__(self): return self.latents.shape[0] def __getitem__(self, index): x = self.data[index] z = self.latents[index] y= self.intervention_indices[index] return x, z, y def load_data(self, data_case): x_obs= np.load(self.obs_data_dir + data_case + '_' + 'x' + '.npy') z_obs= np.load(self.obs_data_dir + data_case + '_' + 'z' + '.npy') y_obs= np.load(self.obs_data_dir + data_case + '_' + 'y' + '.npy') x_itv= np.load(self.itv_data_dir + data_case + '_' + 'x' + '.npy') z_itv= np.load(self.itv_data_dir + data_case + '_' + 'z' + '.npy') y_itv= np.load(self.itv_data_dir + data_case + '_' + 'y' + '.npy') if self.observation_case and self.intervention_case: x= np.concatenate((x_obs, x_itv), axis=0) z= np.concatenate((z_obs, z_itv), axis=0) y= np.concatenate((y_obs, y_itv), axis=0) elif self.observation_case: x= x_obs z= z_obs y= y_obs elif self.intervention_case: x= x_itv y= y_itv z= z_itv x= torch.tensor(x).float() z= torch.tensor(z).float() y= torch.tensor(y).float() return x, z, y
CausalRepID-main
data/data_loader.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import random import argparse import torch import numpy as np import pygame from pygame import gfxdraw, init from typing import Callable, Optional from matplotlib import pyplot as plt if "SDL_VIDEODRIVER" not in os.environ: os.environ["SDL_VIDEODRIVER"] = "dummy" COLOURS_ = [ [2, 156, 154], [222, 100, 100], [149, 59, 123], [74, 114, 179], [27, 159, 119], [218, 95, 2], [117, 112, 180], [232, 41, 139], [102, 167, 30], [231, 172, 2], [167, 118, 29], [102, 102, 102], ] SCREEN_DIM = 64 def circle( x_, y_, surf, color=(204, 204, 0), radius=0.1, screen_width=SCREEN_DIM, y_shift=0.0, offset=None, ): if offset is None: offset = screen_width / 2 scale = screen_width x = scale * x_ + offset y = scale * y_ + offset gfxdraw.aacircle( surf, int(x), int(y - offset * y_shift), int(radius * scale), color ) gfxdraw.filled_circle( surf, int(x), int(y - offset * y_shift), int(radius * scale), color ) class Balls(torch.utils.data.Dataset): ball_rad = 2.0*0.04 screen_dim = 64 def __init__( self, transform: Optional[Callable] = None, n_balls: int = 1, ): super(Balls, self).__init__() if transform is None: def transform(x): return x self.transform = transform pygame.init() self.screen = pygame.display.set_mode((self.screen_dim, self.screen_dim)) self.surf = pygame.Surface((self.screen_dim, self.screen_dim)) self.n_balls = n_balls def __len__(self) -> int: # arbitrary since examples are generated online. return 20000 def draw_scene(self, z): self.surf.fill((255, 255, 255)) if z.ndim == 1: z = z.reshape((1, 2)) for i in range(z.shape[0]): circle( z[i, 0], z[i, 1], self.surf, color=COLOURS_[i], radius=self.ball_rad, screen_width=self.screen_dim, y_shift=0.0, offset=0.0, ) self.surf = pygame.transform.flip(self.surf, False, True) self.screen.blit(self.surf, (0, 0)) return np.transpose( np.array(pygame.surfarray.pixels3d(self.screen)), axes=(1, 0, 2) ) def __getitem__(self, item): raise NotImplemented() class BlockOffset(Balls): def __init__( self, transform: Optional[Callable] = None, n_balls: int = 2, interventions_per_latent: int = 3, latent_case: str = 'iid', scm_mechanism: str = None, ): super().__init__(transform=transform, n_balls=n_balls) self.dataset_size= 20000 self.latent_dim= self.n_balls*2 self.intervention_case= 0 self.intervene_all_latent= 1 self.interventions_per_latent= interventions_per_latent self.latent_case= latent_case self.scm_mechanism= scm_mechanism def __getitem__(self, item): if self.latent_case == 'iid': z = self.get_observational_data_iid() elif self.latent_case == 'scm': z = self.get_observational_data_scm() else: print('Latent type not supported') sys.exit() y = -1*np.ones(2) if self.intervention_case: z= z.flatten() if self.intervene_all_latent: intervene_idx= np.random.randint(self.latent_dim, size=1) else: intervene_idx= 0 if self.interventions_per_latent > 1: intervene_range= np.linspace(0.25, 0.75, num= self.interventions_per_latent) intervene_val= [np.random.choice(intervene_range)] elif self.interventions_per_latent == 1: intervene_val= [0.5] if self.latent_case == 'iid': z= self.get_interventional_data_iid(z, intervene_idx, intervene_val) elif self.latent_case == 'scm': z= self.get_interventional_data_scm(z, intervene_idx, intervene_val) else: print('Latent type not supported') sys.exit() y[0]= intervene_idx y[1]= intervene_val[0] x = self.draw_scene(z) x = self.transform(x) return z.flatten(), y, x def get_observational_data_iid(self): z= np.random.uniform(0.1, 0.9, size=(self.n_balls, 2)) return z def get_interventional_data_iid(self, z, intervene_idx, intervene_val): z[intervene_idx]= intervene_val z= np.reshape(z, (self.n_balls, 2)) return z def get_observational_data_scm(self, x1=None, y1=None): if x1 is None: x1= np.random.uniform(0.1, 0.9, size=1)[0] if y1 is None: y1= np.random.uniform(0.1, 0.9, size=1)[0] if self.scm_mechanism == 'linear': constraint= x1+y1 elif self.scm_mechanism == 'non_linear': constraint= 1.25 * (x1**2 + y1**2) if constraint >= 1.0: x2= np.random.uniform(0.1, 0.5, size=1)[0] y2= np.random.uniform(0.5, 0.9, size=1)[0] else: x2= np.random.uniform(0.5, 0.9, size=1)[0] y2= np.random.uniform(0.1, 0.5, size=1)[0] z= np.array([[x1, y1], [x2, y2]]) return z def get_interventional_data_scm(self, z, intervene_idx, intervene_val): # Internvetion on the child Ball (Ball 2) if intervene_idx in [2, 3]: z[intervene_idx]= intervene_val z= np.reshape(z, (self.n_balls, 2)) # Internvetion on the parent Ball (Ball 1) elif intervene_idx == 0: z= self.get_observational_data_scm(x1= intervene_val[0], y1= z[1]) elif intervene_idx == 1: z= self.get_observational_data_scm(x1= z[0], y1= intervene_val[0]) return z # Input Parsing parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=1, help='') parser.add_argument('--train_size', type=int, default=20000, help='') parser.add_argument('--test_size', type=int, default=20000, help='') parser.add_argument('--distribution_case', type=str, default='observation', help='observation; intervention') parser.add_argument('--latent_case', type=str, default='iid', help='iid; scm') parser.add_argument('--scm_mechanism', type=str, default='linear', help='linear; non_linear') parser.add_argument('--interventions_per_latent', type= int, default=3, help='') args = parser.parse_args() seed= args.seed train_size= args.train_size test_size= args.test_size distribution_case= args.distribution_case latent_case= args.latent_case scm_mechanism= args.scm_mechanism interventions_per_latent= args.interventions_per_latent #Random Seed random.seed(seed*10) np.random.seed(seed*10) data_obj= BlockOffset(interventions_per_latent= interventions_per_latent, latent_case= latent_case, scm_mechanism= scm_mechanism) if distribution_case == 'observation': data_obj.intervention_case= 0 elif distribution_case == 'intervention': data_obj.intervention_case= 1 for data_case in ['train', 'val', 'test']: base_dir= 'data/datasets/balls_' + latent_case + '_' + scm_mechanism + '/' + str(distribution_case) + '/' if not os.path.exists(base_dir): os.makedirs(base_dir) print('Distribution Case: ', distribution_case, 'Data Case: ', data_case) if data_case == 'train': dataset_size= args.train_size if data_case == 'val': dataset_size= int(args.train_size/4) elif data_case == 'test': dataset_size= args.test_size count=0 final_z= [] final_y= [] final_x= [] for batch_idx, (z, y, x) in enumerate(data_obj): z= np.expand_dims(z, axis= 0) y= np.expand_dims(y, axis= 0) x= np.expand_dims(x, axis= 0) final_z.append(z) final_y.append(y) final_x.append(x) count+=1 if count >= dataset_size: break final_z= np.concatenate(final_z, axis=0) final_y= np.concatenate(final_y, axis=0) final_x= np.concatenate(final_x, axis=0) print(final_z.shape, final_y.shape, final_x.shape) print(final_z[:5]) print(final_y[:5]) f= base_dir + data_case + '_' + 'x' + '.npy' np.save(f, final_x) f= base_dir + data_case + '_' + 'z' + '.npy' np.save(f, final_z) f= base_dir + data_case + '_' + 'y' + '.npy' np.save(f, final_y)
CausalRepID-main
data/balls_dataset.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ DAG Generator. Generates a dataset out of an acyclic FCM. Author : Olivier Goudet and Diviyan Kalainathan Modified by Philippe Brouillard, June 25th 2019 Modified by Divyat Mahajan, December 30th 2022 .. MIT License .. .. Copyright (c) 2018 Diviyan Kalainathan .. .. 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. """ import os from sklearn.preprocessing import scale import numpy as np import pandas as pd import networkx as nx from cdt.metrics import get_CPDAG from data.causal_mechanisms import (LinearMechanism, Polynomial_Mechanism, SigmoidAM_Mechanism, SigmoidMix_Mechanism, GaussianProcessAdd_Mechanism, GaussianProcessMix_Mechanism, ANM_Mechanism, NN_Mechanism, NN_Mechanism_Add, pnl_gp_mechanism, pnl_mult_mechanism, PostNonLinear_Mechanism, Multimodal_X_Mechanism, Multimodal_Circle_Mechanism, Multimodal_ADN_Mechanism, gmm_cause, gaussian_cause, variable_gaussian_cause, uniform_cause, uniform_cause_positive, laplace_noise, normal_noise, uniform_noise, nn_noise, absolute_gaussian_noise, variable_normal_noise, NormalCause, UniformCause, HardIntervention) class DagGenerator: """Generate an DAG and data given a causal mechanism. Args: causal_mechanism (str): currently implemented mechanisms: ['linear', 'polynomial', 'sigmoid_add', 'sigmoid_mix', 'gp_add', 'gp_mix', 'nn']. noise (str or function): type of noise to use in the generative process ('gaussian', 'uniform' or a custom noise function). noise_coeff (float): Proportion of noise in the mechanisms. initial_variable_generator (function): Function used to init variables of the graph, defaults to a Gaussian Mixture model. npoints (int): Number of data points to generate. nodes (int): Number of nodes in the graph to generate. expected_density (int): Expected number of edge per node. """ def __init__(self, causal_mechanism, noise='gaussian', noise_coeff=.4, cause=gaussian_cause, npoints=500, nodes=8, expected_density=3, dag_type='erdos', rescale=False, f1=None, f2=None): super().__init__() self.mechanism = {'linear': LinearMechanism, 'polynomial': Polynomial_Mechanism, 'sigmoid_add': SigmoidAM_Mechanism, 'sigmoid_mix': SigmoidMix_Mechanism, 'gp_add': GaussianProcessAdd_Mechanism, 'gp_mix': GaussianProcessMix_Mechanism, 'anm': ANM_Mechanism, 'nn': NN_Mechanism, 'nn_add': NN_Mechanism_Add, 'pnl_gp_mechanism': pnl_gp_mechanism, 'pnl_mult_mechanism': pnl_mult_mechanism, 'x': Multimodal_X_Mechanism, 'circle': Multimodal_Circle_Mechanism, 'adn': Multimodal_ADN_Mechanism, 'post_nonlinear': PostNonLinear_Mechanism }[causal_mechanism] self.causal_mechanism = causal_mechanism self.positive = False self.rescale = rescale self.data = pd.DataFrame(None, columns=["V{}".format(i) for i in range(nodes)]) self.nodes = nodes self.npoints = npoints try: self.initial_generator = {'gmm_cause': gmm_cause, 'gaussian': gaussian_cause, 'variable_gaussian': variable_gaussian_cause, 'uniform': uniform_cause, 'uniform_positive': uniform_cause_positive}[cause] except KeyError: print('This type of cause does not exist') self.initial_generator = cause try: self.noise = {'gaussian': normal_noise, 'variable_gaussian': variable_normal_noise, 'uniform': uniform_noise, 'laplace': laplace_noise, 'absolute_gaussian': absolute_gaussian_noise, 'nn': nn_noise(variable_normal_noise)}[noise] except KeyError: print('This type of noise does not exist') self.noise = noise self.noise_coeff = noise_coeff self.adjacency_matrix = np.zeros((nodes, nodes)) self.expected_density = expected_density self.dag_type = dag_type self.cfunctions = None self.g = None self.f1 = f1 self.f2 = f2 # Constraints on PNL models to make sure they are identifiable if self.causal_mechanism == 'pnl_gp_mechanism': self.noise = laplace_noise print('Forcing noise to be laplacian') elif self.causal_mechanism == 'pnl_mult_mechanism': self.noise = absolute_gaussian_noise initial_variable_generator = uniform_cause_positive self.positive = True print('Forcing noise to be an absolute Gaussian and cause to be uniform with positive support') def estimate_expected_density(self, n=100): """ Estimate the expected density(number of edge per node) of a graph generation by generating multiple graphes Args: n: number of graph generated to estimate the density """ estimated_density = 0. for i in range(n): self.adjacency_matrix = np.zeros((self.nodes, self.nodes)) self.generate_dag() estimated_density += np.sum(self.adjacency_matrix) return estimated_density/(n * self.nodes) def generate_dag(self): """ Create the structure of the graph """ if self.dag_type == 'erdos': nb_edges = self.expected_density * self.nodes self.prob_connection = 2 * nb_edges/(self.nodes**2 - self.nodes) self.causal_order = np.random.permutation(np.arange(self.nodes)) for i in range(self.nodes - 1): node = self.causal_order[i] possible_parents = self.causal_order[(i+1):] num_parents = np.random.binomial(n=self.nodes - i - 1, p=self.prob_connection) parents = np.random.choice(possible_parents, size=num_parents, replace=False) self.adjacency_matrix[parents,node] = 1 elif self.dag_type == 'default': for j in range(1, self.nodes): nb_parents = np.random.randint(0, min([self.parents_max, j])+1) for i in np.random.choice(range(0, j), nb_parents, replace=False): self.adjacency_matrix[i, j] = 1 try: self.g = nx.DiGraph(self.adjacency_matrix) assert not list(nx.simple_cycles(self.g)) except AssertionError: if verbose: print("Regenerating, graph non valid...") self.generate_dag() self.original_adjacency_matrix = np.copy(self.adjacency_matrix) def change_npoints(self, npoints): self.npoints = npoints self.reinitialize() for f in self.cfunctions: f.points = npoints self.data = pd.DataFrame(None, columns=["V{}".format(i) for i in range(self.nodes)]) def init_variables(self, verbose=False): """Redefine the causes, mechanisms and the structure of the graph, called by ``self.generate()`` if never called. Args: verbose (bool): Verbosity """ self.generate_dag() # Mechanisms self.original_cfunctions = [] for i in range(self.nodes): if sum(self.adjacency_matrix[:, i]): if self.mechanism is PostNonLinear_Mechanism: self.original_cfunctions.append(self.mechanism(int(sum(self.adjacency_matrix[:, i])), self.npoints, self.noise, f1=self.f1, f2=self.f2, noise_coeff=self.noise_coeff)) else: self.original_cfunctions.append(self.mechanism(int(sum(self.adjacency_matrix[:, i])), self.npoints, self.noise, noise_coeff=self.noise_coeff)) else: self.original_cfunctions.append(self.initial_generator) # = [self.mechanism(int(sum(self.adjacency_matrix[:, i])), self.npoints, self.noise, noise_coeff=self.noise_coeff) if sum(self.adjacency_matrix[:, i]) else self.initial_generator for i in range(self.nodes)] # increase nb_step in order to save the gaussian processes if self.causal_mechanism == 'gp_mix': for cfunction in self.original_cfunctions: if isinstance(cfunction, GaussianProcessMix_Mechanism): cfunction.nb_step += 1 self.cfunctions = self.original_cfunctions[:] def reinitialize(self): """ Reinitialize the adjacency matrix and the cfunctions """ self.adjacency_matrix = np.copy(self.original_adjacency_matrix) # for parametric change: for i,c in enumerate(self.cfunctions): if isinstance(c, LinearMechanism) or isinstance(c, NN_Mechanism) or \ isinstance(c, NN_Mechanism_Add) or isinstance(c, Multimodal_ADN_Mechanism) or \ isinstance(c, Multimodal_X_Mechanism): c.reinit() self.cfunctions = self.original_cfunctions[:] def generate(self, npoints=None): """Generate data from an FCM defined in ``self.init_variables()``. Returns: tuple: (pandas.DataFrame, networkx.DiGraph), respectively the generated data and graph. """ if npoints is None: npoints = self.npoints if self.cfunctions is None: print('Variables initialized') self.init_variables() for i in nx.topological_sort(self.g): # Root cause if not sum(self.adjacency_matrix[:, i]): self.data['V{}'.format(i)] = self.cfunctions[i](npoints) # Generating causes else: self.data['V{}'.format(i)] = self.cfunctions[i](self.data.iloc[:, self.adjacency_matrix[:, i].nonzero()[0]].values) if self.rescale: self.data['V{}'.format(i)] = scale(self.data['V{}'.format(i)].values) if self.positive: self.data['V{}'.format(i)] -= np.min(self.data['V{}'.format(i)].values) - 1e-8 return self.data, self.g def choose_randomly_intervention_nodes(num_nodes=1, on_child_only=True): """ Pick randomly nodes Args: num_nodes(int): number of nodes to intervene on on_child_only(boolean): if True, exclude root nodes from the selection Returns: list: contains the indices of the chosen nodes """ assert self.cfunctions is not None, "You first need to create a graph" assert num_nodes <= self.nodes, "num_nodes has to been smaller or equal \ to the total number of nodes" if on_child_only: num_parent = np.sum(self.adjacency_matrix, axis=0) self.avail_nodes = np.arange(self.nodes)[num_parent > 0] else: self.avail_nodes = np.arange(self.nodes) intervention_nodes = np.random.choice(self.avail_nodes, num_nodes, replace=False) return intervention_nodes def intervene(self, intervention_type="structural", intervention_nodes=None, npoints=None, target_distribution=None): """ change the probability distribution of the nodes in intervention_nodes and then generate data Args: intervention_nodes(list of int): sets of nodes to intervene on Returns: tuple: (pandas.DataFrame, networkx.DiGraph), respectively the generated data and graph. """ assert self.cfunctions is not None, "You first need to create a graph" assert intervention_nodes is not None, "You must at least choose one node to do \ an intervention on" if npoints is not None: self.change_npoints(npoints) if intervention_type == "structural": if target_distribution is None or target_distribution == "normal": target_distribution = NormalCause() elif target_distribution == "uniform": target_distribution = UniformCause() elif target_distribution == "shifted_normal": # target_distribution = NormalCause(1, 0.1) target_distribution = NormalCause(2) elif target_distribution == "small_uniform": target_distribution = UniformCause(-0.25, 0.25) elif target_distribution == "hard_intervention": target_distribution = HardIntervention(2.0) for node in intervention_nodes: self.cfunctions[node] = target_distribution self.adjacency_matrix[:, node] = 0 elif intervention_type == "parametric": for node in intervention_nodes: if isinstance(self.cfunctions[node], LinearMechanism) or \ isinstance(self.cfunctions[node], NN_Mechanism) or \ isinstance(self.cfunctions[node], NN_Mechanism_Add) or \ isinstance(self.cfunctions[node], Multimodal_X_Mechanism) or \ isinstance(self.cfunctions[node], Multimodal_ADN_Mechanism) : self.cfunctions[node].unique_parametric_intervention() else: target_distribution = NormalCause(2) self.cfunctions[node] = target_distribution if npoints is not None: self.generate(npoints) else: self.generate() return self.data.values, self.g def to_csv(self, fname_radical, **kwargs): """ Save the generated data to the csv format by default, in two separate files: data, and the adjacency matrix of the corresponding graph. Args: fname_radical (str): radical of the file names. Completed by ``_data.csv`` for the data file and ``_target.csv`` for the adjacency matrix of the generated graph. \**kwargs: Optional keyword arguments can be passed to pandas. """ if self.data is not None: self.data.to_csv(fname_radical+'_data.csv', index=False, **kwargs) pd.DataFrame(self.adjacency_matrix).to_csv(fname_radical \ + '_target.csv', index=False, **kwargs) else: raise ValueError("Graph has not yet been generated. \ Use self.generate() to do so.") def save_dag_cpdag(self, fname_radical, i_dataset): dag_path = os.path.join(fname_radical, f'DAG{i_dataset}.npy') cpdag_path = os.path.join(fname_radical, f'CPDAG{i_dataset}.npy') cpdag = get_CPDAG(self.adjacency_matrix) np.save(dag_path, self.adjacency_matrix) np.save(cpdag_path, cpdag) def save_data(self, fname_radical, i_dataset): data_path = os.path.join(fname_radical, f'data{i_dataset}.npy') np.save(data_path, self.data) def to_npy(self, fname_radical, i_dataset): """ Save the generated data to the npy format, in two separate files: data and the adjacency matrix of the corresponding graph. Args: fname_radical (str): radical of the file names. i_dataset (int): i-th dataset """ if self.data is not None: self.save_dag_cpdag(fname_radical, i_dataset) self.save_data(fname_radical, i_dataset) else: raise ValueError("Graph has not yet been generated. \ Use self.generate() to do so.")
CausalRepID-main
data/dag_generator.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import copy import numpy as np import torch import torch.utils.data as data_utils from torchvision import datasets, transforms from sklearn.preprocessing import StandardScaler #Base Class from data.data_loader import BaseDataLoader class FineTuneDataLoader(BaseDataLoader): def __init__(self, pred_z, true_z, data_dir='', data_case='train'): super().__init__(data_dir= data_dir, data_case= data_case) self.data, self.latents= self.load_data_updated(pred_z, true_z, self.data_case) def load_data_updated(self, pred_z, true_z, data_case): if data_case == 'train': x= pred_z['tr'] z= true_z['tr'] elif data_case == 'val': x= pred_z['val'] z= true_z['val'] elif data_case == 'test': x= pred_z['te'] z= true_z['te'] scaler = StandardScaler() scaler.fit(x) x= scaler.transform(x) x= torch.tensor(x).float() z= torch.tensor(z).float() return x, z
CausalRepID-main
data/fine_tune_loader.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import argparse import glob import os import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt plt.rc('font', family='serif') plt.rc('font', size=12) import numpy as np if __name__ == "__main__": parser = argparse.ArgumentParser(description='Deep convexity') parser.add_argument('--save_dir', type=str, default='results/') parser.add_argument('--plot_dir', type=str, default='plots/') parser.add_argument('--n_layers', type=int, default=2) parser.add_argument('--n_hiddens', type=int, default=50) parser.add_argument('--n_embeddings', type=int, default=50) args = parser.parse_args() functions = [ "ackley", "michal", "schwefel", "sphere", "tang", "rastrigin", "rosenbrock", "levy", "energy" ] plt.figure(figsize=(10, 6)) for f, function in enumerate(functions): plt.subplot(3, 3, f + 1) shallows = glob.glob(os.path.join(args.save_dir, "f={}_emb={}_lay=0_hid={}_*".format(function, args.n_embeddings, args.n_hiddens))) deeps = glob.glob(os.path.join(args.save_dir, "f={}_emb={}_lay={}_hid={}_*".format(function, args.n_embeddings, args.n_layers, args.n_hiddens))) print(len(shallows), len(deeps)) for shallow in shallows: data = np.genfromtxt(shallow) if len(data): data = data[:, 2:] plt.plot(data[:, 0], data[:, 1], color="C2", alpha=0.5) for deep in deeps: data = np.genfromtxt(deep) if len(data): data = data[:, 2:] plt.plot(data[:, 0], data[:, 1], color="C1", alpha=0.5) plt.xscale("log") if function == "rastrigin" or function == "rosenbrock": plt.yscale("log") plt.margins(0.05) plt.title(function) plt.tight_layout(pad=0) pdf_name = os.path.join(args.plot_dir, 'plot_{}_{}.pdf'.format(args.n_layers, args.n_hiddens)) if not os.path.exists(args.plot_dir): os.makedirs(args.plot_dir) plt.savefig(pdf_name)
DeepConvexity-master
plot.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # from torch.optim.lr_scheduler import ReduceLROnPlateau import argparse import torch import time import math import os def rescale(x, a, b, c, d): """ Rescales variable from [a, b] to [c, d] """ return c + ((d - c) / (b - a)) * (x - a) def ackley(x, xmin=-1, xmax=1): """ https://www.sfu.ca/~ssurjano/ackley.html """ a = 20 b = 0.2 c = 2 * math.pi x = rescale(x, xmin, xmax, -32.768, 32.768) term1 = x.pow(2).mean(1).sqrt().mul(-b).exp().mul(-a) term2 = x.mul(c).cos().mean(1).exp().mul(-1) return term1 + term2 + a + math.exp(1) def michal(x, xmin=-1, xmax=1): """ https://www.sfu.ca/~ssurjano/michal.html """ x = rescale(x, xmin, xmax, 0, math.pi) mask = torch.arange(1, x.size(1) + 1).view(1, -1) return x.sin().mul((x.pow(2) * mask / math.pi).sin().pow(20)).sum(1).mul(-1) def schwefel(x, xmin=-1, xmax=1): """ https://www.sfu.ca/~ssurjano/schwef.html """ x = rescale(x, xmin, xmax, -500, 500) result = x.abs().sqrt().sin().mul(x).sum(1).mul(-1).add(418.9829 * x.size(1)) return result def sphere(x, xmin=-1, xmax=1): """ https://www.sfu.ca/~ssurjano/spheref.html """ x = rescale(x, xmin, xmax, -5.12, 5.12) return x.pow(2).mean(1) def tang(x, xmin=-1, xmax=1): """ https://www.sfu.ca/~ssurjano/stybtang.html """ x = rescale(x, xmin, xmax, -5, 5) result = (x.pow(4) - x.pow(2).mul(16) + x.mul(5)).sum(1).div(2) return result def rastrigin(x, xmin=-1, xmax=1): """ https://www.sfu.ca/~ssurjano/rastr.html """ x = rescale(x, xmin, xmax, -5.12, 5.12) result = (x.pow(2.0) - x.mul(2.0 * math.pi).cos().mul(10) ).sum(1).add(10 * x.size(1)) return result def rosenbrock(x, xmin=-1, xmax=1): """ https://www.sfu.ca/~ssurjano/rosen.html """ x = rescale(x, xmin, xmax, -5, 10) term1 = (x[:, 1:] - x[:, :-1].pow(2)).pow(2).mul(100).sum(1) term2 = x[:, :-1].add(-1).pow(2).sum(1) return term1 + term2 def levy(x, xmin=-1, xmax=1): """ https://www.sfu.ca/~ssurjano/levy.html """ x = rescale(x, xmin, xmax, -10, 10) w = 1 + (x - 1).div(4) w1 = w[:, 0] ww = w[:, :x.size(1) - 1] wd = w[:, x.size(1) - 1] if ww.dim() == 1: ww = ww.view(-1, 1) term1 = w1.mul(math.pi).sin().pow(2) termw = ww.mul(math.pi).add(1).sin().pow(2).mul( 10).add(1).mul(ww.add(-1).pow(2)).mean(1) termd = wd.mul(math.pi * 2).sin().pow(2).add(1).mul(wd.add(-1).pow(2)) return term1 + termw + termd def energy(d): """ https://en.wikipedia.org/wiki/Spin_glass """ coeff = torch.randn(d, d, d) def foo(x, xmin=-1, xmax=1): x = rescale(x, xmin, xmax, -1, 1) x_norm = x.norm(2, 1).view(-1, 1) + 1e-10 x = x / x_norm * math.sqrt(x.size(1)) bs = x.size(0) tmp1 = torch.mul(x.view(bs, d, 1), x.view(bs, 1, d)) tmp2 = torch.mul(tmp1.view(bs, d * d, 1), x.view(bs, 1, d)) tmp3 = torch.mul(tmp2.view(bs, d * d * d), coeff.view(1, -1)) return tmp3.sum(1) / d return foo test_functions = { "ackley": ackley, "michal": michal, "schwefel": schwefel, "sphere": sphere, "tang": tang, "rastrigin": rastrigin, "rosenbrock": rosenbrock, "levy": levy } class ScaledTanh(torch.nn.Module): def __init__(self, a=1): super(ScaledTanh, self).__init__() self.a = a def forward(self, x): return x.mul(self.a).tanh() class EmbeddingPerceptron(torch.nn.Module): """ Multilayer ReLU perceptron with learnable inputs """ def __init__(self, sizes, multiplier=3): super(EmbeddingPerceptron, self).__init__() self.inputs = torch.arange(0, sizes[0]).long() layers = [torch.nn.Embedding(sizes[0], sizes[1])] for i in range(1, len(sizes) - 1): layers.append(torch.nn.Linear(sizes[i], sizes[i + 1])) if i < (len(sizes) - 2): layers.append(torch.nn.ReLU()) self.net = torch.nn.Sequential(*layers) net_min, net_max = self().min().item(), self().max().item() a = 1.7159 / max(abs(net_min), abs(net_max)) self.net = torch.nn.Sequential(self.net, ScaledTanh(a)) def forward(self): return self.net(self.inputs) def run_experiment(args, lr): if args.seed >= 0: torch.manual_seed(args.seed) if args.function == "energy": the_function = energy(args.dimension) else: the_function = test_functions[args.function] network = EmbeddingPerceptron([args.n_embeddings] + [args.n_hiddens] * args.n_layers + [args.dimension]) optimizer = torch.optim.SGD(network.parameters(), lr) scheduler = ReduceLROnPlateau(optimizer, patience=1, factor=0.99, threshold=1e-10, min_lr=1e-10, threshold_mode='abs') time_start = time.time() history = [] for i in range(args.n_iters): errors = the_function(network()) mean_error = errors.mean() min_error = errors.min() optimizer.zero_grad() mean_error.backward() optimizer.step() history.append([i, time.time() - time_start, min_error.item()]) if min_error.item() != min_error.item(): return None scheduler.step(mean_error.item()) return torch.Tensor(history) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Deep convexity') parser.add_argument('--save_dir', type=str, default='results/') parser.add_argument('--function', type=str, default="ackley") parser.add_argument('--dimension', type=int, default=50) parser.add_argument('--n_iters', type=int, default=10000) parser.add_argument('--min_lr', type=float, default=-6) parser.add_argument('--max_lr', type=float, default=1) parser.add_argument('--n_lr', type=int, default=20) parser.add_argument('--n_embeddings', type=int, default=50) parser.add_argument('--n_hiddens', type=int, default=50) parser.add_argument('--n_layers', type=int, default=0) parser.add_argument('--seed', type=int, default=0) args = parser.parse_args() torch.set_default_tensor_type(torch.DoubleTensor) best_history = None best_lr = None best_err = 1e10 for lr in torch.logspace(args.min_lr, args.max_lr, args.n_lr): history = run_experiment(args, lr) if history is not None: err = history[:, -1].min().item() if err < best_err: best_lr = lr best_err = err best_history = history #print("+ Success at lr={:1.0e} with value {:.5f}".format(lr, err)) #else: #print("- Failure at lr={:1.0e}".format(lr)) print("* Best run at lr={:1.0e} with value {:.5f}".format(best_lr, best_err)) fname = "f={}_emb={}_lay={}_hid={}_seed={}.txt".format(args.function, args.n_embeddings, args.n_layers, args.n_hiddens, args.seed) if not os.path.exists(args.save_dir): os.makedirs(args.save_dir) with open(os.path.join(args.save_dir, fname), "w") as f: f.write("# {}\n".format(str(vars(args)))) for line in best_history: f.write("{:1.0e} {:.0f} {:.5f} {:.5f}\n".format(best_lr, *line))
DeepConvexity-master
main.py
from setuptools import setup if __name__ == "__main__": setup(name='epoxy', version='0.0.0a0', description='Interactive Model Iteration with Weak Supervision and Pre-Trained Embeddings', url='https://github.com/HazyResearch/epoxy', author='Dan Fu', author_email='danfu@cs.stanford.edu', license='Apache 2.0', install_requires=['cytoolz'], packages=['epoxy'])
epoxy-master
setup.py
from flyingsquid.label_model import LabelModel from sklearn.metrics import precision_recall_fscore_support, accuracy_score import numpy as np def train_fs_model_spam(L_train): label_model = LabelModel(L_train.shape[1]) label_model.fit( L_train, # These parameters tuned for spam class_balance = np.array([0.4, 0.6]), solve_method = 'triplet_median' ) return label_model def evaluate_fs_model_spam(label_model, L_mat, Y_mat): preds = label_model.predict_proba_marginalized(L_mat) preds = [ 1 if pred > 0.5 else -1 for pred in preds ] pre, rec, f1, support = precision_recall_fscore_support( Y_mat, preds ) acc = accuracy_score(Y_mat, preds) print('Acc: {:.4f}\tPre: {:.4f}\tRec: {:.4f}\tF1: {:.4f}'.format( acc, pre[1], rec[1], f1[1] ))
epoxy-master
examples/helpers.py
from .epoxy import preprocess_lfs, extend_lfs, Epoxy __all__ = [ 'preprocess_lfs', 'extend_lfs', 'Epoxy' ]
epoxy-master
epoxy/__init__.py
import numpy as np import faiss from sklearn.metrics import pairwise import cytoolz as tz import torch class Epoxy: ''' Class wrapping the functionality to extend LF's. Uses FAISS for nearest-neighbor search under the hood. ''' def __init__( self, L_train, train_embeddings, gpu = False, metric = 'cosine', method = 'pytorch' ): ''' Initialize an instance of Epoxy. Args: L_train: The training matrix to look through to find nearest neighbors train_embeddings: embeddings of each item in L_train gpu: if True, build the FAISS index on GPU metric: 'cosine' or 'L2' -- prefer cosine method: 'pytorch', 'faiss', or 'sklearn' ''' self.L_train = L_train self.gpu = gpu self.metric = metric self.method = method self.preprocessed = False if metric not in ['cosine', 'l2']: raise NotImplementedError('Metric {} not supported'.format(metric)) if self.method == 'faiss': if metric == 'cosine': # Copy because faiss.normalize_L2() modifies the original train_embeddings = np.copy(train_embeddings) # Normalize the vectors before adding to the index faiss.normalize_L2(train_embeddings) elif metric == 'L2': pass else: raise NotImplementedError('Metric {} not supported'.format(metric)) d = train_embeddings.shape[1] m = L_train.shape[1] self.m = m if metric == 'cosine': # use IndexFlatIP (inner product) label_fn_indexes = [faiss.IndexFlatIP(d) for i in range(m)] elif metric == 'l2': # 'L2': label_fn_indexes = [faiss.IndexFlatL2(d) for i in range(m)] if gpu: res = faiss.StandardGpuResources() label_fn_indexes = [faiss.index_cpu_to_gpu(res, 0, x) for x in label_fn_indexes] support = [] for i in range(m): support.append(np.argwhere(L_train[:, i] != 0).flatten()) label_fn_indexes[i].add(train_embeddings[support[i]]) self.label_fn_indexes = label_fn_indexes self.support = support elif self.method in ['sklearn', 'pytorch']: self.train_embeddings = train_embeddings else: raise NotImplementedError('Method {} not supported'.format(self.method)) def preprocess( self, L_mat, mat_embeddings, batch_size = None ): ''' Preprocess L_mat for extension. Args: L_mat: The matrix to extend mat_embeddings: embeddings of each item in L_mat batch_size: if not None, compute in batches of this size (especially important for PyTorch similarity if done on GPU) ''' self.preprocessed = True self.L_mat = L_mat if self.method == 'faiss': mat_abstains = [ np.argwhere(L_mat[:, i] == 0).flatten() for i in range(self.m) ] self.mat_abstains = mat_abstains dists_and_nearest = [] for i in range(self.m): if self.metric == 'cosine': embs_query = np.copy(mat_embeddings[mat_abstains[i]]) faiss.normalize_L2(embs_query) else: embs_query = mat_embeddings[mat_abstains[i]] if batch_size is not None: raise NotImplementedError('batch_size not supported yet for FAISS') dists_and_nearest.append(self.label_fn_indexes[i].search(embs_query, 1)) self.dists = [ dist_and_nearest[0].flatten() for dist_and_nearest in dists_and_nearest ] self.nearest = [ dist_and_nearest[1].flatten() for dist_and_nearest in dists_and_nearest ] elif self.method in ['sklearn', 'pytorch']: self.mat_embeddings = mat_embeddings def comp_similarity(embs): if self.metric == 'cosine': if self.method == 'sklearn': return pairwise.cosine_similarity(embs, self.train_embeddings) else: if self.gpu: return pytorch_cosine_similarity( torch.tensor(embs).type(torch.float16).cuda(), torch.tensor(self.train_embeddings).type(torch.float16).cuda() ).cpu().numpy() else: return pytorch_cosine_similarity( torch.tensor(embs).type(torch.float32), torch.tensor(self.train_embeddings).type(torch.float32) ).numpy() else: if self.method == 'sklearn': return pairwise.euclidean_distances(embs, self.train_embeddings) else: if self.gpu: return pytorch_l2_distance( torch.tensor(embs).type(torch.float16).cuda(), torch.tensor(self.train_embeddings).type(torch.float16).cuda() ).cpu().numpy() else: return pytorch_l2_distance( torch.tensor(embs).type(torch.float32), torch.tensor(self.train_embeddings).type(torch.float32) ).numpy() if batch_size is None: mat_to_train_sims = comp_similarity(self.mat_embeddings) else: sims = [] for mat_batch in tz.partition_all(batch_size, self.mat_embeddings): sims.append(comp_similarity(mat_batch)) mat_to_train_sims = np.concatenate(sims) self.mat_to_train_sims = mat_to_train_sims mat_abstains, closest_pos, closest_neg = preprocess_lfs( self.L_train, self.L_mat, mat_to_train_sims, use_dists = self.metric == 'l2' ) self.mat_abstains = mat_abstains self.closest_pos = closest_pos self.closest_neg = closest_neg def extend(self, thresholds): ''' Extend L_mat (which was specified during pre-processing). ''' if self.method == 'faiss': expanded_L_mat = np.copy(self.L_mat) new_points = [ (self.dists[i] > thresholds[i]) if self.metric == 'cosine' else (self.dists[i] < thresholds[i]) for i in range(self.m) ] for i in range(self.m): expanded_L_mat[ self.mat_abstains[i][new_points[i]], i ] = self.L_train[ self.support[i], i ][self.nearest[i][new_points[i]]] return expanded_L_mat elif self.method in ['sklearn', 'pytorch']: return extend_lfs( self.L_mat, self.mat_abstains, self.closest_pos, self.closest_neg, thresholds, metric = self.metric ) def get_distance_matrix(self): if not self.preprocessed: raise NotImplementedError('Need to run preprocessing first!') if self.method == 'faiss': raise NotImplementedError("FAISS doesn't compute the distance matrix!") return self.mat_to_train_sims def pytorch_cosine_similarity(a, b): """ https://stackoverflow.com/questions/50411191/how-to-compute-the-cosine-similarity-in-pytorch-for-all-rows-in-a-matrix-with-re """ a_norm = a / a.norm(dim=1)[:, None] b_norm = b / b.norm(dim=1)[:, None] return torch.mm(a_norm, b_norm.transpose(0,1)) def pytorch_l2_distance(a, b): return torch.cdist(a, b) def preprocess_lfs( L_train, L_mat, sim_from_mat_to_train, use_dists = False, ): ''' Preprocessing for sklearn method. Preprocess similarity scores and get the closest item in the support set for each LF. Args: L_train: The training matrix to look through to find nearest neighbors L_mat: The matrix to extend sim_from_mat_to_train: Similarity scores from L_mat to L_train. sim_from_mat_to_train[i][j] stores the similarity between element i of L_mat to element j of L_train. use_dists: if True, sim_from_mat_to_train actually stores distances. Returns: A tuple of three Numpy matrices. The first matrix stores which elements of L_mat have abstains, the second matrix stores, for each labeling function, the closest point in L_train where that same labeling function voted positive, and the third matrix stores, for each labeling function, the closest point in L_train where the labeling function voted negative. ''' m = L_mat.shape[1] expanded_L_mat = np.copy(L_mat) train_support_pos = [ np.argwhere(L_train[:, i] == 1).flatten() for i in range(m) ] train_support_neg = [ np.argwhere(L_train[:, i] == -1).flatten() for i in range(m) ] mat_abstains = [ np.argwhere(L_mat[:, i] == 0).flatten() for i in range(m) ] pos_dists = [ sim_from_mat_to_train[mat_abstains[i]][:, train_support_pos[i]] for i in range(m) ] neg_dists = [ sim_from_mat_to_train[mat_abstains[i]][:, train_support_neg[i]] for i in range(m) ] closest_pos = [ (np.max(pos_dists[i], axis=1) if not use_dists else np.min(pos_dists[i], axis = 1)) if pos_dists[i].shape[1] > 0 else np.full(mat_abstains[i].shape, -1) for i in range(m) ] closest_neg = [ (np.max(neg_dists[i], axis=1) if not use_dists else np.min(neg_dists[i], axis = 1)) if neg_dists[i].shape[1] > 0 else np.full(mat_abstains[i].shape, -1) for i in range(m) ] return mat_abstains, closest_pos, closest_neg def extend_lfs( L_mat, mat_abstains, closest_pos, closest_neg, thresholds, metric = 'cosine' ): ''' Preprocessing for sklearn method. Extend LF's with fixed thresholds. Args: L_mat: The matrix to extend. mat_abstains, closest_pos, closest_neg: The outputs of the preprocess_lfs function. thresholds: The thresholds to extend each LF. For each item that an LF abstains on, if closest point that the LF votes on in the training is closer to the threshold, the LF is extended with the vote on that point. This information is encoded in mat_abstains, closest_pos, and closest_neg. Returns: An extended version of L_mat. ''' m = L_mat.shape[1] expanded_L_mat = np.copy(L_mat) if metric == 'cosine': new_pos = [ (closest_pos[i] > closest_neg[i]) & (closest_pos[i] > thresholds[i]) for i in range(m) ] new_neg = [ (closest_neg[i] > closest_pos[i]) & (closest_neg[i] > thresholds[i]) for i in range(m) ] else: new_pos = [ (closest_pos[i] > closest_neg[i]) & (closest_pos[i] < thresholds[i]) for i in range(m) ] new_neg = [ (closest_neg[i] > closest_pos[i]) & (closest_neg[i] < thresholds[i]) for i in range(m) ] for i in range(m): expanded_L_mat[mat_abstains[i][new_pos[i]], i] = 1 expanded_L_mat[mat_abstains[i][new_neg[i]], i] = -1 return expanded_L_mat
epoxy-master
epoxy/epoxy.py
from pathlib import Path import torch from einops import rearrange try: from cauchy_mult import cauchy_mult_sym_fwd, cauchy_mult_sym_bwd except ImportError: from torch.utils.cpp_extension import load current_dir = Path(__file__).parent.absolute() cauchy_mult_extension = load( name='cauchy_mult', sources=[str(current_dir / 'cauchy.cpp'), str(current_dir / 'cauchy_cuda.cu')], extra_cflags=['-g', '-march=native', '-funroll-loops'], extra_cuda_cflags=['-O3', '-lineinfo', '--use_fast_math'], extra_include_paths=str(current_dir), build_directory=str(current_dir), verbose=True ) cauchy_mult_sym_fwd = cauchy_mult_extension.cauchy_mult_sym_fwd cauchy_mult_sym_bwd = cauchy_mult_extension.cauchy_mult_sym_bwd def cauchy_mult_torch(v: torch.Tensor, z: torch.Tensor, w: torch.Tensor, symmetric=True) -> torch.Tensor: """ v: (B, N) z: (L) w: (B, N) symmetric: whether to assume that v and w contain complex conjugate pairs, of the form [v_half, v_half.conj()] and [w_half, w_half.conj()] """ if not symmetric: return (rearrange(v, 'b n -> b 1 n') / (rearrange(z, 'l -> l 1') - rearrange(w, 'b n -> b 1 n'))).sum(dim=-1) else: N = v.shape[-1] assert N % 2 == 0 vv = rearrange(v[:, :N // 2], 'b n -> b 1 n') zz = rearrange(z, 'l -> l 1') ww = rearrange(w[:, :N // 2], 'b n -> b 1 n') # return 2 * ((zz * vv.real - vv.real * ww.real - vv.imag * ww.imag) # / (zz * zz - 2 * zz * ww.real + ww.abs().square())).sum(dim=-1) return (vv / (zz - ww) + vv.conj() / (zz - ww.conj())).sum(dim=-1) def cauchy_mult_keops(v, z, w): from pykeops.torch import LazyTensor v_l = LazyTensor(rearrange(v, 'b N -> b 1 N 1')) z_l = LazyTensor(rearrange(z, 'L -> 1 L 1 1')) w_l = LazyTensor(rearrange(w, 'b N -> b 1 N 1')) sub = z_l - w_l # (b N L 1), for some reason it doesn't display the last dimension div = v_l / sub s = div.sum(dim=2, backend='GPU') return s.squeeze(-1) def _cauchy_mult(v, z, w): return CauchyMultiplySymmetric.apply(v, z, w) def cauchy_mult(v, z, w): """ Wrap the cuda method to deal with shapes """ v, w = torch.broadcast_tensors(v, w) shape = v.shape # z_shape = z.shape z = z.squeeze() assert len(z.shape) == 1 v = v.contiguous() w = w.contiguous() z = z.contiguous() N = v.size(-1) assert w.size(-1) == N y = _cauchy_mult(v.view(-1, N), z, w.view(-1, N)) y = y.view(*shape[:-1], z.size(-1)) return y class CauchyMultiplySymmetric(torch.autograd.Function): @staticmethod def forward(ctx, v, z, w): batch, N = v.shape supported_N_values = [1 << log_n for log_n in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] L = z.shape[-1] if not N in supported_N_values: raise NotImplementedError(f'Only support N values in {supported_N_values}') max_L_value = 32 * 1024 * 64 * 1024 if L > max_L_value: raise NotImplementedError(f'Only support L values <= {max_L_value}') if not v.is_cuda and z.is_cuda and w.is_cuda: raise NotImplementedError(f'Only support CUDA tensors') ctx.save_for_backward(v, z, w) return cauchy_mult_sym_fwd(v, z, w) @staticmethod def backward(ctx, dout): v, z, w = ctx.saved_tensors dv, dw = cauchy_mult_sym_bwd(v, z, w, dout) return dv, None, dw
H3-main
csrc/cauchy/cauchy.py
# Adapted from https://github.com/NVIDIA/apex/blob/master/setup.py import torch from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME from setuptools import setup, find_packages import subprocess import sys import warnings import os # ninja build does not work unless include_dirs are abs path this_dir = os.path.dirname(os.path.abspath(__file__)) def get_cuda_bare_metal_version(cuda_dir): raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True) output = raw_output.split() release_idx = output.index("release") + 1 release = output[release_idx].split(".") bare_metal_major = release[0] bare_metal_minor = release[1][0] return raw_output, bare_metal_major, bare_metal_minor def check_cuda_torch_binary_vs_bare_metal(cuda_dir): raw_output, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(cuda_dir) torch_binary_major = torch.version.cuda.split(".")[0] torch_binary_minor = torch.version.cuda.split(".")[1] print("\nCompiling cuda extensions with") print(raw_output + "from " + cuda_dir + "/bin\n") if (bare_metal_major != torch_binary_major) or (bare_metal_minor != torch_binary_minor): raise RuntimeError( "Cuda extensions are being compiled with a version of Cuda that does " "not match the version used to compile Pytorch binaries. " "Pytorch binaries were compiled with Cuda {}.\n".format(torch.version.cuda) + "In some cases, a minor-version mismatch will not cause later errors: " "https://github.com/NVIDIA/apex/pull/323#discussion_r287021798. " "You can try commenting out this check (at your own risk)." ) def raise_if_cuda_home_none(global_option: str) -> None: if CUDA_HOME is not None: return raise RuntimeError( f"{global_option} was requested, but nvcc was not found. Are you sure your environment has nvcc available? " "If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, " "only images whose names contain 'devel' will provide nvcc." ) def append_nvcc_threads(nvcc_extra_args): _, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(CUDA_HOME) if int(bare_metal_major) >= 11 and int(bare_metal_minor) >= 2: return nvcc_extra_args + ["--threads", "4"] return nvcc_extra_args if not torch.cuda.is_available(): # https://github.com/NVIDIA/apex/issues/486 # Extension builds after https://github.com/pytorch/pytorch/pull/23408 attempt to query torch.cuda.get_device_capability(), # which will fail if you are compiling in an environment without visible GPUs (e.g. during an nvidia-docker build command). print( "\nWarning: Torch did not find available GPUs on this system.\n", "If your intention is to cross-compile, this is not an error.\n" "By default, Apex will cross-compile for Pascal (compute capabilities 6.0, 6.1, 6.2),\n" "Volta (compute capability 7.0), Turing (compute capability 7.5),\n" "and, if the CUDA version is >= 11.0, Ampere (compute capability 8.0).\n" "If you wish to cross-compile for a single specific architecture,\n" 'export TORCH_CUDA_ARCH_LIST="compute capability" before running setup.py.\n', ) if os.environ.get("TORCH_CUDA_ARCH_LIST", None) is None: _, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(CUDA_HOME) if int(bare_metal_major) == 11: os.environ["TORCH_CUDA_ARCH_LIST"] = "6.0;6.1;6.2;7.0;7.5;8.0" if int(bare_metal_minor) > 0: os.environ["TORCH_CUDA_ARCH_LIST"] = "6.0;6.1;6.2;7.0;7.5;8.0;8.6" else: os.environ["TORCH_CUDA_ARCH_LIST"] = "6.0;6.1;6.2;7.0;7.5" print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__)) TORCH_MAJOR = int(torch.__version__.split(".")[0]) TORCH_MINOR = int(torch.__version__.split(".")[1]) cmdclass = {} ext_modules = [] raise_if_cuda_home_none("cauchy_mult") # Check, if CUDA11 is installed for compute capability 8.0 cc_flag = [] cc_flag.append("-arch=compute_70") ext_modules.append( CUDAExtension( 'cauchy_mult', [ 'cauchy.cpp', 'cauchy_cuda.cu', ], extra_compile_args={'cxx': ['-g', '-march=native', '-funroll-loops'], 'nvcc': ['-O3', '-lineinfo', '--use_fast_math'] } ) ) setup( name="cauchy_mult", version="0.1", ext_modules=ext_modules, cmdclass={"build_ext": BuildExtension} if ext_modules else {}, )
H3-main
csrc/cauchy/setup.py
import math from functools import partial import torch from einops import rearrange from cauchy import cauchy_mult_torch, cauchy_mult_keops, cauchy_mult from benchmarks.utils import benchmark_all, benchmark_combined, benchmark_forward, benchmark_backward, pytorch_profiler def generate_data(batch_size, N, L, symmetric=True, device='cuda'): if not symmetric: v = torch.randn(batch_size, N, dtype=torch.complex64, device=device, requires_grad=True) w = torch.randn(batch_size, N, dtype=torch.complex64, device=device, requires_grad=True) z = torch.randn(L, dtype=torch.complex64, device=device) else: assert N % 2 == 0 v_half = torch.randn(batch_size, N // 2, dtype=torch.complex64, device=device) v = torch.cat([v_half, v_half.conj()], dim=-1).requires_grad_(True) w_half = torch.randn(batch_size, N // 2, dtype=torch.complex64, device=device) w = torch.cat([w_half, w_half.conj()], dim=-1).requires_grad_(True) z = torch.exp(1j * torch.randn(L, dtype=torch.float32, device=device)) return v, z, w if __name__ == '__main__': device = 'cuda' bs = 1024 N = 64 L = 16384 v, z, w = generate_data(bs, N, L, symmetric=True) v_half = v[:, :N // 2].clone().detach().requires_grad_(True) w_half = w[:, :N // 2].clone().detach().requires_grad_(True) repeats = 30 benchmark_all(cauchy_mult_keops, v, z, w, repeats=repeats, desc='Cauchy mult keops') benchmark_all(cauchy_mult, v_half, z, w_half, repeats=repeats, desc='Cauchy mult symmetric') pytorch_profiler(cauchy_mult, v_half, z, w_half, backward=True, verbose=True) # out = cauchy_mult(v_half, z, w_half) # g = torch.randn_like(out) # out.backward(g)
H3-main
csrc/cauchy/benchmark_cauchy.py
import importlib import json import argparse import torch from benchmark.utils import benchmark_forward def generate_data(batch_size, N, L, symmetric=True, device='cuda'): if not symmetric: v = torch.randn(batch_size, N, dtype=torch.complex64, device=device, requires_grad=True) w = torch.randn(batch_size, N, dtype=torch.complex64, device=device, requires_grad=True) z = torch.randn(L, dtype=torch.complex64, device=device) else: assert N % 2 == 0 v_half = torch.randn(batch_size, N // 2, dtype=torch.complex64, device=device) v = torch.cat([v_half, v_half.conj()], dim=-1).requires_grad_(True) w_half = torch.randn(batch_size, N // 2, dtype=torch.complex64, device=device) w = torch.cat([w_half, w_half.conj()], dim=-1).requires_grad_(True) z = torch.exp(1j * torch.randn(L, dtype=torch.float32, device=device)) return v, z, w parser = argparse.ArgumentParser(description='Tuning Cauchy multiply') parser.add_argument('--name', default='cauchy_mult') parser.add_argument('--mode', default='forward', choices=['forward', 'backward']) parser.add_argument('-bs', '--batch-size', default=1024, type=int) parser.add_argument('-N', default=64, type=int) parser.add_argument('-L', default=2 ** 14, type=int) if __name__ == '__main__': args = parser.parse_args() device = 'cuda' bs = args.batch_size N = args.N L = args.L repeat = 30 v, z, w = generate_data(bs, N, L, symmetric=True) v_half = v[:, :N // 2].clone().detach().requires_grad_(True) w_half = w[:, :N // 2].clone().detach().requires_grad_(True) tuning_extension_name = args.name # print('Extension name:', tuning_extension_name) module = importlib.import_module(tuning_extension_name) if args.mode == 'forward': _, m = benchmark_forward(repeat, module.cauchy_mult_sym_fwd, v_half, z, w_half, verbose=False, desc='Cauchy mult symmetric fwd') else: out = module.cauchy_mult_sym_fwd(v_half, z, w_half) dout = torch.randn_like(out) _, m = benchmark_forward(repeat, module.cauchy_mult_sym_bwd, v_half, z, w_half, dout, verbose=False, desc='Cauchy mult symmetric bwd') result_dict = dict(time_mean = m.mean, time_iqr = m.iqr) print(json.dumps(result_dict))
H3-main
csrc/cauchy/benchmark_cauchy_tune.py
import os import shutil import subprocess import sys # import tempfile # import importlib import random import string import json from functools import partial from multiprocessing import Pipe, Pool, Process from pathlib import Path from tqdm import tqdm import numpy as np def read_file(filename): """ return the contents of the file named filename or None if file not found """ if os.path.isfile(filename): with open(filename, 'r') as f: return f.read() def write_file(filename, string): """dump the contents of string to a file called filename""" with open(filename, 'w', encoding="utf-8") as f: f.write(string) def prepare_kernel_string(kernel_string, params): for k, v in params.items(): kernel_string = "#define " + k + " " + str(v) + "\n" + kernel_string return kernel_string def compile_extension(temp_dir, install=False, verbose=True): # Need to copy this process's environments, otherwise it can't find the compilers env = {**os.environ, 'TUNING_SOURCE_DIR': str(temp_dir), 'TUNING_EXTENSION_NAME': str(temp_dir.stem)} # https://stackoverflow.com/questions/53173314/how-to-change-distutils-output-directory # Need separate build directories for parallel compilation output = subprocess.run( # [sys.executable, "tuning_setup.py", 'build', f'--build-base={str(temp_dir)}', # f'--build-lib={str(temp_dir)}'], [sys.executable, "tuning_setup.py", 'build' if not install else 'develop'], cwd=temp_dir, env=env, capture_output=True, # check=True ) if verbose: print(output) print('Done compiling' if not install else 'Done installing') def uninstall_extensions(tuning_extension_names, verbose=True): # Need to copy this process's environments, otherwise it can't find the compilers env = {**os.environ} output = subprocess.run( [sys.executable, '-m', 'pip', 'uninstall', '-y', *tuning_extension_names], env=env, capture_output=True, # check=True ) if verbose: print(output) print('Done uninstalling') def benchmark_extension(benchmark_script, *benchmark_args, verbose=True): # Need to copy this process's environments, otherwise it can't find the compilers env = os.environ # https://stackoverflow.com/questions/53173314/how-to-change-distutils-output-directory # Need separate build directories for parallel compilation process = subprocess.run( [sys.executable, benchmark_script, *benchmark_args], env=os.environ, capture_output=True, # check=True ) if verbose: print(process) print('Done benchmarking') return json.loads(process.stdout.decode(sys.stdout.encoding)) # def benchmark(connection, temp_dir): # import torch # # module = importlib.import_module(tuning_extension_name) # torch.ops.load_library(temp_dir / 'torch_butterfly_tuning.so') # batch_size = 1024 # n = 32 # twiddle = torch.randn(1, 1, 5, n // 2, 2, 2, device='cuda') # input = torch.randn(batch_size, 1, n, device=twiddle.device) # output = torch.ops.torch_butterfly.butterfly_multiply_fw(twiddle, input, True) # # https://medium.com/@auro_227/timing-your-pytorch-code-fragments-e1a556e81f2 # res = [] # for _ in range(32): # start = torch.cuda.Event(enable_timing=True) # end = torch.cuda.Event(enable_timing=True) # start.record() # output = torch.ops.torch_butterfly.butterfly_multiply_fw(twiddle, input, True) # end.record() # torch.cuda.synchronize() # res.append(start.elapsed_time(end)) # print(output.shape) # res = np.array(res) # connection.send((np.mean(res), np.std(res))) def set_up_tuning_temp_dir(params: dict, source_files, extension_dir, verbose=True): if verbose: print('params: ', params) # TD [2021-10-22]: tempfile.mkdtemp sometimes create dir name with '_' in it, thus messing up # the extension name. # temp_dir = Path(tempfile.mkdtemp(prefix="temp_", dir=Path.cwd().parent)).absolute() tuning_extension_name = 'temp_' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)) temp_dir = (Path.cwd().parent / tuning_extension_name).absolute() if temp_dir.exists(): shutil.rmtree(temp_dir) # shutil.copytree doesn't want directory that already exists shutil.copytree(extension_dir, temp_dir) sources = [temp_dir / name for name in source_files] for kernel_source in sources: ks = read_file(kernel_source) ks = prepare_kernel_string(ks, params) write_file(kernel_source, ks) return temp_dir class KernelTuner: def __init__(self, extension_dir, source_files, params_list, benchmark_script, benchmark_args, npool=8, verbose=True): self.extension_dir = extension_dir self.source_files = source_files self.params_list = params_list self.benchmark_script = benchmark_script self.benchmark_args = benchmark_args self.npool = npool self.verbose = verbose def tune(self): temp_dirs = [set_up_tuning_temp_dir(params, self.source_files, self.extension_dir, verbose=self.verbose) for params in self.params_list] # Compile in parallel (for speed), then install sequentially to ensure correctness with Pool(self.npool) as p: p.map(compile_extension, temp_dirs) # with Pool(1) as p: # p.map(partial(compile_extension, install=True), [temp_dirs]) for temp_dir in tqdm(temp_dirs): try: compile_extension(temp_dir, install=True) except: pass # # We benchmark on a separate process so that they can import the extension that just got compiled. # for params, temp_dir in params_tempdir: # print('Benchmarking: ', params) # recv_conn, send_conn = Pipe(duplex=False) # benchmark_process = Process(target=benchmark_fwd, args=(send_conn, str(temp_dir.stem))) # benchmark_process.start() # result = recv_conn.recv() # benchmark_process.join() # print('result', result) results = [] for params, temp_dir in tqdm(list(zip(self.params_list, temp_dirs))): try: results.append((params, benchmark_extension(self.benchmark_script, *['--name', temp_dir.stem] + self.benchmark_args))) except: pass print(results) uninstall_extensions([temp_dir.stem for temp_dir in temp_dirs]) for temp_dir in temp_dirs: shutil.rmtree(temp_dir) return results
H3-main
csrc/cauchy/tuner.py
import os from setuptools import setup from pathlib import Path import torch.cuda from torch.utils.cpp_extension import CppExtension, CUDAExtension, BuildExtension from torch.utils.cpp_extension import CUDA_HOME extensions_dir = Path(os.getenv('TUNING_SOURCE_DIR')).absolute() assert extensions_dir.exists() source_files=[ 'cauchy.cpp', 'cauchy_cuda.cu', ] sources = [str(extensions_dir / name) for name in source_files] extension_name = os.getenv('TUNING_EXTENSION_NAME', default='cauchy_mult_tuning') ext_modules = [] if torch.cuda.is_available() and CUDA_HOME is not None: extension = CUDAExtension( extension_name, sources, include_dirs=[extensions_dir], extra_compile_args={'cxx': ['-g', '-march=native', '-funroll-loops'], # 'nvcc': ['-O2', '-lineinfo'] 'nvcc': ['-O2', '-lineinfo', '--use_fast_math'] } ) ext_modules.append(extension) setup( name=extension_name, ext_modules=ext_modules, # cmdclass={'build_ext': BuildExtension.with_options(use_ninja=False)}) cmdclass={'build_ext': BuildExtension})
H3-main
csrc/cauchy/tuning_setup.py
import math import json import argparse import itertools from pathlib import Path from tuner import KernelTuner def forward_params_list(N): blocksize_params = ('MAX_BLOCK_SIZE_VALUE', [64, 128, 256, 512, 1024]) thread_value_default = [2, 4, 8, 16, 32, 32, 32, 32, 32, 32] thread_values_supported = [2, 4, 8, 16, 32, 64, 128] log_N_half = int(math.log2(N)) - 1 thread_values = [] for val in thread_values_supported: if val <= N // 2: array = list(thread_value_default) array[log_N_half - 1] = val thread_values.append('{' + ', '.join(str(v) for v in array) + '}') thread_params = ('ITEMS_PER_THREAD_SYM_FWD_VALUES', thread_values) value_prod = itertools.product(thread_params[1], blocksize_params[1]) params_list = [{thread_params[0]: value[0], blocksize_params[0]: value[1]} for value in value_prod] return params_list def backward_params_list(L): thread_value_supported = [8, 16, 32, 64, 128] thread_params = ('ITEMS_PER_THREAD_SYM_BWD_VALUE', [v for v in thread_value_supported if (L + v - 1) // v <= 1024]) params_list = [{thread_params[0]: value} for value in thread_params[1]] return params_list parser = argparse.ArgumentParser(description='Tuning Cauchy multiply') parser.add_argument('--mode', default='forward', choices=['forward', 'backward']) parser.add_argument('-N', default=64, type=int) parser.add_argument('-L', default=2 ** 14, type=int) parser.add_argument('--filename', default='tuning_result.json') if __name__ == '__main__': args = parser.parse_args() extension_dir = Path(__file__).absolute().parent source_files = ['cauchy_cuda.cu'] if args.mode == 'forward': params_list = forward_params_list(args.N) tuner = KernelTuner(extension_dir, source_files, params_list, benchmark_script='benchmark_cauchy_tune.py', benchmark_args=['--mode', 'forward', '-N', str(args.N), '-L', '16384'], npool=16) else: params_list = backward_params_list(args.L) tuner = KernelTuner(extension_dir, source_files, params_list, benchmark_script='benchmark_cauchy_tune.py', benchmark_args=['--mode', 'backward', '-N', '64', '-L', str(args.L)], npool=16) result = tuner.tune() with open(args.filename, 'w') as f: json.dump(result, f)
H3-main
csrc/cauchy/tune_cauchy.py
import math import torch import pytest from einops import rearrange from cauchy import cauchy_mult_torch, cauchy_mult_keops, cauchy_mult def generate_data(batch_size, N, L, symmetric=True, device='cuda'): if not symmetric: v = torch.randn(batch_size, N, dtype=torch.complex64, device=device, requires_grad=True) w = torch.randn(batch_size, N, dtype=torch.complex64, device=device, requires_grad=True) z = torch.randn(L, dtype=torch.complex64, device=device) else: assert N % 2 == 0 v_half = torch.randn(batch_size, N // 2, dtype=torch.complex64, device=device) v = torch.cat([v_half, v_half.conj()], dim=-1).requires_grad_(True) w_half = torch.randn(batch_size, N // 2, dtype=torch.complex64, device=device) w = torch.cat([w_half, w_half.conj()], dim=-1).requires_grad_(True) z = torch.exp(1j * torch.randn(L, dtype=torch.float32, device=device)) return v, z, w def grad_to_half_grad(dx): dx_half, dx_half_conj = dx.chunk(2, dim=-1) return dx_half + dx_half_conj.conj() @pytest.mark.parametrize('L', [3, 17, 489, 2**10, 1047, 2**11, 2**12, 2**13, 2**14, 2**18]) @pytest.mark.parametrize('N', [4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]) def test_cauchy_mult_symmetric(N, L): # rtol, atol = (1e-4, 1e-4) if N <= 64 and L <= 1024 else(1e-3, 1e-3) atol = 1e-4 tol_factor = 2.0 # Our error shouldn't be this much higher than Keops' error device = 'cuda' batch_size = 4 torch.random.manual_seed(2357) v, z, w = generate_data(batch_size, N, L, symmetric=True, device=device) v_half = v[:, :N // 2].clone().detach().requires_grad_(True) w_half = w[:, :N // 2].clone().detach().requires_grad_(True) # out_torch = cauchy_mult_torch(v, z, w, symmetric=True) out_torch = cauchy_mult_torch(v.cdouble(), z.cdouble(), w.cdouble(), symmetric=True).cfloat() out_keops = cauchy_mult_keops(v, z, w) out = cauchy_mult(v_half, z, w_half) relerr_out_keops = (out_keops - out_torch).abs() / out_torch.abs() relerr_out = (out - out_torch).abs() / out_torch.abs() dout = torch.randn_like(out) dv_torch, dw_torch = torch.autograd.grad(out_torch, (v, w), dout, retain_graph=True) dv_torch, dw_torch = dv_torch[:, :N // 2], dw_torch[:, :N // 2] dv_keops, dw_keops = torch.autograd.grad(out_keops, (v, w), dout, retain_graph=True) dv_keops, dw_keops = grad_to_half_grad(dv_keops), grad_to_half_grad(dw_keops) dv, dw = torch.autograd.grad(out, (v_half, w_half), dout, retain_graph=True) relerr_dv_keops = (dv_keops - dv_torch).abs() / dv_torch.abs() relerr_dv = (dv - dv_torch).abs() / dv_torch.abs() relerr_dw_keops = (dw_keops - dw_torch).abs() / dw_torch.abs() relerr_dw = (dw - dw_torch).abs() / dw_torch.abs() print(f'Keops out relative error: max {relerr_out_keops.amax().item():.6f}, mean {relerr_out_keops.mean().item():6f}') print(f'out relative error: max {relerr_out.amax().item():.6f}, mean {relerr_out.mean().item():.6f}') print(f'Keops dv relative error: max {relerr_dv_keops.amax().item():.6f}, mean {relerr_dv_keops.mean().item():6f}') print(f'dv relative error: max {relerr_dv.amax().item():.6f}, mean {relerr_dv.mean().item():.6f}') print(f'Keops dw relative error: max {relerr_dw_keops.amax().item():.6f}, mean {relerr_dw_keops.mean().item():6f}') print(f'dw relative error: max {relerr_dw.amax().item():.6f}, mean {relerr_dw.mean().item():.6f}') assert (relerr_out.amax() <= relerr_out_keops.amax() * tol_factor + atol) assert (relerr_out.mean() <= relerr_out_keops.mean() * tol_factor + atol) # assert torch.allclose(out, out_torch, rtol=rtol, atol=atol) # assert torch.allclose(out, out_keops, rtol=rtol, atol=atol) assert (relerr_dv.amax() <= relerr_dv_keops.amax() * tol_factor + atol) assert (relerr_dv.mean() <= relerr_dv_keops.mean() * tol_factor + atol) assert (relerr_dw.amax() <= relerr_dw_keops.amax() * tol_factor + atol) assert (relerr_dw.mean() <= relerr_dw_keops.mean() * tol_factor + atol) # assert torch.allclose(dv, dv_torch, rtol=1e-4, atol=1e-4) # assert torch.allclose(dv, dv_keops, rtol=1e-4, atol=1e-4) # assert torch.allclose(dw, dw_torch, rtol=1e-4, atol=1e-4) # assert torch.allclose(dw, dw_keops, rtol=1e-4, atol=1e-4)
H3-main
csrc/cauchy/test_cauchy.py
import torch import torch.nn.functional as F from einops import rearrange from fftconv import fftconv_fwd, fftconv_bwd def fftconv_ref(u, k, D, dropout_mask): seqlen = u.shape[-1] fft_size = 2 * seqlen k_f = torch.fft.rfft(k, n=fft_size) / fft_size u_f = torch.fft.rfft(u.to(dtype=k.dtype), n=fft_size) y = torch.fft.irfft(u_f * k_f, n=fft_size, norm='forward')[..., :seqlen] out = y + u * D.unsqueeze(-1) return (F.gelu(out) * rearrange(dropout_mask, 'b H -> b H 1')).to(dtype=u.dtype) def fftconv_fast(u, k, D, dropout_mask): """Fuse padding + rfft + pointwise mult + ifft + multiply with D + gelu + dropout """ seqlen = u.shape[-1] fft_size = 2 * seqlen k_f = torch.fft.rfft(k, n=fft_size) out = fftconv_fwd(u, k_f, D, dropout_mask, fft_size) return out def fftconv_fast_bwd(dout, u, k, D, dropout_mask=None): seqlen = u.shape[-1] fft_size = 2 * seqlen k_f = torch.fft.rfft(k, n=fft_size) dx, dk_f, dD = fftconv_bwd(dout, u, k_f, D, dropout_mask, fft_size) dk = torch.fft.irfft(dk_f, n=fft_size, norm='forward')[..., :seqlen] return dx, dk, dD device = 'cuda' dtype = torch.float32 # dtype = torch.float16 batch_size = 64 H = 256 fft_size = 2048 seqlen = 1024 dropout_prob = 0.37 torch.manual_seed(0) u = torch.randn(batch_size, H, seqlen, device=device, dtype=dtype, requires_grad=True) k = torch.randn(H, seqlen, device=device, requires_grad=True) D = torch.randn(H, device=device, requires_grad=True) dropout_mask = F.dropout(torch.ones(batch_size, H, device=device), dropout_prob) out = fftconv_ref(u, k, D, dropout_mask) out = fftconv_fast(u, k, D, dropout_mask) g = torch.randn_like(out) fftconv_fast_bwd(g, u, k, D, dropout_mask)
H3-main
csrc/fftconv/launch_fftconv.py
# Adapted from https://github.com/NVIDIA/apex/blob/master/setup.py import torch from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME from setuptools import setup, find_packages import subprocess import sys import warnings import os # ninja build does not work unless include_dirs are abs path this_dir = os.path.dirname(os.path.abspath(__file__)) def get_cuda_bare_metal_version(cuda_dir): raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True) output = raw_output.split() release_idx = output.index("release") + 1 release = output[release_idx].split(".") bare_metal_major = release[0] bare_metal_minor = release[1][0] return raw_output, bare_metal_major, bare_metal_minor def check_cuda_torch_binary_vs_bare_metal(cuda_dir): raw_output, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(cuda_dir) torch_binary_major = torch.version.cuda.split(".")[0] torch_binary_minor = torch.version.cuda.split(".")[1] print("\nCompiling cuda extensions with") print(raw_output + "from " + cuda_dir + "/bin\n") if (bare_metal_major != torch_binary_major) or (bare_metal_minor != torch_binary_minor): raise RuntimeError( "Cuda extensions are being compiled with a version of Cuda that does " "not match the version used to compile Pytorch binaries. " "Pytorch binaries were compiled with Cuda {}.\n".format(torch.version.cuda) + "In some cases, a minor-version mismatch will not cause later errors: " "https://github.com/NVIDIA/apex/pull/323#discussion_r287021798. " "You can try commenting out this check (at your own risk)." ) def raise_if_cuda_home_none(global_option: str) -> None: if CUDA_HOME is not None: return raise RuntimeError( f"{global_option} was requested, but nvcc was not found. Are you sure your environment has nvcc available? " "If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, " "only images whose names contain 'devel' will provide nvcc." ) def append_nvcc_threads(nvcc_extra_args): _, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(CUDA_HOME) if int(bare_metal_major) >= 11 and int(bare_metal_minor) >= 2: return nvcc_extra_args + ["--threads", "4"] return nvcc_extra_args if not torch.cuda.is_available(): # https://github.com/NVIDIA/apex/issues/486 # Extension builds after https://github.com/pytorch/pytorch/pull/23408 attempt to query torch.cuda.get_device_capability(), # which will fail if you are compiling in an environment without visible GPUs (e.g. during an nvidia-docker build command). print( "\nWarning: Torch did not find available GPUs on this system.\n", "If your intention is to cross-compile, this is not an error.\n" "By default, Apex will cross-compile for Pascal (compute capabilities 6.0, 6.1, 6.2),\n" "Volta (compute capability 7.0), Turing (compute capability 7.5),\n" "and, if the CUDA version is >= 11.0, Ampere (compute capability 8.0).\n" "If you wish to cross-compile for a single specific architecture,\n" 'export TORCH_CUDA_ARCH_LIST="compute capability" before running setup.py.\n', ) if os.environ.get("TORCH_CUDA_ARCH_LIST", None) is None: _, bare_metal_major, bare_metal_minor = get_cuda_bare_metal_version(CUDA_HOME) if int(bare_metal_major) == 11: os.environ["TORCH_CUDA_ARCH_LIST"] = "6.0;6.1;6.2;7.0;7.5;8.0" if int(bare_metal_minor) > 0: os.environ["TORCH_CUDA_ARCH_LIST"] = "6.0;6.1;6.2;7.0;7.5;8.0;8.6" else: os.environ["TORCH_CUDA_ARCH_LIST"] = "6.0;6.1;6.2;7.0;7.5" print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__)) TORCH_MAJOR = int(torch.__version__.split(".")[0]) TORCH_MINOR = int(torch.__version__.split(".")[1]) cmdclass = {} ext_modules = [] raise_if_cuda_home_none("fftconv") # Check, if CUDA11 is installed for compute capability 8.0 cc_flag = [] # cc_flag.append("-gencode") # cc_flag.append("arch=compute_70,code=sm_70") cc_flag.append("-gencode") cc_flag.append("arch=compute_80,code=sm_80") ext_modules.append( CUDAExtension( 'fftconv', [ 'fftconv.cpp', 'fftconv_cuda.cu', ], extra_compile_args={'cxx': ['-g', '-march=native', '-funroll-loops'], 'nvcc': ['-O3', '--threads', '4', '-lineinfo', '--use_fast_math', '-std=c++17', '-arch=compute_70'] # extra_compile_args={'cxx': ['-O3'], # 'nvcc': append_nvcc_threads(['-O3', '-lineinfo', '--use_fast_math', '-std=c++17'] + cc_flag) }, include_dirs=[os.path.join(this_dir, 'mathdx/22.02/include')] ) ) torch.utils.cpp_extension.COMMON_NVCC_FLAGS.remove('-D__CUDA_NO_HALF2_OPERATORS__') setup( name="fftconv", version="0.1", description="FFTConv for state-space models", ext_modules=ext_modules, cmdclass={"build_ext": BuildExtension} if ext_modules else {}, )
H3-main
csrc/fftconv/setup.py
import math import re import numpy as np # N = 8192 N = 16384 # The case of 0 / N is special, we want to simplify it to 0 / 2 instead of 0 / 1 numerator = np.arange(1, N // 8 + 1) gcd = np.gcd(numerator, N) num = numerator // gcd denom = N // gcd lut_vals = ['T_2_0'] + [f'T_{d}_{n}' for n, d in zip(num, denom)] lut_string = f"static const __device__ float2 lut_mine_sp_8_{N}[{N // 8 + 1}] = {{\n {','.join(lut_vals)}\n}};" print(lut_string) # Only define new values if it's not already in the cuFFTDx lookup table cufftdx_lut_filename = 'mathdx/22.02/include/cufftdx/include/database/lut_defines_0.hpp.inc' matches = set() reg = re.compile(f'^#define T_{N}_([0-9]+) ') with open(cufftdx_lut_filename, 'r') as f: for line in f: if (match := reg.match(line)) is not None: matches.add(int(match[1])) numerator = np.arange(1, N // 8 + 1, 2) angle = -2 * math.pi * numerator.astype(np.float64) / N cos, sin = np.cos(angle), np.sin(angle) defs = [f'#define T_{N}_{n} {{{c:.40f},{s:.40f}}}' for n, c, s in zip(numerator, cos, sin) if n not in matches] def_string = '\n'.join(defs) print(def_string)
H3-main
csrc/fftconv/lut_code_gen.py
import math import torch import torch.nn.functional as F import pytest from einops import rearrange from src.ops.fftconv import fftconv_ref, fftconv_h3_ref, fftconv_func @pytest.mark.parametrize('output_hbl_layout', [False, True]) # @pytest.mark.parametrize('output_hbl_layout', [False]) @pytest.mark.parametrize('input_hbl_layout', [False, True]) # @pytest.mark.parametrize('input_hbl_layout', [True]) @pytest.mark.parametrize('force_fp16_output', [False, True]) # @pytest.mark.parametrize('force_fp16_output', [False]) @pytest.mark.parametrize('dtype', [torch.float32, torch.float16, torch.bfloat16]) # @pytest.mark.parametrize('dtype', [torch.float32]) @pytest.mark.parametrize('dropout_prob', [None, 0.0, 0.17]) # @pytest.mark.parametrize('dropout_prob', [None]) @pytest.mark.parametrize('seqlen', [8, 16, 32, 64, 128, 256, 372, 512, 784, 1024, 1134, 2048, 4096, 8192]) # @pytest.mark.parametrize('seqlen', [2048, 4096, 8192]) # There was an issue with batch_size=1 and output_hbl_layout=True where we previously had a bug # So I'm putting batch_size=1 here in the test to make sure we don't regress. @pytest.mark.parametrize('batch_size', [1, 4]) # @pytest.mark.parametrize('batch_size', [4]) @pytest.mark.parametrize('gelu', [True, False]) # @pytest.mark.parametrize('gelu', [False]) def test_fftconv(gelu, batch_size, seqlen, dropout_prob, dtype, force_fp16_output, input_hbl_layout, output_hbl_layout): if dtype == torch.bfloat16 and force_fp16_output: pytest.skip() device = 'cuda' rtol, atol = (1e-4, 5e-4) if dtype == torch.float32 and not force_fp16_output else (1e-3, 1e-3) if dtype == torch.bfloat16: rtol, atol = 1e-2, 1e-2 # set seed torch.random.manual_seed(0) H = 256 if not input_hbl_layout: u_fp32 = torch.randn(batch_size, H, seqlen, device=device, dtype=torch.float32, requires_grad=True) u = u_fp32.detach().clone().type(dtype).requires_grad_() else: u_fp32 = rearrange(torch.randn(H, batch_size, seqlen, device=device), 'h b l -> b h l').requires_grad_() u = u_fp32.detach().clone().type(dtype).requires_grad_() u_ref = u.detach().clone().requires_grad_() u_fp32_ref = u_fp32.detach().clone().requires_grad_() k = torch.randn(H, seqlen, device=device, requires_grad=True) k_rev = torch.randn(H, seqlen, device=device, requires_grad=True) k_ref = k.detach().clone().requires_grad_() k_rev_ref = k_rev.detach().clone().requires_grad_() D = torch.randn(H, device=device, requires_grad=True) D_ref = D.detach().clone().requires_grad_() dropout_mask = (F.dropout(torch.ones(batch_size, H, device=device), dropout_prob) if dropout_prob is not None else None) out_ref = fftconv_ref(u_ref, k_ref, D_ref, dropout_mask, gelu=gelu, k_rev=k_rev_ref) if force_fp16_output: out_ref = out_ref.to(dtype=torch.float16) out_ref_fp32 = fftconv_ref(u_fp32_ref, k_ref, D_ref, dropout_mask, gelu=gelu, k_rev=k_rev_ref) out = fftconv_func(u, k, D, dropout_mask, gelu, force_fp16_output, output_hbl_layout, k_rev=k_rev) assert out.dtype == dtype if not force_fp16_output else torch.float16 if not output_hbl_layout: assert out.is_contiguous() else: assert rearrange(out, 'b h l -> h b l').is_contiguous() print(f'Output max diff: {(out - out_ref).abs().max().item()}') print(f'Output mean diff: {(out - out_ref).abs().mean().item()}') g = torch.randn_like(out) / 32 out_ref.backward(g) out.backward(g) print(f'du max diff: {(u.grad - u_ref.grad).abs().max().item()}') print(f'dk max diff: {(k.grad - k_ref.grad).abs().max().item()}') print(f'dk_rev max diff: {(k_rev.grad - k_rev_ref.grad).abs().max().item()}') print(f'dD max diff: {(D.grad - D_ref.grad).abs().max().item()}') assert u.grad.dtype == u.dtype assert k.grad.dtype == k.dtype assert k_rev.grad.dtype == k_rev.dtype assert D.grad.dtype == D.dtype if dtype == torch.float32: assert torch.allclose(out, out_ref, rtol=rtol, atol=atol) else: # Check that FFTConv's numerical error is at most twice the numerical error # of a Pytorch implementation. assert (out - out_ref_fp32).abs().max().item() <= 2 * (out_ref - out_ref_fp32).abs().max().item() assert torch.allclose(u.grad, u_ref.grad, rtol=rtol, atol=atol) assert torch.allclose(k.grad, k_ref.grad, rtol=rtol, atol=atol) assert torch.allclose(k_rev.grad, k_rev_ref.grad, rtol=rtol, atol=atol) assert torch.allclose(D.grad, D_ref.grad, rtol=rtol, atol=atol) @pytest.mark.parametrize('output_hbl_layout', [False, True]) # @pytest.mark.parametrize('output_hbl_layout', [True]) @pytest.mark.parametrize('input_hbl_layout', [False, True]) # @pytest.mark.parametrize('input_hbl_layout', [True]) # @pytest.mark.parametrize('force_fp16_output', [False, True]) @pytest.mark.parametrize('force_fp16_output', [False]) # @pytest.mark.parametrize('dtype', [torch.float32, torch.float16, torch.bfloat16]) @pytest.mark.parametrize('dtype', [torch.float16, torch.bfloat16]) @pytest.mark.parametrize('dropout_prob', [None]) @pytest.mark.parametrize('head_dim', [1, 8]) # @pytest.mark.parametrize('head_dim', [1]) @pytest.mark.parametrize('seqlen', [1024, 2048, 4096, 8192]) # @pytest.mark.parametrize('seqlen', [2048]) @pytest.mark.parametrize('batch_size', [1, 4]) # @pytest.mark.parametrize('batch_size', [8]) @pytest.mark.parametrize('gelu', [False]) def test_fftconv_h3(gelu, batch_size, seqlen, head_dim, dropout_prob, dtype, force_fp16_output, input_hbl_layout, output_hbl_layout): if dtype == torch.bfloat16 and force_fp16_output: pytest.skip() assert not gelu assert dropout_prob is None device = 'cuda' rtol, atol = (1e-4, 1e-4) if dtype == torch.float32 and not force_fp16_output else (1e-2, 1e-1) if dtype == torch.bfloat16: rtol, atol = 5e-2, 5e-1 if head_dim > 1: rtol *= head_dim atol *= head_dim # set seed torch.random.manual_seed(0) H = 256 if not input_hbl_layout: k_fp32 = torch.randn(batch_size, H, seqlen, device=device, requires_grad=True) q_fp32 = torch.randn(batch_size, H, seqlen, device=device, requires_grad=True) v_fp32 = torch.randn(batch_size, H, seqlen, device=device, requires_grad=True) k = k_fp32.detach().clone().type(dtype).requires_grad_() q = q_fp32.detach().clone().type(dtype).requires_grad_() v = v_fp32.detach().clone().type(dtype).requires_grad_() else: k_fp32 = rearrange(torch.randn(H, batch_size, seqlen, device=device), 'h b l -> b h l').requires_grad_() q_fp32 = rearrange(torch.randn(H, batch_size, seqlen, device=device), 'h b l -> b h l').requires_grad_() v_fp32 = rearrange(torch.randn(H, batch_size, seqlen, device=device), 'h b l -> b h l').requires_grad_() k = k_fp32.detach().clone().type(dtype).requires_grad_() q = q_fp32.detach().clone().type(dtype).requires_grad_() v = v_fp32.detach().clone().type(dtype).requires_grad_() k_ref = k.detach().clone().requires_grad_() q_ref = q.detach().clone().requires_grad_() v_ref = v.detach().clone().requires_grad_() k_fp32_ref = k_fp32.detach().clone().requires_grad_() q_fp32_ref = q_fp32.detach().clone().requires_grad_() v_fp32_ref = v_fp32.detach().clone().requires_grad_() ssm_kernel = torch.randn(H // head_dim, seqlen, device=device, requires_grad=True) ssm_kernel_rev = torch.randn(H // head_dim, seqlen, device=device, requires_grad=True) ssm_kernel_ref = ssm_kernel.detach().clone().requires_grad_() ssm_kernel_rev_ref = ssm_kernel_rev.detach().clone().requires_grad_() D = torch.randn(H // head_dim, device=device, requires_grad=True) D_ref = D.detach().clone().requires_grad_() dropout_mask = (F.dropout(torch.ones(batch_size, H, device=device), dropout_prob) if dropout_prob is not None else None) out_ref = fftconv_h3_ref(k_ref, ssm_kernel_ref, D_ref, q_ref, v_ref, head_dim, ssm_kernel_rev=ssm_kernel_rev_ref) if force_fp16_output: out_ref = out_ref.to(dtype=torch.float16) out_ref_fp32 = fftconv_h3_ref(k_fp32_ref, ssm_kernel_ref, D_ref, q_fp32_ref, v_fp32_ref, head_dim, ssm_kernel_rev=ssm_kernel_rev_ref) out = fftconv_func(k, ssm_kernel, D, dropout_mask, gelu, force_fp16_output, output_hbl_layout, v, head_dim, q, k_rev=ssm_kernel_rev) assert out.dtype == dtype if not force_fp16_output else torch.float16 if not output_hbl_layout: assert out.is_contiguous() else: assert rearrange(out, 'b h l -> h b l').is_contiguous() print(f'Output max diff: {(out - out_ref).abs().max().item()}') print(f'Output max relative diff: {(out - out_ref).abs().max().item() / out_ref.abs().max().item()}') print(f'Output mean diff: {(out - out_ref).abs().mean().item()}') g = torch.randn_like(out) / 32 out_ref.backward(g) out.backward(g) print(f'dk max diff: {(k.grad - k_ref.grad).abs().max().item()}') print(f'dq max diff: {(q.grad - q_ref.grad).abs().max().item()}') print(f'dv max diff: {(v.grad - v_ref.grad).abs().max().item()}') print(f'dssm_kernel max diff: {(ssm_kernel.grad - ssm_kernel_ref.grad).abs().max().item()}') print(f'dssm_kernel_rev max diff: {(ssm_kernel_rev.grad - ssm_kernel_rev_ref.grad).abs().max().item()}') print(f'dD max diff: {(D.grad - D_ref.grad).abs().max().item()}') assert k.grad.dtype == k.dtype assert ssm_kernel.grad.dtype == ssm_kernel.dtype assert D.grad.dtype == D.dtype # Check that FFTConv's numerical error is at most twice the numerical error # of a Pytorch implementation. assert (out - out_ref_fp32).abs().max().item() <= 2 * (out_ref - out_ref_fp32).abs().max().item() assert torch.allclose(k.grad, k_ref.grad, rtol=rtol, atol=atol) assert torch.allclose(q.grad, q_ref.grad, rtol=rtol, atol=atol) assert torch.allclose(v.grad, v_ref.grad, rtol=rtol, atol=atol) assert torch.allclose(ssm_kernel.grad, ssm_kernel_ref.grad, rtol=rtol, atol=atol) assert torch.allclose(ssm_kernel_rev.grad, ssm_kernel_rev_ref.grad, rtol=rtol, atol=atol) assert torch.allclose(D.grad, D_ref.grad, rtol=rtol, atol=atol)
H3-main
tests/ops/test_fftconv.py
import argparse import torch from transformers import GPT2Tokenizer from src.models.ssm_seq import SSMLMHeadModel parser = argparse.ArgumentParser(description='H3 text generation') parser.add_argument('--dmodel', type=int, default=2048) parser.add_argument('--nlayer', type=int, default=24) parser.add_argument('--attn-layer-idx', nargs='+', type=int, default=[8,16]) parser.add_argument('--rotary_emb_dim', type=int, default=None, help='For rotary embeddings, set to 64. Default is None.') parser.add_argument('--nheads', type=int, default=16) parser.add_argument('--ckpt', type=str, default=None) parser.add_argument('--genlen', type=int, default=128) parser.add_argument('--top_p', type=float, default=0.9) parser.add_argument('--top_k', type=int, default=50) parser.add_argument('--prompt', type=str, default='Hungry Hungry Hippos: Towards Language Modeling With State Space Models is a new language model that') args = parser.parse_args() device = 'cuda' dtype = torch.float16 tokenizer = GPT2Tokenizer.from_pretrained("gpt2") # set seed torch.random.manual_seed(0) d_model = args.dmodel n_layer = args.nlayer ssm_cfg = dict(mode='diag', measure='diag-lin') attn_layer_idx = args.attn_layer_idx if args.rotary_emb_dim is None: attn_cfg = dict(num_heads=args.nheads) else: attn_cfg = dict(num_heads=args.nheads, rotary_emb_dim=args.rotary_emb_dim) model = SSMLMHeadModel(d_model, n_layer=n_layer, d_inner=4 * d_model, vocab_size=len(tokenizer), ssm_cfg=ssm_cfg, attn_layer_idx=attn_layer_idx, attn_cfg=attn_cfg, pad_vocab_size_multiple=8).to(device=device) if args.ckpt is not None: state_dict = torch.load(args.ckpt, map_location=device) if 'pytorch-lightning_version' in state_dict: state_dict = {k[len('model.'):]: v for k, v in state_dict['state_dict'].items() if k.startswith('model.')} model.load_state_dict(state_dict) model.eval() # Only cast the nn.Linear parameters to dtype, the SSM params stay in fp32 # Pytorch lacks support for complex32 (i.e. complex<float16>) and complex<bfloat16>. for name, module in model.named_modules(): if isinstance(module, (torch.nn.Linear, torch.nn.Embedding, torch.nn.LayerNorm)): module.to(dtype=dtype) prompt = args.prompt input_ids = torch.tensor(tokenizer.encode(prompt)).unsqueeze(0).to(device=device) max_length = input_ids.shape[1] + args.genlen output_ids = model.generate(input_ids=input_ids, max_length=max_length, return_dict_in_generate=False, output_scores=False, timing=False, top_p=args.top_p, top_k=args.top_k, eos_token_id=tokenizer.eos_token_id) print(tokenizer.batch_decode(output_ids)[0])
H3-main
examples/generate_text_h3.py
from typing import Optional import argparse import time import torch import torch.nn.functional as F from einops import rearrange from transformers import GPT2Tokenizer, GPT2Config, GPT2LMHeadModel from src.models.ssm.h3 import H3 from src.models.ssm_seq import SSMLMHeadModel from flash_attn.utils.generation import InferenceParams parser = argparse.ArgumentParser(description='H3 generation benchmarking') parser.add_argument('--dmodel', type=int, default=2048) parser.add_argument('--nlayer', type=int, default=24) parser.add_argument('--attn-layer-idx', type=list, default=[8, 16]) parser.add_argument('--nheads', type=int, default=16) parser.add_argument('--ckpt', type=str, default=None) parser.add_argument('--promptlen', type=int, default=1024) parser.add_argument('--genlen', type=int, default=128) args = parser.parse_args() repeats = 3 device = 'cuda' dtype = torch.float16 tokenizer = GPT2Tokenizer.from_pretrained("gpt2") # set seed torch.random.manual_seed(0) d_model = args.dmodel n_layer = args.nlayer ssm_cfg = dict(mode='diag', measure='diag-lin') attn_layer_idx = args.attn_layer_idx attn_cfg = dict(num_heads=args.nheads) model = SSMLMHeadModel(d_model, n_layer=n_layer, d_inner=4 * d_model, vocab_size=len(tokenizer), ssm_cfg=ssm_cfg, attn_layer_idx=attn_layer_idx, attn_cfg=attn_cfg, pad_vocab_size_multiple=8).to(device=device) print(f'Number of parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad)}') if args.ckpt is not None: state_dict = torch.load(args.ckpt, map_location=device) if 'pytorch-lightning_version' in state_dict: state_dict = {k[len('model.'):]: v for k, v in state_dict['state_dict'].items() if k.startswith('model.')} model.load_state_dict(state_dict) model.eval() # Only cast the nn.Linear parameters to dtype, the SSM params stay in fp32 # Pytorch lacks support for complex32 (i.e. complex<float16>) and complex<bfloat16>. for name, module in model.named_modules(): if isinstance(module, (torch.nn.Linear, torch.nn.Embedding, torch.nn.LayerNorm)): module.to(dtype=dtype) input_ids = torch.randint(0, 100, (64, args.promptlen), dtype=torch.long, device='cuda') max_length = input_ids.shape[1] + args.genlen fn = lambda: model.generate(input_ids=input_ids, max_length=max_length, return_dict_in_generate=True, output_scores=True, timing=False) fn() torch.cuda.synchronize() start = time.time() for _ in range(repeats): fn() torch.cuda.synchronize() print(f'Prompt processing + decoding time: {(time.time() - start) / repeats * 1000:.0f}ms') config = GPT2Config(vocab_size=len(tokenizer), n_positions=2048, n_embd=d_model, n_layer=n_layer, activation_function='gelu', num_attention_heads=args.nheads) model_hf = GPT2LMHeadModel(config).to(dtype=dtype, device=device) print(f'Transformer number of parameters: {sum(p.numel() for p in model_hf.parameters() if p.requires_grad)}') model_hf.eval() fn = lambda: model_hf.generate(input_ids=input_ids, max_length=max_length, return_dict_in_generate=True, output_scores=True) fn() torch.cuda.synchronize() start = time.time() for _ in range(repeats): fn() torch.cuda.synchronize() print(f'Transformer prompt processing + decoding time: {(time.time() - start) / repeats * 1000:.0f}ms')
H3-main
benchmarks/benchmark_generation_h3.py
import logging from pytorch_lightning.utilities import rank_zero_only # Copied from https://docs.python.org/3/howto/logging-cookbook.html#using-a-context-manager-for-selective-logging class LoggingContext: def __init__(self, logger, level=None, handler=None, close=True): self.logger = logger self.level = level self.handler = handler self.close = close def __enter__(self): if self.level is not None: self.old_level = self.logger.level self.logger.setLevel(self.level) if self.handler: self.logger.addHandler(self.handler) def __exit__(self, et, ev, tb): if self.level is not None: self.logger.setLevel(self.old_level) if self.handler: self.logger.removeHandler(self.handler) if self.handler and self.close: self.handler.close() # implicit return of None => don't swallow exceptions def get_logger(name=__name__) -> logging.Logger: """Initializes multi-GPU-friendly python logger.""" logger = logging.getLogger(name) # this ensures all logging levels get marked with the rank zero decorator # otherwise logs would get multiplied for each GPU process in multi-GPU setup for level in ("debug", "info", "warning", "error", "exception", "fatal", "critical"): setattr(logger, level, rank_zero_only(getattr(logger, level))) return logger
H3-main
src/utils/utils.py
# Copyright (c) 2023, Tri Dao, Dan Fu. import math import re from functools import partial from collections import namedtuple, OrderedDict from collections.abc import Sequence import torch import torch.nn as nn import torch.nn.functional as F from transformers.models.gpt2.configuration_gpt2 import GPT2Config from flash_attn.modules.mha import MHA from flash_attn.modules.mlp import Mlp, FusedMLP from flash_attn.modules.block import Block from flash_attn.modules.embedding import GPT2Embeddings from flash_attn.utils.generation import GenerationMixin try: from flash_attn.ops.layer_norm import dropout_add_layer_norm except ImportError: dropout_add_layer_norm = None from src.models.ssm.h3 import H3 def create_mixer_cls(ssm_cls=H3, ssm_cfg=None, attn_layer_idx=None, attn_cfg=None, layer_idx=None): if attn_layer_idx is not None and layer_idx in attn_layer_idx: causal = True if attn_cfg is None else attn_cfg.pop('causal', True) mixer_cls = partial(MHA, layer_idx=layer_idx, causal=causal, **(attn_cfg if attn_cfg is not None else {})) else: mixer_cls = partial(ssm_cls, layer_idx=layer_idx, **(ssm_cfg if ssm_cfg is not None else {})) return mixer_cls def create_mlp_cls(d_model, d_inner=None, fused_mlp=False): inner_dim = d_inner if d_inner is not None else 4 * d_model if not fused_mlp: mlp_cls = partial(Mlp, hidden_features=inner_dim, activation=partial(F.gelu, approximate='tanh')) else: mlp_cls = partial(FusedMLP, hidden_features=inner_dim) return mlp_cls def create_block(d_model, d_inner=None, ssm_cls=H3, ssm_cfg=None, attn_layer_idx=None, attn_cfg=None, layer_norm_epsilon=1e-5, resid_dropout1=0.0, resid_dropout2=0.0, residual_in_fp32=False, fused_mlp=False, fused_dropout_add_ln=False, layer_idx=None): mixer_cls = create_mixer_cls(ssm_cls=ssm_cls, ssm_cfg=ssm_cfg, attn_layer_idx=attn_layer_idx, attn_cfg=attn_cfg, layer_idx=layer_idx) mlp_cls = create_mlp_cls(d_model, d_inner=d_inner, fused_mlp=fused_mlp) norm_cls = partial(nn.LayerNorm, eps=layer_norm_epsilon) block = Block(d_model, mixer_cls, mlp_cls, norm_cls=norm_cls, prenorm=True, resid_dropout1=resid_dropout1, resid_dropout2=resid_dropout2, fused_dropout_add_ln=fused_dropout_add_ln, residual_in_fp32=residual_in_fp32) block.layer_idx = layer_idx return block # https://github.com/huggingface/transformers/blob/c28d04e9e252a1a099944e325685f14d242ecdcd/src/transformers/models/gpt2/modeling_gpt2.py#L454 def _init_weights(module, n_layer, initializer_range=0.02, rescale_prenorm_residual=True, glu_act=False): if isinstance(module, nn.Linear): nn.init.normal_(module.weight, std=initializer_range) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): nn.init.normal_(module.weight, std=initializer_range) if rescale_prenorm_residual: # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. # > -- GPT-2 :: https://openai.com/blog/better-language-models/ # # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py for name, p in module.named_parameters(): if name in ["out_proj.weight", "fc2.weight"]: # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block nn.init.normal_(p, mean=0.0, std=initializer_range / math.sqrt(2 * n_layer)) # If using GLU activation for now, we scale the std by 2 elif name in ["output_linear.0.weight"]: # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block if not glu_act: nn.init.normal_(p, mean=0.0, std=initializer_range / math.sqrt(2 * n_layer)) else: out_features = p.shape[0] # Multiplying the first half of the matrix by 2 since sigmoid scales it down by 0.5 # on average. nn.init.normal_(p[:out_features // 2], mean=0.0, std=initializer_range / math.sqrt(2 * n_layer) * 2) class SSMModel(nn.Module): def __init__(self, d_model: int, n_layer: int, d_inner: int, vocab_size: int, ssm_cfg=None, attn_layer_idx=None, attn_cfg=None, max_position_embeddings=0, resid_dropout: float = 0.0, embed_dropout: float = 0.1, dropout_cls=nn.Dropout, layer_norm_epsilon: float = 1e-5, initializer_cfg=None, fused_mlp=False, fused_dropout_add_ln=False, residual_in_fp32=False, **kwargs) -> None: super().__init__() self.embeddings = GPT2Embeddings(d_model, vocab_size, max_position_embeddings) self.residual_in_fp32 = residual_in_fp32 # We change the order of dropout, residual and layer norm: # Instead of LN -> Attn / MLP -> Dropout -> Add, we do: # Dropout -> Add -> LN -> Attn / MLP, returning both the residual branch (output of Add) and # the main branch (output of MLP). The model definition is unchanged, but the mapping of the # nn.Dropout probabilities are changed. # This is for performance reason: we can fuse dropout + add + layer_norm. self.fused_dropout_add_ln = fused_dropout_add_ln if self.fused_dropout_add_ln and dropout_add_layer_norm is None: raise ImportError('dropout_add_layer_norm is not installed') self.layers = nn.ModuleList([create_block( d_model, d_inner=d_inner, ssm_cfg=ssm_cfg, attn_layer_idx=attn_layer_idx, attn_cfg=attn_cfg, layer_norm_epsilon=layer_norm_epsilon, resid_dropout1=embed_dropout if i == 0 else resid_dropout, resid_dropout2=resid_dropout, residual_in_fp32=residual_in_fp32, fused_mlp=fused_mlp, fused_dropout_add_ln=fused_dropout_add_ln, layer_idx=i ) for i in range(n_layer)]) self.drop_f = nn.Dropout(resid_dropout) self.ln_f = nn.LayerNorm(d_model, eps=layer_norm_epsilon) self.apply(partial(_init_weights, n_layer=n_layer, **(initializer_cfg if initializer_cfg is not None else {}))) def forward(self, input_ids, position_ids=None, inference_params=None): hidden_states = self.embeddings(input_ids, position_ids=position_ids) residual = None mixer_kwargs = None if inference_params is not None: mixer_kwargs = dict(inference_params=inference_params) for layer in self.layers: hidden_states, residual = layer(hidden_states, residual, mixer_kwargs=mixer_kwargs) if not self.fused_dropout_add_ln: dropped = self.drop_f(hidden_states) residual = (dropped + residual) if residual is not None else dropped hidden_states = self.ln_f(residual.to(dtype=self.ln_f.weight.dtype)) else: # Set prenorm=False here since we don't need the residual hidden_states = dropout_add_layer_norm( hidden_states, residual, self.ln_f.weight, self.ln_f.bias, self.drop_f.p if self.training else 0.0, self.ln_f.eps, prenorm=False, residual_in_fp32=self.residual_in_fp32 ) return hidden_states class SSMLMHeadModel(nn.Module, GenerationMixin): def __init__(self, d_model: int, n_layer: int, d_inner: int, vocab_size: int, ssm_cfg=None, attn_layer_idx=None, attn_cfg=None, max_position_embeddings=0, resid_dropout: float = 0.0, embed_dropout: float = 0.1, dropout_cls=nn.Dropout, layer_norm_epsilon: float = 1e-5, initializer_cfg=None, fused_mlp=False, fused_dropout_add_ln=False, residual_in_fp32=False, pad_vocab_size_multiple: int = 1, **kwargs) -> None: super().__init__() if vocab_size % pad_vocab_size_multiple != 0: vocab_size += pad_vocab_size_multiple - (vocab_size % pad_vocab_size_multiple) self.backbone = SSMModel( d_model=d_model, n_layer=n_layer, d_inner=d_inner, vocab_size=vocab_size, ssm_cfg=ssm_cfg, attn_layer_idx=attn_layer_idx, attn_cfg=attn_cfg, max_position_embeddings=max_position_embeddings, resid_dropout=resid_dropout, embed_dropout=embed_dropout, dropout_cls=dropout_cls, layer_norm_epsilon=layer_norm_epsilon, initializer_cfg=initializer_cfg, fused_mlp=fused_mlp, fused_dropout_add_ln=fused_dropout_add_ln, residual_in_fp32=residual_in_fp32, **kwargs ) self.lm_head = nn.Linear(d_model, vocab_size, bias=False) # Initialize weights and apply final processing self.apply(partial(_init_weights, n_layer=n_layer, **(initializer_cfg if initializer_cfg is not None else {}))) self.tie_weights() def tie_weights(self): self.lm_head.weight = self.backbone.embeddings.word_embeddings.weight def forward(self, input_ids, position_ids=None, inference_params=None): hidden_states = self.backbone(input_ids, position_ids=position_ids, inference_params=inference_params) lm_logits = self.lm_head(hidden_states) CausalLMOutput = namedtuple('CausalLMOutput', ['logits']) return CausalLMOutput(logits=lm_logits) def load_state_dict(self, state_dict, strict=True): # Remapping from our checkpoints that used different names def key_mapping_backbone(key): key = re.sub(r'^s4seq.encoder.', 'backbone.', key) key = re.sub(r'^embedding.', 'backbone.embeddings.word_embeddings.', key) key = re.sub(r'^backbone.norm', 'backbone.ln_0', key) return key state_dict = OrderedDict((key_mapping_backbone(k), v) for k, v in state_dict.items()) # Remapping from our checkpoints that used a different ordering of layers in the block # Previous: Mixer / MLP -> Dropout -> Add -> LN # Current: Dropout -> Add -> LN -> Attn / MLP if 'backbone.ln_0.weight' in state_dict: n_layers = len(self.backbone.layers) ln_weight = state_dict.pop(f'backbone.layers.{n_layers - 1}.norm2.weight') ln_bias = state_dict.pop(f'backbone.layers.{n_layers - 1}.norm2.bias') state_dict['backbone.ln_f.weight'] = ln_weight state_dict['backbone.ln_f.bias'] = ln_bias for l in reversed(range(n_layers)): ln_weight = state_dict.pop(f'backbone.layers.{l}.norm1.weight') ln_bias = state_dict.pop(f'backbone.layers.{l}.norm1.bias') state_dict[f'backbone.layers.{l}.norm2.weight'] = ln_weight state_dict[f'backbone.layers.{l}.norm2.bias'] = ln_bias if l > 0: ln_weight = state_dict.pop(f'backbone.layers.{l - 1}.norm2.weight') ln_bias = state_dict.pop(f'backbone.layers.{l - 1}.norm2.bias') state_dict[f'backbone.layers.{l}.norm1.weight'] = ln_weight state_dict[f'backbone.layers.{l}.norm1.bias'] = ln_bias ln_weight = state_dict.pop('backbone.ln_0.weight') ln_bias = state_dict.pop('backbone.ln_0.bias') state_dict[f'backbone.layers.0.norm1.weight'] = ln_weight state_dict[f'backbone.layers.0.norm1.bias'] = ln_bias return super().load_state_dict(state_dict, strict=strict)
H3-main
src/models/ssm_seq.py
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from src.models.ssm.ss_kernel import SSKernel try: from src.ops.fftconv import fftconv_func except ImportError: fftconv_func = None @torch.jit.script def mul_sum(q, y): return (q * y).sum(dim=1) class H3(nn.Module): def __init__( self, d_model, d_state=64, l_max=None, head_dim=1, use_fast_fftconv=False, dropout=0.0, # Just to absorb the kwarg layer_idx=None, device=None, dtype=None, # SSM Kernel arguments **kernel_args, ): """ d_state: the dimension of the state, also denoted by N l_max: the maximum kernel length, also denoted by L. Set l_max=None to always use a global kernel See the class .kernel.SSKernel for the kernel constructor which accepts kernel_args. Relevant options that are worth considering and tuning include "mode" + "measure", "dt_min", "dt_max", "lr" Other options are all experimental and should not need to be configured """ factory_kwargs = {'device': device, 'dtype': dtype} super().__init__() self.d_model = d_model self.head_dim = head_dim assert d_model % head_dim == 0 self.H = d_model // head_dim self.N = d_state self.L = l_max self.layer_idx = layer_idx self.use_fast_fftconv = use_fast_fftconv if self.use_fast_fftconv: assert fftconv_func is not None, 'Need to install fftconv' self.q_proj = nn.Linear(self.d_model, self.d_model, **factory_kwargs) self.k_proj = nn.Linear(self.d_model, self.d_model, **factory_kwargs) self.v_proj = nn.Linear(self.d_model, self.d_model, **factory_kwargs) # TODO: SSKernel doesn't take device argument yet self.ssm_k_kernel = SSKernel(self.d_model, N=d_state, L=self.L, mode='shift', lr=kernel_args.get('lr', None)) self.ssm_k_D = nn.Parameter(torch.randn(self.d_model)) # S4D Kernel self.kernel = SSKernel(self.H, N=self.N, L=self.L, channels=1, **kernel_args) self.D = nn.Parameter(torch.randn(self.H, **factory_kwargs)) # Pointwise # position-wise output transform to mix features # Don't use FusedDense since the layout is H first self.output_linear = nn.Linear(self.d_model, self.d_model) def forward(self, u, inference_params=None): """ u: (B L H) Returns: same shape as u """ L_og = u.size(-2) if self.use_fast_fftconv and L_og % 2 != 0: u = F.pad(u, (0, 0, 0, 1)) L = u.size(-2) use_fast_fftconv = self.use_fast_fftconv and inference_params is None state_k, state = None, None if inference_params is not None: assert self.layer_idx is not None if self.layer_idx not in inference_params.key_value_memory_dict: batch_shape = (u.shape[0] * self.head_dim * self.head_dim,) state_k = self.ssm_k_kernel.default_state(*batch_shape) state = self.kernel.default_state(*batch_shape) inference_params.key_value_memory_dict[self.layer_idx] = (state_k, state) else: state_k, state = inference_params.key_value_memory_dict[self.layer_idx] if inference_params.sequence_len_offset == 0: self.ssm_k_kernel._setup_step() self.kernel._setup_step() if inference_params is not None and inference_params.sequence_len_offset > 0: y, next_state_k, next_state = self.step(u, state_k, state) inference_params.key_value_memory_dict[self.layer_idx][0].copy_(next_state_k) inference_params.key_value_memory_dict[self.layer_idx][1].copy_(next_state) return y # Compute SS Kernel L_kernel = L if self.L is None else min(L, self.L ) ssm_kernel, k_state = self.kernel(L=L_kernel, state=state, rate=1.0) # (C H L) (B C H L) ssm_kernel = rearrange(ssm_kernel, '1 h l -> h l') u = rearrange(u, 'b l h -> (b l) h') dtype = (self.q_proj.weight.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype()) q = self.q_proj.weight @ u.T + self.q_proj.bias.to(dtype).unsqueeze(-1) k = self.k_proj.weight @ u.T + self.k_proj.bias.to(dtype).unsqueeze(-1) v = self.v_proj.weight @ u.T + self.v_proj.bias.to(dtype).unsqueeze(-1) q, k, v = [rearrange(x, 'h (b l) -> b h l', l=L) for x in [q, k, v]] k_og = k ssm_k_kernel, _ = self.ssm_k_kernel(L=L_kernel, state=state_k, rate=1.0) # (C H L) (B C H L) ssm_k_kernel = rearrange(ssm_k_kernel, '1 h l -> h l') if not use_fast_fftconv: fft_size = L_kernel + L ssm_k_kernel_f = torch.fft.rfft(ssm_k_kernel, n=fft_size) # (H 2L) k_f = torch.fft.rfft(k.to(ssm_kernel.dtype), n=fft_size) # (B H 2L) shift_k_out = torch.fft.irfft(ssm_k_kernel_f * k_f, n=fft_size)[..., :L] k = shift_k_out + rearrange(self.ssm_k_D, 'h -> h 1') * k else: dropout_mask = None # No GeLU after the SSM # We want output_hbl=True so that k has the same layout as q and v for the next # fftconv k = fftconv_func(k, ssm_k_kernel, self.ssm_k_D, dropout_mask, False, False, True) # This line below looks like it doesn't do anything, but it gets the stride right # for the case batch_size=1. In that case k has stride (L, L, 1), but q and v has # stride (H * L, L, 1). The two strides are equivalent because batch_size=1, but # the C++ code doesn't like that. k = rearrange(rearrange(k, 'b h l -> h b l'), 'h b l -> b h l') if not use_fast_fftconv: fft_size = L_kernel + L # kv = k * v kv = (rearrange(k, 'b (h d1) l -> b d1 1 h l', d1=self.head_dim) * rearrange(v, 'b (h d2) l -> b 1 d2 h l', d2=self.head_dim)) # b d1 d2 h l kv_f = torch.fft.rfft(kv.to(dtype=ssm_kernel.dtype), n=fft_size) / fft_size ssm_kernel_f = torch.fft.rfft(ssm_kernel, n=fft_size) # h L+1 y = torch.fft.irfft(kv_f * ssm_kernel_f, n=fft_size, norm='forward')[..., :L] # b d1 d2 h l y = y + kv * self.D.unsqueeze(-1) # b d1 d2 h l q = rearrange(q, 'b (h d1) l -> b d1 1 h l', d1=self.head_dim) # einsum is way slower than multiply and then sum. if self.head_dim > 1: y = mul_sum(y, q) y = rearrange(y, 'b d h l -> b (d h) l') else: y = rearrange(y * q, 'b 1 1 h l -> b h l') else: dropout_mask = None # No GeLU after the SSM # Set output_hbl_layout=True since we'll be doing a matmul right after y = fftconv_func(k, ssm_kernel, self.D, dropout_mask, False, torch.is_autocast_enabled(), True, v, self.head_dim, q) y = rearrange(y, 'b h l -> b l h') if state is not None: assert inference_params is not None # TODO: This doesn't ever happen? # if inference_params.sequence_len_offset > 0: # y = y + k_state inference_params.key_value_memory_dict[self.layer_idx][0].copy_( self.ssm_k_kernel.forward_state(k_og, state_k) ) inference_params.key_value_memory_dict[self.layer_idx][1].copy_( self.kernel.forward_state(rearrange(kv, 'b d1 d2 h l -> (b d1 d2) h l'), state) ) # y could be in fp32 because of the SSMs if not torch.is_autocast_enabled(): y = y.to(dtype=self.output_linear.weight.dtype) y = self.output_linear(y) if L_og < L: y = y[:, :L_og, :] return y def step(self, u, state_k, state): q, k, v = self.q_proj(u), self.k_proj(u), self.v_proj(u) shift_k, next_state_k = self.ssm_k_kernel.step(rearrange(k, 'b 1 h -> b h'), state_k) k = shift_k + k * self.ssm_k_D # kv = k * v kv = (rearrange(k, 'b 1 (h d1) -> b d1 1 h', d1=self.head_dim) * rearrange(v, 'b 1 (h d2) -> b 1 d2 h', d2=self.head_dim)) # b d1 d2 h y, next_state = self.kernel.step(rearrange(kv, 'b d1 d2 h -> (b d1 d2) h'), state) y = (rearrange(y, '(b d1 d2) 1 h -> b d1 d2 h', d1=self.head_dim, d2=self.head_dim) + kv * self.D) q = rearrange(q, 'b 1 (h d1) -> b d1 1 h', d1=self.head_dim) if self.head_dim > 1: y = mul_sum(y, q) y = rearrange(y, 'b d h l -> b (d h) l') else: y = rearrange(y * q, 'b 1 1 h -> b 1 h') # y could be in fp32 because of the SSMs if not torch.is_autocast_enabled(): y = y.to(dtype=self.output_linear.weight.dtype) return self.output_linear(y), next_state_k, next_state
H3-main
src/models/ssm/h3.py
# TD: [2023-01-05]: Extracted the OptimModule class from # https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/sequence/ss/kernel.py import torch.nn as nn class OptimModule(nn.Module): """ Interface for Module that allows registering buffers/parameters with configurable optimizer hyperparameters """ def register(self, name, tensor, lr=None): """Register a tensor with a configurable learning rate and 0 weight decay""" if lr == 0.0: self.register_buffer(name, tensor) else: self.register_parameter(name, nn.Parameter(tensor)) optim = {"weight_decay": 0.0} if lr is not None: optim["lr"] = lr setattr(getattr(self, name), "_optim", optim)
H3-main
src/models/ssm/ssm_utils.py
# TD: [2023-01-05]: Extracted the SSKernel class from # https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/sequence/ss/kernel.py # We add option to use the shift kernel, and remove the option of SSKernelNPLR """SSM convolution kernels. SSKernel wraps different kernels with common options and handles the initialization. """ import math import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from opt_einsum import contract from src.models.ssm.ss_kernel_diag import SSKernelDiag, EMAKernel from src.models.ssm.ss_kernel_shift import SSKernelShift from src.models.ssm import hippo from src.models.ssm import dplr from src.ops.krylov import power from src.utils.utils import get_logger log = get_logger(__name__) _conj = lambda x: torch.cat([x, x.conj()], dim=-1) class SSKernel(nn.Module): """Wrapper around SSKernel parameterizations. The SSKernel is expected to support the interface forward() default_state() _setup_step() step() """ def __init__( self, H, N=64, L=None, measure="diag-lin", rank=1, channels=1, dt_min=0.001, dt_max=0.1, deterministic=False, lr=None, mode="diag", n_ssm=None, verbose=False, measure_args={}, **kernel_args, ): """State Space Kernel which computes the convolution kernel $\\bar{K}$ H: Number of independent SSM copies; controls the size of the model. Also called d_model in the config. N: State size (dimensionality of parameters A, B, C). Also called d_state in the config. Generally shouldn't need to be adjusted and doens't affect speed much. L: Maximum length of convolution kernel, if known. Should work in the majority of cases even if not known. measure: Options for initialization of (A, B). For NPLR mode, recommendations are "legs", "fout", "hippo" (combination of both). For Diag mode, recommendations are "diag-inv", "diag-lin", "diag-legs", and "diag" (combination of diag-inv and diag-lin) rank: Rank of low-rank correction for NPLR mode. Needs to be increased for measure "legt" channels: C channels turns the SSM from a 1-dim to C-dim map; can think of it having C separate "heads" per SSM. This was partly a feature to make it easier to implement bidirectionality; it is recommended to set channels=1 and adjust H to control parameters instead dt_min, dt_max: min and max values for the step size dt (\Delta) mode: Which kernel algorithm to use. 'nplr' is the full S4 model; 'diag' is the simpler S4D; 'slow' is a dense version for testing n_ssm: Number of independent trainable (A, B) SSMs, e.g. n_ssm=1 means all A/B parameters are tied across the H different instantiations of C. n_ssm=None means all H SSMs are completely independent. Generally, changing this option can save parameters but doesn't affect performance or speed much. This parameter must divide H lr: Passing in a number (e.g. 0.001) sets attributes of SSM parameers (A, B, dt). A custom optimizer hook is needed to configure the optimizer to set the learning rates appropriately for these parameters. """ super().__init__() self.N = N self.H = H dtype, cdtype = torch.float, torch.cfloat self.channels = channels self.n_ssm = n_ssm if n_ssm is not None else H self.mode = mode self.verbose = verbose self.kernel_args = kernel_args # Generate dt if deterministic: log_dt = torch.exp(torch.linspace(math.log(dt_min), math.log(dt_max), H)) else: log_dt = torch.rand(self.H, dtype=dtype) * ( math.log(dt_max) - math.log(dt_min) ) + math.log(dt_min) # Compute the preprocessed representation if mode == "ema": self.kernel = EMAKernel(H, N=N, channels=channels, **kernel_args) else: w, P, B, V = dplr.combination(measure, self.N, rank, self.n_ssm, **measure_args) # Broadcast C to have H channels if deterministic: C = torch.zeros(channels, self.n_ssm, self.N, dtype=cdtype) C[:, :, :1] = 1. C = contract('hmn, chn -> chm', V.conj().transpose(-1, -2), C) # V^* C C = repeat(C, 'c t n -> c (v t) n', v=self.n_ssm // C.size(-2)).clone().contiguous() else: C = torch.randn(channels, self.H, self.N//2, dtype=cdtype) # Broadcast other parameters to have n_ssm copies assert self.n_ssm % B.size(-2) == 0 \ and self.n_ssm % P.size(-2) == 0 \ and self.n_ssm % w.size(-2) == 0 # Broadcast tensors to n_ssm copies # These will be the parameters, so make sure tensors are materialized and contiguous B = repeat(B, 't n -> (v t) n', v=self.n_ssm // B.size(-2)).clone().contiguous() P = repeat(P, 'r t n -> r (v t) n', v=self.n_ssm // P.size(-2)).clone().contiguous() w = repeat(w, 't n -> (v t) n', v=self.n_ssm // w.size(-2)).clone().contiguous() if mode == "diag": if not measure.startswith("diag"): log.warning("Diagonal kernel (S4D) activated but initialization is not intended for S4D. Set `measure` to 'diag-lin', 'diag-inv', or 'diag-legs' for the main variants, or 'diag' for a combination of S4D-Lin and S4D-Inv.") C = C * repeat(B, 't n -> (v t) n', v=H//self.n_ssm) self.kernel = SSKernelDiag( w, B, C, log_dt, L=L, lr=lr, **kernel_args, ) elif mode == 'shift': # Initializing B to be e_1 B = torch.zeros(self.H, self.N) B[..., 0] = 1.0 # Match torch.Conv1d init C = torch.randn(self.H, self.channels, self.N) nn.init.kaiming_uniform_(C, a=math.sqrt(5)) C = rearrange(C, 'h c n -> c h n') self.kernel = SSKernelShift(B, C, L=L, lr=lr, **kernel_args) else: raise NotImplementedError(f"{mode=} is not valid") def forward(self, state=None, L=None, rate=None): return self.kernel(state=state, L=L, rate=rate) @torch.no_grad() def forward_state(self, u, state): """ Forward the state through a sequence, i.e. computes the state after passing chunk through SSM state: (B, H, N) u: (B, H, L) Returns: (B, H, N) """ if hasattr(self.kernel, "forward_state"): return self.kernel.forward_state(u, state) dA, dB = self.kernel._setup_state() # Construct dA, dB matrices # dA, dB = self.kernel.dA, self.kernel.dB # (H N N) (H N) conj = state.size(-1) != dA.size(-1) if conj: state = _conj(state) v = contract('h n, b h l -> b h n l', dB, u.flip(-1)) # dB.unsqueeze(-1) * u.flip(-1).unsqueeze(-2) AL, v = power(u.size(-1), dA, v) next_state = contract("h m n, b h n -> b h m", AL, state) next_state = next_state + v if conj: next_state = next_state[..., : next_state.size(-1) // 2] return next_state def _setup_step(self, **kwargs): # This method is intended to be private so that setting up an S4 module with # ``` # if hasattr(module, 'setup_step'): module.setup_step() # ``` # will not trigger this method multiple times self.kernel._setup_step(**kwargs) def step(self, u, state, **kwargs): y, state = self.kernel.step(u, state, **kwargs) return y, state def default_state(self, *args, **kwargs): return self.kernel.default_state(*args, **kwargs)
H3-main
src/models/ssm/ss_kernel.py
# Copied from https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/hippo/hippo.py """ Definitions of A and B matrices for various HiPPO operators. """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from scipy import special as ss from einops import rearrange, repeat from opt_einsum import contract def embed_c2r(A): A = rearrange(A, '... m n -> ... m () n ()') A = np.pad(A, ((0, 0), (0, 1), (0, 0), (0, 1))) + \ np.pad(A, ((0, 0), (1, 0), (0, 0), (1,0))) return rearrange(A, 'm x n y -> (m x) (n y)') # TODO take in 'torch' option to return torch instead of numpy, and converts the shape of B from (N, 1) to (N) def transition(measure, N, **measure_args): """ A, B transition matrices for different measures measure: the type of measure legt - Legendre (translated) legs - Legendre (scaled) glagt - generalized Laguerre (translated) lagt, tlagt - previous versions of (tilted) Laguerre with slightly different normalization """ # Laguerre (translated) if measure == 'lagt': b = measure_args.get('beta', 1.0) A = np.eye(N) / 2 - np.tril(np.ones((N, N))) B = b * np.ones((N, 1)) # Generalized Laguerre # alpha 0, beta small is most stable (limits to the 'lagt' measure) # alpha 0, beta 1 has transition matrix A = [lower triangular 1] elif measure == 'glagt': alpha = measure_args.get('alpha', 0.0) beta = measure_args.get('beta', 0.01) A = -np.eye(N) * (1 + beta) / 2 - np.tril(np.ones((N, N)), -1) B = ss.binom(alpha + np.arange(N), np.arange(N))[:, None] L = np.exp(.5 * (ss.gammaln(np.arange(N)+alpha+1) - ss.gammaln(np.arange(N)+1))) A = (1./L[:, None]) * A * L[None, :] B = (1./L[:, None]) * B * np.exp(-.5 * ss.gammaln(1-alpha)) * beta**((1-alpha)/2) # Legendre (translated) elif measure == 'legt': Q = np.arange(N, dtype=np.float64) R = (2*Q + 1) ** .5 j, i = np.meshgrid(Q, Q) A = R[:, None] * np.where(i < j, (-1.)**(i-j), 1) * R[None, :] B = R[:, None] A = -A # Halve again for timescale correctness A *= 0.5 B *= 0.5 # LMU: equivalent to LegT up to normalization elif measure == 'lmu': Q = np.arange(N, dtype=np.float64) R = (2*Q + 1)[:, None] # / theta j, i = np.meshgrid(Q, Q) A = np.where(i < j, -1, (-1.)**(i-j+1)) * R B = (-1.)**Q[:, None] * R # Legendre (scaled) elif measure == 'legs': q = np.arange(N, dtype=np.float64) col, row = np.meshgrid(q, q) r = 2 * q + 1 M = -(np.where(row >= col, r, 0) - np.diag(q)) T = np.sqrt(np.diag(2 * q + 1)) A = T @ M @ np.linalg.inv(T) B = np.diag(T)[:, None] B = B.copy() # Otherwise "UserWarning: given NumPY array is not writeable..." after torch.as_tensor(B) elif measure == 'legsd': q = np.arange(N, dtype=np.float64) col, row = np.meshgrid(q, q) r = 2 * q + 1 M = -(np.where(row >= col, r, 0) - np.diag(q)) T = np.sqrt(np.diag(2 * q + 1)) A = T @ M @ np.linalg.inv(T) B = np.diag(T)[:, None] B = B.copy() # Otherwise "UserWarning: given NumPY array is not writeable..." after torch.as_tensor(B) A += .5 * B*B[None, :, 0] B = B / 2.0 elif measure in ['fourier_diag', 'foud']: freqs = np.arange(N//2) d = np.stack([freqs, np.zeros(N//2)], axis=-1).reshape(-1)[:-1] A = 2*np.pi*(-np.diag(d, 1) + np.diag(d, -1)) A = A - .5 * np.eye(N) B = np.zeros(N) B[0::2] = 2**.5 B[0] = 1 B = B[:, None] elif measure in ['fourier', 'fout']: freqs = np.arange(N//2) d = np.stack([np.zeros(N//2), freqs], axis=-1).reshape(-1)[1:] A = np.pi*(-np.diag(d, 1) + np.diag(d, -1)) B = np.zeros(N) B[0::2] = 2**.5 B[0] = 1 # Subtract off rank correction - this corresponds to the other endpoint u(t-1) in this case A = A - B[:, None] * B[None, :] B = B[:, None] elif measure == 'fourier_decay': freqs = np.arange(N//2) d = np.stack([np.zeros(N//2), freqs], axis=-1).reshape(-1)[1:] A = np.pi*(-np.diag(d, 1) + np.diag(d, -1)) B = np.zeros(N) B[0::2] = 2**.5 B[0] = 1 # Subtract off rank correction - this corresponds to the other endpoint u(t-1) in this case A = A - .5 * B[:, None] * B[None, :] B = .5 * B[:, None] elif measure == 'fourier2': # Double everything: orthonormal on [0, 1] freqs = 2*np.arange(N//2) d = np.stack([np.zeros(N//2), freqs], axis=-1).reshape(-1)[1:] A = np.pi*(-np.diag(d, 1) + np.diag(d, -1)) B = np.zeros(N) B[0::2] = 2**.5 B[0] = 1 # Subtract off rank correction - this corresponds to the other endpoint u(t-1) in this case A = A - B[:, None] * B[None, :] * 2 B = B[:, None] * 2 elif measure == 'random': A = np.random.randn(N, N) / N B = np.random.randn(N, 1) elif measure == 'diagonal': A = -np.diag(np.exp(np.random.randn(N))) B = np.random.randn(N, 1) else: raise NotImplementedError return A, B def rank_correction(measure, N, rank=1, dtype=torch.float): """ Return low-rank matrix L such that A + L is normal """ if measure == 'legs': assert rank >= 1 P = torch.sqrt(.5+torch.arange(N, dtype=dtype)).unsqueeze(0) # (1 N) elif measure == 'legt': assert rank >= 2 P = torch.sqrt(1+2*torch.arange(N, dtype=dtype)) # (N) P0 = P.clone() P0[0::2] = 0. P1 = P.clone() P1[1::2] = 0. P = torch.stack([P0, P1], dim=0) # (2 N) P *= 2**(-0.5) # Halve the rank correct just like the original matrix was halved elif measure == 'lagt': assert rank >= 1 P = .5**.5 * torch.ones(1, N, dtype=dtype) elif measure in ['fourier', 'fout']: P = torch.zeros(N) P[0::2] = 2**.5 P[0] = 1 P = P.unsqueeze(0) elif measure == 'fourier_decay': P = torch.zeros(N) P[0::2] = 2**.5 P[0] = 1 P = P.unsqueeze(0) P = P / 2**.5 elif measure == 'fourier2': P = torch.zeros(N) P[0::2] = 2**.5 P[0] = 1 P = 2**.5 * P.unsqueeze(0) elif measure in ['fourier_diag', 'foud', 'legsd']: P = torch.zeros(1, N, dtype=dtype) else: raise NotImplementedError d = P.size(0) if rank > d: P = torch.cat([P, torch.zeros(rank-d, N, dtype=dtype)], dim=0) # (rank N) return P def initial_C(measure, N, dtype=torch.float): """ Return C that captures the other endpoint in the HiPPO approximation """ if measure == 'legt': C = (torch.arange(N, dtype=dtype)*2+1)**.5 * (-1)**torch.arange(N) elif measure == 'fourier': C = torch.zeros(N) C[0::2] = 2**.5 C[0] = 1 else: C = torch.zeros(N, dtype=dtype) # (N) return C def nplr(measure, N, rank=1, dtype=torch.float, diagonalize_precision=True): """ Return w, p, q, V, B such that (w - p q^*, B) is unitarily equivalent to the original HiPPO A, B by the matrix V i.e. A = V[w - p q^*]V^*, B = V B """ assert dtype == torch.float or dtype == torch.double cdtype = torch.cfloat if dtype == torch.float else torch.cdouble A, B = transition(measure, N) A = torch.as_tensor(A, dtype=dtype) # (N, N) B = torch.as_tensor(B, dtype=dtype)[:, 0] # (N,) P = rank_correction(measure, N, rank=rank, dtype=dtype) # (r N) AP = A + torch.sum(P.unsqueeze(-2)*P.unsqueeze(-1), dim=-3) # We require AP to be nearly skew-symmetric _A = AP + AP.transpose(-1, -2) if (err := torch.sum((_A - _A[0,0]*torch.eye(N))**2) / N) > 1e-5: # if not torch.allclose(_A - _A[0,0]*torch.eye(N), torch.zeros(N, N), atol=1e-5): print("WARNING: HiPPO matrix not skew symmetric", err) # Take advantage of identity + skew-symmetric form to calculate real and imaginary parts separately # Imaginary part can use eigh instead of eig w_re = torch.mean(torch.diagonal(AP), -1, keepdim=True) # Diagonalize in double precision if diagonalize_precision: AP = AP.to(torch.double) # w, V = torch.linalg.eig(AP) # (..., N) (..., N, N) w_im, V = torch.linalg.eigh(AP*-1j) # (..., N) (..., N, N) if diagonalize_precision: w_im, V = w_im.to(cdtype), V.to(cdtype) w = w_re + 1j * w_im # Check: V w V^{-1} = A # print("check", V @ torch.diag_embed(w) @ V.conj().transpose(-1, -2)) # Only keep half of each conjugate pair _, idx = torch.sort(w.imag) w_sorted = w[idx] V_sorted = V[:, idx] # There is an edge case when eigenvalues can be 0, which requires some machinery to handle # We use a huge hack here: Assume only one pair is 0, and that it is the first row/column of A (only happens in Fourier case) V = V_sorted[:, :N//2] w = w_sorted[:N//2] assert w[-2].abs() > 1e-4, "Only 1 zero eigenvalue allowed in diagonal part of A" if w[-1].abs() < 1e-4: V[:, -1] = 0. V[0, -1] = 2**-0.5 V[1, -1] = 2**-0.5 * 1j _AP = V @ torch.diag_embed(w) @ V.conj().transpose(-1, -2) if ((err := torch.sum((2*_AP.real-AP)**2)/N) > 1e-5): print("Warning: Diagonalization of A matrix not numerically precise - error", err) # print("check", V @ torch.diag_embed(w) @ V.conj().transpose(-1, -2)) V_inv = V.conj().transpose(-1, -2) # C = initial_C(measure, N, dtype=dtype) B = contract('ij, j -> i', V_inv, B.to(V)) # V^* B # C = contract('ij, j -> i', V_inv, C.to(V)) # V^* C P = contract('ij, ...j -> ...i', V_inv, P.to(V)) # V^* P # return w, P, B, C, V return w, P, B, V
H3-main
src/models/ssm/hippo.py
# TD: [2023-01-05]: Extracted the SSKernelDiag class from # https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/sequence/ss/kernel.py # We make a small change to use the log_vandermonde CUDA code. """SSKernelDiag is the S4D kernel, a simpler algorithm for computing the kernel for the case of diagonal state matrices A. """ import math import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from opt_einsum import contract from src.models.ssm.ssm_utils import OptimModule class SSKernelShift(OptimModule): def __init__(self, B, C, L=None, lr=None, **kwargs): """ B: (H, d), real C: (channel, H, d), real """ super().__init__() self.L = L self.N = B.size(-1) self.H = B.shape[0] # Register parameters if lr is None or isinstance(lr, float): lr_dict = {} else: lr_dict, lr = lr, None self.register("B", B, lr_dict.get('B', lr)) self.C = nn.Parameter(C) def forward(self, state=None, rate=1.0, L=None): if L is None: L = self.L # This class doesn't support variable length functionalities, since it's a discrete SSM assert rate == 1.0 and L is not None # Augment B with state B = self.B if state is not None: B = rearrange(torch.cat([rearrange(B, 'h n -> 1 h n'), state], dim=-3), 'bp1 h n -> bp1 1 h n') # (1 + B, 1, H, N) B_f = torch.fft.rfft(B, n=2*self.N) C_f = torch.fft.rfft(self.C, n=2*self.N) k = torch.fft.irfft(B_f.conj() * C_f, n=2*self.N)[..., :min(self.N, L)] # If self.N < L, need to pad with zeros to reach length L if self.N < L: k = F.pad(k, (0, L - self.N)) k = k.float() # Otherwise it could be dtype half if state is not None: k, k_state = k[0], k[1:] else: k_state = None return k, k_state def _setup_step(self): # Just here to conform to the interface, eventually we should refactor out pass def default_state(self, *batch_shape): return torch.zeros(*batch_shape, self.H, self.N, dtype=self.C.dtype, device=self.C.device) def step(self, u, state): """u: (B, H), state: (B, H, N)""" next_state = F.pad(state, (1, -1)) + contract("h n, b h -> b h n", self.B, u) y = contract("c h n, b h n -> b c h", self.C, next_state) return y, next_state def forward_state(self, u, state): """u: (B, H, L), state: (B, H, N)""" L = u.shape[-1] B_f = torch.fft.rfft(self.B, n=2 * self.N) u_f = torch.fft.rfft(u[..., -self.N:].flip(-1).to(dtype=self.B.dtype), n=2 * self.N) v = torch.fft.irfft(B_f * u_f, n=2 * self.N)[..., :self.N] if L < self.N: next_state = F.pad(state, (L, -L)) + v else: next_state = v return next_state
H3-main
src/models/ssm/ss_kernel_shift.py
# TD: [2023-01-05]: Extracted the SSKernelDiag class from # https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/sequence/ss/kernel.py # We make a small change to use the log_vandermonde CUDA code. """SSKernelDiag is the S4D kernel, a simpler algorithm for computing the kernel for the case of diagonal state matrices A. """ import math import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from opt_einsum import contract from src.models.ssm.ssm_utils import OptimModule from src.utils.utils import get_logger log = get_logger(__name__) # This could be None if the CUDA import fails from src.ops.vandermonde import log_vandermonde_fast try: import pykeops from src.ops.vandermonde import log_vandermonde, log_vandermonde_transpose has_pykeops = True log.info("Pykeops installation found.") except ImportError: has_pykeops = False from src.ops.vandermonde import log_vandermonde_naive as log_vandermonde from src.ops.vandermonde import log_vandermonde_transpose_naive as log_vandermonde_transpose log.warning( "Falling back on slow Vandermonde kernel. Install pykeops for improved memory efficiency." ) _c2r = torch.view_as_real _r2c = torch.view_as_complex if tuple(map(int, torch.__version__.split('.')[:2])) >= (1, 10): _resolve_conj = lambda x: x.conj().resolve_conj() else: _resolve_conj = lambda x: x.conj() class SSKernelDiag(OptimModule): """Version using (complex) diagonal state matrix (S4D)""" def __init__( self, A, B, C, log_dt, L=None, disc='bilinear', real_type='exp', lr=None, bandlimit=None, force_real=False, ): super().__init__() self.L = L self.disc = disc self.bandlimit = bandlimit self.real_type = real_type self.force_real = force_real # Rank of low-rank correction assert A.size(-1) == C.size(-1) self.H = log_dt.size(-1) self.N = A.size(-1) assert A.size(-2) == B.size(-2) # Number of independent SSMs trained assert self.H % A.size(-2) == 0 self.n_ssm = A.size(-2) self.repeat = self.H // A.size(0) self.channels = C.shape[0] self.C = nn.Parameter(_c2r(_resolve_conj(C))) # Register parameters if lr is None or isinstance(lr, float): lr_dict = {} else: lr_dict, lr = lr, None self.register("log_dt", log_dt, lr_dict.get('dt', lr)) self.register("B", _c2r(B), lr_dict.get('B', lr)) self.register("inv_A_real", self._A_init(A.real), lr_dict.get('A', lr)) self.register("A_imag", A.imag, lr_dict.get('A', lr)) def _A_init(self, A_real): A_real = torch.clamp(A_real, max=-1e-4) if self.real_type == 'none': return -A_real elif self.real_type == 'exp': return torch.log(-A_real) # Some of the HiPPO methods have real part 0 elif self.real_type == 'relu': return -A_real elif self.real_type == 'sigmoid': return torch.logit(-A_real) elif self.real_type == 'softplus': return torch.log(torch.exp(-A_real)-1) else: raise NotImplementedError def _A(self): # Get the internal A (diagonal) parameter if self.real_type == 'none': A_real = -self.inv_A_real elif self.real_type == 'exp': A_real = -torch.exp(self.inv_A_real) elif self.real_type == 'relu': # JAX version seems to NaN if you alloA 0's, although this code Aas fine Aithout it A_real = -F.relu(self.inv_A_real)-1e-4 elif self.real_type == 'sigmoid': A_real = -F.sigmoid(self.inv_A_real) elif self.real_type == 'softplus': A_real = -F.softplus(self.inv_A_real) else: raise NotImplementedError A = A_real + 1j * self.A_imag return A def forward(self, L, state=None, rate=1.0, u=None): """ state: (B, H, N) initial state rate: sampling rate factor L: target length returns: (C, H, L) convolution kernel (generally C=1) (B, H, L) output from initial state """ dt = torch.exp(self.log_dt) * rate # (H) C = _r2c(self.C) # (C H N) A = self._A() # (H N) B = _r2c(self.B) B = repeat(B, 't n -> 1 (v t) n', v=self.repeat) # Force A to be real valued, so the whole kernel can be interpreted as a "multi-head EMA" if self.force_real: A = A.real + 0j if self.bandlimit is not None: freqs = dt[:, None] / rate * A.imag.abs() / (2*math.pi) # (H, N) mask = torch.where(freqs < self.bandlimit * .5, 1, 0) C = C * mask # Incorporate dt into A A = repeat(A, 't n -> (v t) n', v=self.repeat) dtA = A * dt.unsqueeze(-1) # (H N) # Augment B with state if state is not None: s = state / dt.unsqueeze(-1) if self.disc == 'bilinear': s = s * (1. + dtA/2) elif self.disc == 'zoh': s = s * dtA * dtA.exp() / (dtA.exp() - 1.) B = torch.cat([s, B], dim=-3) # (1+B H N) C = (B[:, None, :, :] * C).view(-1, self.H, self.N) if self.disc == 'zoh': # Power up C = C * (torch.exp(dtA)-1.) / A # TODO (TD): make it work for C.shape[0] > 1 if log_vandermonde_fast is not None and C.shape[0] == 1: K = log_vandermonde_fast(C.squeeze(0), dtA, L).unsqueeze(0) # (H L) else: K = log_vandermonde(C, dtA, L) # (H L) elif self.disc == 'bilinear': C = C * (1. - dtA/2).reciprocal() * dt.unsqueeze(-1) # or * dtA / A dA = (1. + dtA/2) / (1. - dtA/2) if log_vandermonde_fast is not None: dA_log = repeat(dA.log(), 'h d -> (c h) d', c=C.shape[0]) K = rearrange(log_vandermonde_fast(rearrange(C, 'c h d -> (c h) d'), dA_log, L), '(c h) d -> c h d', c=C.shape[0]) else: K = log_vandermonde(C, dA.log(), L) elif self.disc == 'dss': # Implementation from DSS meant for case when real eigenvalues can be positive P = dtA.unsqueeze(-1) * torch.arange(L, device=C.device) # [H N L] A_gt_0 = A.real > 0 # [N] if A_gt_0.any(): with torch.no_grad(): P_max = dtA * (A_gt_0 * (L-1)) # [H N] P = P - P_max.unsqueeze(-1) # [H N L] S = P.exp() # [H N L] dtA_neg = dtA * (1 - 2*A_gt_0) # [H N] num = dtA_neg.exp() - 1 # [H N] den = (dtA_neg * L).exp() - 1 # [H N] # Inline reciprocal function for DSS logic x = den * A x_conj = _resolve_conj(x) r = x_conj / (x*x_conj + 1e-7) C = C * num * r # [C H N] K = contract('chn,hnl->chl', C, S).float() else: assert False, f"{self.disc} not supported" K = K.view(-1, self.channels, self.H, L) # (1+B C H L) if state is not None: K_state = K[:-1, :, :, :] # (B C H L) else: K_state = None K = K[-1, :, :, :] # (C H L) return K, K_state def _setup_step(self): # These methods are organized like this to be compatible with the NPLR kernel interface dt = torch.exp(self.log_dt) # (H) B = _r2c(self.B) # (H N) C = _r2c(self.C) # (C H N) self.dC = C A = self._A() # (H N) A = repeat(A, 't n -> (v t) n', v=self.repeat) B = repeat(B, 't n -> (v t) n', v=self.repeat) # Incorporate dt into A dtA = A * dt.unsqueeze(-1) # (H N) if self.disc == 'zoh': self.dA = torch.exp(dtA) # (H N) self.dB = B * (torch.exp(dtA)-1.) / A # (C H N) elif self.disc == 'bilinear': self.dA = (1. + dtA/2) / (1. - dtA/2) self.dB = B * (1. - dtA/2).reciprocal() * dt.unsqueeze(-1) # or * dtA / A def default_state(self, *batch_shape): C = _r2c(self.C) state = torch.zeros(*batch_shape, self.H, self.N, dtype=C.dtype, device=C.device) return state def step(self, u, state): next_state = contract("h n, b h n -> b h n", self.dA, state) \ + contract("h n, b h -> b h n", self.dB, u) y = contract("c h n, b h n -> b c h", self.dC, next_state) return 2*y.real, next_state def forward_state(self, u, state): self._setup_step() AL = self.dA ** u.size(-1) u = u.flip(-1).to(self.dA).contiguous() # (B H L) v = log_vandermonde_transpose(u, self.dB, self.dA.log(), u.size(-1)) next_state = AL * state + v return next_state class EMAKernel(OptimModule): """Translation of Mega's MultiHeadEMA. This is a minimal implementation of the convolution kernel part of the module. This module, together with the main S4 block in src.models.sequence.ss.s4 (which is really just a fft-conv wrapper around any convolution kernel, such as this one), should be exactly equivalent to using the original Mega EMA module in src.models.sequence.ss.ema. Two additional flags have been provided to resolve discrepencies in parameter count between S4(D) and EMA - `dt_tie` makes the shape of the step size \Delta (H, 1) instead of (H, N) - `efficient_bidirectional` ties the A/B/dt parameters for the conv kernels in both forwards and backwards directions. This should have exactly the same speed, slightly more parameter efficiency, and unchanged performance. """ def __init__( self, H, N=2, channels=1, l_max=None, dt_tie=False, efficient_bidirectional=False, ): super().__init__() self.H = H self.N = N self.channels = channels self.l_max = l_max self.scale = math.sqrt(1.0 / self.N) # Exactly match the parameter count of S4(D) when bididirectional is on self.efficient_bidirectional = efficient_bidirectional if self.efficient_bidirectional: H_C = H * channels else: H *= channels H_C = H self.delta = nn.Parameter(torch.Tensor(H, 1 if dt_tie else N, 1)) self.alpha = nn.Parameter(torch.Tensor(H, N, 1)) self.beta = nn.Parameter(torch.Tensor(H, N, 1)) self.gamma = nn.Parameter(torch.Tensor(H_C, N)) # self.omega = nn.Parameter(torch.Tensor(H)) # D skip connection handled by outside class self.reset_parameters() def reset_parameters(self): with torch.no_grad(): nn.init.normal_(self.delta, mean=0.0, std=0.2) nn.init.normal_(self.alpha, mean=0.0, std=0.2) # Mega comment: beta [1, -1, 1, -1, ...] seems more stable. val = torch.ones(self.N, 1) if self.N > 1: idx = torch.tensor(list(range(1, self.N, 2))) val.index_fill_(0, idx, -1.0) self.beta.normal_(mean=0.0, std=0.02).add_(val) nn.init.normal_(self.gamma, mean=0.0, std=1.0) # nn.init.normal_(self.omega, mean=0.0, std=1.0) def coeffs(self): # Same as discretize p = torch.sigmoid(self.delta) # (H N 1) alpha = torch.sigmoid(self.alpha) q = 1.0 - p * alpha return p, q def forward(self, L=None, state=None, rate=1.0): L = L if self.l_max is None else min(self.l_max, L) p, q = self.coeffs() # (H N 1) vander = torch.arange(L).to(p).view(1, 1, L) * torch.log(q) # (H N L) kernel = (p * self.beta) * torch.exp(vander) if self.efficient_bidirectional: C = rearrange(self.gamma * self.scale, '(c h) n -> c h n', c=self.channels) kernel = torch.einsum('dnl,cdn->cdl', kernel, C) # kernel = rearrange(kernel, 'c d l -> (c d) l') else: kernel = torch.einsum('dnl,dn->dl', kernel, self.gamma * self.scale) kernel = rearrange(kernel, '(c h) l -> c h l', c=self.channels) kernel = kernel[..., :L] # kernel = rearrange(kernel, '(c h) l -> c h l', c=self.channels) return kernel, None # k_state
H3-main
src/models/ssm/ss_kernel_diag.py
# Copied from https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/sequence/ss/dplr.py """Initializations of structured state space models""" import math import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from src.models.ssm import hippo def dplr(scaling='linear', N=64, rank=1, H=1, dtype=torch.float, real_scale=1.0, imag_scale=1.0, random_real=False, random_imag=False, normalize=False, diagonal=True, random_B=False): assert dtype == torch.float or dtype == torch.double dtype = torch.cfloat if dtype == torch.float else torch.cdouble pi = torch.tensor(math.pi) if random_real: real_part = torch.rand(H, N//2) else: real_part = .5 * torch.ones(H, N//2) if random_imag: imag_part = N//2 * torch.rand(H, N//2) else: imag_part = repeat(torch.arange(N//2), 'n -> h n', h=H) real_part = real_scale * real_part if scaling == 'random': imag_part = torch.randn(H, N//2) elif scaling == 'real': imag_part = 0 * imag_part real_part = 1 + repeat(torch.arange(N//2), 'n -> h n', h=H) elif scaling in ['linear', 'lin']: imag_part = pi * imag_part elif scaling in ['inverse', 'inv']: # Based on asymptotics of the default HiPPO matrix imag_part = 1/pi * N * (N/(1+2*imag_part)-1) elif scaling in ['inverse2', 'inv2']: imag_part = 1/pi * N * (N/(1+imag_part)-1) elif scaling in ['quadratic', 'quad']: imag_part = 1/pi * (1+2*imag_part)**2 elif scaling in ['legs', 'hippo']: w, _, _, _ = hippo.nplr('legsd', N) imag_part = w.imag else: raise NotImplementedError imag_part = imag_scale * imag_part w = -real_part + 1j * imag_part # Initialize B if random_B: B = torch.randn(H, N//2, dtype=dtype) else: B = torch.ones(H, N//2, dtype=dtype) if normalize: norm = -B/w # (H, N) # Result if you integrate the kernel with constant 1 function zeta = 2*torch.sum(torch.abs(norm)**2, dim=-1, keepdim=True) # Variance with a random C vector B = B / zeta**.5 P = torch.randn(rank, H, N//2, dtype=dtype) if diagonal: P = P * 0.0 V = torch.eye(N, dtype=dtype)[:, :N//2] # Only used in testing V = repeat(V, 'n m -> h n m', h=H) return w, P, B, V def ssm(measure, N, R, H, **ssm_args): """Dispatcher to create single SSM initialization N: state size R: rank (for DPLR parameterization) H: number of independent SSM copies """ if measure == "dplr": w, P, B, V = dplr(N=N, rank=R, H=H, **ssm_args) elif measure.startswith("diag"): args = measure.split("-") assert args[0] == "diag" and len(args) > 1 scaling = args[1] w, P, B, V = dplr(scaling=scaling, N=N, rank=R, H=H, diagonal=True, **ssm_args) else: w, P, B, V = hippo.nplr(measure, N, R, **ssm_args) w = repeat(w, 'n -> s n', s=H) P = repeat(P, 'r n -> r s n', s=H) B = repeat(B, 'n -> s n', s=H) V = repeat(V, 'n m -> s n m', s=H) return w, P, B, V combinations = { 'hippo': ['legs', 'fourier'], 'diag': ['diag-inv', 'diag-lin'], 'all': ['legs', 'fourier', 'diag-inv', 'diag-lin'], } def combination(measures, N, R, S, **ssm_args): if isinstance(measures, str): measures = combinations[measures] if measures in combinations else [measures] assert S % len(measures) == 0, f"{S} independent trainable SSM copies must be multiple of {len(measures)} different measures" w, P, B, V = zip( *[ssm(measure, N, R, S // len(measures), **ssm_args) for measure in measures] ) w = torch.cat(w, dim=0) # (S N) P = torch.cat(P, dim=1) # (R S N) B = torch.cat(B, dim=0) # (S N) V = torch.cat(V, dim=0) # (S N N) return w, P, B, V
H3-main
src/models/ssm/dplr.py
import math import torch import torch.nn.functional as F from einops import rearrange from fftconv import fftconv_fwd, fftconv_bwd @torch.jit.script def _mul_sum(y, q): return (y * q).sum(dim=1) # reference convolution with residual connection def fftconv_ref(u, k, D, dropout_mask, gelu=True, k_rev=None): seqlen = u.shape[-1] fft_size = 2 * seqlen k_f = torch.fft.rfft(k, n=fft_size) / fft_size if k_rev is not None: k_rev_f = torch.fft.rfft(k_rev, n=fft_size) / fft_size k_f = k_f + k_rev_f.conj() u_f = torch.fft.rfft(u.to(dtype=k.dtype), n=fft_size) y = torch.fft.irfft(u_f * k_f, n=fft_size, norm='forward')[..., :seqlen] out = y + u * D.unsqueeze(-1) if gelu: out = F.gelu(out) if dropout_mask is not None: return (out * rearrange(dropout_mask, 'b H -> b H 1')).to(dtype=u.dtype) else: return out.to(dtype=u.dtype) # reference H3 forward pass def fftconv_h3_ref(k, ssm_kernel, D, q, v, head_dim=1, ssm_kernel_rev=None): seqlen = k.shape[-1] fft_size = 2 * seqlen kv = (rearrange(k, 'b (h d1) l -> b d1 1 h l', d1=head_dim) * rearrange(v, 'b (h d2) l -> b 1 d2 h l', d2=head_dim)) # b d1 d2 h l kv_f = torch.fft.rfft(kv.to(dtype=ssm_kernel.dtype), n=fft_size) / fft_size ssm_kernel_f = torch.fft.rfft(ssm_kernel, n=fft_size) # h L+1 if ssm_kernel_rev is not None: ssm_kernel_rev_f = torch.fft.rfft(ssm_kernel_rev, n=fft_size) # h L+1 ssm_kernel_f = ssm_kernel_f + ssm_kernel_rev_f.conj() y = torch.fft.irfft(kv_f * ssm_kernel_f, n=fft_size, norm='forward')[..., :seqlen] # b d1 d2 h l out = y + kv * D.unsqueeze(-1) # b d1 d2 h l q = rearrange(q, 'b (h d1) l -> b d1 1 h l', d1=head_dim) if head_dim > 1: out = _mul_sum(out, q) return rearrange(out, 'b d2 h l -> b (h d2) l').to(dtype=k.dtype) else: return rearrange(out * q, 'b 1 1 h l -> b h l').to(dtype=k.dtype) class FFTConvFunc(torch.autograd.Function): @staticmethod def forward(ctx, u, k, D, dropout_mask=None, gelu=True, force_fp16_output=False, output_hbl_layout=False, v=None, head_dim=1, q=None, fftfp16=False, k_rev=None): seqlen = u.shape[-1] fft_size = max(2 * 2 ** int(math.ceil(math.log2(seqlen))), 16) k_f = torch.fft.rfft(k, n=fft_size) if k_rev is not None: k_f = k_f + torch.fft.rfft(k_rev, n=fft_size).conj() if u.stride(-1) != 1: u = u.contiguous() k_f = k_f.contiguous() D = D.contiguous() if v is not None and v.stride(-1) != 1: v = v.contiguous() if q is not None and q.stride(-1) != 1: q = q.contiguous() if dropout_mask is not None: dropout_mask = dropout_mask.contiguous() ctx.save_for_backward(u, k_f, D, dropout_mask, v, q) ctx.output_hbl_layout = output_hbl_layout ctx.head_dim = head_dim ctx.gelu = gelu ctx.fftfp16 = fftfp16 ctx.has_k_rev = k_rev is not None out = fftconv_fwd(u, k_f, D, v, head_dim, q, dropout_mask, gelu, False, False, fft_size, force_fp16_output, output_hbl_layout, fftfp16) return out @staticmethod def backward(ctx, dout): if ctx.output_hbl_layout: dout = rearrange(rearrange(dout, 'b h l -> h b l').contiguous(), 'h b l -> b h l') else: dout = dout.contiguous() u, k_f, D, dropout_mask, v, q = ctx.saved_tensors seqlen = u.shape[-1] fft_size = max(2 * 2 ** int(math.ceil(math.log2(seqlen))), 16) du, dk_f, dD, dv, dq = fftconv_bwd(dout, u, k_f, D, v, ctx.head_dim, q, dropout_mask, ctx.gelu, False, False, fft_size, ctx.output_hbl_layout, ctx.fftfp16) dk = torch.fft.irfft(dk_f, n=fft_size, norm='forward')[..., :seqlen] dk_rev = (None if not ctx.has_k_rev else torch.fft.irfft(dk_f.conj(), n=fft_size, norm='forward')[..., :seqlen]) if v is not None: dv = dv.to(dtype=v.dtype) # We do atomicAdd in fp32 so might need to convert to fp16 return du, dk, dD, None, None, None, None, dv if v is not None else None, None, dq if q is not None else None, None, dk_rev def fftconv_func(u, k, D, dropout_mask=None, gelu=True, force_fp16_output=False, output_hbl_layout=False, v=None, head_dim=1, q=None, fftfp16=False, k_rev=None): return FFTConvFunc.apply(u, k, D, dropout_mask, gelu, force_fp16_output, output_hbl_layout, v, head_dim, q, fftfp16, k_rev)
H3-main
src/ops/fftconv.py
# TD [2023-01-05]: Copied from https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/functional/vandermonde.py # We add the interface to the log vandermonde CUDA code """pykeops implementations of the Vandermonde matrix multiplication kernel used in the S4D kernel.""" import math import torch from einops import rearrange, repeat from opt_einsum import contract import os try: import pykeops from pykeops.torch import LazyTensor, Genred except: pass try: from cauchy_mult import vand_log_mult_sym_fwd, vand_log_mult_sym_bwd except: vand_log_mult_sym_fwd, vand_log_mult_sym_bwd = None, None _conj = lambda x: torch.cat([x, x.conj()], dim=-1) def _broadcast_dims(*tensors): max_dim = max([len(tensor.shape) for tensor in tensors]) tensors = [tensor.view((1,)*(max_dim-len(tensor.shape))+tensor.shape) for tensor in tensors] return tensors def _c2r(x): return torch.view_as_real(x) def _r2c(x): return torch.view_as_complex(x) def vandermonde_naive(v, x, L, conj=True): """ v: (..., N) x: (..., N) returns: (..., L) \sum v x^l """ if conj: x = _conj(x) v = _conj(v) vandermonde_matrix = x.unsqueeze(-1) ** torch.arange(L).to(x) # (... N L) vandermonde_prod = torch.sum(v.unsqueeze(-1) * vandermonde_matrix, dim=-2) # (... L) return vandermonde_prod def log_vandermonde_naive(v, x, L, conj=True): """ v: (..., N) x: (..., N) returns: (..., L) \sum v x^l """ vandermonde_matrix = torch.exp(x.unsqueeze(-1) * torch.arange(L).to(x)) # (... N L) vandermonde_prod = contract('... n, ... n l -> ... l', v, vandermonde_matrix) # (... L) if conj: return 2*vandermonde_prod.real else: return vandermonde_prod def log_vandermonde_lazy(v, x, L, conj=True): if conj: v = _conj(v) x = _conj(x) l = torch.arange(L).to(x) v, x, l = _broadcast_dims(v, x, l) v_l = LazyTensor(rearrange(v, '... N -> ... N 1 1')) x_l = LazyTensor(rearrange(x, '... N -> ... N 1 1')) l_l = LazyTensor(rearrange(l, '... L -> ... 1 L 1')) # exp vand = (x_l * l_l).exp() s = (v_l*vand).sum(dim=len(v_l.shape)-2) return s.squeeze(-1) def log_vandermonde(v, x, L, conj=True): expr = 'ComplexMult(v, ComplexExp(ComplexMult(x, l)))' vandermonde_mult = Genred( expr, [ 'v = Vj(2)', 'x = Vj(2)', 'l = Vi(2)', ], reduction_op='Sum', axis=1, ) l = torch.arange(L).to(x) v, x, l = _broadcast_dims(v, x, l) v = _c2r(v) x = _c2r(x) l = _c2r(l) r = vandermonde_mult(v, x, l, backend='GPU') if conj: return 2*_r2c(r).real else: return _r2c(r) def log_vandermonde_transpose_naive(u, v, x, L): vandermonde_matrix = torch.exp(x.unsqueeze(-1) * torch.arange(L).to(x)) # (... N L) vandermonde_prod = contract('... l, ... n, ... n l -> ... n', u.to(x), v.to(x), vandermonde_matrix) # (... L) return vandermonde_prod def log_vandermonde_transpose(u, v, x, L): """ u: ... H L v: ... H N x: ... H N Returns: ... H N V = Vandermonde(a, L) : (H N L) contract_L(V * u * v) """ expr = 'ComplexMult(ComplexMult(v, u), ComplexExp(ComplexMult(x, l)))' vandermonde_mult = Genred( expr, [ 'u = Vj(2)', 'v = Vi(2)', 'x = Vi(2)', 'l = Vj(2)', ], reduction_op='Sum', axis=1, ) l = torch.arange(L).to(x) u, v, x, l = _broadcast_dims(u, v, x, l) u = _c2r(u) v = _c2r(v) x = _c2r(x) l = _c2r(l) r = vandermonde_mult(u, v, x, l, backend='GPU') return _r2c(r) def _log_vandermonde_matmul(x, L): vandermonde_matrix = torch.exp(x.unsqueeze(-1) * torch.arange(L).to(x)) # (... N L) return vandermonde_matrix def log_vandermonde_matmul(v, K): prod = contract('...n, ...nl -> ...l', v, K) return 2*prod.real class LogVandMultiplySymmetric(torch.autograd.Function): @staticmethod def forward(ctx, v, x, L): batch, N = v.shape supported_N_values = [1 << log_n for log_n in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] if not N in supported_N_values: raise NotImplementedError(f'Only support N values in {supported_N_values}') max_L_value = 32 * 1024 * 64 * 1024 if L > max_L_value: raise NotImplementedError(f'Only support L values <= {max_L_value}') if not v.is_cuda and x.is_cuda: raise NotImplementedError(f'Only support CUDA tensors') ctx.save_for_backward(v, x) return vand_log_mult_sym_fwd(v, x, L) @staticmethod def backward(ctx, dout): v, x = ctx.saved_tensors dv, dx = vand_log_mult_sym_bwd(v, x, dout) return dv, dx, None if vand_log_mult_sym_fwd and vand_log_mult_sym_bwd is not None: log_vandermonde_fast = LogVandMultiplySymmetric.apply else: log_vandermonde_fast = None
H3-main
src/ops/vandermonde.py
# Downloaded from https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/functional/krylov.py """ Compute a Krylov function efficiently. (S4 renames the Krylov function to a "state space kernel") A : (N, N) b : (N,) c : (N,) Return: [c^T A^i b for i in [L]] """ import torch import torch.nn.functional as F from einops import rearrange, repeat from src.ops.toeplitz import causal_convolution def krylov_sequential(L, A, b, c=None): """ Constant matrix A A : (..., N, N) b : (..., N) c : (..., N) Returns if c: x : (..., L) x[i, l] = c[i] @ A^l @ b[i] else: x : (..., N, L) x[i, l] = A^l @ b[i] """ # Check which of dim b and c is smaller to save memory if c is not None and c.numel() < b.numel(): return krylov_sequential(L, A.transpose(-1, -2), c, b) b_ = b x = [] for _ in range(L): if c is not None: x_ = torch.sum(c*b_, dim=-1) # (...) # could be faster with matmul or einsum? else: x_ = b_ x.append(x_) b_ = (A @ b_.unsqueeze(-1)).squeeze(-1) x = torch.stack(x, dim=-1) return x def krylov(L, A, b, c=None, return_power=False): """ Compute the Krylov matrix (b, Ab, A^2b, ...) using the squaring trick. If return_power=True, return A^{L-1} as well """ # TODO There is an edge case if L=1 where output doesn't get broadcasted, which might be an issue if caller is expecting broadcasting semantics... can deal with it if it arises x = b.unsqueeze(-1) # (..., N, 1) A_ = A AL = None if return_power: AL = torch.eye(A.shape[-1], dtype=A.dtype, device=A.device) _L = L-1 done = L == 1 # loop invariant: _L represents how many indices left to compute while not done: if return_power: if _L % 2 == 1: AL = A_ @ AL _L //= 2 # Save memory on last iteration l = x.shape[-1] if L - l <= l: done = True _x = x[..., :L-l] else: _x = x _x = A_ @ _x x = torch.cat([x, _x], dim=-1) # there might be a more efficient way of ordering axes if not done: A_ = A_ @ A_ assert x.shape[-1] == L if c is not None: x = torch.einsum('...nl, ...n -> ...l', x, c) x = x.contiguous() # WOW!! if return_power: return x, AL else: return x @torch.no_grad() def power(L, A, v=None): """ Compute A^L and the scan sum_i A^i v_i A: (..., N, N) v: (..., N, L) """ I = torch.eye(A.shape[-1]).to(A) # , dtype=A.dtype, device=A.device) powers = [A] l = 1 while True: if L % 2 == 1: I = powers[-1] @ I L //= 2 if L == 0: break l *= 2 if v is None: powers = [powers[-1] @ powers[-1]] else: powers.append(powers[-1] @ powers[-1]) if v is None: return I # Invariants: # powers[-1] := A^l # l := largest po2 at most L # Note that an alternative divide and conquer to compute the reduction is possible and can be embedded into the above loop without caching intermediate powers of A # We do this reverse divide-and-conquer for efficiency reasons: # 1) it involves fewer padding steps for non-po2 L # 2) it involves more contiguous arrays # Take care of edge case for non-po2 arrays # Note that this initial step is a no-op for the case of power of 2 (l == L) k = v.size(-1) - l v_ = powers.pop() @ v[..., l:] v = v[..., :l] v[..., :k] = v[..., :k] + v_ # Handle reduction for power of 2 while v.size(-1) > 1: v = rearrange(v, '... (z l) -> ... z l', z=2) v = v[..., 0, :] + powers.pop() @ v[..., 1, :] return I, v.squeeze(-1) def krylov_toeplitz(L, A, b, c=None): """ Specializes to lower triangular Toeplitz matrix A represented by its diagonals A : (..., N) b : (..., N) c : (..., N) Returns x : (..., N, L) x[i, l] = A^l @ b[i] """ x = b.unsqueeze(0) # (1, ..., N) A_ = A while x.shape[0] < L: xx = causal_convolution(A_, x) x = torch.cat([x, xx], dim=0) # there might be a more efficient way of ordering axes A_ = causal_convolution(A_, A_) x = x[:L, ...] # (L, ..., N) if c is not None: x = torch.einsum('l...n, ...n -> ...l', x, c) else: x = rearrange(x, 'l ... n -> ... n l') x = x.contiguous() return x def krylov_toeplitz_(L, A, b, c=None): """ Padded version of krylov_toeplitz that saves some fft's TODO currently not faster than original version, not sure why """ N = A.shape[-1] x = b.unsqueeze(0) # (1, ..., N) x = F.pad(x, (0, N)) A = F.pad(A, (0, N)) done = L == 1 while not done: l = x.shape[0] # Save memory on last iteration if L - l <= l: done = True _x = x[:L-l] else: _x = x Af = torch.fft.rfft(A, n=2*N, dim=-1) xf = torch.fft.rfft(_x, n=2*N, dim=-1) xf_ = Af * xf x_ = torch.fft.irfft(xf_, n=2*N, dim=-1) x_[..., N:] = 0 x = torch.cat([x, x_], dim=0) # there might be a more efficient way of ordering axes if not done: A = torch.fft.irfft(Af*Af, n=2*N, dim=-1) A[..., N:] = 0 x = x[:L, ..., :N] # (L, ..., N) if c is not None: x = torch.einsum('l...n, ...n -> ...l', x, c) else: x = rearrange(x, 'l ... n -> ... n l') x = x.contiguous() return x
H3-main
src/ops/krylov.py
# Downloaded from https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/functional/toeplitz.py """ Utilities for computing convolutions. There are 3 equivalent views: 1. causal convolution 2. multiplication of (lower) triangular Toeplitz matrices 3. polynomial multiplication (mod x^N) """ import torch import torch.nn as nn import torch.nn.functional as F def construct_toeplitz(v, f=0.0): """Explicit construction of Krylov matrix [v A @ v A^2 @ v ... A^{n-1} @ v] where A = Z_f. This uses vectorized indexing and cumprod so it's much faster than using the Krylov function. Parameters: v: the starting vector of size n or (rank, n). f: real number Returns: K: Krylov matrix of size (n, n) or (rank, n, n). """ n = v.shape[-1] a = torch.arange(n, device=v.device) b = -a indices = a[:, None] + b[None] K = v[..., indices] K[..., indices < 0] *= f return K def triangular_toeplitz_multiply_(u, v, sum=None): n = u.shape[-1] u_expand = F.pad(u, (0, n)) v_expand = F.pad(v, (0, n)) u_f = torch.fft.rfft(u_expand, n=2*n, dim=-1) v_f = torch.fft.rfft(v_expand, n=2*n, dim=-1) uv_f = u_f * v_f if sum is not None: uv_f = uv_f.sum(dim=sum) output = torch.fft.irfft(uv_f, n=2*n, dim=-1)[..., :n] return output def triangular_toeplitz_multiply_padded_(u, v): """ Same as triangular_toeplitz_multiply but inputs and output assume to be 0-padded already. """ n = u.shape[-1] assert n % 2 == 0 u_f = torch.fft.rfft(u, n=n, dim=-1) v_f = torch.fft.rfft(v, n=n, dim=-1) uv_f = u_f * v_f output = torch.fft.irfft(uv_f, n=n, dim=-1) output[..., n:] = 0 return output class TriangularToeplitzMult(torch.autograd.Function): @staticmethod def forward(ctx, u, v): ctx.save_for_backward(u, v) return triangular_toeplitz_multiply_(u, v) @staticmethod def backward(ctx, grad): u, v = ctx.saved_tensors d_u = triangular_toeplitz_multiply_(grad.flip(-1), v).flip(-1) d_v = triangular_toeplitz_multiply_(grad.flip(-1), u).flip(-1) return d_u, d_v class TriangularToeplitzMultFast(torch.autograd.Function): @staticmethod def forward(ctx, u, v): n = u.shape[-1] u_expand = F.pad(u, (0, n)) v_expand = F.pad(v, (0, n)) u_f = torch.fft.rfft(u_expand, n=2*n, dim=-1) v_f = torch.fft.rfft(v_expand, n=2*n, dim=-1) ctx.save_for_backward(u_f, v_f) uv_f = u_f * v_f output = torch.fft.irfft(uv_f, n=2*n, dim=-1)[..., :n] return output @staticmethod def backward(ctx, grad): u_f, v_f = ctx.saved_tensors n = grad.shape[-1] g_expand = F.pad(grad.flip(-1), (0, n)) g_f = torch.fft.rfft(g_expand, n=2*n, dim=-1) gu_f = g_f * u_f gv_f = g_f * v_f d_u = torch.fft.irfft(gv_f, n=2*n, dim=-1)[..., :n] d_v = torch.fft.irfft(gu_f, n=2*n, dim=-1)[..., :n] d_u = d_u.flip(-1) d_v = d_v.flip(-1) return d_u, d_v class TriangularToeplitzMultPadded(torch.autograd.Function): @staticmethod def forward(ctx, u, v): ctx.save_for_backward(u, v) output = triangular_toeplitz_multiply_(u, v) return output @staticmethod def backward(ctx, grad): u, v = ctx.saved_tensors d_u = triangular_toeplitz_multiply_padded_(grad.flip(-1), v).flip(-1) d_v = triangular_toeplitz_multiply_padded_(grad.flip(-1), u).flip(-1) return d_u, d_v class TriangularToeplitzMultPaddedFast(torch.autograd.Function): """ Trade off speed (20-25% faster) for more memory (20-25%) """ @staticmethod def forward(ctx, u, v): n = u.shape[-1] u_f = torch.fft.rfft(u, n=n, dim=-1) v_f = torch.fft.rfft(v, n=n, dim=-1) ctx.save_for_backward(u_f, v_f) uv_f = u_f * v_f output = torch.fft.irfft(uv_f, n=n, dim=-1) output[..., n//2:].zero_() return output @staticmethod def backward(ctx, grad): u_f, v_f = ctx.saved_tensors n = grad.shape[-1] g_expand = F.pad(grad[..., :n//2].flip(-1), (0, n//2)) g_f = torch.fft.rfft(g_expand, n=n, dim=-1) gu_f = g_f * u_f gv_f = g_f * v_f d_u = torch.fft.irfft(gv_f, n=n, dim=-1) d_v = torch.fft.irfft(gu_f, n=n, dim=-1) d_u[..., n//2:].zero_() d_v[..., n//2:].zero_() d_u[..., :n//2] = d_u[..., :n//2].flip(-1) # TODO d_v[..., :n//2] = d_v[..., :n//2].flip(-1) # TODO return d_u, d_v # triangular_toeplitz_multiply = triangular_toeplitz_multiply_ triangular_toeplitz_multiply = TriangularToeplitzMult.apply triangular_toeplitz_multiply_fast = TriangularToeplitzMultFast.apply triangular_toeplitz_multiply_padded = TriangularToeplitzMultPadded.apply triangular_toeplitz_multiply_padded_fast = TriangularToeplitzMultPaddedFast.apply def causal_convolution(u, v, fast=True, pad=False): if not pad and not fast: return triangular_toeplitz_multiply(u, v) if not pad and fast: return triangular_toeplitz_multiply_fast(u, v) if pad and not fast: return triangular_toeplitz_multiply_padded(u, v) if pad and fast: return triangular_toeplitz_multiply_padded_fast(u, v)
H3-main
src/ops/toeplitz.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from distutils.core import setup ext_modules = [] cmdclass = {} with open("requirements.txt", "r") as handle: install_requires = handle.read().splitlines() setup( name="cpa", version="1.0.0", description="", url="http://github.com/facebookresearch/CPA", author="See README.md", author_email="dlp@fb.com", license="MIT", packages=["cpa"], cmdclass=cmdclass, ext_modules=ext_modules, install_requires=install_requires, )
CPA-main
setup.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from collections import defaultdict import matplotlib.font_manager import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from adjustText import adjust_text from sklearn.decomposition import KernelPCA from sklearn.metrics import r2_score from sklearn.metrics.pairwise import cosine_similarity FONT_SIZE = 10 font = {"size": FONT_SIZE} matplotlib.rc("font", **font) matplotlib.rc("ytick", labelsize=FONT_SIZE) matplotlib.rc("xtick", labelsize=FONT_SIZE) class CPAVisuals: """ A wrapper for automatic plotting CompPert latent embeddings and dose-response curve. Sets up prefix for all files and default dictionaries for atomic perturbations and cell types. """ def __init__( self, cpa, fileprefix=None, perts_palette=None, covars_palette=None, plot_params={"fontsize": None}, ): """ Parameters ---------- cpa : CompPertAPI Variable from API class. fileprefix : str, optional (default: None) Prefix (with path) to the filename to save all embeddings in a standartized manner. If None, embeddings are not saved to file. perts_palette : dict (default: None) Dictionary of colors for the embeddings of perturbations. Keys correspond to perturbations and values to their colors. If None, default dicitonary will be set up. covars_palette : dict (default: None) Dictionary of colors for the embeddings of covariates. Keys correspond to covariates and values to their colors. If None, default dicitonary will be set up. """ self.fileprefix = fileprefix self.perturbation_key = cpa.perturbation_key self.dose_key = cpa.dose_key self.covariate_keys = cpa.covariate_keys self.measured_points = cpa.measured_points self.unique_perts = cpa.unique_perts self.unique_covars = cpa.unique_covars if perts_palette is None: self.perts_palette = dict( zip(self.unique_perts, get_palette(len(self.unique_perts))) ) else: self.perts_palette = perts_palette if covars_palette is None: self.covars_palette = {} for cov in self.unique_covars: self.covars_palette[cov] = dict( zip( self.unique_covars[cov], get_palette(len(self.unique_covars[cov]), palette_name="tab10"), ) ) else: self.covars_palette = covars_palette if plot_params["fontsize"] is None: self.fontsize = FONT_SIZE else: self.fontsize = plot_params["fontsize"] def plot_latent_embeddings( self, emb, titlename="Example", kind="perturbations", palette=None, labels=None, dimred="KernelPCA", filename=None, show_text=True, ): """ Parameters ---------- emb : np.array Multi-dimensional embedding of perturbations or covariates. titlename : str, optional (default: 'Example') Title. kind : int, optional, optional (default: 'perturbations') Specify if this is embedding of perturbations, covariates or some other. If it is perturbations or covariates, it will use default saved dictionaries for colors. palette : dict, optional (default: None) If embedding of kind not perturbations or covariates, the user can specify color dictionary for the embedding. labels : list, optional (default: None) Labels for the embeddings. dimred : str, optional (default: 'KernelPCA') Dimensionality reduction method for plotting low dimensional representations. Options: 'KernelPCA', 'UMAPpre', 'UMAPcos', None. If None, uses first 2 dimensions of the embedding. filename : str (default: None) Name of the file to save the plot. If None, will automatically generate name from prefix file. """ if filename is None: if self.fileprefix is None: filename = None file_name_similarity = None else: filename = f"{self.fileprefix}_emebdding.png" file_name_similarity = f"{self.fileprefix}_emebdding_similarity.png" else: file_name_similarity = filename.split(".")[0] + "_similarity.png" if labels is None: if kind == "perturbations": palette = self.perts_palette labels = self.unique_perts elif kind in self.unique_covars: palette = self.covars_palette[kind] labels = self.unique_covars[kind] if len(emb) < 2: print(f"Embedding contains only {len(emb)} vectors. Not enough to plot.") else: plot_embedding( fast_dimred(emb, method=dimred), labels, show_lines=True, show_text=show_text, col_dict=palette, title=titlename, file_name=filename, fontsize=self.fontsize, ) plot_similarity( emb, labels, col_dict=palette, fontsize=self.fontsize, file_name=file_name_similarity, ) def plot_contvar_response2D( self, df_response2D, df_ref=None, levels=15, figsize=(4, 4), xlims=(0, 1.03), ylims=(0, 1.03), palette="coolwarm", response_name="response", title_name=None, fontsize=None, postfix="", filename=None, alpha=0.4, sizes=(40, 160), logdose=False, ): """ Parameters ---------- df_response2D : pd.DataFrame Data frame with responses of combinations with columns=(dose1, dose2, response). levels: int, optional (default: 15) Number of levels for contour plot. response_name : str (default: 'response') Name of column in df_response to plot as response. alpha: float (default: 0.4) Transparency of the background contour. figsize: tuple (default: (4,4)) Size of the figure in inches. palette : dict, optional (default: None) Colors dictionary for perturbations to plot. title_name : str, optional (default: None) Title for the plot. postfix : str, optional (defualt: '') Postfix to add to the output file name to save the model. filename : str, optional (defualt: None) Name of the file to save the plot. If None, will automatically generate name from prefix file. logdose: bool (default: False) If True, dose values will be log10. 0 values will be mapped to minumum value -1,e.g. if smallest non-zero dose was 0.001, 0 will be mapped to -4. """ sns.set_style("white") if (filename is None) and not (self.fileprefix is None): filename = f"{self.fileprefix}_{postfix}response2D.png" if fontsize is None: fontsize = self.fontsize x_name, y_name = df_response2D.columns[:2] x = df_response2D[x_name].values y = df_response2D[y_name].values if logdose: x = log10_with0(x) y = log10_with0(y) z = df_response2D[response_name].values n = int(np.sqrt(len(x))) X = x.reshape(n, n) Y = y.reshape(n, n) Z = z.reshape(n, n) fig, ax = plt.subplots(figsize=figsize) CS = ax.contourf(X, Y, Z, cmap=palette, levels=levels, alpha=alpha) CS = ax.contour(X, Y, Z, levels=15, cmap=palette) ax.clabel(CS, inline=1, fontsize=fontsize) ax.set(xlim=(0, 1), ylim=(0, 1)) ax.axis("equal") ax.axis("square") ax.yaxis.set_tick_params(labelsize=fontsize) ax.xaxis.set_tick_params(labelsize=fontsize) ax.set_xlabel(x_name, fontsize=fontsize, fontweight="bold") ax.set_ylabel(y_name, fontsize=fontsize, fontweight="bold") ax.set_xlim(xlims) ax.set_ylim(ylims) # sns.despine(left=False, bottom=False, right=True) sns.despine() if not (df_ref is None): sns.scatterplot( x=x_name, y=y_name, hue="split", size="num_cells", sizes=sizes, alpha=1.0, palette={"train": "#000000", "training": "#000000", "ood": "#e41a1c"}, data=df_ref, ax=ax, ) ax.legend_.remove() ax.set_title(title_name, fontweight="bold", fontsize=fontsize) plt.tight_layout() if filename: save_to_file(fig, filename) def plot_contvar_response( self, df_response, response_name="response", var_name=None, df_ref=None, palette=None, title_name=None, postfix="", xlabelname=None, filename=None, logdose=False, fontsize=None, measured_points=None, bbox=(1.35, 1.0), figsize=(7.0, 4.0), ): """ Parameters ---------- df_response : pd.DataFrame Data frame of responses. response_name : str (default: 'response') Name of column in df_response to plot as response. var_name : str, optional (default: None) Name of conditioning variable, e.g. could correspond to covariates. df_ref : pd.DataFrame, optional (default: None) Reference values. Fields for plotting should correspond to df_response. palette : dict, optional (default: None) Colors dictionary for perturbations to plot. title_name : str, optional (default: None) Title for the plot. postfix : str, optional (defualt: '') Postfix to add to the output file name to save the model. filename : str, optional (defualt: None) Name of the file to save the plot. If None, will automatically generate name from prefix file. logdose: bool (default: False) If True, dose values will be log10. 0 values will be mapped to minumum value -1,e.g. if smallest non-zero dose was 0.001, 0 will be mapped to -4. figsize: tuple (default: (7., 4.)) Size of output figure """ if (filename is None) and not (self.fileprefix is None): filename = f"{self.fileprefix}_{postfix}response.png" if fontsize is None: fontsize = self.fontsize if logdose: dose_name = f"log10-{self.dose_key}" df_response[dose_name] = log10_with0(df_response[self.dose_key].values) if not (df_ref is None): df_ref[dose_name] = log10_with0(df_ref[self.dose_key].values) else: dose_name = self.dose_key if var_name is None: if len(self.unique_covars) > 1: var_name = self.covars_key else: var_name = self.perturbation_key if palette is None: if var_name == self.perturbation_key: palette = self.perts_palette elif var_name in self.covariate_keys: palette = self.covars_palette[var_name] plot_dose_response( df_response, dose_name, var_name, xlabelname=xlabelname, df_ref=df_ref, response_name=response_name, title_name=title_name, use_ref_response=(not (df_ref is None)), col_dict=palette, plot_vertical=False, f1=figsize[0], f2=figsize[1], fname=filename, logscale=measured_points, measured_points=measured_points, bbox=bbox, fontsize=fontsize, figformat="png", ) def plot_scatter( self, df, x_axis, y_axis, hue=None, size=None, style=None, figsize=(4.5, 4.5), title=None, palette=None, filename=None, alpha=0.75, sizes=(30, 90), text_dict=None, postfix="", fontsize=14, ): sns.set_style("white") if (filename is None) and not (self.fileprefix is None): filename = f"{self.fileprefix}_scatter{postfix}.png" if fontsize is None: fontsize = self.fontsize fig = plt.figure(figsize=figsize) ax = plt.gca() sns.scatterplot( x=x_axis, y=y_axis, hue=hue, style=style, size=size, sizes=sizes, alpha=alpha, palette=palette, data=df, ) ax.legend_.remove() ax.set_xlabel(x_axis, fontsize=fontsize) ax.set_ylabel(y_axis, fontsize=fontsize) ax.xaxis.set_tick_params(labelsize=fontsize) ax.yaxis.set_tick_params(labelsize=fontsize) ax.set_title(title) if not (text_dict is None): texts = [] for label in text_dict.keys(): texts.append( ax.text( text_dict[label][0], text_dict[label][1], label, fontsize=fontsize, ) ) adjust_text( texts, arrowprops=dict(arrowstyle="-", color="black", lw=0.1), ax=ax ) plt.tight_layout() if filename: save_to_file(fig, filename) def log10_with0(x): mx = np.min(x[x > 0]) x[x == 0] = mx / 10 return np.log10(x) def get_palette(n_colors, palette_name="Set1"): try: palette = sns.color_palette(palette_name) except: print("Palette not found. Using default palette tab10") palette = sns.color_palette() while len(palette) < n_colors: palette += palette return palette def fast_dimred(emb, method="KernelPCA"): """ Takes high dimensional embeddings and produces a 2-dimensional representation for plotting. emb: np.array Embeddings matrix. method: str (default: 'KernelPCA') Method for dimensionality reduction: KernelPCA, UMAPpre, UMAPcos, tSNE. If None return first 2 dimensions of the embedding vector. """ if method is None: return emb[:, :2] elif method == "KernelPCA": similarity_matrix = cosine_similarity(emb) np.fill_diagonal(similarity_matrix, 1.0) X = KernelPCA(n_components=2, kernel="precomputed").fit_transform( similarity_matrix ) else: raise NotImplementedError return X def plot_dose_response( df, contvar_key, perturbation_key, df_ref=None, response_name="response", use_ref_response=False, palette=None, col_dict=None, fontsize=8, measured_points=None, interpolate=True, f1=7, f2=3.0, bbox=(1.35, 1.0), ref_name="origin", title_name="None", plot_vertical=True, fname=None, logscale=None, xlabelname=None, figformat="png", ): """Plotting decoding of the response with respect to dose. Params ------ df : `DataFrame` Table with columns=[perturbation_key, contvar_key, response_name]. The last column is always "response". contvar_key : str Name of the column in df for values to use for x axis. perturbation_key : str Name of the column in df for the perturbation or covariate to plot. response_name: str (default: response) Name of the column in df for values to use for y axis. df_ref : `DataFrame` (default: None) Table with the same columns as in df to plot ground_truth or another condition for comparison. Could also be used to just extract reference values for x-axis. use_ref_response : bool (default: False) A flag indicating if to use values for y axis from df_ref (True) or j ust to extract reference values for x-axis. col_dict : dictionary (default: None) Dictionary with colors for each value in perturbation_key. bbox : tuple (default: (1.35, 1.)) Coordinates to adjust the legend. plot_vertical : boolean (default: False) Flag if to plot reference values for x axis from df_ref dataframe. f1 : float (default: 7.0)) Width in inches for the plot. f2 : float (default: 3.0)) Hight in inches for the plot. fname : str (default: None) Name of the file to export the plot. The name comes without format extension. format : str (default: png) Format for the file to export the plot. """ sns.set_style("white") if use_ref_response and not (df_ref is None): df[ref_name] = "predictions" df_ref[ref_name] = "observations" if interpolate: df_plt = pd.concat([df, df_ref]) else: df_plt = df else: df_plt = df df_plt = df_plt.reset_index() atomic_drugs = np.unique(df[perturbation_key].values) if palette is None: current_palette = get_palette(len(list(atomic_drugs))) if col_dict is None: col_dict = dict(zip(list(atomic_drugs), current_palette)) fig = plt.figure(figsize=(f1, f2)) ax = plt.gca() if use_ref_response: sns.lineplot( x=contvar_key, y=response_name, palette=col_dict, hue=perturbation_key, style=ref_name, dashes=[(1, 0), (2, 1)], legend="full", style_order=["predictions", "observations"], data=df_plt, ax=ax, ) df_ref = df_ref.replace("training_treated", "train") sns.scatterplot( x=contvar_key, y=response_name, hue="split", size="num_cells", sizes=(10, 100), alpha=1.0, palette={"train": "#000000", "training": "#000000", "ood": "#e41a1c"}, data=df_ref, ax=ax, ) sns.despine() ax.legend_.remove() else: sns.lineplot( x=contvar_key, y=response_name, palette=col_dict, hue=perturbation_key, data=df_plt, ax=ax, ) ax.legend(loc="upper right", bbox_to_anchor=bbox, fontsize=fontsize) sns.despine() if not (title_name is None): ax.set_title(title_name, fontsize=fontsize, fontweight="bold") ax.grid("off") if xlabelname is None: ax.set_xlabel(contvar_key, fontsize=fontsize) else: ax.set_xlabel(xlabelname, fontsize=fontsize) ax.set_ylabel(f"{response_name}", fontsize=fontsize) ax.xaxis.set_tick_params(labelsize=fontsize) ax.yaxis.set_tick_params(labelsize=fontsize) if not (logscale is None): ax.set_xticks(np.log10(logscale)) ax.set_xticklabels(logscale, rotation=90) if not (df_ref is None): atomic_drugs = np.unique(df_ref[perturbation_key].values) for drug in atomic_drugs: x = df_ref[df_ref[perturbation_key] == drug][contvar_key].values m1 = np.min(df[df[perturbation_key] == drug][response_name].values) m2 = np.max(df[df[perturbation_key] == drug][response_name].values) if plot_vertical: for x_dot in x: ax.plot( [x_dot, x_dot], [m1, m2], ":", color="black", linewidth=0.5, alpha=0.5, ) fig.tight_layout() if fname: plt.savefig(f"{fname}.{figformat}", format=figformat, dpi=600) return fig def plot_uncertainty_comb_dose( cpa_api, cov, pert, N=11, metric="cosine", measured_points=None, cond_key="condition", figsize=(4, 4), vmin=None, vmax=None, sizes=(40, 160), df_ref=None, xlims=(0, 1.03), ylims=(0, 1.03), fixed_drugs="", fixed_doses="", title="", filename=None, ): """Plotting uncertainty for a single perturbation at a dose range for a particular covariate. Params ------ cpa_api Api object for the model class. cov : dict Name of covariate. pert : str Name of the perturbation. N : int Number of dose values. metric: str (default: 'cosine') Metric to evaluate uncertainty. measured_points : dict (default: None) A dicitionary of dictionaries. Per each covariate a dictionary with observed doses per perturbation, e.g. {'covar1': {'pert1': [0.1, 0.5, 1.0], 'pert2': [0.3]} cond_key : str (default: 'condition') Name of the variable to use for plotting. filename : str (default: None) Full path to the file to export the plot. File extension should be included. Returns ------- pd.DataFrame of uncertainty estimations. """ cov_name = "_".join([cov[cov_key] for cov_key in cpa_api.covariate_keys]) df_list = [] for i in np.round(np.linspace(0, 1, N), decimals=2): for j in np.round(np.linspace(0, 1, N), decimals=2): df_list.append( { "covariates": cov_name, "condition": pert + fixed_drugs, "dose_val": str(i) + "+" + str(j) + fixed_doses, } ) df_pred = pd.DataFrame(df_list) uncert_cos = [] uncert_eucl = [] closest_cond_cos = [] closest_cond_eucl = [] for i in range(df_pred.shape[0]): ( uncert_cos_, uncert_eucl_, closest_cond_cos_, closest_cond_eucl_, ) = cpa_api.compute_uncertainty( cov=cov, pert=df_pred.iloc[i]["condition"], dose=df_pred.iloc[i]["dose_val"] ) uncert_cos.append(uncert_cos_) uncert_eucl.append(uncert_eucl_) closest_cond_cos.append(closest_cond_cos_) closest_cond_eucl.append(closest_cond_eucl_) df_pred["uncertainty_cosine"] = uncert_cos df_pred["uncertainty_eucl"] = uncert_eucl df_pred["closest_cond_cos"] = closest_cond_cos df_pred["closest_cond_eucl"] = closest_cond_eucl doses = df_pred.dose_val.apply(lambda x: x.split("+")) X = np.array(doses.apply(lambda x: x[0]).astype(float)).reshape(N, N) Y = np.array(doses.apply(lambda x: x[1]).astype(float)).reshape(N, N) Z = np.array(df_pred[f"uncertainty_{metric}"].values.astype(float)).reshape(N, N) fig, ax = plt.subplots(1, 1, figsize=figsize) CS = ax.contourf(X, Y, Z, cmap="coolwarm", levels=20, alpha=1, vmin=vmin, vmax=vmax) ax.set_xlabel(pert.split("+")[0], fontweight="bold") ax.set_ylabel(pert.split("+")[1], fontweight="bold") if not (df_ref is None): sns.scatterplot( x=pert.split("+")[0], y=pert.split("+")[1], hue="split", size="num_cells", sizes=sizes, alpha=1.0, palette={"train": "#000000", "training": "#000000", "ood": "#e41a1c"}, data=df_ref, ax=ax, ) ax.legend_.remove() if measured_points: ticks = measured_points[cov_name][pert] xticks = [float(x.split("+")[0]) for x in ticks] yticks = [float(x.split("+")[1]) for x in ticks] ax.set_xticks(xticks) ax.set_xticklabels(xticks, rotation=90) ax.set_yticks(yticks) fig.colorbar(CS) sns.despine() ax.axis("equal") ax.axis("square") ax.set_xlim(xlims) ax.set_ylim(ylims) ax.set_title(title, fontsize=10, fontweight='bold') plt.tight_layout() if filename: plt.savefig(filename, dpi=600) return df_pred def plot_uncertainty_dose( cpa_api, cov, pert, N=11, metric="cosine", measured_points=None, cond_key="condition", log=False, min_dose=None, filename=None, ): """Plotting uncertainty for a single perturbation at a dose range for a particular covariate. Params ------ cpa_api Api object for the model class. cov : str Name of covariate. pert : str Name of the perturbation. N : int Number of dose values. metric: str (default: 'cosine') Metric to evaluate uncertainty. measured_points : dict (default: None) A dicitionary of dictionaries. Per each covariate a dictionary with observed doses per perturbation, e.g. {'covar1': {'pert1': [0.1, 0.5, 1.0], 'pert2': [0.3]} cond_key : str (default: 'condition') Name of the variable to use for plotting. log : boolean (default: False) A flag if to plot on a log scale. min_dose : float (default: None) Minimum dose for the uncertainty estimate. filename : str (default: None) Full path to the file to export the plot. File extension should be included. Returns ------- pd.DataFrame of uncertainty estimations. """ df_list = [] if log: if min_dose is None: min_dose = 1e-3 N_val = np.round(np.logspace(np.log10(min_dose), np.log10(1), N), decimals=10) else: if min_dose is None: min_dose = 0 N_val = np.round(np.linspace(min_dose, 1.0, N), decimals=3) cov_name = "_".join([cov[cov_key] for cov_key in cpa_api.covariate_keys]) for i in N_val: df_list.append({"covariates": cov_name, "condition": pert, "dose_val": repr(i)}) df_pred = pd.DataFrame(df_list) uncert_cos = [] uncert_eucl = [] closest_cond_cos = [] closest_cond_eucl = [] for i in range(df_pred.shape[0]): ( uncert_cos_, uncert_eucl_, closest_cond_cos_, closest_cond_eucl_, ) = cpa_api.compute_uncertainty( cov=cov, pert=df_pred.iloc[i]["condition"], dose=df_pred.iloc[i]["dose_val"] ) uncert_cos.append(uncert_cos_) uncert_eucl.append(uncert_eucl_) closest_cond_cos.append(closest_cond_cos_) closest_cond_eucl.append(closest_cond_eucl_) df_pred["uncertainty_cosine"] = uncert_cos df_pred["uncertainty_eucl"] = uncert_eucl df_pred["closest_cond_cos"] = closest_cond_cos df_pred["closest_cond_eucl"] = closest_cond_eucl x = df_pred.dose_val.values.astype(float) y = df_pred[f"uncertainty_{metric}"].values.astype(float) fig, ax = plt.subplots(1, 1) ax.plot(x, y) ax.set_xlabel(pert) ax.set_ylabel("Uncertainty") ax.set_title(cov_name) if log: ax.set_xscale("log") if measured_points: ticks = measured_points[cov_name][pert] ax.set_xticks(ticks) ax.set_xticklabels(ticks, rotation=90) else: plt.draw() ax.set_xticklabels(ax.get_xticklabels(), rotation=90) sns.despine() plt.tight_layout() if filename: plt.savefig(filename) return df_pred def save_to_file(fig, file_name, file_format=None): if file_format is None: if file_name.split(".")[-1] in ["png", "pdf"]: file_format = file_name.split(".")[-1] savename = file_name else: file_format = "pdf" savename = f"{file_name}.{file_format}" else: savename = file_name fig.savefig(savename, format=file_format, dpi=600) print(f"Saved file to: {savename}") def plot_embedding( emb, labels=None, col_dict=None, title=None, show_lines=False, show_text=False, show_legend=True, axis_equal=True, circle_size=40, circe_transparency=1.0, line_transparency=0.8, line_width=1.0, fontsize=9, fig_width=4, fig_height=4, file_name=None, file_format=None, labels_name=None, width_ratios=[7, 1], bbox=(1.3, 0.7), ): sns.set_style("white") # create data structure suitable for embedding df = pd.DataFrame(emb, columns=["dim1", "dim2"]) if not (labels is None): if labels_name is None: labels_name = "labels" df[labels_name] = labels fig = plt.figure(figsize=(fig_width, fig_height)) ax = plt.gca() sns.despine(left=False, bottom=False, right=True) if (col_dict is None) and not (labels is None): col_dict = get_colors(labels) sns.scatterplot( x="dim1", y="dim2", hue=labels_name, palette=col_dict, alpha=circe_transparency, edgecolor="none", s=circle_size, data=df, ax=ax, ) try: ax.legend_.remove() except: pass if show_lines: for i in range(len(emb)): if col_dict is None: ax.plot( [0, emb[i, 0]], [0, emb[i, 1]], alpha=line_transparency, linewidth=line_width, c=None, ) else: ax.plot( [0, emb[i, 0]], [0, emb[i, 1]], alpha=line_transparency, linewidth=line_width, c=col_dict[labels[i]], ) if show_text and not (labels is None): texts = [] labels = np.array(labels) unique_labels = np.unique(labels) for label in unique_labels: idx_label = np.where(labels == label)[0] texts.append( ax.text( np.mean(emb[idx_label, 0]), np.mean(emb[idx_label, 1]), label, #fontsize=fontsize, ) ) adjust_text( texts, arrowprops=dict(arrowstyle="-", color="black", lw=0.1), ax=ax ) if axis_equal: ax.axis("equal") ax.axis("square") if title: ax.set_title(title, fontweight="bold") ax.set_xlabel("dim1"),# fontsize=fontsize) ax.set_ylabel("dim2"),# fontsize=fontsize) #ax.xaxis.set_tick_params(labelsize=fontsize) #ax.yaxis.set_tick_params(labelsize=fontsize) plt.tight_layout() if file_name: save_to_file(fig, file_name, file_format) return plt def get_colors(labels, palette=None, palette_name=None): n_colors = len(labels) if palette is None: palette = get_palette(n_colors, palette_name) col_dict = dict(zip(labels, palette[:n_colors])) return col_dict def plot_similarity( emb, labels=None, col_dict=None, fig_width=4, fig_height=4, cmap="coolwarm", fmt="png", fontsize=7, file_format=None, file_name=None, ): # first we take construct similarity matrix # add another similarity similarity_matrix = cosine_similarity(emb) df = pd.DataFrame( similarity_matrix, columns=labels, index=labels, ) if col_dict is None: col_dict = get_colors(labels) network_colors = pd.Series(df.columns, index=df.columns).map(col_dict) sns_plot = sns.clustermap( df, cmap=cmap, center=0, row_colors=network_colors, col_colors=network_colors, mask=False, metric="euclidean", figsize=(fig_height, fig_width), vmin=-1, vmax=1, fmt=file_format, ) sns_plot.ax_heatmap.xaxis.set_tick_params(labelsize=fontsize) sns_plot.ax_heatmap.yaxis.set_tick_params(labelsize=fontsize) sns_plot.ax_heatmap.axis("equal") sns_plot.cax.yaxis.set_tick_params(labelsize=fontsize) if file_name: save_to_file(sns_plot, file_name, file_format) from scipy import sparse, stats from sklearn.metrics import r2_score def mean_plot( adata, pred, condition_key, exp_key, path_to_save="./reg_mean.pdf", gene_list=None, deg_list=None, show=False, title=None, verbose=False, x_coeff=0.30, y_coeff=0.8, fontsize=11, R2_type="R2", figsize=(3.5, 3.5), **kwargs, ): """ Plots mean matching. # Parameters adata: `~anndata.AnnData` Contains real v pred: `~anndata.AnnData` Contains predicted values. condition_key: Str adata.obs key to look for x-axis and y-axis condition exp_key: Str Condition in adata.obs[condition_key] to be ploted path_to_save: basestring Path to save the plot. gene_list: list List of gene names to be plotted. deg_list: list List of DEGs to compute R2 show: boolean if True plots the figure Verbose: boolean If true prints the value title: Str Title of the plot x_coeff: float Shifts R2 text horizontally by x_coeff y_coeff: float Shifts R2 text vertically by y_coeff show: bool if `True`: will show to the plot after saving it. fontsize: int Font size for R2 texts R2_type: Str How to compute R2 value, should be either Pearson R2 or R2 (sklearn) Returns: Calluated R2 values """ r2_types = ["R2", "Pearson R2"] if R2_type not in r2_types: raise ValueError("R2 caclulation should be one of" + str(r2_types)) if sparse.issparse(adata.X): adata.X = adata.X.A if sparse.issparse(pred.X): pred.X = pred.X.A diff_genes = deg_list real = adata[adata.obs[condition_key] == exp_key] pred = pred[pred.obs[condition_key] == exp_key] if diff_genes is not None: if hasattr(diff_genes, "tolist"): diff_genes = diff_genes.tolist() real_diff = adata[:, diff_genes][adata.obs[condition_key] == exp_key] pred_diff = pred[:, diff_genes][pred.obs[condition_key] == exp_key] x_diff = np.average(pred_diff.X, axis=0) y_diff = np.average(real_diff.X, axis=0) if R2_type == "R2": r2_diff = r2_score(y_diff, x_diff) if R2_type == "Pearson R2": m, b, pearson_r_diff, p_value_diff, std_err_diff = stats.linregress( y_diff, x_diff ) r2_diff = pearson_r_diff ** 2 if verbose: print(f"Top {len(diff_genes)} DEGs var: ", r2_diff) x = np.average(pred.X, axis=0) y = np.average(real.X, axis=0) if R2_type == "R2": r2 = r2_score(y, x) if R2_type == "Pearson R2": m, b, pearson_r, p_value, std_err = stats.linregress(y, x) r2 = pearson_r ** 2 if verbose: print("All genes var: ", r2) df = pd.DataFrame({f"{exp_key}_true": x, f"{exp_key}_pred": y}) plt.figure(figsize=figsize) ax = sns.regplot(x=f"{exp_key}_true", y=f"{exp_key}_pred", data=df) ax.tick_params(labelsize=fontsize) if "range" in kwargs: start, stop, step = kwargs.get("range") ax.set_xticks(np.arange(start, stop, step)) ax.set_yticks(np.arange(start, stop, step)) ax.set_xlabel("true", fontsize=fontsize) ax.set_ylabel("pred", fontsize=fontsize) if gene_list is not None: for i in gene_list: j = adata.var_names.tolist().index(i) x_bar = x[j] y_bar = y[j] plt.text(x_bar, y_bar, i, fontsize=fontsize, color="black") plt.plot(x_bar, y_bar, "o", color="red", markersize=5) if title is None: plt.title(f"", fontsize=fontsize, fontweight="bold") else: plt.title(title, fontsize=fontsize, fontweight="bold") ax.text( max(x) - max(x) * x_coeff, max(y) - y_coeff * max(y), r"$\mathrm{R^2_{\mathrm{\mathsf{all\ genes}}}}$= " + f"{r2:.2f}", fontsize=fontsize, ) if diff_genes is not None: ax.text( max(x) - max(x) * x_coeff, max(y) - (y_coeff + 0.15) * max(y), r"$\mathrm{R^2_{\mathrm{\mathsf{DEGs}}}}$= " + f"{r2_diff:.2f}", fontsize=fontsize, ) plt.savefig(f"{path_to_save}", bbox_inches="tight", dpi=100) if show: plt.show() plt.close() if diff_genes is not None: return r2, r2_diff else: return r2 def plot_r2_matrix(pred, adata, de_genes=None, **kwds): """Plots a pairwise R2 heatmap between predicted and control conditions. Params ------ pred : `AnnData` Must have the field `cov_drug_dose_name` adata : `AnnData` Original gene expression data, with the field `cov_drug_dose_name`. de_genes : `dict` Dictionary of de_genes, where the keys match the categories in `cov_drug_dose_name` """ r2s_mean = defaultdict(list) r2s_var = defaultdict(list) conditions = pred.obs["cov_drug_dose_name"].cat.categories for cond in conditions: if de_genes: degs = de_genes[cond] y_pred = pred[:, degs][pred.obs["cov_drug_dose_name"] == cond].X y_true_adata = adata[:, degs] else: y_pred = pred[pred.obs["cov_drug_dose_name"] == cond].X y_true_adata = adata # calculate r2 between pairwise for cond_real in conditions: y_true = y_true_adata[ y_true_adata.obs["cov_drug_dose_name"] == cond_real ].X.toarray() r2s_mean[cond_real].append( r2_score(y_true.mean(axis=0), y_pred.mean(axis=0)) ) r2s_var[cond_real].append(r2_score(y_true.var(axis=0), y_pred.var(axis=0))) for r2_dict in [r2s_mean, r2s_var]: r2_df = pd.DataFrame.from_dict(r2_dict, orient="index") r2_df.columns = conditions plt.figure(figsize=(5, 5)) p = sns.heatmap( data=r2_df, vmin=max(r2_df.min(0).min(), 0), cmap="Blues", cbar=False, annot=True, fmt=".2f", annot_kws={"fontsize": 5}, **kwds, ) plt.xticks(fontsize=6) plt.yticks(fontsize=6) plt.xlabel("y_true") plt.ylabel("y_pred") plt.show() def arrange_history(history): print(history.keys()) class CPAHistory: """ A wrapper for automatic plotting history of CPA model.. """ def __init__(self, cpa_api, fileprefix=None): """ Parameters ---------- cpa_api : dict cpa api instance fileprefix : str, optional (default: None) Prefix (with path) to the filename to save all embeddings in a standartized manner. If None, embeddings are not saved to file. """ self.history = cpa_api.history self.time = self.history["elapsed_time_min"] self.losses_list = [ "loss_reconstruction", "loss_adv_drugs", "loss_adv_covariates", ] self.penalties_list = ["penalty_adv_drugs", "penalty_adv_covariates"] subset_keys = ["epoch"] + self.losses_list + self.penalties_list self.losses = pd.DataFrame( dict((k, self.history[k]) for k in subset_keys if k in self.history) ) self.header = ["mean", "mean_DE", "var", "var_DE"] self.eval_metrics = False if 'perturbation disentanglement' in list (self.history): #check that metrics were evaluated self.eval_metrics = True self.metrics = pd.DataFrame(columns=["epoch", "split"] + self.header) for split in ["training", "test", "ood"]: df_split = pd.DataFrame(np.array(self.history[split]), columns=self.header) df_split["split"] = split df_split["epoch"] = self.history["stats_epoch"] self.metrics = pd.concat([self.metrics, df_split]) self.covariate_names = list(cpa_api.datasets["training"].covariate_names) self.disent = pd.DataFrame( dict( (k, self.history[k]) for k in ['perturbation disentanglement'] + [f'{cov} disentanglement' for cov in self.covariate_names] if k in self.history ) ) self.disent["epoch"] = self.history["stats_epoch"] self.fileprefix = fileprefix def print_time(self): print(f"Computation time: {self.time:.0f} min") def plot_losses(self, filename=None): """ Parameters ---------- filename : str (default: None) Name of the file to save the plot. If None, will automatically generate name from prefix file. """ if filename is None: if self.fileprefix is None: filename = None else: filename = f"{self.fileprefix}_history_losses.png" fig, ax = plt.subplots(1, 4, sharex=True, sharey=False, figsize=(12, 3)) i = 0 for i in range(4): if i < 3: ax[i].plot( self.losses["epoch"].values, self.losses[self.losses_list[i]].values ) ax[i].set_title(self.losses_list[i], fontweight="bold") else: ax[i].plot( self.losses["epoch"].values, self.losses[self.penalties_list].values ) ax[i].set_title("Penalties", fontweight="bold") sns.despine() plt.tight_layout() if filename: save_to_file(fig, filename) def plot_r2_metrics(self, epoch_min=0, filename=None): """ Parameters ---------- epoch_min : int (default: 0) Epoch from which to show metrics history plot. Done for readability. filename : str (default: None) Name of the file to save the plot. If None, will automatically generate name from prefix file. """ assert self.eval_metrics == True, 'The evaluation metrics were not computed' if filename is None: if self.fileprefix is None: filename = None else: filename = f"{self.fileprefix}_history_metrics.png" df = self.metrics.melt(id_vars=["epoch", "split"]) col_dict = dict( zip(["training", "test", "ood"], ["#377eb8", "#4daf4a", "#e41a1c"]) ) fig, axs = plt.subplots(2, 2, sharex=True, sharey=False, figsize=(7, 5)) ax = plt.gca() i = 0 for i1 in range(2): for i2 in range(2): sns.lineplot( data=df[ (df["variable"] == self.header[i]) & (df["epoch"] > epoch_min) ], x="epoch", y="value", palette=col_dict, hue="split", ax=axs[i1, i2], ) axs[i1, i2].set_title(self.header[i], fontweight="bold") i += 1 sns.despine() plt.tight_layout() if filename: save_to_file(fig, filename) def plot_disentanglement_metrics(self, epoch_min=0, filename=None): """ Parameters ---------- epoch_min : int (default: 0) Epoch from which to show metrics history plot. Done for readability. filename : str (default: None) Name of the file to save the plot. If None, will automatically generate name from prefix file. """ assert self.eval_metrics == True, 'The evaluation metrics were not computed' if filename is None: if self.fileprefix is None: filename = None else: filename = f"{self.fileprefix}_history_metrics.png" fig, axs = plt.subplots( 1, 1+len(self.covariate_names), sharex=True, sharey=False, figsize=(2 + 5*(len(self.covariate_names)), 3) ) ax = plt.gca() sns.lineplot( data=self.disent[self.disent["epoch"] > epoch_min], x="epoch", y="perturbation disentanglement", legend=False, ax=axs[0], ) axs[0].set_title("perturbation disent", fontweight="bold") for i, cov in enumerate(self.covariate_names): sns.lineplot( data=self.disent[self.disent['epoch'] > epoch_min], x="epoch", y=f"{cov} disentanglement", legend=False, ax=axs[1+i] ) axs[1+i].set_title(f"{cov} disent", fontweight="bold") fig.tight_layout() sns.despine()
CPA-main
cpa/plotting.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from cpa.api import API from cpa.plotting import CPAVisuals
CPA-main
cpa/__init__.py