Skip to content

Instantly share code, notes, and snippets.

View xmodar's full-sized avatar

Modar M. Alfadly xmodar

View GitHub Profile
from math import log
import torch
from torch import nn
class L0Sparse(nn.Module):
def __init__(self, layer, init_sparsity=0.5, heat=2 / 3, stretch=0.1):
assert all(0 < x < 1 for x in [init_sparsity, heat, stretch])
super().__init__()
self.layer = layer
import torch
def unravel_index(index, shape):
out = []
for dim in reversed(shape):
out.append(index % dim)
index = index // dim
return tuple(reversed(out))
@xmodar
xmodar / grid_search.py
Created December 4, 2019 08:55
Coarse-to-fine grid search
from argparse import Namespace
import torch
def grid_search(objective, *bounds, density=10, eps=1e-5, max_steps=None):
"""Perfrom coarse-to-fine grid search for the minimum objective.
>>> def f(x, y):
>>> x = x + 0.5
import torch
from torch import nn
from torch import functional as F
class Expression:
def __init__(self, out=None, **units):
self.out = out
self.terms = {}
self.coeffs = {}
@xmodar
xmodar / larc.py
Last active January 15, 2020 23:56
Layer-wise Adaptive Rate Control (LARC) in PyTorch. It is LARS with clipping support in addition to scaling.
class LARC:
"""Layer-wise Adaptive Rate Control.
LARC is LARS that supports clipping along with scaling:
https://arxiv.org/abs/1708.03888
This implementation is inspired by:
https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py
See also:
@xmodar
xmodar / pytorch_experiment.py
Last active March 1, 2020 15:04
Modular experiment class to train a PyTorch module. It can be easily inherited or used with mixins to extend its functionality. We us it to train VGG on Cifar10.
import json
import math
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import torch
import torchvision.transforms as T
from torch import nn
from torch.optim import lr_scheduler
@xmodar
xmodar / color_toning.py
Created March 16, 2020 22:52
A color-toning transform made to match TorchVision implementations. Inspired by https://www.pyimagesearch.com/2014/06/30/super-fast-color-transfer-images/
import numpy as np
from PIL import Image
from skimage.color import lab2rgb, rgb2lab
class RandomColorToning:
def __init__(self, scale_mean, scale_std, shift_mean, shift_std):
self.scale_mean = scale_mean
self.scale_std = scale_std
@xmodar
xmodar / autoencoder.py
Last active March 17, 2020 05:50
PyTorch fully-convolutional auto-encoder for any arbitrary image sizes (including rectangles). Can, also, be used for a DCGAN.
from torch import nn
class Generator(nn.Module):
def __init__(self, input_dim, image_shape, memory):
super().__init__()
self.memory = memory
self.input_dim = input_dim
self.image_shape = image_shape
@xmodar
xmodar / matrix_square_root.py
Last active October 25, 2020 00:05
Compute the square root of a positive definite matrix with differentiable operations in pytorch (supports batching).
"""Matrix square root: https://github.com/pytorch/pytorch/issues/25481"""
import torch
def psd_matrix_sqrt(matrix, num_iterations=20):
"""Compute the square root of a PSD matrix using Newton's method.
This implementation was adopted from code by @JonathanVacher.
https://gist.github.com/ModarTensai/7c4aeb3d75bf1e0ab99b24cf2b3b37a3
"""
from typing import Tuple, Optional, Union, List
import torch
import torch.nn as nn
__all__ = [
'dot', 'get_neighbors', 'gather_features', 'point_sparsity',
'weighted_sampling'
]