python_code
stringlengths
0
1.02M
repo_name
stringlengths
9
48
file_path
stringlengths
5
114
import logging from pathlib2 import Path from memcnn.utils.log import setup, SummaryWriter def test_setup(tmp_path): logfile = str(tmp_path / 'testlog.log') setup(use_stdout=True, filename=logfile, log_level=logging.DEBUG) def test_summary_writer(tmp_path): logfile = Path(tmp_path / 'scalars.json') assert not logfile.exists() writer = SummaryWriter(log_dir=str(tmp_path)) writer.add_scalar("test_value", 0.5, 1) writer.add_scalar("test_value", 2.5, 2) writer.add_scalar("test_value2", 123, 1) writer.flush() assert logfile.exists() writer = SummaryWriter(log_dir=str(tmp_path)) assert "test_value" in writer._summary assert "test_value2" in writer._summary assert len(writer._summary["test_value"]) == 2 writer.add_scalar("test_value", 123.4, 3) writer.close() writer = SummaryWriter(log_dir=str(tmp_path)) assert "test_value" in writer._summary assert "test_value2" in writer._summary assert len(writer._summary["test_value"]) == 3
memcnn-master
memcnn/utils/tests/test_log.py
import torch from memcnn.utils.loss import _assert_no_grad, CrossEntropyLossTF def test_assert_no_grad(): data = torch.ones(3, 3, 3) data.requires_grad = False _assert_no_grad(data) def test_crossentropy_tf(): batch_size = 5 shape = (batch_size, 2) loss = CrossEntropyLossTF() ypred = torch.ones(*shape) ypred.requires_grad = True y = torch.ones(batch_size, dtype=torch.int64) y.requires_grad = False w = torch.ones(*shape) w.requires_grad = False w2 = torch.zeros(*shape) w2.requires_grad = False out1 = loss(ypred, y) assert len(out1.shape) == 0 out2 = loss(ypred, y, w) assert len(out2.shape) == 0 out3 = loss(ypred, y, w2) assert out3 == 0 assert len(out3.shape) == 0
memcnn-master
memcnn/utils/tests/test_loss.py
# -*- coding: utf-8 -*- from functools import partial import numpy as np import torch import torch.nn as nn import warnings from memcnn.models.additive import AdditiveCoupling from memcnn.models.affine import AffineCoupling from memcnn.models.utils import pytorch_version_one_and_above warnings.filterwarnings(action='ignore', category=UserWarning) def signal_hook(grad_output, valid_states, state_index): # pragma: no cover state = valid_states[state_index] valid_states[state_index] = not state def backward_hook(grad_output, keep_input, compute_input_fn, compute_output_fn, input_tensor, output_tensor, valid_states, state_index): # pragma: no cover perform_action = valid_states[state_index] valid_states[state_index] = not perform_action if perform_action: # restore input if not keep_input: with torch.no_grad(): input_inverted = compute_input_fn(output_tensor) if pytorch_version_one_and_above: input_tensor.storage().resize_(int(np.prod(input_tensor.size()))) input_tensor.set_(input_inverted) else: input_tensor.set_(input_inverted) # compute gradients with torch.set_grad_enabled(True): temp_output = compute_output_fn(input_tensor) temp_output.backward(gradient=grad_output) class InvertibleModuleWrapper(nn.Module): def __init__(self, fn, keep_input=False, keep_input_inverse=False, disable=False): """ The InvertibleModuleWrapper which enables memory savings during training by exploiting the invertible properties of the wrapped module. Parameters ---------- fn : :obj:`torch.nn.Module` A torch.nn.Module which has a forward and an inverse function implemented with :math:`x == m.inverse(m.forward(x))` keep_input : :obj:`bool`, optional Set to retain the input information on forward, by default it can be discarded since it will be reconstructed upon the backward pass. keep_input_inverse : :obj:`bool`, optional Set to retain the input information on inverse, by default it can be discarded since it will be reconstructed upon the backward pass. disable : :obj:`bool`, optional This will disable the detached graph approach with the backward hook. Essentially this renders the function as `y = fn(x)` without any of the memory savings. Setting this to true will also ignore the keep_input and keep_input_inverse properties. Attributes ---------- keep_input : :obj:`bool`, optional Set to retain the input information on forward, by default it can be discarded since it will be reconstructed upon the backward pass. keep_input_inverse : :obj:`bool`, optional Set to retain the input information on inverse, by default it can be discarded since it will be reconstructed upon the backward pass. Raises ------ NotImplementedError If an unknown coupling or implementation is given. """ super(InvertibleModuleWrapper, self).__init__() self.disable = disable self.keep_input = keep_input self.keep_input_inverse = keep_input_inverse self._fn = fn self._valid_states = [] self._state_counter = 0 def forward(self, xin): """Forward operation :math:`R(x) = y` Parameters ---------- xin : :obj:`torch.Tensor` Input torch tensor. Returns ------- :obj:`torch.Tensor` Output torch tensor y. """ if not self.disable: x = xin.detach() # Makes a detached copy which shares the storage y = self._fn(x) input_tensor = xin output_tensor = y # clears the referenced storage data linked to the input tensor as it can be reversed on the backward pass if not self.keep_input: if not pytorch_version_one_and_above: # PyTorch 0.4 way to clear storage input_tensor.data.set_() else: # PyTorch 1.0+ way to clear storage input_tensor.storage().resize_(0) if self.training: self._valid_states.append(True) xin.register_hook(hook=partial(signal_hook, valid_states=self._valid_states, state_index=self._state_counter)) y.register_hook(hook=partial(backward_hook, keep_input=self.keep_input, compute_input_fn=self._fn.inverse, compute_output_fn=self._fn.forward, valid_states=self._valid_states, state_index=self._state_counter, input_tensor=input_tensor, output_tensor=output_tensor)) self._state_counter += 1 y.detach_() # Detaches y in-place (inbetween computations can now be discarded) y.requires_grad = self.training else: y = self._fn(xin) return y def inverse(self, yin): """Inverse operation :math:`R^{-1}(y) = x` Parameters ---------- yin : :obj:`torch.Tensor` Input torch tensor. Returns ------- :obj:`torch.Tensor` Output torch tensor x. """ if not self.disable: y = yin.detach() # Makes a detached copy which shares the storage x = self._fn.inverse(y) input_tensor = yin output_tensor = x # clears the referenced storage data linked to the input tensor as it can be reversed on the backward pass if not self.keep_input_inverse: if not pytorch_version_one_and_above: # PyTorch 0.4 way to clear storage input_tensor.data.set_() else: # PyTorch 1.0+ way to clear storage input_tensor.storage().resize_(0) if self.training: self._valid_states.append(True) yin.register_hook(hook=partial(signal_hook, valid_states=self._valid_states, state_index=self._state_counter)) x.register_hook(hook=partial(backward_hook, keep_input=self.keep_input_inverse, compute_input_fn=self._fn.forward, compute_output_fn=self._fn.inverse, valid_states=self._valid_states, state_index=self._state_counter, input_tensor=input_tensor, output_tensor=output_tensor)) self._state_counter += 1 x.detach_() # Detaches x in-place (inbetween computations can now be discarded) x.requires_grad = self.training else: x = self._fn.inverse(yin) return x class ReversibleBlock(InvertibleModuleWrapper): def __init__(self, Fm, Gm=None, coupling='additive', keep_input=False, keep_input_inverse=False, implementation_fwd=-1, implementation_bwd=-1, adapter=None): """The ReversibleBlock Warning ------- This class has been deprecated. Use the more flexible InvertibleModuleWrapper class. Note ---- The `implementation_fwd` and `implementation_bwd` parameters can be set to one of the following implementations: * -1 Naive implementation without reconstruction on the backward pass. * 0 Memory efficient implementation, compute gradients directly. * 1 Memory efficient implementation, similar to approach in Gomez et al. 2017. Parameters ---------- Fm : :obj:`torch.nn.Module` A torch.nn.Module encapsulating an arbitrary function Gm : :obj:`torch.nn.Module`, optional A torch.nn.Module encapsulating an arbitrary function (If not specified a deepcopy of Fm is used as a Module) coupling : :obj:`str`, optional Type of coupling ['additive', 'affine']. Default = 'additive' keep_input : :obj:`bool`, optional Set to retain the input information on forward, by default it can be discarded since it will be reconstructed upon the backward pass. keep_input_inverse : :obj:`bool`, optional Set to retain the input information on inverse, by default it can be discarded since it will be reconstructed upon the backward pass. implementation_fwd : :obj:`int`, optional Switch between different Operation implementations for forward training (Default = 1). If using the naive implementation (-1) then `keep_input` should be True. implementation_bwd : :obj:`int`, optional Switch between different Operation implementations for backward training (Default = 1). If using the naive implementation (-1) then `keep_input_inverse` should be True. adapter : :obj:`class`, optional Only relevant when using the 'affine' coupling. Should be a class of type :obj:`torch.nn.Module` that serves as an optional wrapper class A for Fm and Gm which must output s, t = A(x) with shape(s) = shape(t) = shape(x). s, t are respectively the scale and shift tensors for the affine coupling. Attributes ---------- keep_input : :obj:`bool`, optional Set to retain the input information on forward, by default it can be discarded since it will be reconstructed upon the backward pass. keep_input_inverse : :obj:`bool`, optional Set to retain the input information on inverse, by default it can be discarded since it will be reconstructed upon the backward pass. Raises ------ NotImplementedError If an unknown coupling or implementation is given. """ warnings.warn("This class has been deprecated. Use the more flexible InvertibleModuleWrapper class", DeprecationWarning) fn = create_coupling(Fm=Fm, Gm=Gm, coupling=coupling, implementation_fwd=implementation_fwd, implementation_bwd=implementation_bwd, adapter=adapter) super(ReversibleBlock, self).__init__(fn, keep_input=keep_input, keep_input_inverse=keep_input_inverse) def create_coupling(Fm, Gm=None, coupling='additive', implementation_fwd=-1, implementation_bwd=-1, adapter=None): if coupling == 'additive': fn = AdditiveCoupling(Fm, Gm, implementation_fwd=implementation_fwd, implementation_bwd=implementation_bwd) elif coupling == 'affine': fn = AffineCoupling(Fm, Gm, adapter=adapter, implementation_fwd=implementation_fwd, implementation_bwd=implementation_bwd) else: raise NotImplementedError('Unknown coupling method: %s' % coupling) return fn def is_invertible_module(module_in, test_input_shape, test_input_dtype=torch.float32, atol=1e-6): """Test if a :obj:`torch.nn.Module` is invertible Parameters ---------- module_in : :obj:`torch.nn.Module` A torch.nn.Module to test. test_input_shape : :obj:`tuple` Dimensions of test tensor object to perform the test with. test_input_dtype : :obj:`torch.dtype`, optional Data type of test tensor object to perform the test with. atol : :obj:`float`, optional Tolerance value used for comparing the outputs Returns ------- :obj:`bool` True if the input module is invertible, False otherwise. """ test_input = torch.rand(test_input_shape, dtype=test_input_dtype) if not hasattr(module_in, "inverse"): return False with torch.no_grad(): if not torch.allclose(module_in.inverse(module_in(test_input)), test_input, atol=atol): return False if not torch.allclose(module_in(module_in.inverse(test_input)), test_input, atol=atol): return False if test_input is module_in(test_input): return False if test_input is module_in.inverse(test_input): return False return True
memcnn-master
memcnn/models/revop.py
import torch import torch.nn as nn import copy import warnings from torch import set_grad_enabled warnings.filterwarnings(action='ignore', category=UserWarning) class AffineAdapterNaive(nn.Module): """ Naive Affine adapter Outputs exp(f(x)), f(x) given f(.) and x """ def __init__(self, module): super(AffineAdapterNaive, self).__init__() self.f = module def forward(self, x): t = self.f(x) s = torch.exp(t) return s, t class AffineAdapterSigmoid(nn.Module): """ Sigmoid based affine adapter Partitions the output h of f(x) = h into s and t by extracting every odd and even channel Outputs sigmoid(s), t """ def __init__(self, module): super(AffineAdapterSigmoid, self).__init__() self.f = module def forward(self, x): h = self.f(x) assert h.shape[1] % 2 == 0 # nosec scale = torch.sigmoid(h[:, 1::2, :] + 2.0) shift = h[:, 0::2, :] return scale, shift class AffineCoupling(nn.Module): def __init__(self, Fm, Gm=None, adapter=None, implementation_fwd=-1, implementation_bwd=-1): """ This computes the output :math:`y` on forward given input :math:`x` and arbitrary modules :math:`Fm` and :math:`Gm` according to: :math:`(x1, x2) = x` :math:`(log({s1}), t1) = Fm(x2)` :math:`s1 = exp(log({s1}))` :math:`y1 = s1 * x1 + t1` :math:`(log({s2}), t2) = Gm(y1)` :math:`s2 = exp(log({s2}))` :math:`y2 = s2 * x2 + t2` :math:`y = (y1, y2)` Parameters ---------- Fm : :obj:`torch.nn.Module` A torch.nn.Module encapsulating an arbitrary function Gm : :obj:`torch.nn.Module` A torch.nn.Module encapsulating an arbitrary function (If not specified a deepcopy of Gm is used as a Module) adapter : :obj:`torch.nn.Module` class An optional wrapper class A for Fm and Gm which must output s, t = A(x) with shape(s) = shape(t) = shape(x) s, t are respectively the scale and shift tensors for the affine coupling. implementation_fwd : :obj:`int` Switch between different Affine Operation implementations for forward pass. Default = -1 implementation_bwd : :obj:`int` Switch between different Affine Operation implementations for inverse pass. Default = -1 """ super(AffineCoupling, self).__init__() # mirror the passed module, without parameter sharing... if Gm is None: Gm = copy.deepcopy(Fm) # apply the adapter class if it is given self.Gm = adapter(Gm) if adapter is not None else Gm self.Fm = adapter(Fm) if adapter is not None else Fm self.implementation_fwd = implementation_fwd self.implementation_bwd = implementation_bwd if implementation_bwd != -1 or implementation_fwd != -1: warnings.warn("Other implementations than the default (-1) are now deprecated.", DeprecationWarning) def forward(self, x): args = [x, self.Fm, self.Gm] + [w for w in self.Fm.parameters()] + [w for w in self.Gm.parameters()] if self.implementation_fwd == 0: out = AffineBlockFunction.apply(*args) elif self.implementation_fwd == 1: out = AffineBlockFunction2.apply(*args) elif self.implementation_fwd == -1: x1, x2 = torch.chunk(x, 2, dim=1) x1, x2 = x1.contiguous(), x2.contiguous() fmr1, fmr2 = self.Fm.forward(x2) y1 = (x1 * fmr1) + fmr2 gmr1, gmr2 = self.Gm.forward(y1) y2 = (x2 * gmr1) + gmr2 out = torch.cat([y1, y2], dim=1) else: raise NotImplementedError("Selected implementation ({}) not implemented..." .format(self.implementation_fwd)) return out def inverse(self, y): args = [y, self.Fm, self.Gm] + [w for w in self.Fm.parameters()] + [w for w in self.Gm.parameters()] if self.implementation_bwd == 0: x = AffineBlockInverseFunction.apply(*args) elif self.implementation_bwd == 1: x = AffineBlockInverseFunction2.apply(*args) elif self.implementation_bwd == -1: y1, y2 = torch.chunk(y, 2, dim=1) y1, y2 = y1.contiguous(), y2.contiguous() gmr1, gmr2 = self.Gm.forward(y1) x2 = (y2 - gmr2) / gmr1 fmr1, fmr2 = self.Fm.forward(x2) x1 = (y1 - fmr2) / fmr1 x = torch.cat([x1, x2], dim=1) else: raise NotImplementedError("Inverse for selected implementation ({}) not implemented..." .format(self.implementation_bwd)) return x class AffineBlock(AffineCoupling): def __init__(self, Fm, Gm=None, implementation_fwd=1, implementation_bwd=1): warnings.warn("This class has been deprecated. Use the AffineCoupling class instead.", DeprecationWarning) super(AffineBlock, self).__init__(Fm=Fm, Gm=Gm, implementation_fwd=implementation_fwd, implementation_bwd=implementation_bwd) class AffineBlockFunction(torch.autograd.Function): @staticmethod def forward(ctx, xin, Fm, Gm, *weights): """Forward pass for the affine block computes: {x1, x2} = x {log_s1, t1} = Fm(x2) s1 = exp(log_s1) y1 = s1 * x1 + t1 {log_s2, t2} = Gm(y1) s2 = exp(log_s2) y2 = s2 * x2 + t2 output = {y1, y2} Parameters ---------- ctx : torch.autograd.function.RevNetFunctionBackward The backward pass context object x : TorchTensor Input tensor. Must have channels (2nd dimension) that can be partitioned in two equal partitions Fm : nn.Module Module to use for computation, must retain dimensions such that Fm(X)=Y, X.shape == Y.shape Gm : nn.Module Module to use for computation, must retain dimensions such that Gm(X)=Y, X.shape == Y.shape *weights : TorchTensor weights for Fm and Gm in that order {Fm_w1, ... Fm_wn, Gm_w1, ... Gm_wn} Note ---- All tensor/autograd variable input arguments and the output are TorchTensors for the scope of this function """ # check if possible to partition into two equally sized partitions assert xin.shape[1] % 2 == 0 # nosec # store partition size, Fm and Gm functions in context ctx.Fm = Fm ctx.Gm = Gm with torch.no_grad(): # partition in two equally sized set of channels x = xin.detach() x1, x2 = torch.chunk(x, 2, dim=1) x1, x2 = x1.contiguous(), x2.contiguous() # compute outputs x2var = x2 fmr1, fmr2 = Fm.forward(x2var) y1 = (x1 * fmr1) + fmr2 x1.set_() del x1 y1var = y1 gmr1, gmr2 = Gm.forward(y1var) y2 = (x2 * gmr1) + gmr2 x2.set_() del x2 output = torch.cat([y1, y2], dim=1).detach_() # save the (empty) input and (non-empty) output variables ctx.save_for_backward(xin, output) return output @staticmethod def backward(ctx, grad_output): # pragma: no cover # retrieve weight references Fm, Gm = ctx.Fm, ctx.Gm # retrieve input and output references xin, output = ctx.saved_tensors x = xin.detach() x1, x2 = torch.chunk(x.detach(), 2, dim=1) GWeights = [p for p in Gm.parameters()] # partition output gradient also on channels assert (grad_output.shape[1] % 2 == 0) # nosec with set_grad_enabled(True): # compute outputs building a sub-graph x1.requires_grad = True x2.requires_grad = True fmr1, fmr2 = Fm.forward(x2) y1 = x1 * fmr1 + fmr2 gmr1, gmr2 = Gm.forward(y1) y2 = x2 * gmr1 + gmr2 y = torch.cat([y1, y2], dim=1) # perform full backward pass on graph... dd = torch.autograd.grad(y, (x1, x2) + tuple(Gm.parameters()) + tuple(Fm.parameters()), grad_output) GWgrads = dd[2:2 + len(GWeights)] FWgrads = dd[2 + len(GWeights):] grad_input = torch.cat([dd[0], dd[1]], dim=1) return (grad_input, None, None) + FWgrads + GWgrads class AffineBlockInverseFunction(torch.autograd.Function): @staticmethod def forward(cty, yin, Fm, Gm, *weights): """Forward inverse pass for the affine block computes: {y1, y2} = y {log_s2, t2} = Gm(y1) s2 = exp(log_s2) x2 = (y2 - t2) / s2 {log_s1, t1} = Fm(x2) s1 = exp(log_s1) x1 = (y1 - t1) / s1 output = {x1, x2} Parameters ---------- cty : torch.autograd.function.RevNetInverseFunctionBackward The backward pass context object y : TorchTensor Input tensor. Must have channels (2nd dimension) that can be partitioned in two equal partitions Fm : nn.Module Module to use for computation, must retain dimensions such that Fm(X)=Y, X.shape == Y.shape Gm : nn.Module Module to use for computation, must retain dimensions such that Gm(X)=Y, X.shape == Y.shape *weights : TorchTensor weights for Fm and Gm in that order {Fm_w1, ... Fm_wn, Gm_w1, ... Gm_wn} Note ---- All tensor/autograd variable input arguments and the output are TorchTensors for the scope of this fuction """ # check if possible to partition into two equally sized partitions assert yin.shape[1] % 2 == 0 # nosec # store partition size, Fm and Gm functions in context cty.Fm = Fm cty.Gm = Gm with torch.no_grad(): # partition in two equally sized set of channels y = yin.detach() y1, y2 = torch.chunk(y, 2, dim=1) y1, y2 = y1.contiguous(), y2.contiguous() # compute outputs y1var = y1 gmr1, gmr2 = Gm.forward(y1var) x2 = (y2 - gmr2) / gmr1 y2.set_() del y2 x2var = x2 fmr1, fmr2 = Fm.forward(x2var) x1 = (y1 - fmr2) / fmr1 y1.set_() del y1 output = torch.cat([x1, x2], dim=1).detach_() # save input and output variables cty.save_for_backward(yin, output) return output @staticmethod def backward(cty, grad_output): # pragma: no cover # retrieve weight references Fm, Gm = cty.Fm, cty.Gm # retrieve input and output references yin, output = cty.saved_tensors y = yin.detach() y1, y2 = torch.chunk(y.detach(), 2, dim=1) FWeights = [p for p in Gm.parameters()] # partition output gradient also on channels assert grad_output.shape[1] % 2 == 0 # nosec with set_grad_enabled(True): # compute outputs building a sub-graph y2.requires_grad = True y1.requires_grad = True gmr1, gmr2 = Gm.forward(y1) # x2 = (y2 - gmr2) / gmr1 fmr1, fmr2 = Fm.forward(x2) x1 = (y1 - fmr2) / fmr1 x = torch.cat([x1, x2], dim=1) # perform full backward pass on graph... dd = torch.autograd.grad(x, (y2, y1) + tuple(Fm.parameters()) + tuple(Gm.parameters()), grad_output) FWgrads = dd[2:2 + len(FWeights)] GWgrads = dd[2 + len(FWeights):] grad_input = torch.cat([dd[0], dd[1]], dim=1) return (grad_input, None, None) + FWgrads + GWgrads class AffineBlockFunction2(torch.autograd.Function): @staticmethod def forward(ctx, xin, Fm, Gm, *weights): """Forward pass for the affine block computes: {x1, x2} = x {log_s1, t1} = Fm(x2) s1 = exp(log_s1) y1 = s1 * x1 + t1 {log_s2, t2} = Gm(y1) s2 = exp(log_s2) y2 = s2 * x2 + t2 output = {y1, y2} Parameters ---------- ctx : torch.autograd.function.RevNetFunctionBackward The backward pass context object x : TorchTensor Input tensor. Must have channels (2nd dimension) that can be partitioned in two equal partitions Fm : nn.Module Module to use for computation, must retain dimensions such that Fm(X)=Y, X.shape == Y.shape Gm : nn.Module Module to use for computation, must retain dimensions such that Gm(X)=Y, X.shape == Y.shape *weights : TorchTensor weights for Fm and Gm in that order {Fm_w1, ... Fm_wn, Gm_w1, ... Gm_wn} Note ---- All tensor/autograd variable input arguments and the output are TorchTensors for the scope of this fuction """ # check if possible to partition into two equally sized partitions assert xin.shape[1] % 2 == 0 # nosec # store partition size, Fm and Gm functions in context ctx.Fm = Fm ctx.Gm = Gm with torch.no_grad(): # partition in two equally sized set of channels x = xin.detach() x1, x2 = torch.chunk(x, 2, dim=1) x1, x2 = x1.contiguous(), x2.contiguous() # compute outputs x2var = x2 fmr1, fmr2 = Fm.forward(x2var) y1 = x1 * fmr1 + fmr2 x1.set_() del x1 y1var = y1 gmr1, gmr2 = Gm.forward(y1var) y2 = x2 * gmr1 + gmr2 x2.set_() del x2 output = torch.cat([y1, y2], dim=1).detach_() # save the input and output variables ctx.save_for_backward(xin, output) return output @staticmethod def backward(ctx, grad_output): # pragma: no cover Fm, Gm = ctx.Fm, ctx.Gm # are all variable objects now x, output = ctx.saved_tensors with set_grad_enabled(False): y1, y2 = torch.chunk(output, 2, dim=1) y1, y2 = y1.contiguous(), y2.contiguous() # partition output gradient also on channels assert (grad_output.shape[1] % 2 == 0) # nosec y1_grad, y2_grad = torch.chunk(grad_output, 2, dim=1) y1_grad, y2_grad = y1_grad.contiguous(), y2_grad.contiguous() # Recreate computation graphs for functions Gm and Fm with gradient collecting leaf nodes: # z1_stop, x2_stop, GW, FW # Also recompute inputs (x1, x2) from outputs (y1, y2) with set_grad_enabled(True): z1_stop = y1 z1_stop.requires_grad = True G_z11, G_z12 = Gm.forward(z1_stop) x2 = (y2 - G_z12) / G_z11 x2_stop = x2.detach() x2_stop.requires_grad = True F_x21, F_x22 = Fm.forward(x2_stop) x1 = (y1 - F_x22) / F_x21 x1_stop = x1.detach() x1_stop.requires_grad = True # compute outputs building a sub-graph z1 = x1_stop * F_x21 + F_x22 y2_ = x2_stop * G_z11 + G_z12 y1_ = z1 # calculate the final gradients for the weights and inputs dd = torch.autograd.grad(y2_, (z1_stop,) + tuple(Gm.parameters()), y2_grad) z1_grad = dd[0] + y1_grad GWgrads = dd[1:] dd = torch.autograd.grad(y1_, (x1_stop, x2_stop) + tuple(Fm.parameters()), z1_grad, retain_graph=False) FWgrads = dd[2:] x2_grad = dd[1] + y2_grad x1_grad = dd[0] grad_input = torch.cat([x1_grad, x2_grad], dim=1) y1_.detach_() y2_.detach_() del y1_, y2_ return (grad_input, None, None) + FWgrads + GWgrads class AffineBlockInverseFunction2(torch.autograd.Function): @staticmethod def forward(cty, yin, Fm, Gm, *weights): """Forward pass for the affine block computes: Parameters ---------- cty : torch.autograd.function.RevNetInverseFunctionBackward The backward pass context object y : TorchTensor Input tensor. Must have channels (2nd dimension) that can be partitioned in two equal partitions Fm : nn.Module Module to use for computation, must retain dimensions such that Fm(X)=Y, X.shape == Y.shape Gm : nn.Module Module to use for computation, must retain dimensions such that Gm(X)=Y, X.shape == Y.shape *weights : TorchTensor weights for Fm and Gm in that order {Fm_w1, ... Fm_wn, Gm_w1, ... Gm_wn} Note ---- All tensor/autograd variable input arguments and the output are TorchTensors for the scope of this fuction """ # check if possible to partition into two equally sized partitions assert yin.shape[1] % 2 == 0 # nosec # store partition size, Fm and Gm functions in context cty.Fm = Fm cty.Gm = Gm with torch.no_grad(): # partition in two equally sized set of channels y = yin.detach() y1, y2 = torch.chunk(y, 2, dim=1) y1, y2 = y1.contiguous(), y2.contiguous() # compute outputs y1var = y1 gmr1, gmr2 = Gm.forward(y1var) x2 = (y2 - gmr2) / gmr1 y2.set_() del y2 x2var = x2 fmr1, fmr2 = Fm.forward(x2var) x1 = (y1 - fmr2) / fmr1 y1.set_() del y1 output = torch.cat([x1, x2], dim=1).detach_() # save the input and output variables cty.save_for_backward(yin, output) return output @staticmethod def backward(cty, grad_output): # pragma: no cover Fm, Gm = cty.Fm, cty.Gm # are all variable objects now y, output = cty.saved_tensors with set_grad_enabled(False): x1, x2 = torch.chunk(output, 2, dim=1) x1, x2 = x1.contiguous(), x2.contiguous() # partition output gradient also on channels assert (grad_output.shape[1] % 2 == 0) # nosec x1_grad, x2_grad = torch.chunk(grad_output, 2, dim=1) x1_grad, x2_grad = x1_grad.contiguous(), x2_grad.contiguous() # Recreate computation graphs for functions Gm and Fm with gradient collecting leaf nodes: # z1_stop, y1_stop, GW, FW # Also recompute inputs (y1, y2) from outputs (x1, x2) with set_grad_enabled(True): z1_stop = x2 z1_stop.requires_grad = True F_z11, F_z12 = Fm.forward(z1_stop) y1 = x1 * F_z11 + F_z12 y1_stop = y1.detach() y1_stop.requires_grad = True G_y11, G_y12 = Gm.forward(y1_stop) y2 = x2 * G_y11 + G_y12 y2_stop = y2.detach() y2_stop.requires_grad = True # compute outputs building a sub-graph z1 = (y2_stop - G_y12) / G_y11 x1_ = (y1_stop - F_z12) / F_z11 x2_ = z1 # calculate the final gradients for the weights and inputs dd = torch.autograd.grad(x1_, (z1_stop,) + tuple(Fm.parameters()), x1_grad) z1_grad = dd[0] + x2_grad FWgrads = dd[1:] dd = torch.autograd.grad(x2_, (y2_stop, y1_stop) + tuple(Gm.parameters()), z1_grad, retain_graph=False) GWgrads = dd[2:] y1_grad = dd[1] + x1_grad y2_grad = dd[0] grad_input = torch.cat([y1_grad, y2_grad], dim=1) return (grad_input, None, None) + FWgrads + GWgrads
memcnn-master
memcnn/models/affine.py
memcnn-master
memcnn/models/__init__.py
"""ResNet/RevNet implementation used for The Reversible Residual Network Implemented in PyTorch instead of TensorFlow. @inproceedings{gomez17revnet, author = {Aidan N. Gomez and Mengye Ren and Raquel Urtasun and Roger B. Grosse}, title = {The Reversible Residual Network: Backpropagation without Storing Activations} booktitle = {NIPS}, year = {2017}, } Github: https://github.com/renmengye/revnet-public Author: Sil van de Leemput """ import torch.nn as nn import math from memcnn.models.revop import InvertibleModuleWrapper, create_coupling __all__ = ['ResNet', 'BasicBlock', 'Bottleneck', 'RevBasicBlock', 'RevBottleneck', 'BasicBlockSub', 'BottleneckSub', 'conv3x3', 'batch_norm'] def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) def batch_norm(x): """match Tensorflow batch norm settings""" return nn.BatchNorm2d(x, momentum=0.99, eps=0.001) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, noactivation=False): super(BasicBlock, self).__init__() self.basicblock_sub = BasicBlockSub(inplanes, planes, stride, noactivation) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.basicblock_sub(x) if self.downsample is not None: residual = self.downsample(x) out += residual return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, noactivation=False): super(Bottleneck, self).__init__() self.bottleneck_sub = BottleneckSub(inplanes, planes, stride, noactivation) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.bottleneck_sub(x) if self.downsample is not None: residual = self.downsample(x) out += residual return out class RevBasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, noactivation=False): super(RevBasicBlock, self).__init__() if downsample is None and stride == 1: gm = BasicBlockSub(inplanes // 2, planes // 2, stride, noactivation) fm = BasicBlockSub(inplanes // 2, planes // 2, stride, noactivation) coupling = create_coupling(Fm=fm, Gm=gm, coupling='additive') self.revblock = InvertibleModuleWrapper(fn=coupling, keep_input=False) else: self.basicblock_sub = BasicBlockSub(inplanes, planes, stride, noactivation) self.downsample = downsample self.stride = stride def forward(self, x): if self.downsample is not None: out = self.basicblock_sub(x) residual = self.downsample(x) out += residual else: out = self.revblock(x) return out class RevBottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, noactivation=False): super(RevBottleneck, self).__init__() if downsample is None and stride == 1: gm = BottleneckSub(inplanes // 2, planes // 2, stride, noactivation) fm = BottleneckSub(inplanes // 2, planes // 2, stride, noactivation) coupling = create_coupling(Fm=fm, Gm=gm, coupling='additive') self.revblock = InvertibleModuleWrapper(fn=coupling, keep_input=False) else: self.bottleneck_sub = BottleneckSub(inplanes, planes, stride, noactivation) self.downsample = downsample self.stride = stride def forward(self, x): if self.downsample is not None: out = self.bottleneck_sub(x) residual = self.downsample(x) out += residual else: out = self.revblock(x) return out class BottleneckSub(nn.Module): def __init__(self, inplanes, planes, stride=1, noactivation=False): super(BottleneckSub, self).__init__() self.noactivation = noactivation if not self.noactivation: self.bn1 = batch_norm(inplanes) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn2 = batch_norm(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn3 = batch_norm(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): if not self.noactivation: x = self.bn1(x) x = self.relu(x) x = self.conv1(x) x = self.bn2(x) x = self.relu(x) x = self.conv2(x) x = self.bn3(x) x = self.relu(x) x = self.conv3(x) return x class BasicBlockSub(nn.Module): def __init__(self, inplanes, planes, stride=1, noactivation=False): super(BasicBlockSub, self).__init__() self.noactivation = noactivation if not self.noactivation: self.bn1 = batch_norm(inplanes) self.conv1 = conv3x3(inplanes, planes, stride) self.bn2 = batch_norm(planes) self.conv2 = conv3x3(planes, planes) self.relu = nn.ReLU(inplace=True) def forward(self, x): if not self.noactivation: x = self.bn1(x) x = self.relu(x) x = self.conv1(x) x = self.bn2(x) x = self.relu(x) x = self.conv2(x) return x class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, channels_per_layer=None, strides=None, init_max_pool=False, init_kernel_size=7, batch_norm_fix=True, implementation=0): if channels_per_layer is None: channels_per_layer = [2 ** (i + 6) for i in range(len(layers))] channels_per_layer = [channels_per_layer[0]] + channels_per_layer if strides is None: strides = [2] * len(channels_per_layer) self.batch_norm_fix = batch_norm_fix self.channels_per_layer = channels_per_layer self.strides = strides self.init_max_pool = init_max_pool self.implementation = implementation assert(len(self.channels_per_layer) == len(layers) + 1) # nosec self.inplanes = channels_per_layer[0] # 64 by default super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=init_kernel_size, stride=strides[0], padding=(init_kernel_size - 1) // 2, bias=False) self.bn1 = batch_norm(self.inplanes) self.relu = nn.ReLU(inplace=False) if self.init_max_pool: self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, channels_per_layer[1], layers[0], stride=strides[1], noactivation=True) self.layer2 = self._make_layer(block, channels_per_layer[2], layers[1], stride=strides[2]) self.layer3 = self._make_layer(block, channels_per_layer[3], layers[2], stride=strides[3]) self.has_4_layers = len(layers) >= 4 if self.has_4_layers: self.layer4 = self._make_layer(block, channels_per_layer[4], layers[3], stride=strides[4]) self.bn_final = batch_norm(self.inplanes) # channels_per_layer[-1]) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(channels_per_layer[-1] * block.expansion, num_classes) self.configure() self.init_weights() def init_weights(self): """Initialization using He initialization""" for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.reset_parameters() def configure(self): """Initialization specific configuration settings""" for m in self.modules(): if isinstance(m, InvertibleModuleWrapper): m.implementation = self.implementation elif isinstance(m, nn.BatchNorm2d): if self.batch_norm_fix: m.momentum = 0.99 m.eps = 0.001 else: m.momentum = 0.1 m.eps = 1e-05 def _make_layer(self, block, planes, blocks, stride=1, noactivation=False): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), batch_norm(planes * block.expansion), ) layers = [block(self.inplanes, planes, stride, downsample, noactivation)] self.inplanes = planes * block.expansion for _ in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) if self.init_max_pool: x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) if self.has_4_layers: x = self.layer4(x) x = self.bn_final(x) x = self.relu(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x
memcnn-master
memcnn/models/resnet.py
import torch # for backwards compatibility use_context_mans = True try: pytorch_version_one_and_above = int(torch.__version__[0]) > 0 except TypeError: pytorch_version_one_and_above = True
memcnn-master
memcnn/models/utils.py
import warnings import torch import torch.nn as nn import copy from torch import set_grad_enabled class AdditiveCoupling(nn.Module): def __init__(self, Fm, Gm=None, implementation_fwd=-1, implementation_bwd=-1): """ This computes the output :math:`y` on forward given input :math:`x` and arbitrary modules :math:`Fm` and :math:`Gm` according to: :math:`(x1, x2) = x` :math:`y1 = x1 + Fm(x2)` :math:`y2 = x2 + Gm(y1)` :math:`y = (y1, y2)` Parameters ---------- Fm : :obj:`torch.nn.Module` A torch.nn.Module encapsulating an arbitrary function Gm : :obj:`torch.nn.Module` A torch.nn.Module encapsulating an arbitrary function (If not specified a deepcopy of Fm is used as a Module) implementation_fwd : :obj:`int` Switch between different Additive Operation implementations for forward pass. Default = -1 implementation_bwd : :obj:`int` Switch between different Additive Operation implementations for inverse pass. Default = -1 """ super(AdditiveCoupling, self).__init__() # mirror the passed module, without parameter sharing... if Gm is None: Gm = copy.deepcopy(Fm) self.Gm = Gm self.Fm = Fm self.implementation_fwd = implementation_fwd self.implementation_bwd = implementation_bwd if implementation_bwd != -1 or implementation_fwd != -1: warnings.warn("Other implementations than the default (-1) are now deprecated.", DeprecationWarning) def forward(self, x): args = [x, self.Fm, self.Gm] + [w for w in self.Fm.parameters()] + [w for w in self.Gm.parameters()] if self.implementation_fwd == 0: out = AdditiveBlockFunction.apply(*args) elif self.implementation_fwd == 1: out = AdditiveBlockFunction2.apply(*args) elif self.implementation_fwd == -1: x1, x2 = torch.chunk(x, 2, dim=1) x1, x2 = x1.contiguous(), x2.contiguous() fmd = self.Fm.forward(x2) y1 = x1 + fmd gmd = self.Gm.forward(y1) y2 = x2 + gmd out = torch.cat([y1, y2], dim=1) else: raise NotImplementedError("Selected implementation ({}) not implemented..." .format(self.implementation_fwd)) return out def inverse(self, y): args = [y, self.Fm, self.Gm] + [w for w in self.Fm.parameters()] + [w for w in self.Gm.parameters()] if self.implementation_bwd == 0: x = AdditiveBlockInverseFunction.apply(*args) elif self.implementation_bwd == 1: x = AdditiveBlockInverseFunction2.apply(*args) elif self.implementation_bwd == -1: y1, y2 = torch.chunk(y, 2, dim=1) y1, y2 = y1.contiguous(), y2.contiguous() gmd = self.Gm.forward(y1) x2 = y2 - gmd fmd = self.Fm.forward(x2) x1 = y1 - fmd x = torch.cat([x1, x2], dim=1) else: raise NotImplementedError("Inverse for selected implementation ({}) not implemented..." .format(self.implementation_bwd)) return x class AdditiveBlock(AdditiveCoupling): def __init__(self, Fm, Gm=None, implementation_fwd=1, implementation_bwd=1): warnings.warn("This class has been deprecated. Use the AdditiveCoupling class instead.", DeprecationWarning) super(AdditiveBlock, self).__init__(Fm=Fm, Gm=Gm, implementation_fwd=implementation_fwd, implementation_bwd=implementation_bwd) class AdditiveBlockFunction(torch.autograd.Function): @staticmethod def forward(ctx, xin, Fm, Gm, *weights): """Forward pass computes: {x1, x2} = x y1 = x1 + Fm(x2) y2 = x2 + Gm(y1) output = {y1, y2} Parameters ---------- ctx : torch.autograd.Function The backward pass context object x : TorchTensor Input tensor. Must have channels (2nd dimension) that can be partitioned in two equal partitions Fm : nn.Module Module to use for computation, must retain dimensions such that Fm(X)=Y, X.shape == Y.shape Gm : nn.Module Module to use for computation, must retain dimensions such that Gm(X)=Y, X.shape == Y.shape *weights : TorchTensor weights for Fm and Gm in that order {Fm_w1, ... Fm_wn, Gm_w1, ... Gm_wn} Note ---- All tensor/autograd variable input arguments and the output are TorchTensors for the scope of this function """ # check if possible to partition into two equally sized partitions assert(xin.shape[1] % 2 == 0) # nosec # store partition size, Fm and Gm functions in context ctx.Fm = Fm ctx.Gm = Gm with torch.no_grad(): x = xin.detach() # partition in two equally sized set of channels x1, x2 = torch.chunk(x, 2, dim=1) x1, x2 = x1.contiguous(), x2.contiguous() # compute outputs fmr = Fm.forward(x2) y1 = x1 + fmr x1.set_() del x1 gmr = Gm.forward(y1) y2 = x2 + gmr x2.set_() del x2 output = torch.cat([y1, y2], dim=1) ctx.save_for_backward(xin, output) return output @staticmethod def backward(ctx, grad_output): # pragma: no cover # retrieve weight references Fm, Gm = ctx.Fm, ctx.Gm # retrieve input and output references xin, output = ctx.saved_tensors x = xin.detach() x1, x2 = torch.chunk(x, 2, dim=1) GWeights = [p for p in Gm.parameters()] # partition output gradient also on channels assert grad_output.shape[1] % 2 == 0 # nosec with set_grad_enabled(True): # compute outputs building a sub-graph x1.requires_grad_() x2.requires_grad_() y1 = x1 + Fm.forward(x2) y2 = x2 + Gm.forward(y1) y = torch.cat([y1, y2], dim=1) # perform full backward pass on graph... dd = torch.autograd.grad(y, (x1, x2 ) + tuple(Gm.parameters()) + tuple(Fm.parameters()), grad_output) GWgrads = dd[2:2+len(GWeights)] FWgrads = dd[2+len(GWeights):] grad_input = torch.cat([dd[0], dd[1]], dim=1) return (grad_input, None, None) + FWgrads + GWgrads class AdditiveBlockInverseFunction(torch.autograd.Function): @staticmethod def forward(cty, y, Fm, Gm, *weights): """Forward pass computes: {y1, y2} = y x2 = y2 - Gm(y1) x1 = y1 - Fm(x2) output = {x1, x2} Parameters ---------- cty : torch.autograd.Function The backward pass context object y : TorchTensor Input tensor. Must have channels (2nd dimension) that can be partitioned in two equal partitions Fm : nn.Module Module to use for computation, must retain dimensions such that Fm(X)=Y, X.shape == Y.shape Gm : nn.Module Module to use for computation, must retain dimensions such that Gm(X)=Y, X.shape == Y.shape *weights : TorchTensor weights for Fm and Gm in that order {Fm_w1, ... Fm_wn, Gm_w1, ... Gm_wn} Note ---- All tensor/autograd variable input arguments and the output are TorchTensors for the scope of this fuction """ # check if possible to partition into two equally sized partitions assert(y.shape[1] % 2 == 0) # nosec # store partition size, Fm and Gm functions in context cty.Fm = Fm cty.Gm = Gm with torch.no_grad(): # partition in two equally sized set of channels y1, y2 = torch.chunk(y, 2, dim=1) y1, y2 = y1.contiguous(), y2.contiguous() # compute outputs gmr = Gm.forward(y1) x2 = y2 - gmr y2.set_() del y2 fmr = Fm.forward(x2) x1 = y1 - fmr y1.set_() del y1 output = torch.cat([x1, x2], dim=1) x1.set_() x2.set_() del x1, x2 # save the (empty) input and (non-empty) output variables cty.save_for_backward(y.data, output) return output @staticmethod def backward(cty, grad_output): # pragma: no cover # retrieve weight references Fm, Gm = cty.Fm, cty.Gm # retrieve input and output references yin, output = cty.saved_tensors y = yin.detach() y1, y2 = torch.chunk(y, 2, dim=1) FWeights = [p for p in Fm.parameters()] # partition output gradient also on channels assert grad_output.shape[1] % 2 == 0 # nosec with set_grad_enabled(True): # compute outputs building a sub-graph y2.requires_grad = True y1.requires_grad = True x2 = y2 - Gm.forward(y1) x1 = y1 - Fm.forward(x2) x = torch.cat([x1, x2], dim=1) # perform full backward pass on graph... dd = torch.autograd.grad(x, (y2, y1 ) + tuple(Fm.parameters()) + tuple(Gm.parameters()), grad_output) FWgrads = dd[2:2+len(FWeights)] GWgrads = dd[2+len(FWeights):] grad_input = torch.cat([dd[0], dd[1]], dim=1) return (grad_input, None, None) + FWgrads + GWgrads class AdditiveBlockFunction2(torch.autograd.Function): @staticmethod def forward(ctx, xin, Fm, Gm, *weights): """Forward pass computes: {x1, x2} = x y1 = x1 + Fm(x2) y2 = x2 + Gm(y1) output = {y1, y2} Parameters ---------- ctx : torch.autograd.Function The backward pass context object x : TorchTensor Input tensor. Must have channels (2nd dimension) that can be partitioned in two equal partitions Fm : nn.Module Module to use for computation, must retain dimensions such that Fm(X)=Y, X.shape == Y.shape Gm : nn.Module Module to use for computation, must retain dimensions such that Gm(X)=Y, X.shape == Y.shape *weights : TorchTensor weights for Fm and Gm in that order {Fm_w1, ... Fm_wn, Gm_w1, ... Gm_wn} Note ---- All tensor/autograd variable input arguments and the output are TorchTensors for the scope of this fuction """ # check if possible to partition into two equally sized partitions assert xin.shape[1] % 2 == 0 # nosec # store partition size, Fm and Gm functions in context ctx.Fm = Fm ctx.Gm = Gm with torch.no_grad(): # partition in two equally sized set of channels x = xin.detach() x1, x2 = torch.chunk(x, 2, dim=1) x1, x2 = x1.contiguous(), x2.contiguous() # compute outputs fmr = Fm.forward(x2) y1 = x1 + fmr x1.set_() del x1 gmr = Gm.forward(y1) y2 = x2 + gmr x2.set_() del x2 output = torch.cat([y1, y2], dim=1).detach_() # save the input and output variables ctx.save_for_backward(x, output) return output @staticmethod def backward(ctx, grad_output): # pragma: no cover Fm, Gm = ctx.Fm, ctx.Gm # are all variable objects now x, output = ctx.saved_tensors with torch.no_grad(): y1, y2 = torch.chunk(output, 2, dim=1) y1, y2 = y1.contiguous(), y2.contiguous() # partition output gradient also on channels assert(grad_output.shape[1] % 2 == 0) # nosec y1_grad, y2_grad = torch.chunk(grad_output, 2, dim=1) y1_grad, y2_grad = y1_grad.contiguous(), y2_grad.contiguous() # Recreate computation graphs for functions Gm and Fm with gradient collecting leaf nodes: # z1_stop, x2_stop, GW, FW # Also recompute inputs (x1, x2) from outputs (y1, y2) with set_grad_enabled(True): z1_stop = y1.detach() z1_stop.requires_grad = True G_z1 = Gm.forward(z1_stop) x2 = y2 - G_z1 x2_stop = x2.detach() x2_stop.requires_grad = True F_x2 = Fm.forward(x2_stop) x1 = y1 - F_x2 x1_stop = x1.detach() x1_stop.requires_grad = True # compute outputs building a sub-graph y1 = x1_stop + F_x2 y2 = x2_stop + G_z1 # calculate the final gradients for the weights and inputs dd = torch.autograd.grad(y2, (z1_stop,) + tuple(Gm.parameters()), y2_grad, retain_graph=False) z1_grad = dd[0] + y1_grad GWgrads = dd[1:] dd = torch.autograd.grad(y1, (x1_stop, x2_stop) + tuple(Fm.parameters()), z1_grad, retain_graph=False) FWgrads = dd[2:] x2_grad = dd[1] + y2_grad x1_grad = dd[0] grad_input = torch.cat([x1_grad, x2_grad], dim=1) return (grad_input, None, None) + FWgrads + GWgrads class AdditiveBlockInverseFunction2(torch.autograd.Function): @staticmethod def forward(cty, y, Fm, Gm, *weights): """Forward pass computes: {y1, y2} = y x2 = y2 - Gm(y1) x1 = y1 - Fm(x2) output = {x1, x2} Parameters ---------- cty : torch.autograd.Function The backward pass context object y : TorchTensor Input tensor. Must have channels (2nd dimension) that can be partitioned in two equal partitions Fm : nn.Module Module to use for computation, must retain dimensions such that Fm(X)=Y, X.shape == Y.shape Gm : nn.Module Module to use for computation, must retain dimensions such that Gm(X)=Y, X.shape == Y.shape *weights : TorchTensor weights for Fm and Gm in that order {Fm_w1, ... Fm_wn, Gm_w1, ... Gm_wn} Note ---- All tensor/autograd variable input arguments and the output are TorchTensors for the scope of this fuction """ # check if possible to partition into two equally sized partitions assert(y.shape[1] % 2 == 0) # nosec # store partition size, Fm and Gm functions in context cty.Fm = Fm cty.Gm = Gm with torch.no_grad(): # partition in two equally sized set of channels y1, y2 = torch.chunk(y, 2, dim=1) y1, y2 = y1.contiguous(), y2.contiguous() # compute outputs gmr = Gm.forward(y1) x2 = y2 - gmr y2.set_() del y2 fmr = Fm.forward(x2) x1 = y1 - fmr y1.set_() del y1 output = torch.cat([x1, x2], dim=1).detach_() # save the input and output variables cty.save_for_backward(y, output) return output @staticmethod def backward(cty, grad_output): # pragma: no cover Fm, Gm = cty.Fm, cty.Gm # are all variable objects now y, output = cty.saved_tensors with torch.no_grad(): x1, x2 = torch.chunk(output, 2, dim=1) x1, x2 = x1.contiguous(), x2.contiguous() # partition output gradient also on channels assert(grad_output.shape[1] % 2 == 0) # nosec x1_grad, x2_grad = torch.chunk(grad_output, 2, dim=1) x1_grad, x2_grad = x1_grad.contiguous(), x2_grad.contiguous() # Recreate computation graphs for functions Gm and Fm with gradient collecting leaf nodes: # z1_stop, y1_stop, GW, FW # Also recompute inputs (y1, y2) from outputs (x1, x2) with set_grad_enabled(True): z1_stop = x2.detach() z1_stop.requires_grad = True F_z1 = Fm.forward(z1_stop) y1 = x1 + F_z1 y1_stop = y1.detach() y1_stop.requires_grad = True G_y1 = Gm.forward(y1_stop) y2 = x2 + G_y1 y2_stop = y2.detach() y2_stop.requires_grad = True # compute outputs building a sub-graph z1 = y2_stop - G_y1 x1 = y1_stop - F_z1 x2 = z1 # calculate the final gradients for the weights and inputs dd = torch.autograd.grad(x1, (z1_stop,) + tuple(Fm.parameters()), x1_grad) z1_grad = dd[0] + x2_grad FWgrads = dd[1:] dd = torch.autograd.grad(x2, (y2_stop, y1_stop) + tuple(Gm.parameters()), z1_grad, retain_graph=False) GWgrads = dd[2:] y1_grad = dd[1] + x1_grad y2_grad = dd[0] grad_input = torch.cat([y1_grad, y2_grad], dim=1) return (grad_input, None, None) + FWgrads + GWgrads
memcnn-master
memcnn/models/additive.py
import pytest import torch from memcnn.models.resnet import ResNet, BasicBlock, Bottleneck, RevBasicBlock, RevBottleneck @pytest.mark.parametrize('block,batch_norm_fix', [(BasicBlock, True), (Bottleneck, False), (RevBasicBlock, False), (RevBottleneck, True)]) def test_resnet(block, batch_norm_fix): model = ResNet(block, [2, 2, 2, 2], num_classes=2, channels_per_layer=None, init_max_pool=True, batch_norm_fix=batch_norm_fix, strides=None) model.eval() with torch.no_grad(): x = torch.ones(2, 3, 32, 32) model.forward(x)
memcnn-master
memcnn/models/tests/test_resnet.py
memcnn-master
memcnn/models/tests/__init__.py
import pytest import gc import numpy as np import math from collections import defaultdict import torch import torch.nn from memcnn.models.tests.test_revop import SubModuleStack, SubModule def readable_size(num_bytes): return '{:.2f}'.format(float(num_bytes) / float(1024 ** 2)) LEN = 79 # some pytorch low-level memory management constant # the minimal allocate memory size (Byte) PYTORCH_MIN_ALLOCATE = 2 ** 9 # the minimal cache memory size (Byte) PYTORCH_MIN_CACHE = 2 ** 20 class MemReporter(object): """A memory reporter that collects tensors and memory usages Parameters: - model: an extra nn.Module can be passed to infer the name of Tensors """ def __init__(self, model=None): self.tensor_name = defaultdict(list) self.device_mapping = defaultdict(list) self.device_tensor_stat = {} # to numbering the unknown tensors self.name_idx = 0 if model is not None: assert isinstance(model, torch.nn.Module) # for model with tying weight, multiple parameters may share # the same underlying tensor for name, param in model.named_parameters(): self.tensor_name[param].append(name) for param, name in self.tensor_name.items(): self.tensor_name[param] = '+'.join(name) def _get_tensor_name(self, tensor): if tensor in self.tensor_name: name = self.tensor_name[tensor] # use numbering if no name can be inferred else: name = type(tensor).__name__ + str(self.name_idx) self.tensor_name[tensor] = name self.name_idx += 1 return name def collect_tensor(self): """Collect all tensor objects tracked by python NOTICE: - the buffers for backward which is implemented in C++ are not tracked by python's reference counting. - the gradients(.grad) of Parameters is not collected, and I don't know why. """ # FIXME: make the grad tensor collected by gc objects = gc.get_objects() tensors = [obj for obj in objects if isinstance(obj, torch.Tensor)] for t in tensors: self.device_mapping[str(t.device)].append(t) def get_stats(self): """Get the memory stat of tensors and then release them As a memory profiler, we cannot hold the reference to any tensors, which causes possibly inaccurate memory usage stats, so we delete the tensors after getting required stats""" visited_data = {} self.device_tensor_stat.clear() def get_tensor_stat(tensor): """Get the stat of a single tensor Returns: - stat: a tuple containing (tensor_name, tensor_size, tensor_numel, tensor_memory) """ assert isinstance(tensor, torch.Tensor) name = self._get_tensor_name(tensor) numel = tensor.numel() element_size = tensor.element_size() fact_numel = tensor.storage().size() fact_memory_size = fact_numel * element_size # since pytorch allocate at least 512 Bytes for any tensor, round # up to a multiple of 512 memory_size = math.ceil(fact_memory_size / PYTORCH_MIN_ALLOCATE) * PYTORCH_MIN_ALLOCATE # tensor.storage should be the actual object related to memory # allocation data_ptr = tensor.storage().data_ptr() if data_ptr in visited_data: name = '{}(->{})'.format( name, visited_data[data_ptr], ) # don't count the memory for reusing same underlying storage memory_size = 0 else: visited_data[data_ptr] = name size = tuple(tensor.size()) # torch scalar has empty size if not size: size = (1,) return (name, size, numel, memory_size) for device, tensors in self.device_mapping.items(): tensor_stats = [] for tensor in tensors: if tensor.numel() == 0: continue stat = get_tensor_stat(tensor) # (name, shape, numel, memory_size) tensor_stats.append(stat) if isinstance(tensor, torch.nn.Parameter): if tensor.grad is not None: # manually specify the name of gradient tensor self.tensor_name[tensor.grad] = '{}.grad'.format( self._get_tensor_name(tensor) ) stat = get_tensor_stat(tensor.grad) tensor_stats.append(stat) self.device_tensor_stat[device] = tensor_stats self.device_mapping.clear() def print_stats(self, verbose=False): # header show_reuse = verbose template_format = '{:<40s}{:>20s}{:>10s}' print(template_format.format('Element type', 'Size', 'Used MEM')) for device, tensor_stats in self.device_tensor_stat.items(): print('-' * LEN) print('Storage on {}'.format(device)) total_mem = 0 total_numel = 0 for stat in tensor_stats: name, size, numel, mem = stat if not show_reuse: name = name.split('(')[0] print(template_format.format( str(name), str(size), readable_size(mem), )) total_mem += mem total_numel += numel print('-'*LEN) print('Total Tensors: {} \tUsed Memory: {}'.format( total_numel, readable_size(total_mem), )) if device != torch.device('cpu'): # with torch.cuda.device(device): NOTE not supported in memory_allocated = torch.cuda.memory_allocated() print('The allocated memory on {}: {}'.format( device, readable_size(memory_allocated), )) if memory_allocated != total_mem: print('Memory differs due to the matrix alignment or' ' invisible gradient buffer tensors') print('-'*LEN) def collect_stats(self): self.collect_tensor() self.get_stats() for _, tensor_stats in self.device_tensor_stat.items(): total_mem = 0 for stat in tensor_stats: total_mem += stat[3] return total_mem def report(self, verbose=False): """Interface for end-users to directly print the memory usage args: - verbose: flag to show tensor.storage reuse information """ self.collect_tensor() self.get_stats() self.print_stats(verbose) @pytest.mark.parametrize('coupling', ['additive', 'affine']) @pytest.mark.parametrize('keep_input', [True, False]) @pytest.mark.parametrize('device', ['cpu', 'cuda']) def test_memory_saving_invertible_model_wrapper(device, coupling, keep_input): """Test memory saving of the invertible model wrapper * tests fitting a large number of images by creating a deep network requiring large intermediate feature maps for training * keep_input = False should use less memory than keep_input = True on both GPU and CPU RAM * input size in bytes: np.prod((2, 10, 10, 10)) * 4 / 1024.0 = 7.8125 kB for a depth=5 this yields 7.8125 * 5 = 39.0625 kB Notes ----- * CPU RAM estimates uses the MemReporter from https://github.com/Stonesjtu/pytorch_memlab which tries to estimate torch CPU RAM usage by collecting torch.Tensors from the gc. This reliably finds the difference between keep_input=(True|False), however it greatly underestimates the total memory consumptions w.r.t. the GPU RAM estimates using PyTorch cuda module. It appears to be missing some tensors. FIXME CPU Ram estimates - Sil """ if device == 'cuda' and not torch.cuda.is_available(): pytest.skip('This test requires a GPU to be available') mem_reporter = MemReporter() gc.disable() gc.collect() with torch.set_grad_enabled(True): dims = [2, 10, 10, 10] depth = 5 xx = torch.rand(*dims, device=device, dtype=torch.float32).requires_grad_() ytarget = torch.rand(*dims, device=device, dtype=torch.float32) # same convolution test network = SubModuleStack(SubModule(in_filters=5, out_filters=5), depth=depth, keep_input=keep_input, coupling=coupling, implementation_fwd=-1, implementation_bwd=-1) network.to(device) network.train() network.zero_grad() optim = torch.optim.RMSprop(network.parameters()) optim.zero_grad() mem_start = 0 if not device == 'cuda' else \ torch.cuda.memory_allocated() / float(1024 ** 2) y = network(xx) gc.collect() mem_after_forward = mem_reporter.collect_stats() / float(1024 ** 2) if not device == 'cuda' else \ torch.cuda.memory_allocated() / float(1024 ** 2) loss = torch.nn.MSELoss()(y, ytarget) optim.zero_grad() loss.backward() optim.step() gc.collect() # mem_after_backward = mem_reporter.collect_stats() / float(1024 ** 2) if not device == 'cuda' else \ # torch.cuda.memory_allocated() / float(1024 ** 2) gc.enable() if device == 'cpu': memuse = 0.05 else: memuse = float(np.prod(dims + [depth, 4, ])) / float(1024 ** 2) measured_memuse = mem_after_forward - mem_start if keep_input: assert measured_memuse >= memuse else: assert measured_memuse < (1 if device == 'cuda' else memuse) # assert math.floor(mem_after_backward - mem_start) >= 9
memcnn-master
memcnn/models/tests/test_memory_saving.py
import torch import torch.nn import pytest import copy import warnings from memcnn import create_coupling, InvertibleModuleWrapper from memcnn.models.tests.test_revop import set_seeds, SubModule from memcnn.models.affine import AffineAdapterNaive, AffineBlock from memcnn.models.additive import AdditiveBlock @pytest.mark.parametrize('coupling', ['additive', 'affine']) @pytest.mark.parametrize('bwd', [False, True]) @pytest.mark.parametrize('implementation', [-1, 0, 1]) def test_coupling_implementations_against_reference(coupling, bwd, implementation): """Test if similar gradients and weights results are obtained after similar training for the couplings""" with warnings.catch_warnings(): warnings.simplefilter(action='ignore', category=DeprecationWarning) for seed in range(10): set_seeds(seed) X = torch.rand(2, 4, 5, 5) # define models and their copies c1 = torch.nn.Conv2d(2, 2, 3, padding=1) c2 = torch.nn.Conv2d(2, 2, 3, padding=1) c1_2 = copy.deepcopy(c1) c2_2 = copy.deepcopy(c2) # are weights between models the same, but do they differ between convolutions? assert torch.equal(c1.weight, c1_2.weight) assert torch.equal(c2.weight, c2_2.weight) assert torch.equal(c1.bias, c1_2.bias) assert torch.equal(c2.bias, c2_2.bias) assert not torch.equal(c1.weight, c2.weight) # define optimizers optim1 = torch.optim.SGD([e for e in c1.parameters()] + [e for e in c2.parameters()], 0.1) optim2 = torch.optim.SGD([e for e in c1_2.parameters()] + [e for e in c2_2.parameters()], 0.1) for e in [c1, c2, c1_2, c2_2]: e.train() # define an arbitrary reversible function and define graph for model 1 XX = X.detach().clone().requires_grad_() coupling_fn = create_coupling(Fm=c1, Gm=c2, coupling=coupling, implementation_fwd=-1, implementation_bwd=-1, adapter=AffineAdapterNaive) Y = coupling_fn.inverse(XX) if bwd else coupling_fn.forward(XX) loss = torch.mean(Y) # define the reversible function without custom backprop and define graph for model 2 XX2 = X.detach().clone().requires_grad_() coupling_fn2 = create_coupling(Fm=c1_2, Gm=c2_2, coupling=coupling, implementation_fwd=implementation, implementation_bwd=implementation, adapter=AffineAdapterNaive) Y2 = coupling_fn2.inverse(XX2) if bwd else coupling_fn2.forward(XX2) loss2 = torch.mean(Y2) # compute gradients manually grads = torch.autograd.grad(loss2, (XX2, c1_2.weight, c2_2.weight, c1_2.bias, c2_2.bias), None, retain_graph=True) # compute gradients using backward and perform optimization model 2 loss2.backward() optim2.step() # gradients computed manually match those of the .backward() pass assert torch.equal(c1_2.weight.grad, grads[1]) assert torch.equal(c2_2.weight.grad, grads[2]) assert torch.equal(c1_2.bias.grad, grads[3]) assert torch.equal(c2_2.bias.grad, grads[4]) # weights differ after training a single model? assert not torch.equal(c1.weight, c1_2.weight) assert not torch.equal(c2.weight, c2_2.weight) assert not torch.equal(c1.bias, c1_2.bias) assert not torch.equal(c2.bias, c2_2.bias) # compute gradients and perform optimization model 1 loss.backward() optim1.step() # weights are approximately the same after training both models? assert torch.allclose(c1.weight.detach(), c1_2.weight.detach()) assert torch.allclose(c2.weight.detach(), c2_2.weight.detach()) assert torch.allclose(c1.bias.detach(), c1_2.bias.detach()) assert torch.allclose(c2.bias.detach(), c2_2.bias.detach()) # gradients are approximately the same after training both models? assert torch.allclose(c1.weight.grad.detach(), c1_2.weight.grad.detach()) assert torch.allclose(c2.weight.grad.detach(), c2_2.weight.grad.detach()) assert torch.allclose(c1.bias.grad.detach(), c1_2.bias.grad.detach()) assert torch.allclose(c2.bias.grad.detach(), c2_2.bias.grad.detach()) fn = InvertibleModuleWrapper(fn=coupling_fn, keep_input=False, keep_input_inverse=False) Yout = fn.inverse(XX) if bwd else fn.forward(XX) loss = torch.mean(Yout) loss.backward() assert XX.storage().size() > 0 fn2 = InvertibleModuleWrapper(fn=coupling_fn2, keep_input=False, keep_input_inverse=False) Yout2 = fn2.inverse(XX2) if bwd else fn2.forward(XX2) loss = torch.mean(Yout2) loss.backward() assert XX2.storage().size() > 0 def test_legacy_additive_coupling(): with warnings.catch_warnings(): warnings.simplefilter(action='ignore', category=DeprecationWarning) AdditiveBlock(Fm=SubModule()) def test_legacy_affine_coupling(): with warnings.catch_warnings(): warnings.simplefilter(action='ignore', category=DeprecationWarning) AffineBlock(Fm=SubModule())
memcnn-master
memcnn/models/tests/test_couplings.py
import warnings import pytest import random import torch import torch.nn import numpy as np import copy from memcnn.models.affine import AffineAdapterNaive, AffineAdapterSigmoid, AffineCoupling from memcnn import ReversibleBlock from memcnn.models.revop import InvertibleModuleWrapper, create_coupling, is_invertible_module from memcnn.models.additive import AdditiveCoupling def set_seeds(seed): torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) class SubModule(torch.nn.Module): def __init__(self, in_filters=5, out_filters=5): super(SubModule, self).__init__() self.bn = torch.nn.BatchNorm2d(out_filters) self.conv = torch.nn.Conv2d(in_filters, out_filters, (3, 3), padding=1) def forward(self, x): return self.bn(self.conv(x)) class SubModuleStack(torch.nn.Module): def __init__(self, Gm, coupling='additive', depth=10, implementation_fwd=-1, implementation_bwd=-1, keep_input=False, adapter=None): super(SubModuleStack, self).__init__() fn = create_coupling(Fm=Gm, Gm=Gm, coupling=coupling, implementation_fwd=implementation_fwd, implementation_bwd=implementation_bwd, adapter=adapter) self.stack = torch.nn.ModuleList( [InvertibleModuleWrapper(fn=fn, keep_input=keep_input, keep_input_inverse=keep_input) for _ in range(depth)] ) def forward(self, x): for rev_module in self.stack: x = rev_module.forward(x) return x def inverse(self, y): for rev_module in reversed(self.stack): y = rev_module.inverse(y) return y def is_memory_cleared(var, isclear, shape): if isclear: return var.storage().size() == 0 else: return var.storage().size() > 0 and var.shape == shape def test_is_invertible_module(): X = torch.zeros(1, 10, 10, 10) assert not is_invertible_module(torch.nn.Conv2d(10, 10, kernel_size=(1, 1)), test_input_shape=X.shape) fn = AdditiveCoupling(SubModule(), implementation_bwd=-1, implementation_fwd=-1) assert is_invertible_module(fn, test_input_shape=X.shape) class FakeInverse(torch.nn.Module): def forward(self, x): return x * 4 def inverse(self, y): return y * 8 assert not is_invertible_module(FakeInverse(), test_input_shape=X.shape) @pytest.mark.parametrize('coupling', ['additive', 'affine']) def test_reversible_block_notimplemented(coupling): fm = torch.nn.Conv2d(10, 10, (3, 3), padding=1) X = torch.zeros(1, 20, 10, 10) with pytest.raises(NotImplementedError): with warnings.catch_warnings(): warnings.simplefilter(action='ignore', category=DeprecationWarning) f = ReversibleBlock(fm, coupling=coupling, implementation_bwd=0, implementation_fwd=-2, adapter=AffineAdapterNaive) assert isinstance(f, InvertibleModuleWrapper) f.forward(X) with pytest.raises(NotImplementedError): with warnings.catch_warnings(): warnings.simplefilter(action='ignore', category=DeprecationWarning) f = ReversibleBlock(fm, coupling=coupling, implementation_bwd=-2, implementation_fwd=0, adapter=AffineAdapterNaive) assert isinstance(f, InvertibleModuleWrapper) f.inverse(X) with pytest.raises(NotImplementedError): with warnings.catch_warnings(): warnings.simplefilter(action='ignore', category=DeprecationWarning) ReversibleBlock(fm, coupling='unknown', implementation_bwd=-2, implementation_fwd=0, adapter=AffineAdapterNaive) class MultiplicationInverse(torch.nn.Module): def __init__(self, factor=2): super(MultiplicationInverse, self).__init__() self.factor = torch.nn.Parameter(torch.ones(1) * factor) def forward(self, x): return x * self.factor def inverse(self, y): return y / self.factor class IdentityInverse(torch.nn.Module): def __init__(self, multiply_forward=False, multiply_inverse=False): super(IdentityInverse, self).__init__() self.factor = torch.nn.Parameter(torch.ones(1)) self.multiply_forward = multiply_forward self.multiply_inverse = multiply_inverse def forward(self, x): if self.multiply_forward: return x * self.factor else: return x def inverse(self, y): if self.multiply_inverse: return y * self.factor else: return y def test_input_output_invertible_function_share_tensor(): fn = IdentityInverse() rm = InvertibleModuleWrapper(fn=fn, keep_input=True, keep_input_inverse=True) X = torch.rand(1, 2, 5, 5, dtype=torch.float32).requires_grad_() assert not is_invertible_module(fn, test_input_shape=X.shape, atol=1e-6) with pytest.raises(RuntimeError): rm.forward(X) fn.multiply_forward = True rm.forward(X) assert not is_invertible_module(fn, test_input_shape=X.shape, atol=1e-6) with pytest.raises(RuntimeError): rm.inverse(X) fn.multiply_inverse = True rm.inverse(X) assert is_invertible_module(fn, test_input_shape=X.shape, atol=1e-6) @pytest.mark.parametrize('fn', [ AdditiveCoupling(Fm=SubModule(), implementation_fwd=-1, implementation_bwd=-1), AffineCoupling(Fm=SubModule(), implementation_fwd=-1, implementation_bwd=-1, adapter=AffineAdapterNaive), AffineCoupling(Fm=SubModule(out_filters=10), implementation_fwd=-1, implementation_bwd=-1, adapter=AffineAdapterSigmoid), MultiplicationInverse() ]) @pytest.mark.parametrize('bwd', [False, True]) @pytest.mark.parametrize('keep_input', [False, True]) @pytest.mark.parametrize('keep_input_inverse', [False, True]) def test_invertible_module_wrapper_fwd_bwd(fn, bwd, keep_input, keep_input_inverse): """InvertibleModuleWrapper tests for the memory saving forward and backward passes * test inversion Y = RB(X) and X = RB.inverse(Y) * test training the block for a single step and compare weights for implementations: 0, 1 * test automatic discard of input X and its retrieval after the backward pass * test usage of BN to identify non-contiguous memory blocks """ for seed in range(10): set_seeds(seed) dims = (2, 10, 8, 8) data = torch.rand(*dims, dtype=torch.float32) target_data = torch.rand(*dims, dtype=torch.float32) assert is_invertible_module(fn, test_input_shape=data.shape, atol=1e-4) # test with zero padded convolution with torch.set_grad_enabled(True): X = data.clone().requires_grad_() Ytarget = target_data.clone() Xshape = X.shape rb = InvertibleModuleWrapper(fn=fn, keep_input=keep_input, keep_input_inverse=keep_input_inverse) s_grad = [p.detach().clone() for p in rb.parameters()] rb.train() rb.zero_grad() optim = torch.optim.RMSprop(rb.parameters()) optim.zero_grad() if not bwd: Xin = X.clone().requires_grad_() Y = rb(Xin) Yrev = Y.detach().clone().requires_grad_() Xinv = rb.inverse(Yrev) else: Xin = X.clone().requires_grad_() Y = rb.inverse(Xin) Yrev = Y.detach().clone().requires_grad_() Xinv = rb(Yrev) loss = torch.nn.MSELoss()(Y, Ytarget) # has input been retained/discarded after forward (and backward) passes? if not bwd: assert is_memory_cleared(Yrev, not keep_input_inverse, Xshape) assert is_memory_cleared(Xin, not keep_input, Xshape) else: assert is_memory_cleared(Xin, not keep_input_inverse, Xshape) assert is_memory_cleared(Yrev, not keep_input, Xshape) optim.zero_grad() loss.backward() optim.step() assert Y.shape == Xshape assert X.detach().shape == data.shape assert torch.allclose(X.detach(), data, atol=1e-06) assert torch.allclose(X.detach(), Xinv.detach(), atol=1e-04) # Model is now trained and will differ grads = [p.detach().clone() for p in rb.parameters()] assert not torch.allclose(grads[0], s_grad[0]) @pytest.mark.parametrize('coupling,adapter', [('additive', None), ('affine', AffineAdapterNaive), ('affine', AffineAdapterSigmoid)]) def test_chained_invertible_module_wrapper(coupling, adapter): set_seeds(42) dims = (2, 10, 8, 8) data = torch.rand(*dims, dtype=torch.float32) target_data = torch.rand(*dims, dtype=torch.float32) with torch.set_grad_enabled(True): X = data.clone().requires_grad_() Ytarget = target_data.clone() Gm = SubModule(in_filters=5, out_filters=5 if coupling == 'additive' or adapter is AffineAdapterNaive else 10) rb = SubModuleStack(Gm, coupling=coupling, depth=2, keep_input=False, adapter=adapter, implementation_bwd=-1, implementation_fwd=-1) rb.train() optim = torch.optim.RMSprop(rb.parameters()) rb.zero_grad() optim.zero_grad() Xin = X.clone() Y = rb(Xin) loss = torch.nn.MSELoss()(Y, Ytarget) loss.backward() optim.step() assert not torch.isnan(loss) def test_chained_invertible_module_wrapper_shared_fwd_and_bwd_train_passes(): set_seeds(42) Gm = SubModule(in_filters=5, out_filters=5) rb_temp = SubModuleStack(Gm=Gm, coupling='additive', depth=5, keep_input=True, adapter=None, implementation_bwd=-1, implementation_fwd=-1) optim = torch.optim.SGD(rb_temp.parameters(), lr=0.01) initial_params = [p.detach().clone() for p in rb_temp.parameters()] initial_state = copy.deepcopy(rb_temp.state_dict()) initial_optim_state = copy.deepcopy(optim.state_dict()) dims = (2, 10, 8, 8) data = torch.rand(*dims, dtype=torch.float32) target_data = torch.rand(*dims, dtype=torch.float32) forward_outputs = [] inverse_outputs = [] for i in range(10): is_forward_pass = i % 2 == 0 set_seeds(42) rb = SubModuleStack(Gm=Gm, coupling='additive', depth=5, keep_input=True, adapter=None, implementation_bwd=-1, implementation_fwd=-1) rb.train() with torch.no_grad(): for (name, p), p_initial in zip(rb.named_parameters(), initial_params): p.set_(p_initial) rb.load_state_dict(initial_state) optim = torch.optim.SGD(rb_temp.parameters(), lr=0.01) optim.load_state_dict(initial_optim_state) with torch.set_grad_enabled(True): X = data.detach().clone().requires_grad_() Ytarget = target_data.detach().clone() optim.zero_grad() if is_forward_pass: Y = rb(X) Xinv = rb.inverse(Y) Xinv2 = rb.inverse(Y) Xinv3 = rb.inverse(Y) else: Y = rb.inverse(X) Xinv = rb(Y) Xinv2 = rb(Y) Xinv3 = rb(Y) for item in [Xinv, Xinv2, Xinv3]: assert torch.allclose(X, item, atol=1e-04) loss = torch.nn.MSELoss()(Xinv, Ytarget) assert not torch.isnan(loss) assert Xinv2.grad is None assert Xinv3.grad is None loss.backward() assert Y.grad is not None assert Xinv.grad is not None assert Xinv2.grad is None assert Xinv3.grad is None loss2 = torch.nn.MSELoss()(Xinv2, Ytarget) assert not torch.isnan(loss2) loss2.backward() assert Xinv2.grad is not None optim.step() if is_forward_pass: forward_outputs.append(Y.detach().clone()) else: inverse_outputs.append(Y.detach().clone()) for i in range(4): assert torch.allclose(forward_outputs[-1], forward_outputs[i], atol=1e-06) assert torch.allclose(inverse_outputs[-1], inverse_outputs[i], atol=1e-06) @pytest.mark.parametrize("inverted", [False, True]) def test_invertible_module_wrapper_disabled_versus_enabled(inverted): set_seeds(42) Gm = SubModule(in_filters=5, out_filters=5) coupling_fn = create_coupling(Fm=Gm, Gm=Gm, coupling='additive', implementation_fwd=-1, implementation_bwd=-1) rb = InvertibleModuleWrapper(fn=coupling_fn, keep_input=False, keep_input_inverse=False) rb2 = InvertibleModuleWrapper(fn=copy.deepcopy(coupling_fn), keep_input=False, keep_input_inverse=False) rb.eval() rb2.eval() rb2.disable = True with torch.no_grad(): dims = (2, 10, 8, 8) data = torch.rand(*dims, dtype=torch.float32) X, X2 = data.clone().detach().requires_grad_(), data.clone().detach().requires_grad_() if not inverted: Y = rb(X) Y2 = rb2(X2) else: Y = rb.inverse(X) Y2 = rb2.inverse(X2) assert torch.allclose(Y, Y2) assert is_memory_cleared(X, True, dims) assert is_memory_cleared(X2, False, dims) @pytest.mark.parametrize('coupling', ['additive', 'affine']) def test_invertible_module_wrapper_simple_inverse(coupling): """InvertibleModuleWrapper inverse test""" for seed in range(10): set_seeds(seed) # define some data X = torch.rand(2, 4, 5, 5).requires_grad_() # define an arbitrary reversible function coupling_fn = create_coupling(Fm=torch.nn.Conv2d(2, 2, 3, padding=1), coupling=coupling, implementation_fwd=-1, implementation_bwd=-1, adapter=AffineAdapterNaive) fn = InvertibleModuleWrapper(fn=coupling_fn, keep_input=False, keep_input_inverse=False) # compute output Y = fn.forward(X.clone()) # compute input from output X2 = fn.inverse(Y) # check that the inverted output and the original input are approximately similar assert torch.allclose(X2.detach(), X.detach(), atol=1e-06) @pytest.mark.parametrize('coupling', ['additive', 'affine']) def test_normal_vs_invertible_module_wrapper(coupling): """InvertibleModuleWrapper test if similar gradients and weights results are obtained after similar training""" for seed in range(10): set_seeds(seed) X = torch.rand(2, 4, 5, 5) # define models and their copies c1 = torch.nn.Conv2d(2, 2, 3, padding=1) c2 = torch.nn.Conv2d(2, 2, 3, padding=1) c1_2 = copy.deepcopy(c1) c2_2 = copy.deepcopy(c2) # are weights between models the same, but do they differ between convolutions? assert torch.equal(c1.weight, c1_2.weight) assert torch.equal(c2.weight, c2_2.weight) assert torch.equal(c1.bias, c1_2.bias) assert torch.equal(c2.bias, c2_2.bias) assert not torch.equal(c1.weight, c2.weight) # define optimizers optim1 = torch.optim.SGD([e for e in c1.parameters()] + [e for e in c2.parameters()], 0.1) optim2 = torch.optim.SGD([e for e in c1_2.parameters()] + [e for e in c2_2.parameters()], 0.1) for e in [c1, c2, c1_2, c2_2]: e.train() # define an arbitrary reversible function and define graph for model 1 Xin = X.clone().requires_grad_() coupling_fn = create_coupling(Fm=c1_2, Gm=c2_2, coupling=coupling, implementation_fwd=-1, implementation_bwd=-1, adapter=AffineAdapterNaive) fn = InvertibleModuleWrapper(fn=coupling_fn, keep_input=False, keep_input_inverse=False) Y = fn.forward(Xin) loss2 = torch.mean(Y) # define the reversible function without custom backprop and define graph for model 2 XX = X.clone().detach().requires_grad_() x1, x2 = torch.chunk(XX, 2, dim=1) if coupling == 'additive': y1 = x1 + c1.forward(x2) y2 = x2 + c2.forward(y1) elif coupling == 'affine': fmr2 = c1.forward(x2) fmr1 = torch.exp(fmr2) y1 = (x1 * fmr1) + fmr2 gmr2 = c2.forward(y1) gmr1 = torch.exp(gmr2) y2 = (x2 * gmr1) + gmr2 else: raise NotImplementedError() YY = torch.cat([y1, y2], dim=1) loss = torch.mean(YY) # compute gradients manually grads = torch.autograd.grad(loss, (XX, c1.weight, c2.weight, c1.bias, c2.bias), None, retain_graph=True) # compute gradients and perform optimization model 2 loss.backward() optim1.step() # gradients computed manually match those of the .backward() pass assert torch.equal(c1.weight.grad, grads[1]) assert torch.equal(c2.weight.grad, grads[2]) assert torch.equal(c1.bias.grad, grads[3]) assert torch.equal(c2.bias.grad, grads[4]) # weights differ after training a single model? assert not torch.equal(c1.weight, c1_2.weight) assert not torch.equal(c2.weight, c2_2.weight) assert not torch.equal(c1.bias, c1_2.bias) assert not torch.equal(c2.bias, c2_2.bias) # compute gradients and perform optimization model 1 loss2.backward() optim2.step() # input is contiguous tests assert Xin.is_contiguous() assert Y.is_contiguous() # weights are approximately the same after training both models? assert torch.allclose(c1.weight.detach(), c1_2.weight.detach()) assert torch.allclose(c2.weight.detach(), c2_2.weight.detach()) assert torch.allclose(c1.bias.detach(), c1_2.bias.detach()) assert torch.allclose(c2.bias.detach(), c2_2.bias.detach()) # gradients are approximately the same after training both models? assert torch.allclose(c1.weight.grad.detach(), c1_2.weight.grad.detach()) assert torch.allclose(c2.weight.grad.detach(), c2_2.weight.grad.detach()) assert torch.allclose(c1.bias.grad.detach(), c1_2.bias.grad.detach()) assert torch.allclose(c2.bias.grad.detach(), c2_2.bias.grad.detach())
memcnn-master
memcnn/models/tests/test_revop.py
import time import logging import torch import numpy as np from memcnn.utils.stats import AverageMeter, accuracy from memcnn.utils.log import SummaryWriter logger = logging.getLogger('trainer') def validate(model, ceriterion, val_loader, device): """validation sub-loop""" model.eval() batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() end = time.time() with torch.no_grad(): for x, label in val_loader: x, label = x.to(device), label.to(device) vx, vl = x, label score = model(vx) loss = ceriterion(score, vl) prec1 = accuracy(score.data, label) losses.update(loss.item(), x.size(0)) top1.update(prec1[0][0], x.size(0)) batch_time.update(time.time() - end) end = time.time() logger.info('Test: [{0}/{0}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'.format(len(val_loader), batch_time=batch_time, loss=losses, top1=top1)) return top1.avg, losses.avg def get_model_parameters_count(model): return np.sum([np.prod([int(e) for e in p.shape]) for p in model.parameters()]) def train(manager, train_loader, test_loader, start_iter, disp_iter=100, save_iter=10000, valid_iter=1000, use_cuda=False, loss=None): """train loop""" device = torch.device('cpu' if not use_cuda else 'cuda') model, optimizer = manager.model, manager.optimizer logger.info('Model parameters: {}'.format(get_model_parameters_count(model))) if use_cuda: model_mem_allocation = torch.cuda.memory_allocated(device) logger.info('Model memory allocation: {}'.format(model_mem_allocation)) else: model_mem_allocation = None writer = SummaryWriter(manager.log_dir) data_time = AverageMeter() batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() act_mem_activations = AverageMeter() ceriterion = loss # ensure train_loader enumerates to max_epoch max_iterations = train_loader.sampler.nsamples // train_loader.batch_size train_loader.sampler.nsamples = train_loader.sampler.nsamples - start_iter end = time.time() for ind, (x, label) in enumerate(train_loader): iteration = ind + 1 + start_iter if iteration > max_iterations: logger.info('maximum number of iterations reached: {}/{}'.format(iteration, max_iterations)) break if iteration == 40000 or iteration == 60000: for param_group in optimizer.param_groups: param_group['lr'] *= 0.1 model.train() data_time.update(time.time() - end) end = time.time() x, label = x.to(device), label.to(device) vx, vl = x, label score = model(vx) loss = ceriterion(score, vl) if use_cuda: activation_mem_allocation = torch.cuda.memory_allocated(device) - model_mem_allocation act_mem_activations.update(activation_mem_allocation, iteration) if torch.isnan(loss): raise ValueError("Loss became NaN during iteration {}".format(iteration)) optimizer.zero_grad() loss.backward() optimizer.step() batch_time.update(time.time()-end) prec1 = accuracy(score.data, label) losses.update(loss.item(), x.size(0)) top1.update(prec1[0][0], x.size(0)) if iteration % disp_iter == 0: act = '' if model_mem_allocation is not None: act = 'ActMem {act.val:.3f} ({act.avg:.3f})'.format(act=act_mem_activations) logger.info('iteration: [{0}/{1}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' '{act}' .format(iteration, max_iterations, batch_time=batch_time, data_time=data_time, loss=losses, top1=top1, act=act)) if iteration % disp_iter == 0: writer.add_scalar('train_loss', loss.item(), iteration) writer.add_scalar('train_acc', prec1[0][0], iteration) losses.reset() top1.reset() data_time.reset() batch_time.reset() if use_cuda: writer.add_scalar('act_mem_allocation', act_mem_activations.avg, iteration) act_mem_activations.reset() if iteration % valid_iter == 0: test_top1, test_loss = validate(model, ceriterion, test_loader, device=device) writer.add_scalar('test_loss', test_loss, iteration) writer.add_scalar('test_acc', test_top1, iteration) if iteration % save_iter == 0: manager.save_train_state(iteration) writer.flush() end = time.time() writer.close()
memcnn-master
memcnn/trainers/classification.py
memcnn-master
memcnn/trainers/__init__.py
import json import pytest import os import sys import torch from memcnn.experiment.manager import ExperimentManager from memcnn.train import run_experiment, main try: from pathlib2 import Path except ImportError: from pathlib import Path def test_main(tmp_path): sys.argv = ['train.py', 'cifar10', 'resnet34', '--fresh', '--no-cuda', '--workers=0'] data_dir = str(tmp_path / "tmpdata") results_dir = str(tmp_path / "resdir") os.makedirs(data_dir) os.makedirs(results_dir) with pytest.raises(KeyError): main(data_dir=data_dir, results_dir=results_dir) def dummy_dataloaders(*args, **kwargs): return None, None def dummy_trainer(manager, *args, **kwargs): manager.save_train_state(2) class DummyDataset(object): def __init__(self, *args, **kwargs): pass class DummyModel(torch.nn.Module): def __init__(self, block): super(DummyModel, self).__init__() self.block = block self.conv = torch.nn.Conv2d(1, 1, 1) def forward(self, x): return self.conv(x) def test_run_experiment(tmp_path): exptags = ['testsetup'] exp_file = str(Path(__file__).parent / "resources" / "experiments.json") data_dir = str(tmp_path / "tmpdata") results_dir = str(tmp_path / "resdir") run_params = dict( experiment_tags=exptags, data_dir=data_dir, results_dir=results_dir, start_fresh=True, use_cuda=False, workers=None, experiments_file=exp_file ) with pytest.raises(RuntimeError): run_experiment(**run_params) os.makedirs(data_dir) with pytest.raises(RuntimeError): run_experiment(**run_params) os.makedirs(results_dir) run_experiment(**run_params) run_params["start_fresh"] = False run_experiment(**run_params) @pytest.mark.parametrize("network", [ pytest.param(network, marks=pytest.mark.skipif( condition=("FULL_NETWORK_TESTS" not in os.environ) and ("revnet38" != network), reason="Too memory intensive for CI so these tests are disabled by default. " "Set FULL_NETWORK_TESTS environment variable to enable the tests.") ) for network in ["resnet32", "resnet110", "resnet164", "revnet38", "revnet110", "revnet164"] ]) @pytest.mark.parametrize("use_cuda", [ False, pytest.param(True, marks=pytest.mark.skipif(condition=not torch.cuda.is_available(), reason="No GPU available")) ]) def test_train_networks(tmp_path, network, use_cuda): exptags = ["cifar10", network, "epoch5"] exp_file = str(Path(__file__).parent / "resources" / "experiments.json") data_dir = str(tmp_path / "tmpdata") results_dir = str(tmp_path / "resdir") os.makedirs(data_dir) os.makedirs(results_dir) run_experiment(experiment_tags=exptags, data_dir=data_dir, results_dir=results_dir, start_fresh=True, use_cuda=use_cuda, workers=None, experiments_file=exp_file, disp_iter=1, save_iter=5, valid_iter=5,) experiment_dir = os.path.join(results_dir, '_'.join(exptags)) assert os.path.exists(experiment_dir) manager = ExperimentManager(experiment_dir) scalars_file = os.path.join(manager.log_dir, "scalars.json") assert os.path.exists(scalars_file) with open(scalars_file, "r") as f: results = json.load(f) # no results should hold any NaN values assert not any([val != val for t, i, val in results["train_loss"]])
memcnn-master
memcnn/trainers/tests/test_train.py
memcnn-master
memcnn/trainers/tests/__init__.py
import pytest from memcnn.trainers.classification import train from memcnn.experiment.manager import ExperimentManager from memcnn.data.cifar import get_cifar_data_loaders from memcnn.utils.loss import CrossEntropyLossTF import torch from torchvision.datasets.cifar import CIFAR10 class SimpleTestingModel(torch.nn.Module): def __init__(self, klasses): super(SimpleTestingModel, self).__init__() self.conv = torch.nn.Conv2d(3, klasses, 1) self.avgpool = torch.nn.AvgPool2d(32) self.klasses = klasses def forward(self, x): return self.avgpool(self.conv(x)).reshape(x.shape[0], self.klasses) def test_train(tmp_path): expdir = str(tmp_path / "testexp") tmp_data_dir = str(tmp_path / "tmpdata") num_klasses = 10 model = SimpleTestingModel(num_klasses) optimizer = torch.optim.SGD(params=model.parameters(), lr=0.01) manager = ExperimentManager(expdir, model, optimizer) manager.make_dirs() train_loader, test_loader = get_cifar_data_loaders(CIFAR10, tmp_data_dir, 40000, 2, 0) loss = CrossEntropyLossTF() train(manager, train_loader, test_loader, start_iter=39999, disp_iter=1, save_iter=1, valid_iter=1, use_cuda=False, loss=loss) def test_train_with_nan_loss(tmp_path): class NanLoss(torch.nn.Module): def __init__(self): super(NanLoss, self).__init__() def forward(self, Ypred, Y, W=None): return Ypred.mean() * float('nan') expdir = str(tmp_path / "testexp") tmp_data_dir = str(tmp_path / "tmpdata") num_klasses = 10 model = SimpleTestingModel(num_klasses) optimizer = torch.optim.SGD(params=model.parameters(), lr=0.01) manager = ExperimentManager(expdir, model, optimizer) manager.make_dirs() train_loader, test_loader = get_cifar_data_loaders(CIFAR10, tmp_data_dir, 40000, 2, 0) loss = NanLoss() with pytest.raises(ValueError) as e: train(manager, train_loader, test_loader, start_iter=1, disp_iter=1, save_iter=1, valid_iter=1, use_cuda=False, loss=loss) assert "Loss became NaN during iteration" in str(e.value)
memcnn-master
memcnn/trainers/tests/test_classification.py
import torch import torch.nn as nn import memcnn # define a new torch Module with a sequence of operations: Relu o BatchNorm2d o Conv2d class ExampleOperation(nn.Module): def __init__(self, channels): super(ExampleOperation, self).__init__() self.seq = nn.Sequential( nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=(3, 3), padding=1), nn.BatchNorm2d(num_features=channels), nn.ReLU(inplace=True) ) def forward(self, x): return self.seq(x) # generate some random input data (batch_size, num_channels, y_elements, x_elements) X = torch.rand(2, 10, 8, 8) # application of the operation(s) the normal way model_normal = ExampleOperation(channels=10) model_normal.eval() Y = model_normal(X) # turn the ExampleOperation invertible using an additive coupling invertible_module = memcnn.AdditiveCoupling( Fm=ExampleOperation(channels=10 // 2), Gm=ExampleOperation(channels=10 // 2) ) # test that it is actually a valid invertible module (has a valid inverse method) assert memcnn.is_invertible_module(invertible_module, test_input_shape=X.shape) # wrap our invertible_module using the InvertibleModuleWrapper and benefit from memory savings during training invertible_module_wrapper = memcnn.InvertibleModuleWrapper(fn=invertible_module, keep_input=True, keep_input_inverse=True) # by default the module is set to training, the following sets this to evaluation # note that this is required to pass input tensors to the model with requires_grad=False (inference only) invertible_module_wrapper.eval() # test that the wrapped module is also a valid invertible module assert memcnn.is_invertible_module(invertible_module_wrapper, test_input_shape=X.shape) # compute the forward pass using the wrapper Y2 = invertible_module_wrapper.forward(X) # the input (X) can be approximated (X2) by applying the inverse method of the wrapper on Y2 X2 = invertible_module_wrapper.inverse(Y2) # test that the input and approximation are similar assert torch.allclose(X, X2, atol=1e-06)
memcnn-master
memcnn/examples/minimal.py
import torch import sys def test_minimal(): import minimal # Input and inversed output should be approximately the same assert torch.allclose(minimal.X, minimal.X2, atol=1e-06) # Output of the wrapped invertible module is unlikely to match the normal output of F assert not torch.allclose(minimal.Y2, minimal.Y) # Cleanup minimal module and variables del minimal.X del minimal.Y del minimal.Y2 del minimal.X2 del minimal del sys.modules['minimal']
memcnn-master
memcnn/examples/test_examples.py
memcnn-master
memcnn/experiment/__init__.py
import json import copy def get_attr_from_module(pclass): pclass = pclass.rsplit(".", 1) mod = __import__(pclass[0], fromlist=[str(pclass[1])]) return getattr(mod, pclass[1]) def load_experiment_config(experiments_file, experiment_tags): with open(experiments_file, 'r') as f: data = json.load(f) d = {} for tag in experiment_tags: _inject_items(build_dict(data, tag), d) return d def _inject_items(tempdict, d): """inject tempdict into d""" for k, v in tempdict.items(): if isinstance(v, dict): if k not in d: d[k] = {} d[k] = _inject_items(v, d[k]) else: d[k] = v return d def build_dict(experiments_dict, experiment_name, classhist=None): tempdict = experiments_dict[experiment_name] if classhist is None: classhist = [] classhist.append(experiment_name) if not ('base' in tempdict) or (tempdict['base'] is None): return copy.deepcopy(tempdict) elif tempdict['base'] in classhist: raise RuntimeError('Circular dependency found...') else: d = build_dict(experiments_dict, tempdict['base'], classhist) return _inject_items(tempdict, d) def experiment_config_parser(d, data_dir, workers=None): trainer = get_attr_from_module(d['trainer']) model = get_attr_from_module(d['model']) model_params = copy.deepcopy(d['model_params']) if 'block' in model_params: model_params['block'] = get_attr_from_module(model_params['block']) model = model(**model_params) optimizer = get_attr_from_module(d['optimizer']) optimizer = optimizer(model.parameters(), **d['optimizer_params']) dl_params = copy.deepcopy(d['data_loader_params']) dl_params['dataset'] = get_attr_from_module(dl_params['dataset']) dl_params['data_dir'] = data_dir dl_params['workers'] = dl_params['workers'] if workers is None else workers train_loader, val_loader = get_attr_from_module(d['data_loader'])(**dl_params) trainer_params = {} if 'trainer_params' in d: trainer_params = copy.deepcopy(d['trainer_params']) if 'loss' in trainer_params: trainer_params['loss'] = get_attr_from_module(trainer_params['loss'])() trainer_params = dict( train_loader=train_loader, test_loader=val_loader, **trainer_params ) return model, optimizer, trainer, trainer_params
memcnn-master
memcnn/experiment/factory.py
import os import glob import torch import logging import shutil import numpy as np class ExperimentManager(object): def __init__(self, experiment_dir, model=None, optimizer=None): self.logger = logging.getLogger(type(self).__name__) self.experiment_dir = experiment_dir self.model = model self.optimizer = optimizer self.model_dir = os.path.join(self.experiment_dir, "state", "model") self.optim_dir = os.path.join(self.experiment_dir, "state", "optimizer") self.log_dir = os.path.join(self.experiment_dir, "log") self.dirs = (self.experiment_dir, self.model_dir, self.log_dir, self.optim_dir) def make_dirs(self): for d in self.dirs: if not os.path.exists(d): os.makedirs(d) assert(self.all_dirs_exists()) # nosec def delete_dirs(self): for d in self.dirs: if os.path.exists(d): shutil.rmtree(d) assert(not self.any_dir_exists()) # nosec def any_dir_exists(self): return any([os.path.exists(d) for d in self.dirs]) def all_dirs_exists(self): return all([os.path.exists(d) for d in self.dirs]) def save_model_state(self, epoch): model_fname = os.path.join(self.model_dir, "{}.pt".format(epoch)) self.logger.info("Saving model state to: {}".format(model_fname)) torch.save(self.model.state_dict(), model_fname) def load_model_state(self, epoch): model_fname = os.path.join(self.model_dir, "{}.pt".format(epoch)) self.logger.info("Loading model state from: {}".format(model_fname)) self.model.load_state_dict(torch.load(model_fname)) def save_optimizer_state(self, epoch): optim_fname = os.path.join(self.optim_dir, "{}.pt".format(epoch)) self.logger.info("Saving optimizer state to: {}".format(optim_fname)) torch.save(self.optimizer.state_dict(), optim_fname) def load_optimizer_state(self, epoch): optim_fname = os.path.join(self.optim_dir, "{}.pt".format(epoch)) self.logger.info("Loading optimizer state from {}".format(optim_fname)) self.optimizer.load_state_dict(torch.load(optim_fname)) def save_train_state(self, epoch): self.save_model_state(epoch) self.save_optimizer_state(epoch) def load_train_state(self, epoch): self.load_model_state(epoch) self.load_optimizer_state(epoch) def get_last_model_iteration(self): return np.array([0] + [int(os.path.basename(e).split(".")[0]) for e in glob.glob(os.path.join(self.model_dir, "*.pt"))]).max() def load_last_train_state(self): self.load_train_state(self.get_last_model_iteration())
memcnn-master
memcnn/experiment/manager.py
import pytest import os import memcnn.experiment.factory from memcnn.config import Config def test_get_attr_from_module(): a = memcnn.experiment.factory.get_attr_from_module('memcnn.experiment.factory.get_attr_from_module') assert a is memcnn.experiment.factory.get_attr_from_module def test_load_experiment_config(): cfg_fname = os.path.join(Config.get_dir(), 'experiments.json') memcnn.experiment.factory.load_experiment_config(cfg_fname, ['cifar10', 'resnet110']) @pytest.mark.skip(reason="Covered more efficiently by test_train.test_run_experiment") def test_experiment_config_parser(tmp_path): tmp_data_dir = tmp_path / "tmpdata" cfg_fname = os.path.join(Config.get_dir(), 'experiments.json') cfg = memcnn.experiment.factory.load_experiment_config(cfg_fname, ['cifar10', 'resnet110']) memcnn.experiment.factory.experiment_config_parser(cfg, str(tmp_data_dir), workers=None) def test_circular_dependency(tmp_path): p = str(tmp_path / "circular.json") content = u'{ "circ": { "base": "circ" } }' with open(p, 'w') as fh: fh.write(content) with open(p, 'r') as fh: assert fh.read() == content with pytest.raises(RuntimeError): memcnn.experiment.factory.load_experiment_config(p, ['circ'])
memcnn-master
memcnn/experiment/tests/test_factory.py
memcnn-master
memcnn/experiment/tests/__init__.py
from memcnn.experiment.manager import ExperimentManager import torch.nn def test_experiment_manager(tmp_path): exp_dir = tmp_path / "test_exp_dir" man = ExperimentManager(str(exp_dir)) assert man.model is None assert man.optimizer is None man.make_dirs() assert exp_dir.exists() assert (exp_dir / "log").exists() assert (exp_dir / "state" / "model").exists() assert (exp_dir / "state" / "optimizer").exists() assert man.all_dirs_exists() assert man.any_dir_exists() man.delete_dirs() assert not exp_dir.exists() assert not (exp_dir / "log").exists() assert not (exp_dir / "state" / "model").exists() assert not (exp_dir / "state" / "optimizer").exists() assert not man.all_dirs_exists() assert not man.any_dir_exists() man.make_dirs() man.model = torch.nn.Conv2d(2, 1, 3) w = man.model.weight.clone() man.save_model_state(0) with torch.no_grad(): man.model.weight.zero_() man.save_model_state(100) assert not man.model.weight.equal(w) assert man.get_last_model_iteration() == 100 man.load_model_state(0) assert man.model.weight.equal(w) optimizer = torch.optim.SGD(man.model.parameters(), lr=0.01, momentum=0.1) man.optimizer = optimizer man.save_train_state(100) w = man.model.weight.clone() sd = man.optimizer.state_dict().copy() man.model.train() x = torch.ones(5, 2, 5, 5) x.requires_grad = True y = torch.ones(5, 1, 3, 3) y.requires_grad = False ypred = man.model(x) loss = torch.nn.MSELoss()(ypred, y) man.optimizer.zero_grad() loss.backward() man.optimizer.step() man.save_train_state(101) assert not man.model.weight.equal(w) assert sd != man.optimizer.state_dict() w2 = man.model.weight.clone() sd2 = man.optimizer.state_dict().copy() man.load_train_state(100) assert man.model.weight.equal(w) assert sd == man.optimizer.state_dict() man.load_last_train_state() # should be 101 assert not man.model.weight.equal(w) assert sd != man.optimizer.state_dict() assert man.model.weight.equal(w2) print(sd2) print(man.optimizer.state_dict()) def retrieve_mom_buffer(sd): keys = [e for e in sd['state'].keys()] if len(keys) == 0: return torch.zero(0) else: return sd['state'][keys[0]]['momentum_buffer'] assert torch.equal(retrieve_mom_buffer(sd2), retrieve_mom_buffer(man.optimizer.state_dict()))
memcnn-master
memcnn/experiment/tests/test_manager.py
memcnn-master
memcnn/data/__init__.py
import torch from torch.utils.data import DataLoader import torchvision.transforms as transforms import numpy as np from memcnn.data.sampling import NSamplesRandomSampler def random_crop_transform(x, crop_size=3, img_size=(32, 32)): cz = (crop_size + 1) // 2 x_pad = np.pad(x, ((cz, cz), (cz, cz), (0, 0)), mode='constant') sx, sy = np.random.randint(crop_size + 1), np.random.randint(crop_size + 1) return x_pad[sx:sx + img_size[0], sy:sy + img_size[1], :] def get_cifar_data_loaders(dataset, data_dir, max_epoch, batch_size, workers): train_set = dataset(root=data_dir, train=True, download=True) valid_set = dataset(root=data_dir, train=False, download=True) # calculate mean subtraction img with backwards compatibility for torchvision < 0.2.2 tdata = train_set.train_data if hasattr(train_set, 'train_data') else train_set.data vdata = valid_set.test_data if hasattr(valid_set, 'test_data') else valid_set.data mean_img = np.concatenate((tdata, vdata), axis=0).mean(axis=0) # define transforms randomcroplambda = transforms.Lambda(random_crop_transform) tonumpy = transforms.Lambda(lambda x: np.array(x.getdata()).reshape(x.size[1], x.size[0], 3)) randomlrflip = transforms.Lambda(lambda x: np.copy(x[:, ::-1, :]) if np.random.random() >= 0.5 else x) meansubtraction = transforms.Lambda(lambda x: x.astype(np.float) - mean_img) totensor = transforms.Lambda(lambda x: torch.from_numpy(x.transpose(2, 0, 1).astype(np.float32))) tfs = transforms.Compose([ tonumpy, meansubtraction, randomcroplambda, randomlrflip, totensor ]) train_set.transform = tfs valid_set.transform = tfs sampler = NSamplesRandomSampler(train_set, max_epoch * batch_size) train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=False, sampler=sampler, num_workers=workers, pin_memory=True) val_loader = DataLoader(valid_set, batch_size=batch_size, shuffle=False, num_workers=workers, pin_memory=True) return train_loader, val_loader
memcnn-master
memcnn/data/cifar.py
import torch from torch.utils.data.sampler import Sampler class NSamplesRandomSampler(Sampler): """Samples elements randomly, with replacement, always in blocks all elements of the dataset. Only the remainder will be sampled with less elements. Arguments: data_source (Dataset): dataset to sample from nsamples (int): number of total samples. Note: will always be cast to int """ @property def nsamples(self): return self._nsamples @nsamples.setter def nsamples(self, value): self._nsamples = int(value) def __init__(self, data_source, nsamples): self.data_source = data_source self.nsamples = nsamples def __iter__(self): samples = torch.LongTensor() len_data_source = len(self.data_source) for _ in range(self.nsamples // len_data_source): samples = torch.cat((samples, torch.randperm(len_data_source).long())) if self.nsamples % len_data_source > 0: samples = torch.cat((samples, torch.randperm(self.nsamples % len_data_source).long())) return iter(samples) def __len__(self): return self.nsamples
memcnn-master
memcnn/data/sampling.py
import pytest from memcnn.data.cifar import get_cifar_data_loaders, random_crop_transform import torch.utils.data as data import numpy as np from PIL import Image @pytest.mark.parametrize('crop_size,img_size', [(4, (32, 32)), (0, (32, 32))]) def test_random_crop_transform(crop_size, img_size): np.random.seed(42) img = np.random.random((img_size[0], img_size[1], 3)) imgres = random_crop_transform(img, crop_size, img_size) assert imgres.shape == img.shape assert imgres.dtype == img.dtype if crop_size == 0: assert np.array_equal(img, imgres) @pytest.mark.parametrize('max_epoch,batch_size', [(10, 2), (20, 4), (1, 1)]) def test_cifar_data_loaders(max_epoch, batch_size): np.random.seed(42) class TestDataset(data.Dataset): def __init__(self, train=True, *args, **kwargs): self.train = train self.args = args self.kwargs = kwargs if self.train: self.train_data = (np.random.random_sample((20, 32, 32, 3)) * 255).astype(np.uint8) else: self.test_data = (np.random.random_sample((10, 32, 32, 3)) * 255).astype(np.uint8) self.transform = lambda val: val def __getitem__(self, idx): img = self.train_data[idx] if self.train else self.test_data[idx] img = Image.fromarray(img) img = self.transform(img) return img, np.array(idx) def __len__(self): return len(self.train_data) if self.train else len(self.test_data) max_epoch = 10 batch_size = 2 workers = 0 train_loader, val_loader = get_cifar_data_loaders(TestDataset, '', max_epoch, batch_size, workers=workers) xsize = (batch_size, 3, 32, 32) ysize = (batch_size, ) count = 0 for x, y in train_loader: count += 1 assert x.shape == xsize assert y.shape == ysize assert count == max_epoch assert count == len(train_loader) count = 0 for x, y in val_loader: count += 1 assert x.shape == xsize assert y.shape == ysize assert count == len(val_loader.dataset) // batch_size assert count == len(val_loader)
memcnn-master
memcnn/data/tests/test_cifar.py
memcnn-master
memcnn/data/tests/__init__.py
import pytest from memcnn.data.sampling import NSamplesRandomSampler import torch.utils.data as data import numpy as np @pytest.mark.parametrize('nsamples,data_samples', [(1, 1), (14, 10), (10, 14), (5, 1), (1, 5), (0, 10), (np.array(4, dtype=np.int64), 12), (np.int64(4), 12), (np.array(12, dtype=np.int64), 3), (np.int64(12), 3)]) @pytest.mark.parametrize('assign_after_creation', [False, True]) def test_random_sampler(nsamples, data_samples, assign_after_creation): class TestDataset(data.Dataset): def __init__(self, elements): self.elements = elements def __getitem__(self, idx): return idx, idx def __len__(self): return self.elements datasrc = TestDataset(data_samples) sampler = NSamplesRandomSampler(datasrc, nsamples=nsamples if not assign_after_creation else -1) if assign_after_creation: sampler.nsamples = nsamples count = 0 elements = [] for e in sampler: elements.append(e) count += 1 if count % data_samples == 0: assert len(np.unique(elements)) == len(elements) elements = [] assert count == nsamples assert len(sampler) == nsamples assert sampler.__len__() == nsamples
memcnn-master
memcnn/data/tests/test_sampling.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # memcnn documentation build configuration file, created by # sphinx-quickstart on Fri Jun 9 13:47:02 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('..')) # this gets the memcnn_version without importing memcnn and causing troubles with mock later on with open(os.path.join(os.path.dirname(__file__), '..', 'memcnn', '__init__.py'), 'r') as f: memcnn_version = [line.split("'")[1] for line in f.readlines() if '__version__' in line][0] # -- General configuration --------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinx.ext.intersphinx'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # Napoleon settings napoleon_google_docstring = False napoleon_numpy_docstring = True # autodoc settings autoclass_content = 'both' autodoc_mock_imports = ['torch', 'torch.nn', 'numpy', 'torchvision'] intersphinx_mapping = { 'python': ('https://docs.python.org/', None), 'numpy': ('http://docs.scipy.org/doc/numpy/', None), 'torch': ('https://pytorch.org/docs/stable/', None) } mathjax_path = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" mathjax_config = { 'extensions': ['tex2jax.js'], 'jax': ['input/TeX', 'output/HTML-CSS'], } # General information about the project. project = u'MemCNN' copyright = u"2019, Sil van de Leemput" author = u"Sil van de Leemput" # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. version = memcnn_version # The full version, including alpha/beta/rc tags. release = memcnn_version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # -- Options for HTMLHelp output --------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'memcnndoc' # -- Options for LaTeX output ------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto, manual, or own class]). latex_documents = [ (master_doc, 'memcnn.tex', u'MemCNN Documentation', u'Sil van de Leemput', 'manual'), ] # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'memcnn', u'MemCNN Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'memcnn', u'MemCNN Documentation', author, 'memcnn', 'A PyTorch framework for developing memory efficient deep invertible networks.', 'Miscellaneous'), ]
memcnn-master
docs/conf.py
from setuptools import setup, find_packages setup( name = 'logavgexp-pytorch', packages = find_packages(exclude=[]), version = '0.0.6', license='MIT', description = 'LogAvgExp - Pytorch', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', url = 'https://github.com/lucidrains/logavgexp-pytorch', keywords = [ 'artificial intelligence', 'deep learning', 'pytorch', 'logsumexp' ], install_requires=[ 'einops>=0.4.1', 'torch>=1.6', 'unfoldNd' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
logavgexp-torch-main
setup.py
from logavgexp_pytorch.logavgexp_pytorch import logavgexp, LogAvgExp, LogAvgExp2D, LogAvgExp3D
logavgexp-torch-main
logavgexp_pytorch/__init__.py
import math from functools import partial import torch from torch import nn import torch.nn.functional as F from einops import rearrange from unfoldNd import unfoldNd # helper functions def exists(t): return t is not None def log(t, eps = 1e-20): return torch.log(t + eps) def cast_tuple(t, length = 1): return t if isinstance(t, tuple) else ((t,) * length) def calc_conv_output(shape, kernel_size, padding, stride): return tuple(map(lambda x: int((x[0] - x[1] + 2 * x[2]) / x[3] + 1), zip(shape, kernel_size, padding, stride))) # main function def logavgexp( t, mask = None, dim = -1, eps = 1e-20, temp = 0.01, keepdim = False ): if exists(mask): mask_value = -torch.finfo(t.dtype).max t = t.masked_fill(~mask, mask_value) n = mask.sum(dim = dim) norm = torch.log(n) else: n = t.shape[dim] norm = math.log(n) t = t / temp max_t = t.amax(dim = dim).detach() t_exp = (t - max_t.unsqueeze(dim)).exp() avg_exp = t_exp.sum(dim = dim).clamp(min = eps) / n out = log(avg_exp, eps = eps) + max_t - norm out = out * temp out = out.unsqueeze(dim) if keepdim else out return out # learned temperature - logavgexp class class LogAvgExp(nn.Module): def __init__( self, dim = -1, eps = 1e-20, temp = 0.01, keepdim = False, learned_temp = False ): super().__init__() assert temp >= 0 and temp <= 1., 'temperature must be between 0 and 1' self.learned_temp = learned_temp if learned_temp: self.temp = nn.Parameter(torch.ones((1,)) * math.log(temp)) else: self.temp = temp self.dim = dim self.keepdim = keepdim def forward(self, x, mask = None, eps = 1e-8): if not self.learned_temp: temp = self.temp else: temp = self.temp.exp().clamp(min = eps) return logavgexp( x, mask = mask, dim = self.dim, temp = temp, keepdim = self.keepdim ) # logavgexp 2d class LogAvgExp2D(nn.Module): def __init__( self, kernel_size, *, padding = 0, stride = 1, temp = 0.01, learned_temp = True, eps = 1e-20, **kwargs ): super().__init__() self.padding = cast_tuple(padding, 2) self.stride = cast_tuple(stride, 2) self.kernel_size = cast_tuple(kernel_size, 2) self.unfold = nn.Unfold(self.kernel_size, padding = self.padding, stride = self.stride) self.logavgexp = LogAvgExp(dim = -1, eps = eps, learned_temp = learned_temp, temp = temp) def forward(self, x): """ b - batch c - channels h - height w - width j - reducing dimension """ b, c, h, w = x.shape out_h, out_w = calc_conv_output((h, w), self.kernel_size, self.padding, self.stride) # calculate mask for padding, if needed mask = None if any([i > 0 for i in self.padding]): mask = torch.ones((b, 1, h, w), device = x.device) mask = self.unfold(mask) mask = rearrange(mask, 'b j (h w) -> b 1 h w j', h = out_h, w = out_w) mask = mask == 1. x = self.unfold(x) x = rearrange(x, 'b (c j) (h w) -> b c h w j', h = out_h, w = out_w, c = c) return self.logavgexp(x, mask = mask) # logavgexp 3d class LogAvgExp3D(nn.Module): def __init__( self, kernel_size, *, padding = 0, stride = 1, temp = 0.01, learned_temp = True, eps = 1e-20, **kwargs ): super().__init__() self.padding = cast_tuple(padding, 3) self.stride = cast_tuple(stride, 3) self.kernel_size = cast_tuple(kernel_size, 3) self.unfold = partial(unfoldNd, kernel_size = self.kernel_size, padding = self.padding, stride = self.stride) self.logavgexp = LogAvgExp(dim = -1, eps = eps, learned_temp = learned_temp, temp = temp) def forward(self, x): """ b - batch c - channels f - depth h - height w - width j - reducing dimension """ b, c, f, h, w = x.shape out_f, out_h, out_w = calc_conv_output((f, h, w), self.kernel_size, self.padding, self.stride) # calculate mask for padding, if needed mask = None if any([i > 0 for i in self.padding]): mask = torch.ones((b, 1, f, h, w), device = x.device) mask = self.unfold(mask) mask = rearrange(mask, 'b j (f h w) -> b 1 f h w j', f = out_f, h = out_h, w = out_w) mask = mask == 1. x = self.unfold(x) x = rearrange(x, 'b (c j) (f h w) -> b c f h w j', f = out_f, h = out_h, w = out_w, c = c) return self.logavgexp(x, mask = mask)
logavgexp-torch-main
logavgexp_pytorch/logavgexp_pytorch.py
from setuptools import setup, find_packages setup( name = 'lie-transformer-pytorch', packages = find_packages(), version = '0.0.17', license='MIT', description = 'Lie Transformer - Pytorch', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', url = 'https://github.com/lucidrains/lie-transformer-pytorch', keywords = [ 'artificial intelligence', 'attention mechanism', 'transformers', 'equivariance', 'lifting', 'lie groups' ], install_requires=[ 'torch>=1.6', 'einops>=0.3' ], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
lie-transformer-pytorch-main
setup.py
import torch from lie_transformer_pytorch import LieTransformer def test_transformer(): model = LieTransformer( dim = 512, depth = 1 ) feats = torch.randn(1, 64, 512) coors = torch.randn(1, 64, 3) mask = torch.ones(1, 64).bool() out = model(feats, coors, mask = mask) assert out.shape == (1, 256, 512), 'transformer runs'
lie-transformer-pytorch-main
tests.py
import torch import torch.nn as nn from torch.autograd.function import Function from torch.utils.checkpoint import get_device_states, set_device_states # helpers def sum_tuple(x, y, dim = 1): x = list(x) x[dim] += y[dim] return tuple(x) def subtract_tuple(x, y, dim = 1): x = list(x) x[dim] -= y[dim] return tuple(x) def set_tuple(x, dim, value): x = list(x).copy() x[dim] = value return tuple(x) def map_tuple(fn, x, dim = 1): x = list(x) x[dim] = fn(x[dim]) return tuple(x) def chunk_tuple(fn, x, dim = 1): x = list(x) value = x[dim] chunks = fn(value) return tuple(map(lambda t: set_tuple(x, 1, t), chunks)) def cat_tuple(x, y, dim = 1, cat_dim = -1): x = list(x) y = list(y) x[dim] = torch.cat((x[dim], y[dim]), dim = cat_dim) return tuple(x) def del_tuple(x): for el in x: if el is not None: del el # following example for saving and setting rng here https://pytorch.org/docs/stable/_modules/torch/utils/checkpoint.html class Deterministic(nn.Module): def __init__(self, net): super().__init__() self.net = net self.cpu_state = None self.cuda_in_fwd = None self.gpu_devices = None self.gpu_states = None def record_rng(self, *args): self.cpu_state = torch.get_rng_state() if torch.cuda._initialized: self.cuda_in_fwd = True self.gpu_devices, self.gpu_states = get_device_states(*args) def forward(self, *args, record_rng = False, set_rng = False, **kwargs): if record_rng: self.record_rng(*args) if not set_rng: return self.net(*args, **kwargs) rng_devices = [] if self.cuda_in_fwd: rng_devices = self.gpu_devices with torch.random.fork_rng(devices=rng_devices, enabled=True): torch.set_rng_state(self.cpu_state) if self.cuda_in_fwd: set_device_states(self.gpu_devices, self.gpu_states) return self.net(*args, **kwargs) # heavily inspired by https://github.com/RobinBruegger/RevTorch/blob/master/revtorch/revtorch.py # once multi-GPU is confirmed working, refactor and send PR back to source class ReversibleBlock(nn.Module): def __init__(self, f, g): super().__init__() self.f = Deterministic(f) self.g = Deterministic(g) def forward(self, x, f_args = {}, g_args = {}): training = self.training x1, x2 = chunk_tuple(lambda t: torch.chunk(t, 2, dim=2), x) y1, y2 = None, None with torch.no_grad(): y1 = sum_tuple(self.f(x2, record_rng = training, **f_args), x1) y2 = sum_tuple(self.g(y1, record_rng = training, **g_args), x2) return cat_tuple(y1, y2, cat_dim = 2) def backward_pass(self, y, dy, f_args = {}, g_args = {}): y1, y2 = chunk_tuple(lambda t: torch.chunk(t, 2, dim=2), y) del_tuple(y) dy1, dy2 = torch.chunk(dy, 2, dim=2) del dy with torch.enable_grad(): y1[1].requires_grad = True gy1 = self.g(y1, set_rng=True, **g_args) torch.autograd.backward(gy1[1], dy2) with torch.no_grad(): x2 = subtract_tuple(y2, gy1) del_tuple(y2) del gy1 dx1 = dy1 + y1[1].grad del dy1 y1[1].grad = None with torch.enable_grad(): x2[1].requires_grad = True fx2 = self.f(x2, set_rng = True, **f_args) torch.autograd.backward(fx2[1], dx1) with torch.no_grad(): x1 = subtract_tuple(y1, fx2) del fx2 del_tuple(y1) dx2 = dy2 + x2[1].grad del dy2 x2[1].grad = None x2 = map_tuple(lambda t: t.detach(), x2) x = cat_tuple(x1, x2, cat_dim = -1) dx = torch.cat((dx1, dx2), dim=2) return x, dx class _ReversibleFunction(Function): @staticmethod def forward(ctx, x, blocks, kwargs): ctx.kwargs = kwargs x = (kwargs.pop('coords'), x, kwargs.pop('mask'), kwargs.pop('edges')) for block in blocks: x = block(x, **kwargs) ctx.y = map_tuple(lambda t: t.detach(), x, dim = 1) ctx.blocks = blocks return x[1] @staticmethod def backward(ctx, dy): y = ctx.y kwargs = ctx.kwargs for block in ctx.blocks[::-1]: y, dy = block.backward_pass(y, dy, **kwargs) return dy, None, None class SequentialSequence(nn.Module): def __init__(self, blocks): super().__init__() self.blocks = blocks def forward(self, x): for (f, g) in self.blocks: x = sum_tuple(f(x), x, dim = 1) x = sum_tuple(g(x), x, dim = 1) return x class ReversibleSequence(nn.Module): def __init__(self, blocks): super().__init__() self.blocks = nn.ModuleList([ReversibleBlock(f, g) for (f, g) in blocks]) def forward(self, x, **kwargs): x = map_tuple(lambda t: torch.cat((t, t), dim = -1), x) blocks = self.blocks coords, values, mask, edges = x kwargs = {'coords': coords, 'mask': mask, 'edges': edges, **kwargs} x = _ReversibleFunction.apply(values, blocks, kwargs) x = (coords, x, mask, edges) return map_tuple(lambda t: sum(t.chunk(2, dim = -1)) * 0.5, x)
lie-transformer-pytorch-main
lie_transformer_pytorch/reversible.py
from math import pi import torch from functools import wraps from torch import acos, atan2, cos, sin from einops import rearrange, repeat # constants THRES = 7e-2 # helper functions def exists(val): return val is not None def to(t): return {'device': t.device, 'dtype': t.dtype} def taylor(thres): def outer(fn): @wraps(fn) def inner(x): usetaylor = x.abs() < THRES taylor_expanded, full = fn(x, x * x) return torch.where(usetaylor, taylor_expanded, full) return inner return outer # Helper functions for analytic exponential maps. Uses taylor expansions near x=0 # See http://ethaneade.com/lie_groups.pdf for derivations. @taylor(THRES) def sinc(x, x2): """ sin(x)/x """ texpand = 1-x2/6*(1-x2/20*(1-x2/42)) full = sin(x) / x return texpand, full @taylor(THRES) def sincc(x, x2): """ (1-sinc(x))/x^2""" texpand = 1/6*(1-x2/20*(1-x2/42*(1-x2/72))) full = (x-sin(x)) / x**3 return texpand, full @taylor(THRES) def cosc(x, x2): """ (1-cos(x))/x^2""" texpand = 1/2*(1-x2/12*(1-x2/30*(1-x2/56))) full = (1-cos(x)) / x2 return texpand, full @taylor(THRES) def coscc(x, x2): #assert not torch.any(torch.isinf(x2)), f"infs in x2 log" texpand = 1/12*(1+x2/60*(1+x2/42*(1+x2/40))) costerm = (2*(1-cos(x))).clamp(min=1e-6) full = (1-x*sin(x)/costerm) / x2 #Nans can come up here when cos = 1 return texpand, full @taylor(THRES) def sinc_inv(x, _): texpand = 1+(1/6)*x**2 +(7/360)*x**4 full = x / sin(x) assert not torch.any(torch.isinf(texpand)|torch.isnan(texpand)),'sincinv texpand inf'+torch.any(torch.isinf(texpand)) return texpand, full ## Lie Groups acting on R3 # Hodge star on R3 def cross_matrix(k): """Application of hodge star on R3, mapping Λ^1 R3 -> Λ^2 R3""" K = torch.zeros(*k.shape[:-1], 3, 3, **to(k)) K[...,0,1] = -k[...,2] K[...,0,2] = k[...,1] K[...,1,0] = k[...,2] K[...,1,2] = -k[...,0] K[...,2,0] = -k[...,1] K[...,2,1] = k[...,0] return K def uncross_matrix(K): """Application of hodge star on R3, mapping Λ^2 R3 -> Λ^1 R3""" k = torch.zeros(*K.shape[:-1], **to(K)) k[...,0] = (K[...,2,1] - K[...,1,2])/2 k[...,1] = (K[...,0,2] - K[...,2,0])/2 k[...,2] = (K[...,1,0] - K[...,0,1])/2 return k class SO3: lie_dim = 3 rep_dim = 3 q_dim = 1 def __init__(self, alpha = .2): super().__init__() self.alpha = alpha def exp(self,w): """ Computes (matrix) exponential Lie algebra elements (in a given basis). ie out = exp(\sum_i a_i A_i) where A_i are the exponential generators of G. Input: [a (*,lie_dim)] where * is arbitrarily shaped Output: [exp(a) (*,rep_dim,rep_dim)] returns the matrix for each.""" """ Rodriguez's formula, assuming shape (*,3) where components 1,2,3 are the generators for xrot,yrot,zrot""" theta = w.norm(dim=-1)[..., None, None] K = cross_matrix(w) I = torch.eye(3, **to(K)) Rs = I + K * sinc(theta) + (K @ K) * cosc(theta) return Rs def log(self,R): """ Computes components in terms of generators rx,ry,rz. Shape (*,3,3)""" """ Computes (matrix) logarithm for collection of matrices and converts to Lie algebra basis. Input [u (*,rep_dim,rep_dim)] Output [coeffs of log(u) in basis (*,d)] """ trR = R[..., 0, 0] + R[..., 1, 1] + R[..., 2, 2] costheta = ((trR-1) / 2).clamp(max=1, min=-1).unsqueeze(-1) theta = acos(costheta) logR = uncross_matrix(R) * sinc_inv(theta) return logR def inv(self,g): """ We can compute the inverse of elements g (*,rep_dim,rep_dim) as exp(-log(g))""" return self.exp(-self.log(g)) def elems2pairs(self,a): """ computes log(e^-b e^a) for all a b pairs along n dimension of input. inputs: [a (bs,n,d)] outputs: [pairs_ab (bs,n,n,d)] """ vinv = self.exp(-a.unsqueeze(-3)) u = self.exp(a.unsqueeze(-2)) return self.log(vinv@u) # ((bs,1,n,d) -> (bs,1,n,r,r))@((bs,n,1,d) -> (bs,n,1,r,r)) def lift(self, x, nsamples, **kwargs): """assumes p has shape (*,n,2), vals has shape (*,n,c), mask has shape (*,n) returns (a,v) with shapes [(*,n*nsamples,lie_dim),(*,n*nsamples,c)""" p, v, m, e = x expanded_a = self.lifted_elems(p,nsamples,**kwargs) # (bs,n*ns,d), (bs,n*ns,qd) nsamples = expanded_a.shape[-2]//m.shape[-1] # expand v and mask like q expanded_v = repeat(v, 'b n c -> b (n m) c', m = nsamples) # (bs,n,c) -> (bs,n,1,c) -> (bs,n,ns,c) -> (bs,n*ns,c) expanded_mask = repeat(m, 'b n -> b (n m)', m = nsamples) # (bs,n) -> (bs,n,ns) -> (bs,n*ns) expanded_e = repeat(e, 'b n1 n2 c -> b (n1 m1) (n2 m2) c', m1 = nsamples, m2 = nsamples) if exists(e) else None # convert from elems to pairs paired_a = self.elems2pairs(expanded_a) #(bs,n*ns,d) -> (bs,n*ns,n*ns,d) embedded_locations = paired_a return (embedded_locations,expanded_v,expanded_mask, expanded_e) class SE3(SO3): lie_dim = 6 rep_dim = 4 q_dim = 0 def __init__(self, alpha=.2, per_point=True): super().__init__() self.alpha = alpha self.per_point = per_point def exp(self,w): dd_kwargs = to(w) theta = w[...,:3].norm(dim=-1)[...,None,None] K = cross_matrix(w[...,:3]) R = super().exp(w[...,:3]) I = torch.eye(3, **dd_kwargs) V = I + cosc(theta)*K + sincc(theta)*(K@K) U = torch.zeros(*w.shape[:-1],4,4, **dd_kwargs) U[...,:3,:3] = R U[...,:3,3] = (V@w[...,3:].unsqueeze(-1)).squeeze(-1) U[...,3,3] = 1 return U def log(self,U): w = super().log(U[..., :3, :3]) I = torch.eye(3, **to(w)) K = cross_matrix(w[..., :3]) theta = w.norm(dim=-1)[..., None, None]#%(2*pi) #theta[theta>pi] -= 2*pi cosccc = coscc(theta) Vinv = I - K/2 + cosccc*(K@K) u = (Vinv @ U[..., :3, 3].unsqueeze(-1)).squeeze(-1) #assert not torch.any(torch.isnan(u)), f"nans in u log {torch.isnan(u).sum()}, {torch.where(torch.isnan(u))}" return torch.cat([w, u], dim=-1) def lifted_elems(self,pt,nsamples): """ pt (bs,n,D) mask (bs,n), per_point specifies whether to use a different group element per atom in the molecule""" #return farthest_lift(self,pt,mask,nsamples,alpha) # same lifts for each point right now bs,n = pt.shape[:2] dd_kwargs = to(pt) q = torch.randn(bs, (n if self.per_point else 1), nsamples, 4, **dd_kwargs) q /= q.norm(dim=-1).unsqueeze(-1) theta_2 = atan2(q[..., 1:].norm(dim=-1),q[..., 0])[..., None] so3_elem = 2 * sinc_inv(theta_2) * q[...,1:] # (sin(x/2)u -> xu) for x angle and u direction se3_elem = torch.cat([so3_elem, torch.zeros_like(so3_elem)], dim=-1) R = self.exp(se3_elem) T = torch.zeros(bs, n, nsamples, 4, 4, **dd_kwargs) # (bs,n,nsamples,4,4) T[..., :, :] = torch.eye(4, **dd_kwargs) T[..., :3, 3] = pt[..., None, :] # (bs,n,1,3) a = self.log(T @ R) # bs, n, nsamples, 6 return a.reshape(bs, n * nsamples, 6) def distance(self,abq_pairs): dist_rot = abq_pairs[...,:3].norm(dim=-1) dist_trans = abq_pairs[...,3:].norm(dim=-1) return dist_rot * self.alpha + (1-self.alpha) * dist_trans
lie-transformer-pytorch-main
lie_transformer_pytorch/se3.py
from lie_transformer_pytorch.lie_transformer_pytorch import LieTransformer
lie-transformer-pytorch-main
lie_transformer_pytorch/__init__.py
import math from functools import partial import torch import torch.nn.functional as F from torch import nn, einsum from lie_transformer_pytorch.se3 import SE3 from einops import rearrange, repeat from lie_transformer_pytorch.reversible import SequentialSequence, ReversibleSequence # helpers def exists(val): return val is not None def cast_tuple(val, depth): return val if isinstance(val, tuple) else ((val,) * depth) def default(val, d): return val if exists(val) else d def batched_index_select(values, indices, dim = 1): value_dims = values.shape[(dim + 1):] values_shape, indices_shape = map(lambda t: list(t.shape), (values, indices)) indices = indices[(..., *((None,) * len(value_dims)))] indices = indices.expand(*((-1,) * len(indices_shape)), *value_dims) value_expand_len = len(indices_shape) - (dim + 1) values = values[(*((slice(None),) * dim), *((None,) * value_expand_len), ...)] value_expand_shape = [-1] * len(values.shape) expand_slice = slice(dim, (dim + value_expand_len)) value_expand_shape[expand_slice] = indices.shape[expand_slice] values = values.expand(*value_expand_shape) dim += value_expand_len return values.gather(dim, indices) # helper classes class Pass(nn.Module): def __init__(self, fn, dim = 1): super().__init__() self.fn = fn self.dim = dim def forward(self,x): dim = self.dim xs = list(x) xs[dim] = self.fn(xs[dim]) return xs class Lambda(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x): return self.fn(x) class GlobalPool(nn.Module): """computes values reduced over all spatial locations (& group elements) in the mask""" def __init__(self, mean = False): super().__init__() self.mean = mean def forward(self, x): coords, vals, mask = x if not exists(mask): return val.mean(dim = 1) masked_vals = vals.masked_fill_(~mask[..., None], 0.) summed = masked_vals.sum(dim = 1) if not self.mean: return summed count = mask.sum(-1).unsqueeze(-1) return summed / count # subsampling code def FPSindices(dists, frac, mask): """ inputs: pairwise distances DISTS (bs,n,n), downsample_frac (float), valid atom mask (bs,n) outputs: chosen_indices (bs,m) """ m = int(round(frac * dists.shape[1])) bs, n, device = *dists.shape[:2], dists.device dd_kwargs = {'device': device, 'dtype': torch.long} B = torch.arange(bs, **dd_kwargs) chosen_indices = torch.zeros(bs, m, **dd_kwargs) distances = torch.ones(bs, n, device=device) * 1e8 a = torch.randint(0, n, (bs,), **dd_kwargs) # choose random start idx = a % mask.sum(-1) + torch.cat([torch.zeros(1, **dd_kwargs), torch.cumsum(mask.sum(-1), dim=0)[:-1]], dim=0) farthest = torch.where(mask)[1][idx] for i in range(m): chosen_indices[:, i] = farthest # add point that is farthest to chosen dist = dists[B, farthest].masked_fill(~mask, -100) # (bs,n) compute distance from new point to all others closer = dist < distances # if dist from new point is smaller than chosen points so far distances[closer] = dist[closer] # update the chosen set's distance to all other points farthest = torch.max(distances, -1)[1] # select the point that is farthest from the set return chosen_indices class FPSsubsample(nn.Module): def __init__(self, ds_frac, cache = False, group = None): super().__init__() self.ds_frac = ds_frac self.cache = cache self.cached_indices = None self.group = default(group, SE3()) def get_query_indices(self, abq_pairs, mask): if self.cache and exists(self.cached_indices): return self.cached_indices dist = self.group.distance if self.group else lambda ab: ab.norm(dim=-1) value = FPSindices(dist(abq_pairs), self.ds_frac, mask).detach() if self.cache: self.cached_indices = value return value def forward(self, inp, withquery=False): abq_pairs, vals, mask, edges = inp device = vals.device if self.ds_frac != 1: query_idx = self.get_query_indices(abq_pairs, mask) B = torch.arange(query_idx.shape[0], device = device).long()[:,None] subsampled_abq_pairs = abq_pairs[B, query_idx][B, :, query_idx] subsampled_values = batched_index_select(vals, query_idx, dim = 1) subsampled_mask = batched_index_select(mask, query_idx, dim = 1) subsampled_edges = edges[B, query_idx][B, :, query_idx] if exists(edges) else None else: subsampled_abq_pairs = abq_pairs subsampled_values = vals subsampled_mask = mask subsampled_edges = edges query_idx = None ret = ( subsampled_abq_pairs, subsampled_values, subsampled_mask, subsampled_edges ) if withquery: ret = (*ret, query_idx) return ret # lie attention class LieSelfAttention(nn.Module): def __init__( self, dim, edge_dim = None, group = None, mc_samples = 32, ds_frac = 1, fill = 1 / 3, dim_head = 64, heads = 8, cache = False ): super().__init__() self.dim = dim self.mc_samples = mc_samples # number of samples to use to estimate convolution self.group = default(group, SE3()) # Equivariance group for LieConv self.register_buffer('r',torch.tensor(2.)) # Internal variable for local_neighborhood radius, set by fill self.fill_frac = min(fill, 1.) # Average Fraction of the input which enters into local_neighborhood, determines r self.subsample = FPSsubsample(ds_frac, cache = cache, group = self.group) self.coeff = .5 # Internal coefficient used for updating r self.fill_frac_ema = fill # Keeps track of average fill frac, used for logging only # attention related parameters inner_dim = dim_head * heads self.heads = heads self.to_q = nn.Linear(dim, inner_dim, bias = False) self.to_k = nn.Linear(dim, inner_dim, bias = False) self.to_v = nn.Linear(dim, inner_dim, bias = False) self.to_out = nn.Linear(inner_dim, dim) edge_dim = default(edge_dim, 0) edge_dim_in = self.group.lie_dim + edge_dim self.loc_attn_mlp = nn.Sequential( nn.Linear(edge_dim_in, edge_dim_in * 4), nn.ReLU(), nn.Linear(edge_dim_in * 4, 1), ) def extract_neighborhood(self, inp, query_indices): """ inputs: [pairs_abq (bs,n,n,d), inp_vals (bs,n,c), mask (bs,n), query_indices (bs,m)] outputs: [neighbor_abq (bs,m,mc_samples,d), neighbor_vals (bs,m,mc_samples,c)]""" # Subsample pairs_ab, inp_vals, mask to the query_indices pairs_abq, inp_vals, mask, edges = inp device = inp_vals.device if exists(query_indices): abq_at_query = batched_index_select(pairs_abq, query_indices, dim = 1) mask_at_query = batched_index_select(mask, query_indices, dim = 1) edges_at_query = batched_index_select(edges, query_indices, dim = 1) if exists(edges) else None else: abq_at_query = pairs_abq mask_at_query = mask edges_at_query = edges mask_at_query = mask_at_query[..., None] vals_at_query = inp_vals dists = self.group.distance(abq_at_query) #(bs,m,n,d) -> (bs,m,n) mask_value = torch.finfo(dists.dtype).max dists = dists.masked_fill(mask[:,None,:], mask_value) k = min(self.mc_samples, inp_vals.shape[1]) # NBHD: Sampled Distance Ball bs, m, n = dists.shape within_ball = (dists < self.r) & mask[:,None,:] & mask_at_query # (bs,m,n) noise = torch.zeros((bs, m, n), device = device).uniform_(0, 1) valid_within_ball, nbhd_idx = torch.topk(within_ball + noise, k, dim=-1, sorted=False) valid_within_ball = (valid_within_ball > 1) # Retrieve abq_pairs, values, and mask at the nbhd locations nbhd_abq = batched_index_select(abq_at_query, nbhd_idx, dim = 2) nbhd_vals = batched_index_select(vals_at_query, nbhd_idx, dim = 1) nbhd_mask = batched_index_select(mask, nbhd_idx, dim = 1) nbhd_edges = batched_index_select(edges_at_query, nbhd_idx, dim = 2) if exists(edges) else None if self.training: # update ball radius to match fraction fill_frac inside navg = (within_ball.float()).sum(-1).sum() / mask_at_query.sum() avg_fill = (navg / mask.sum(-1).float().mean()).cpu().item() self.r += self.coeff * (self.fill_frac - avg_fill) self.fill_frac_ema += .1 * (avg_fill-self.fill_frac_ema) nbhd_mask &= valid_within_ball.bool() return nbhd_abq, nbhd_vals, nbhd_mask, nbhd_edges, nbhd_idx def forward(self, inp): """inputs: [pairs_abq (bs,n,n,d)], [inp_vals (bs,n,ci)]), [query_indices (bs,m)] outputs [subsampled_abq (bs,m,m,d)], [convolved_vals (bs,m,co)]""" sub_abq, sub_vals, sub_mask, sub_edges, query_indices = self.subsample(inp, withquery = True) nbhd_abq, nbhd_vals, nbhd_mask, nbhd_edges, nbhd_indices = self.extract_neighborhood(inp, query_indices) h, b, n, d, device = self.heads, *sub_vals.shape, sub_vals.device q, k, v = self.to_q(sub_vals), self.to_k(nbhd_vals), self.to_v(nbhd_vals) q = rearrange(q, 'b n (h d) -> b h n d', h = h) k, v = map(lambda t: rearrange(t, 'b n m (h d) -> b h n m d', h = h), (k, v)) sim = einsum('b h i d, b h i j d -> b h i j', q, k) * (q.shape[-1] ** -0.5) edges = nbhd_abq if exists(nbhd_edges): edges = torch.cat((nbhd_abq, nbhd_edges), dim = -1) loc_attn = self.loc_attn_mlp(edges) loc_attn = rearrange(loc_attn, 'b i j () -> b () i j') sim = sim + loc_attn mask_value = -torch.finfo(sim.dtype).max sim.masked_fill_(~rearrange(nbhd_mask, 'b n m -> b () n m'), mask_value) attn = sim.softmax(dim = -1) out = einsum('b h i j, b h i j d -> b h i d', attn, v) out = rearrange(out, 'b h n d -> b n (h d)', h = h) combined = self.to_out(out) return sub_abq, combined, sub_mask, sub_edges class LieSelfAttentionWrapper(nn.Module): def __init__(self, dim, attn): super().__init__() self.dim = dim self.attn = attn self.net = nn.Sequential( Pass(nn.LayerNorm(dim)), self.attn ) def forward(self, inp): sub_coords, sub_values, mask, edges = self.attn.subsample(inp) new_coords, new_values, mask, edges = self.net(inp) new_values[..., :self.dim] += sub_values return new_coords, new_values, mask, edges class FeedForward(nn.Module): def __init__(self, dim, mult = 4): super().__init__() self.dim = dim self.net = nn.Sequential( Pass(nn.LayerNorm(dim)), Pass(nn.Linear(dim, mult * dim)), Pass(nn.GELU()), Pass(nn.Linear(mult * dim, dim)), ) def forward(self,inp): sub_coords, sub_values, mask, edges = inp new_coords, new_values, mask, edges = self.net(inp) new_values = new_values + sub_values return new_coords, new_values, mask, edges # transformer class class LieTransformer(nn.Module): """ [Fill] specifies the fraction of the input which is included in local neighborhood. (can be array to specify a different value for each layer) [nbhd] number of samples to use for Monte Carlo estimation (p) [dim] number of input channels: 1 for MNIST, 3 for RGB images, other for non images [ds_frac] total downsampling to perform throughout the layers of the net. In (0,1) [num_layers] number of BottleNeck Block layers in the network [k] channel width for the network. Can be int (same for all) or array to specify individually. [liftsamples] number of samples to use in lifting. 1 for all groups with trivial stabilizer. Otherwise 2+ [Group] Chosen group to be equivariant to. """ def __init__( self, dim, num_tokens = None, num_edge_types = None, edge_dim = None, heads = 8, dim_head = 64, depth = 2, ds_frac = 1., dim_out = None, k = 1536, nbhd = 128, mean = True, per_point = True, liftsamples = 4, fill = 1 / 4, cache = False, reversible = False, **kwargs ): super().__init__() assert not (ds_frac < 1 and reversible), 'must not downsample if network is reversible' dim_out = default(dim_out, dim) self.token_emb = nn.Embedding(num_tokens, dim) if exists(num_tokens) else None self.edge_emb = nn.Embedding(num_edge_types, edge_dim) if exists(num_edge_types) else None group = SE3() self.group = group self.liftsamples = liftsamples layers_fill = cast_tuple(fill, depth) layers = nn.ModuleList([]) for _, layer_fill in zip(range(depth), layers_fill): layers.append(nn.ModuleList([ LieSelfAttentionWrapper(dim, LieSelfAttention(dim, heads = heads, dim_head = dim_head, edge_dim = edge_dim, mc_samples = nbhd, ds_frac = ds_frac, group = group, fill = fill, cache = cache,**kwargs)), FeedForward(dim) ])) execute_class = ReversibleSequence if reversible else SequentialSequence self.net = execute_class(layers) self.to_logits = nn.Sequential( Pass(nn.LayerNorm(dim)), Pass(nn.Linear(dim, dim_out)) ) self.pool = GlobalPool(mean = mean) def forward(self, feats, coors, edges = None, mask = None, return_pooled = False): b, n, *_ = feats.shape if exists(self.token_emb): feats = self.token_emb(feats) if exists(self.edge_emb): assert exists(edges), 'edges must be passed in on forward' assert edges.shape[1] == edges.shape[2] and edges.shape[1] == n, f'edges must be of the shape ({b}, {n}, {n})' edges = self.edge_emb(edges) inps = (coors, feats, mask, edges) lifted_x = self.group.lift(inps, self.liftsamples) out = self.net(lifted_x) out = self.to_logits(out) if not return_pooled: features = out[1] return features return self.pool(out)
lie-transformer-pytorch-main
lie_transformer_pytorch/lie_transformer_pytorch.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. import torch.autograd as autograd import torch.nn as nn from util import * import torch.nn.utils.rnn as rnn_utils import time import numpy as np import openprotein # seed random generator for reproducibility torch.manual_seed(1) # sample model borrowed from # https://github.com/lblaabjerg/Master/blob/master/Models%20and%20processed%20data/ProteinNet_LSTM_500.py class ExampleModel(openprotein.BaseModel): def __init__(self, embedding_size, minibatch_size, use_gpu): super(ExampleModel, self).__init__(use_gpu, embedding_size) self.hidden_size = 25 self.num_lstm_layers = 2 self.mixture_size = 500 self.bi_lstm = nn.LSTM(self.get_embedding_size(), self.hidden_size, num_layers=self.num_lstm_layers, bidirectional=True, bias=True) self.hidden_to_labels = nn.Linear(self.hidden_size * 2, self.mixture_size, bias=True) # * 2 for bidirectional self.init_hidden(minibatch_size) self.softmax_to_angle = soft_to_angle(self.mixture_size) self.soft = nn.LogSoftmax(2) self.bn = nn.BatchNorm1d(self.mixture_size) def init_hidden(self, minibatch_size): # number of layers (* 2 since bidirectional), minibatch_size, hidden size initial_hidden_state = torch.zeros(self.num_lstm_layers * 2, minibatch_size, self.hidden_size) initial_cell_state = torch.zeros(self.num_lstm_layers * 2, minibatch_size, self.hidden_size) if self.use_gpu: initial_hidden_state = initial_hidden_state.cuda() initial_cell_state = initial_cell_state.cuda() self.hidden_layer = (autograd.Variable(initial_hidden_state), autograd.Variable(initial_cell_state)) def _get_network_emissions(self, original_aa_string): packed_input_sequences = self.embed(original_aa_string) minibatch_size = int(packed_input_sequences[1][0]) self.init_hidden(minibatch_size) (data, bi_lstm_batches, _, _), self.hidden_layer = self.bi_lstm(packed_input_sequences, self.hidden_layer) emissions_padded, batch_sizes = torch.nn.utils.rnn.pad_packed_sequence( torch.nn.utils.rnn.PackedSequence(self.hidden_to_labels(data), bi_lstm_batches)) x = emissions_padded.transpose(0,1).transpose(1,2) # minibatch_size, self.mixture_size, -1 x = self.bn(x) x = x.transpose(1,2) #(minibatch_size, -1, self.mixture_size) p = torch.exp(self.soft(x)) output_angles = self.softmax_to_angle(p).transpose(0,1) # max size, minibatch size, 3 (angels) backbone_atoms_padded, batch_sizes_backbone = get_backbone_positions_from_angular_prediction(output_angles, batch_sizes, self.use_gpu) return output_angles, backbone_atoms_padded, batch_sizes class soft_to_angle(nn.Module): def __init__(self, mixture_size): super(soft_to_angle, self).__init__() # Omega intializer omega_components1 = np.random.uniform(0, 1, int(mixture_size * 0.1)) # Initialize omega 90/10 pos/neg omega_components2 = np.random.uniform(2, math.pi, int(mixture_size * 0.9)) omega_components = np.concatenate((omega_components1, omega_components2)) np.random.shuffle(omega_components) phi_components = np.genfromtxt("data/mixture_model_pfam_"+str(mixture_size)+".txt")[:, 1] psi_components = np.genfromtxt("data/mixture_model_pfam_"+str(mixture_size)+".txt")[:, 2] self.phi_components = nn.Parameter(torch.from_numpy(phi_components).contiguous().view(-1, 1).float()) self.psi_components = nn.Parameter(torch.from_numpy(psi_components).contiguous().view(-1, 1).float()) self.omega_components = nn.Parameter(torch.from_numpy(omega_components).view(-1, 1).float()) def forward(self, x): phi_input_sin = torch.matmul(x, torch.sin(self.phi_components)) phi_input_cos = torch.matmul(x, torch.cos(self.phi_components)) psi_input_sin = torch.matmul(x, torch.sin(self.psi_components)) psi_input_cos = torch.matmul(x, torch.cos(self.psi_components)) omega_input_sin = torch.matmul(x, torch.sin(self.omega_components)) omega_input_cos = torch.matmul(x, torch.cos(self.omega_components)) eps = 10 ** (-4) phi = torch.atan2(phi_input_sin, phi_input_cos + eps) psi = torch.atan2(psi_input_sin, psi_input_cos + eps) omega = torch.atan2(omega_input_sin, omega_input_cos + eps) return torch.cat((phi, psi, omega), 2) class RrnModel(openprotein.BaseModel): def __init__(self, embedding_size, minibatch_size, use_gpu): super(RrnModel, self).__init__(use_gpu, embedding_size) self.recurrent_steps = 2 self.hidden_size = 50 self.msg_output_size = 50 self.output_size = 9 # 3 dimensions * 3 coordinates for each aa self.f_to_hid = nn.Linear((embedding_size*2 + 9), self.hidden_size, bias=True) self.hid_to_pos = nn.Linear(self.hidden_size, self.msg_output_size, bias=True) self.g = nn.Linear(embedding_size + 9 + self.msg_output_size, 9, bias=True) # (last state + orginal state) self.use_gpu = use_gpu def f(self, aa_features): # aa_features: msg_count * 2 * feature_count min_distance = torch.tensor(0.000001) if self.use_gpu: min_distance = min_distance.cuda() aa_features_transformed = torch.cat( ( aa_features[:,0,0:21], aa_features[:,1,0:21], aa_features[:,0,21:30] - aa_features[:,1,21:30] ), dim=1) return self.hid_to_pos(self.f_to_hid(aa_features_transformed)) # msg_count * outputsize def _get_network_emissions(self, original_aa_string): initial_aa_pos = intial_pos_from_aa_string(original_aa_string) packed_input_sequences = self.embed(original_aa_string) backbone_atoms_padded, batch_sizes_backbone = structures_to_backbone_atoms_padded(initial_aa_pos) if self.use_gpu: backbone_atoms_padded = backbone_atoms_padded.cuda() embedding_padded, batch_sizes = torch.nn.utils.rnn.pad_packed_sequence( torch.nn.utils.rnn.PackedSequence(packed_input_sequences)) for i in range(self.recurrent_steps): combined_features = torch.cat((embedding_padded,backbone_atoms_padded),dim=2) for idx, aa_features in enumerate(combined_features.transpose(0,1)): msg = pass_messages(aa_features, self.f, self.use_gpu) # aa_count * output size backbone_atoms_padded[:,idx] = self.g(torch.cat((aa_features, msg), dim=1)) output, batch_sizes = calculate_dihedral_angles_over_minibatch(original_aa_string, backbone_atoms_padded, batch_sizes_backbone, self.use_gpu) return output, backbone_atoms_padded, batch_sizes
openprotein-master
models.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. import torch import torch.utils.data import h5py from datetime import datetime import PeptideBuilder import Bio.PDB import math import numpy as np import os import pnerf.pnerf as pnerf AA_ID_DICT = {'A': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'K': 9, 'L': 10, 'M': 11, 'N': 12, 'P': 13, 'Q': 14, 'R': 15, 'S': 16, 'T': 17, 'V': 18, 'W': 19,'Y': 20} def contruct_dataloader_from_disk(filename, minibatch_size): return torch.utils.data.DataLoader(H5PytorchDataset(filename), batch_size=minibatch_size, shuffle=True, collate_fn=H5PytorchDataset.merge_samples_to_minibatch) class H5PytorchDataset(torch.utils.data.Dataset): def __init__(self, filename): super(H5PytorchDataset, self).__init__() self.h5pyfile = h5py.File(filename, 'r') self.num_proteins, self.max_sequence_len = self.h5pyfile['primary'].shape def __getitem__(self, index): mask = torch.Tensor(self.h5pyfile['mask'][index,:]).type(dtype=torch.uint8) prim = torch.masked_select(torch.Tensor(self.h5pyfile['primary'][index,:]).type(dtype=torch.long), mask) tertiary = torch.Tensor(self.h5pyfile['tertiary'][index][:int(mask.sum())]) # max length x 9 return prim, tertiary, mask def __len__(self): return self.num_proteins def merge_samples_to_minibatch(samples): samples_list = [] for s in samples: samples_list.append(s) # sort according to length of aa sequence samples_list.sort(key=lambda x: len(x[0]), reverse=True) return zip(*samples_list) def set_experiment_id(data_set_identifier, learning_rate, minibatch_size): output_string = datetime.now().strftime('%Y-%m-%d_%H_%M_%S') output_string += "-" + str(os.getpid()) output_string += "-" + data_set_identifier output_string += "-LR" + str(learning_rate).replace(".","_") output_string += "-MB" + str(minibatch_size) globals().__setitem__("experiment_id",output_string) def get_experiment_id(): return globals().get("experiment_id") def write_out(*args, end='\n'): output_string = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ": " + str.join(" ", [str(a) for a in args]) + end if globals().get("experiment_id") is not None: with open("output/"+globals().get("experiment_id")+".txt", "a+") as output_file: output_file.write(output_string) output_file.flush() print(output_string, end="") def write_model_to_disk(model): path = "output/models/"+globals().get("experiment_id")+".model" torch.save(model,path) return path def write_prediction_data_to_disk(prediction_data): filepath = "output/predictions/"+globals().get("experiment_id")+".txt" output_file = open(filepath, 'w') output_file.write(prediction_data) output_file.close() def draw_plot(fig, plt, validation_dataset_size, sample_num, train_loss_values, validation_loss_values): def draw_with_vars(): ax = fig.gca() ax2 = ax.twinx() plt.grid(True) plt.title("Training progress (" + str(validation_dataset_size) + " samples in validation set)") train_loss_plot, = ax.plot(sample_num, train_loss_values) ax.set_ylabel('Train Negative log likelihood') ax.yaxis.labelpad = 0 validation_loss_plot, = ax2.plot(sample_num, validation_loss_values, color='black') ax2.set_ylabel('Validation loss') ax2.set_ylim(bottom=0) plt.legend([train_loss_plot, validation_loss_plot], ['Train loss on last batch', 'Validation loss']) ax.set_xlabel('Minibatches processed (=network updates)', color='black') return draw_with_vars def draw_ramachandran_plot(fig, plt, phi, psi): def draw_with_vars(): ax = fig.gca() plt.grid(True) plt.title("Ramachandran plot") train_loss_plot, = ax.plot(phi, psi) ax.set_ylabel('Psi') ax.yaxis.labelpad = 0 plt.legend([train_loss_plot], ['Phi psi']) ax.set_xlabel('Phi', color='black') return draw_with_vars def write_result_summary(accuracy): output_string = globals().get("experiment_id") + ": " + str(accuracy) + "\n" with open("output/result_summary.txt", "a+") as output_file: output_file.write(output_string) output_file.flush() print(output_string, end="") def calculate_dihedral_angles_over_minibatch(atomic_coords_padded, batch_sizes, use_gpu): angles = [] atomic_coords = atomic_coords_padded.transpose(0,1) for idx, _ in enumerate(batch_sizes): angles.append(calculate_dihedral_angles(atomic_coords[idx][:batch_sizes[idx]], use_gpu)) return torch.nn.utils.rnn.pad_packed_sequence( torch.nn.utils.rnn.pack_sequence(angles)) def protein_id_to_str(protein_id_list): _aa_dict_inverse = {v: k for k, v in AA_ID_DICT.items()} aa_list = [] for a in protein_id_list: aa_symbol = _aa_dict_inverse[int(a)] aa_list.append(aa_symbol) return aa_list def calculate_dihedral_angles(atomic_coords, use_gpu): assert int(atomic_coords.shape[1]) == 9 atomic_coords = atomic_coords.contiguous().view(-1,3) zero_tensor = torch.tensor(0.0) if use_gpu: zero_tensor = zero_tensor.cuda() dihedral_list = [zero_tensor,zero_tensor] dihedral_list.extend(compute_dihedral_list(atomic_coords)) dihedral_list.append(zero_tensor) angles = torch.tensor(dihedral_list).view(-1,3) return angles def compute_dihedral_list(atomic_coords): # atomic_coords is -1 x 3 ba = atomic_coords[1:] - atomic_coords[:-1] ba /= ba.norm(dim=1).unsqueeze(1) ba_neg = -1 * ba n1_vec = torch.cross(ba[:-2], ba_neg[1:-1], dim=1) n2_vec = torch.cross(ba_neg[1:-1], ba[2:], dim=1) n1_vec /= n1_vec.norm(dim=1).unsqueeze(1) n2_vec /= n2_vec.norm(dim=1).unsqueeze(1) m1_vec = torch.cross(n1_vec, ba_neg[1:-1], dim=1) x = torch.sum(n1_vec*n2_vec,dim=1) y = torch.sum(m1_vec*n2_vec,dim=1) return torch.atan2(y,x) def get_structure_from_angles(aa_list_encoded, angles): aa_list = protein_id_to_str(aa_list_encoded) omega_list = angles[1:,0] phi_list = angles[1:,1] psi_list = angles[:-1,2] assert len(aa_list) == len(phi_list)+1 == len(psi_list)+1 == len(omega_list)+1 structure = PeptideBuilder.make_structure(aa_list, list(map(lambda x: math.degrees(x), phi_list)), list(map(lambda x: math.degrees(x), psi_list)), list(map(lambda x: math.degrees(x), omega_list))) return structure def write_to_pdb(structure, prot_id): out = Bio.PDB.PDBIO() out.set_structure(structure) out.save("output/protein_" + str(prot_id) + ".pdb") def calc_pairwise_distances(chain_a, chain_b, use_gpu): distance_matrix = torch.Tensor(chain_a.size()[0], chain_b.size()[0]).type(torch.float) # add small epsilon to avoid boundary issues epsilon = 10 ** (-4) * torch.ones(chain_a.size(0), chain_b.size(0)) if use_gpu: distance_matrix = distance_matrix.cuda() epsilon = epsilon.cuda() for i, row in enumerate(chain_a.split(1)): distance_matrix[i] = torch.sum((row.expand_as(chain_b) - chain_b) ** 2, 1).view(1, -1) return torch.sqrt(distance_matrix + epsilon) def calc_drmsd(chain_a, chain_b, use_gpu=False): assert len(chain_a) == len(chain_b) distance_matrix_a = calc_pairwise_distances(chain_a, chain_a, use_gpu) distance_matrix_b = calc_pairwise_distances(chain_b, chain_b, use_gpu) return torch.norm(distance_matrix_a - distance_matrix_b, 2) \ / math.sqrt((len(chain_a) * (len(chain_a) - 1))) # method for translating a point cloud to its center of mass def transpose_atoms_to_center_of_mass(x): # calculate com by summing x, y and z respectively # and dividing by the number of points centerOfMass = np.matrix([[x[0, :].sum() / x.shape[1]], [x[1, :].sum() / x.shape[1]], [x[2, :].sum() / x.shape[1]]]) # translate points to com and return return x - centerOfMass def calc_rmsd(chain_a, chain_b): # move to center of mass a = chain_a.cpu().numpy().transpose() b = chain_b.cpu().numpy().transpose() X = transpose_atoms_to_center_of_mass(a) Y = transpose_atoms_to_center_of_mass(b) R = Y * X.transpose() # extract the singular values _, S, _ = np.linalg.svd(R) # compute RMSD using the formular E0 = sum(list(np.linalg.norm(x) ** 2 for x in X.transpose()) + list(np.linalg.norm(x) ** 2 for x in Y.transpose())) TraceS = sum(S) RMSD = np.sqrt((1 / len(X.transpose())) * (E0 - 2 * TraceS)) return RMSD def calc_angular_difference(a1, a2): a1 = a1.transpose(0,1).contiguous() a2 = a2.transpose(0,1).contiguous() sum = 0 for idx, _ in enumerate(a1): assert a1[idx].shape[1] == 3 assert a2[idx].shape[1] == 3 a1_element = a1[idx].view(-1, 1) a2_element = a2[idx].view(-1, 1) sum += torch.sqrt(torch.mean( torch.min(torch.abs(a2_element - a1_element), 2 * math.pi - torch.abs(a2_element - a1_element) ) ** 2)) return sum / a1.shape[0] def structures_to_backbone_atoms_padded(structures): backbone_atoms_list = [] for structure in structures: backbone_atoms_list.append(structure_to_backbone_atoms(structure)) backbone_atoms_padded, batch_sizes_backbone = torch.nn.utils.rnn.pad_packed_sequence( torch.nn.utils.rnn.pack_sequence(backbone_atoms_list)) return backbone_atoms_padded, batch_sizes_backbone def structure_to_backbone_atoms(structure): predicted_coords = [] for res in structure.get_residues(): predicted_coords.append(torch.Tensor(res["N"].get_coord())) predicted_coords.append(torch.Tensor(res["CA"].get_coord())) predicted_coords.append(torch.Tensor(res["C"].get_coord())) return torch.stack(predicted_coords).view(-1,9) def get_backbone_positions_from_angular_prediction(angular_emissions, batch_sizes, use_gpu): # angular_emissions -1 x minibatch size x 3 (omega, phi, psi) points = pnerf.dihedral_to_point(angular_emissions, use_gpu) coordinates = pnerf.point_to_coordinate(points, use_gpu) / 100 # devide by 100 to angstrom unit return coordinates.transpose(0,1).contiguous().view(len(batch_sizes),-1,9).transpose(0,1), batch_sizes def calc_avg_drmsd_over_minibatch(backbone_atoms_padded, actual_coords_padded, batch_sizes): backbone_atoms_list = list( [backbone_atoms_padded[:batch_sizes[i], i] for i in range(int(backbone_atoms_padded.size(1)))]) actual_coords_list = list( [actual_coords_padded[:batch_sizes[i], i] for i in range(int(actual_coords_padded.size(1)))]) drmsd_avg = 0 for idx, backbone_atoms in enumerate(backbone_atoms_list): actual_coords = actual_coords_list[idx].transpose(0, 1).contiguous().view(-1, 3) drmsd_avg += calc_drmsd(backbone_atoms.transpose(0, 1).contiguous().view(-1, 3), actual_coords) return drmsd_avg / len(backbone_atoms_list) def encode_primary_string(primary): return list([AA_ID_DICT[aa] for aa in primary]) def intial_pos_from_aa_string(batch_aa_string): structures = [] for aa_string in batch_aa_string: structure = get_structure_from_angles(aa_string, np.repeat([-120], len(aa_string)-1), np.repeat([140], len(aa_string)-1), np.repeat([-370], len(aa_string)-1)) structures.append(structure) return structures def pass_messages(aa_features, message_transformation, use_gpu): # aa_features (#aa, #features) - each row represents the amino acid type (embedding) and the positions of the backbone atoms # message_transformation: (-1 * 2 * feature_size) -> (-1 * output message size) feature_size = aa_features.size(1) aa_count = aa_features.size(0) eye = torch.eye(aa_count,dtype=torch.uint8).view(-1).expand(2,feature_size,-1).transpose(1,2).transpose(0,1) eye_inverted = torch.ones(eye.size(),dtype=torch.uint8) - eye if use_gpu: eye_inverted = eye_inverted.cuda() features_repeated = aa_features.repeat((aa_count,1)).view((aa_count,aa_count,feature_size)) aa_messages = torch.stack((features_repeated.transpose(0,1), features_repeated)).transpose(0,1).transpose(1,2).view(-1,2,feature_size) aa_msg_pairs = torch.masked_select(aa_messages,eye_inverted).view(-1,2,feature_size) # (aa_count^2 - aa_count) x 2 x aa_features (all pairs except for reflexive connections) transformed = message_transformation(aa_msg_pairs).view(aa_count, aa_count - 1, -1) transformed_sum = transformed.sum(dim=1) # aa_count x output message size return transformed_sum def load_model_from_disk(path, force_cpu=True): if force_cpu: # load model with map_location set to storage (main mem) model = torch.load(path, map_location=lambda storage, loc: storage) # flattern parameters in memory model.flatten_parameters() # update internal state accordingly model.use_gpu = False else: # load model using default map_location model = torch.load(path) model.flatten_parameters() return model
openprotein-master
util.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. import torch from util import encode_primary_string, get_structure_from_angles, write_to_pdb, \ calculate_dihedral_angles_over_minibatch input_sequences = ["SRSLVISTINQISEDSKEFYFTLDNGKTMFPSNSQAWGGEKFENGQRAFVIFNELEQPVNGYDYNIQVRDITKVLTKEIVTMDDEENTEEKIGDDKINATYMWISKDKKYLTIEFQYYSTHSEDKKHFLNLVINNKDNTDDEYINLEFRHNSERDSPDHLGEGYVSFKLDKIEEQIEGKKGLNIRVRTLYDGIKNYKVQFP"] model_path = "output/models/2019-01-30_00_38_46-TRAIN-LR0_01-MB1.model" model = torch.load(model_path) input_senquences_encoded = list(torch.LongTensor(encode_primary_string(aa)) for aa in input_sequences) predicted_dihedral_angles, predicted_backbone_atoms, batch_sizes = model(input_senquences_encoded) write_to_pdb( get_structure_from_angles(input_senquences_encoded[0], predicted_dihedral_angles[:,0]), "myprediction" ) print("Wrote prediction to output/protein_myprediction.pdb")
openprotein-master
prediction.py
from preprocessing import * import torch import argparse print("------------------------") print("--- OpenProtein v0.1 ---") print("------------------------") parser = argparse.ArgumentParser(description = "OpenProtein version 0.1") parser.add_argument('--no_force_pre_processing_overwrite', dest='no_force_pre_processing_overwrite', action='store_false', help='Force overwrite existing preprocessed files', default=True) args, unknown = parser.parse_known_args() use_gpu = False if torch.cuda.is_available(): write_out("CUDA is available, using GPU") use_gpu = True process_raw_data(use_gpu, force_pre_processing_overwrite=args.force_pre_processing_overwrite)
openprotein-master
preprocessing_cli.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. from flask import Flask, request, jsonify from flask_cors import CORS, cross_origin import threading app = Flask(__name__) cors = CORS(app) data = None @app.route('/graph',methods=['POST']) def update_graph(): global data data = request.json return jsonify({"result":"OK"}) @app.route('/graph',methods=['GET']) @cross_origin() def get_graph(): return jsonify(data) @app.route('/',methods=['GET']) @cross_origin() def index(): return open("web/index.html","r").read() class graphWebServer (threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): import logging logging.basicConfig(filename="output/app.log", level=logging.DEBUG) app.run(debug=False, host='0.0.0.0') class frontendWebServer (threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): from subprocess import call call(["/bin/bash", "start_web_app.sh"]) def start_dashboard_server(): flask_thread = graphWebServer() flask_thread.start() front_end_thread = frontendWebServer() front_end_thread.start()
openprotein-master
dashboard.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. import glob import os.path import os import platform import numpy as np import h5py from util import AA_ID_DICT, calculate_dihedral_angles, protein_id_to_str, get_structure_from_angles, \ structure_to_backbone_atoms, write_to_pdb, calculate_dihedral_angles_over_minibatch, \ get_backbone_positions_from_angular_prediction, encode_primary_string import torch MAX_SEQUENCE_LENGTH = 2000 def process_raw_data(use_gpu, force_pre_processing_overwrite=True): print("Starting pre-processing of raw data...") input_files = glob.glob("data/raw/*") print(input_files) input_files_filtered = filter_input_files(input_files) for file_path in input_files_filtered: if platform.system() is 'Windows': filename = file_path.split('\\')[-1] else: filename = file_path.split('/')[-1] preprocessed_file_name = "data/preprocessed/"+filename+".hdf5" # check if we should remove the any previously processed files if os.path.isfile(preprocessed_file_name): print("Preprocessed file for " + filename + " already exists.") if force_pre_processing_overwrite: print("force_pre_processing_overwrite flag set to True, overwriting old file...") os.remove(preprocessed_file_name) else: print("Skipping pre-processing for this file...") if not os.path.isfile(preprocessed_file_name): process_file(filename, preprocessed_file_name, use_gpu) print("Completed pre-processing.") def read_protein_from_file(file_pointer): dict_ = {} _dssp_dict = {'L': 0, 'H': 1, 'B': 2, 'E': 3, 'G': 4, 'I': 5, 'T': 6, 'S': 7} _mask_dict = {'-': 0, '+': 1} while True: next_line = file_pointer.readline() if next_line == '[ID]\n': id_ = file_pointer.readline()[:-1] dict_.update({'id': id_}) elif next_line == '[PRIMARY]\n': primary = encode_primary_string(file_pointer.readline()[:-1]) dict_.update({'primary': primary}) elif next_line == '[EVOLUTIONARY]\n': evolutionary = [] for residue in range(21): evolutionary.append( [float(step) for step in file_pointer.readline().split()]) dict_.update({'evolutionary': evolutionary}) elif next_line == '[SECONDARY]\n': secondary = list([_dssp_dict[dssp] for dssp in file_pointer.readline()[:-1]]) dict_.update({'secondary': secondary}) elif next_line == '[TERTIARY]\n': tertiary = [] # 3 dimension for axis in range(3): tertiary.append( [float(coord) for coord in file_pointer.readline().split()]) dict_.update({'tertiary': tertiary}) elif next_line == '[MASK]\n': mask = list([_mask_dict[aa] for aa in file_pointer.readline()[:-1]]) dict_.update({'mask': mask}) elif next_line == '\n': return dict_ elif next_line == '': return None def process_file(input_file, output_file, use_gpu): print("Processing raw data file", input_file) # create output file f = h5py.File(output_file, 'w') current_buffer_size = 1 current_buffer_allocation = 0 dset1 = f.create_dataset('primary',(current_buffer_size,MAX_SEQUENCE_LENGTH),maxshape=(None,MAX_SEQUENCE_LENGTH),dtype='int32') dset2 = f.create_dataset('tertiary',(current_buffer_size,MAX_SEQUENCE_LENGTH,9),maxshape=(None,MAX_SEQUENCE_LENGTH, 9),dtype='float') dset3 = f.create_dataset('mask',(current_buffer_size,MAX_SEQUENCE_LENGTH),maxshape=(None,MAX_SEQUENCE_LENGTH),dtype='uint8') input_file_pointer = open("data/raw/" + input_file, "r") while True: # while there's more proteins to process next_protein = read_protein_from_file(input_file_pointer) if next_protein is None: break sequence_length = len(next_protein['primary']) if sequence_length > MAX_SEQUENCE_LENGTH: print("Dropping protein as length too long:", sequence_length) continue if current_buffer_allocation >= current_buffer_size: current_buffer_size = current_buffer_size + 1 dset1.resize((current_buffer_size,MAX_SEQUENCE_LENGTH)) dset2.resize((current_buffer_size,MAX_SEQUENCE_LENGTH, 9)) dset3.resize((current_buffer_size,MAX_SEQUENCE_LENGTH)) primary_padded = np.zeros(MAX_SEQUENCE_LENGTH) tertiary_padded = np.zeros((9, MAX_SEQUENCE_LENGTH)) mask_padded = np.zeros(MAX_SEQUENCE_LENGTH) # masking and padding here happens so that the stored dataset is of the same size. # when the data is loaded in this padding is removed again. primary_padded[:sequence_length] = next_protein['primary'] t_transposed = np.ravel(np.array(next_protein['tertiary']).T) t_reshaped = np.reshape(t_transposed, (sequence_length,9)).T tertiary_padded[:,:sequence_length] = t_reshaped mask_padded[:sequence_length] = next_protein['mask'] mask = torch.Tensor(mask_padded).type(dtype=torch.uint8) prim = torch.masked_select(torch.Tensor(primary_padded).type(dtype=torch.long), mask) pos = torch.masked_select(torch.Tensor(tertiary_padded), mask).view(9, -1).transpose(0, 1).unsqueeze(1) / 100 if use_gpu: pos = pos.cuda() angles, batch_sizes = calculate_dihedral_angles_over_minibatch(pos, [len(prim)], use_gpu=use_gpu) tertiary, _ = get_backbone_positions_from_angular_prediction(angles, batch_sizes, use_gpu=use_gpu) tertiary = tertiary.squeeze(1) primary_padded = np.zeros(MAX_SEQUENCE_LENGTH) tertiary_padded = np.zeros((MAX_SEQUENCE_LENGTH, 9)) length_after_mask_removed = len(prim) primary_padded[:length_after_mask_removed] = prim.data.cpu().numpy() tertiary_padded[:length_after_mask_removed, :] = tertiary.data.cpu().numpy() mask_padded = np.zeros(MAX_SEQUENCE_LENGTH) mask_padded[:length_after_mask_removed] = np.ones(length_after_mask_removed) dset1[current_buffer_allocation] = primary_padded dset2[current_buffer_allocation] = tertiary_padded dset3[current_buffer_allocation] = mask_padded current_buffer_allocation += 1 print("Wrote output to", current_buffer_allocation, "proteins to", output_file) def filter_input_files(input_files): disallowed_file_endings = (".gitignore", ".DS_Store") return list(filter(lambda x: not x.endswith(disallowed_file_endings), input_files))
openprotein-master
preprocessing.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. import argparse import importlib from dashboard import start_dashboard_server from util import * print("------------------------") print("--- OpenProtein v0.1 ---") print("------------------------") parser = argparse.ArgumentParser(description = "OpenProtein version 0.1") parser.add_argument('--silent', dest='silent', action='store_true', help='Dont print verbose debug statements.') parser.add_argument('--hide-ui', dest = 'hide_ui', action = 'store_true', default=False, help='Hide loss graph and visualization UI while training goes on.') parser.add_argument('--evaluate-on-test', dest = 'evaluate_on_test', action = 'store_true', default=False, help='Run model of test data.') parser.add_argument('--use-gpu', dest = 'use_gpu', action = 'store_true', default=False, help='Use GPU.') parser.add_argument('--eval-interval', dest = 'eval_interval', type=int, default=10, help='Evaluate model on validation set every n minibatches.') parser.add_argument('--min-updates', dest = 'minimum_updates', type=int, default=100, help='Minimum number of minibatch iterations.') parser.add_argument('--minibatch-size', dest = 'minibatch_size', type=int, default=10, help='Size of each minibatch.') parser.add_argument('--experiment-id', dest = 'experiment_id', type=str, default="example", help='Which experiment to run.') args, unknown = parser.parse_known_args() if args.hide_ui: write_out("Live plot deactivated, see output folder for plot.") use_gpu = args.use_gpu if use_gpu and not torch.cuda.is_available(): write_out("Error: --use-gpu was set, but no GPU is available.") exit(1) if not args.hide_ui: # start web server start_dashboard_server() experiment = importlib.import_module("experiments." + args.experiment_id) experiment.run_experiment(parser,use_gpu)
openprotein-master
__main__.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. from util import * import time import torch.nn.utils.rnn as rnn_utils import torch.nn as nn class BaseModel(nn.Module): def __init__(self, use_gpu, embedding_size): super(BaseModel, self).__init__() # initialize model variables self.use_gpu = use_gpu self.embedding_size = embedding_size self.historical_rmsd_avg_values = list() self.historical_drmsd_avg_values = list() def get_embedding_size(self): return self.embedding_size def embed(self, original_aa_string): data, batch_sizes = torch.nn.utils.rnn.pad_packed_sequence( torch.nn.utils.rnn.pack_sequence(original_aa_string)) # one-hot encoding start_compute_embed = time.time() prot_aa_list = data.unsqueeze(1) embed_tensor = torch.zeros(prot_aa_list.size(0), 21, prot_aa_list.size(2)) # 21 classes if self.use_gpu: prot_aa_list = prot_aa_list.cuda() embed_tensor = embed_tensor.cuda() input_sequences = embed_tensor.scatter_(1, prot_aa_list.data, 1).transpose(1,2) end = time.time() write_out("Embed time:", end - start_compute_embed) packed_input_sequences = rnn_utils.pack_padded_sequence(input_sequences, batch_sizes) return packed_input_sequences def compute_loss(self, minibatch): (original_aa_string, actual_coords_list, mask) = minibatch emissions, backbone_atoms_padded, batch_sizes = self._get_network_emissions(original_aa_string) actual_coords_list_padded, batch_sizes_coords = torch.nn.utils.rnn.pad_packed_sequence( torch.nn.utils.rnn.pack_sequence(actual_coords_list)) if self.use_gpu: actual_coords_list_padded = actual_coords_list_padded.cuda() start = time.time() emissions_actual, batch_sizes_actual = \ calculate_dihedral_angles_over_minibatch(actual_coords_list_padded, batch_sizes_coords, self.use_gpu) #drmsd_avg = calc_avg_drmsd_over_minibatch(backbone_atoms_padded, actual_coords_list_padded, batch_sizes) write_out("Angle calculation time:", time.time() - start) if self.use_gpu: emissions_actual = emissions_actual.cuda() #drmsd_avg = drmsd_avg.cuda() angular_loss = calc_angular_difference(emissions, emissions_actual) return angular_loss # + drmsd_avg def forward(self, original_aa_string): return self._get_network_emissions(original_aa_string) def evaluate_model(self, data_loader): loss = 0 data_total = [] dRMSD_list = [] RMSD_list = [] for i, data in enumerate(data_loader, 0): primary_sequence, tertiary_positions, mask = data start = time.time() predicted_angles, backbone_atoms, batch_sizes = self(primary_sequence) write_out("Apply model to validation minibatch:", time.time() - start) cpu_predicted_angles = predicted_angles.transpose(0, 1).cpu().detach() cpu_predicted_backbone_atoms = backbone_atoms.transpose(0, 1).cpu().detach() minibatch_data = list(zip(primary_sequence, tertiary_positions, cpu_predicted_angles, cpu_predicted_backbone_atoms)) data_total.extend(minibatch_data) start = time.time() for primary_sequence, tertiary_positions, predicted_pos, predicted_backbone_atoms in minibatch_data: actual_coords = tertiary_positions.transpose(0, 1).contiguous().view(-1, 3) predicted_coords = predicted_backbone_atoms[:len(primary_sequence)].transpose(0, 1).contiguous().view( -1, 3).detach() rmsd = calc_rmsd(predicted_coords, actual_coords) drmsd = calc_drmsd(predicted_coords, actual_coords) RMSD_list.append(rmsd) dRMSD_list.append(drmsd) error = rmsd loss += error end = time.time() write_out("Calculate validation loss for minibatch took:", end - start) loss /= data_loader.dataset.__len__() self.historical_rmsd_avg_values.append(float(torch.Tensor(RMSD_list).mean())) self.historical_drmsd_avg_values.append(float(torch.Tensor(dRMSD_list).mean())) prim = data_total[0][0] pos = data_total[0][1] pos_pred = data_total[0][3] if self.use_gpu: pos = pos.cuda() pos_pred = pos_pred.cuda() angles = calculate_dihedral_angles(pos, self.use_gpu) angles_pred = calculate_dihedral_angles(pos_pred, self.use_gpu) write_to_pdb(get_structure_from_angles(prim, angles), "test") write_to_pdb(get_structure_from_angles(prim, angles_pred), "test_pred") data = {} data["pdb_data_pred"] = open("output/protein_test_pred.pdb", "r").read() data["pdb_data_true"] = open("output/protein_test.pdb", "r").read() data["phi_actual"] = list([math.degrees(float(v)) for v in angles[1:, 1]]) data["psi_actual"] = list([math.degrees(float(v)) for v in angles[:-1, 2]]) data["phi_predicted"] = list([math.degrees(float(v)) for v in angles_pred[1:, 1]]) data["psi_predicted"] = list([math.degrees(float(v)) for v in angles_pred[:-1, 2]]) data["rmsd_avg"] = self.historical_rmsd_avg_values data["drmsd_avg"] = self.historical_drmsd_avg_values prediction_data = None return (loss, data, prediction_data)
openprotein-master
openprotein.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. from util import * import torch.optim as optim import requests import json import time def train_model(data_set_identifier, model, train_loader, validation_loader, learning_rate, minibatch_size=64, eval_interval=50, hide_ui=False, use_gpu=False, minimum_updates=1000): set_experiment_id(data_set_identifier, learning_rate, minibatch_size) validation_dataset_size = validation_loader.dataset.__len__() if use_gpu: model = model.cuda() optimizer = optim.Adam(model.parameters(), lr=learning_rate) sample_num = list() train_loss_values = list() validation_loss_values = list() best_model_loss = 1e20 best_model_minibatch_time = None best_model_path = None best_json_data = None stopping_condition_met = False minibatches_proccesed = 0 while not stopping_condition_met: optimizer.zero_grad() model.zero_grad() loss_tracker = np.zeros(0) for minibatch_id, training_minibatch in enumerate(train_loader, 0): minibatches_proccesed += 1 start_compute_loss = time.time() loss = model.compute_loss(training_minibatch) write_out("Train loss:", float(loss)) start_compute_grad = time.time() loss.backward() loss_tracker = np.append(loss_tracker, float(loss)) end = time.time() write_out("Loss time:", start_compute_grad-start_compute_loss, "Grad time:", end-start_compute_grad) optimizer.step() optimizer.zero_grad() model.zero_grad() # for every eval_interval samples, plot performance on the validation set if minibatches_proccesed % eval_interval == 0: write_out("Testing model on validation set...") train_loss = float(loss_tracker.mean()) loss_tracker = np.zeros(0) validation_loss, json_data, _ = model.evaluate_model(validation_loader) if validation_loss < best_model_loss: best_model_loss = validation_loss best_model_minibatch_time = minibatches_proccesed best_model_path = write_model_to_disk(model) best_json_data = json_data write_out("Validation loss:", validation_loss, "Train loss:", train_loss) write_out("Best model so far (validation loss): ", best_model_loss, "at time", best_model_minibatch_time) write_out("Best model stored at " + best_model_path) write_out("Minibatches processed:",minibatches_proccesed) sample_num.append(minibatches_proccesed) train_loss_values.append(train_loss) validation_loss_values.append(validation_loss) json_data["validation_dataset_size"] = validation_dataset_size json_data["sample_num"] = sample_num json_data["train_loss_values"] = train_loss_values json_data["validation_loss_values"] = validation_loss_values write_out(json_data) if not hide_ui: res = requests.post('http://localhost:5000/graph', json=json_data) if res.ok: print(res.json()) if minibatches_proccesed > minimum_updates and minibatches_proccesed >= best_model_minibatch_time + minimum_updates: stopping_condition_met = True break write_result_summary(best_model_loss) write_result_summary(json.dumps(best_json_data)) return best_model_path
openprotein-master
training.py
# This file is part of the TMHMM3 project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. import torch from torch.utils.data.dataset import Dataset import numpy as np import math import random from util import write_out class TMDataset(Dataset): def __init__(self, aa_list, label_list, remapped_labels_list_crf_hmm, remapped_labels_list_crf_marg, type_list, topology_list, prot_name_list, original_aa_string_list, original_label_string): assert len(aa_list) == len(label_list) assert len(aa_list) == len(type_list) assert len(aa_list) == len(topology_list) self.aa_list = aa_list self.label_list = label_list self.remapped_labels_list_crf_hmm = remapped_labels_list_crf_hmm self.remapped_labels_list_crf_marg = remapped_labels_list_crf_marg self.type_list = type_list self.topology_list = topology_list self.prot_name_list = prot_name_list self.original_aa_string_list = original_aa_string_list self.original_label_string = original_label_string def __getitem__(self, index): return self.aa_list[index], \ self.label_list[index], \ self.remapped_labels_list_crf_hmm[index], \ self.remapped_labels_list_crf_marg[index], \ self.type_list[index], \ self.topology_list[index], \ self.prot_name_list[index], \ self.original_aa_string_list[index], \ self.original_label_string[index] def __len__(self): return len(self.aa_list) def merge_samples_to_minibatch(samples): samples_list = [] for s in samples: samples_list.append(s) # sort according to length of aa sequence samples_list.sort(key=lambda x: len(x[7]), reverse=True) aa_list, labels_list, remapped_labels_list_crf_hmm, remapped_labels_list_crf_marg, prot_type_list, prot_topology_list, prot_name, original_aa_string, original_label_string = zip(*samples_list) write_out(prot_type_list) return aa_list, labels_list, remapped_labels_list_crf_hmm, remapped_labels_list_crf_marg, prot_type_list, prot_topology_list, prot_name, original_aa_string, original_label_string def from_disk(dataset, use_gpu, re_map_labels=True): print("Constructing data set from disk...") aa_list = [] labels_list = [] remapped_labels_list_crf_hmm = [] remapped_labels_list_crf_marg = [] prot_type_list = [] prot_topology_list_all = [] prot_aa_list_all = [] prot_labels_list_all = [] prot_name_list = [] # sort according to length of aa sequence dataset.sort(key=lambda x: len(x[1]), reverse=True) for prot_name, prot_aa_list, prot_original_label_list, type_id, cluster_id in dataset: prot_name_list.append(prot_name) prot_aa_list_all.append(prot_aa_list) prot_labels_list_all.append(prot_original_label_list) aa_tmp_list_tensor = [] labels = None remapped_labels_crf_hmm = None last_non_membrane_position = None if prot_original_label_list is not None: labels = [] for topology_label in prot_original_label_list: if topology_label is "L": topology_label = "I" if topology_label is "I": last_non_membrane_position = "I" labels.append(3) elif topology_label is "O": last_non_membrane_position = "O" labels.append(4) elif topology_label is "S": last_non_membrane_position = "S" labels.append(2) elif topology_label is "M": if last_non_membrane_position is "I": labels.append(0) elif last_non_membrane_position is "O": labels.append(1) else: print("Error: unexpected label found in last_non_membrane_position:", topology_label) else: print("Error: unexpected label found:", topology_label, "for protein", prot_name) labels = torch.LongTensor(labels) remapped_labels_crf_hmm = [] topology = label_list_to_topology(labels) # given topology, now calculate remapped labels for idx, (pos, l) in enumerate(topology): if l == 0: # I -> O membrane_length = topology[idx+1][0]-pos mm_beginning = 4 for i in range(mm_beginning): remapped_labels_crf_hmm.append(5 + i) for i in range(40-(membrane_length-mm_beginning), 40): remapped_labels_crf_hmm.append(5 + i) elif l == 1: # O -> I membrane_length = topology[idx + 1][0] - pos mm_beginning = 4 for i in range(mm_beginning): remapped_labels_crf_hmm.append(45 + i) for i in range(40 - (membrane_length - mm_beginning), 40): remapped_labels_crf_hmm.append(45 + i) elif l == 2: # S signal_length = topology[idx + 1][0] - pos remapped_labels_crf_hmm.append(2) for i in range(signal_length - 1): remapped_labels_crf_hmm.append(152 - ((signal_length - 1) - i)) if remapped_labels_crf_hmm[-1] == 85: print("Too long signal peptide region found", prot_name) else: if idx == (len(topology) - 1): for i in range(len(labels)-pos): remapped_labels_crf_hmm.append(l) else: for i in range(topology[idx+1][0]-pos): remapped_labels_crf_hmm.append(l) remapped_labels_crf_hmm = torch.LongTensor(remapped_labels_crf_hmm) remapped_labels_crf_marg = list([l + (type_id * 5) for l in labels]) remapped_labels_crf_marg = torch.LongTensor(remapped_labels_crf_marg) # check that protein was properly parsed assert remapped_labels_crf_hmm.size() == labels.size() assert remapped_labels_crf_marg.size() == labels.size() if use_gpu: if labels is not None: labels = labels.cuda() remapped_labels_crf_hmm = remapped_labels_crf_hmm.cuda() remapped_labels_crf_marg = remapped_labels_crf_marg.cuda() aa_list.append(aa_tmp_list_tensor) labels_list.append(labels) remapped_labels_list_crf_hmm.append(remapped_labels_crf_hmm) remapped_labels_list_crf_marg.append(remapped_labels_crf_marg) prot_type_list.append(type_id) prot_topology_list_all.append(label_list_to_topology(labels)) return TMDataset(aa_list, labels_list, remapped_labels_list_crf_hmm, remapped_labels_list_crf_marg, prot_type_list, prot_topology_list_all, prot_name_list, prot_aa_list_all, prot_labels_list_all) def tm_contruct_dataloader_from_disk(tm_dataset, minibatch_size, balance_classes=False): if balance_classes: batch_sampler = RandomBatchClassBalancedSequentialSampler(tm_dataset, minibatch_size) else: batch_sampler = RandomBatchSequentialSampler(tm_dataset, minibatch_size) return torch.utils.data.DataLoader(tm_dataset, batch_sampler = batch_sampler, collate_fn = TMDataset.merge_samples_to_minibatch) class RandomBatchClassBalancedSequentialSampler(torch.utils.data.sampler.Sampler): def __init__(self, dataset, batch_size): self.sampler = torch.utils.data.sampler.SequentialSampler(dataset) self.batch_size = batch_size self.dataset = dataset def sample_at_index(self, rows, offset, sample_num): assert sample_num < len(rows) sample_half = int(sample_num / 2) if offset - sample_half <= 0: # sample start has to be 0 samples = rows[:sample_num] elif offset + sample_half + (sample_num % 2) > len(rows): # sample end has to be a end samples = rows[-(sample_num+1):-1] else: samples = rows[offset-sample_half:offset+sample_half+(sample_num % 2)] assert len(samples) == sample_num return samples def __iter__(self): data_class_map = {} data_class_map[0] = [] data_class_map[1] = [] data_class_map[2] = [] data_class_map[3] = [] for idx in self.sampler: data_class_map[self.dataset[idx][4]].append(idx) num_each_class = int(self.batch_size / 4) max_class_size = max([len(data_class_map[0]),len(data_class_map[1]),len(data_class_map[2]),len(data_class_map[3])]) batch_num = int(max_class_size / num_each_class) if max_class_size % num_each_class != 0: batch_num += 1 batch_relative_offset = (1.0 / float(batch_num)) / 2.0 batches = [] for i in range(batch_num): batch = [] for class_id, data_rows in data_class_map.items(): int_offset = int(batch_relative_offset * len(data_rows)) batch.extend(self.sample_at_index(data_rows, int_offset, num_each_class)) batch_relative_offset += 1.0 / float(batch_num) batches.append(batch) random.shuffle(batches) for batch in batches: write_out("Using minibatch from RandomBatchClassBalancedSequentialSampler") yield batch def __len__(self): length = 0 for idx in self.sampler: length += 1 return length class RandomBatchSequentialSampler(torch.utils.data.sampler.Sampler): def __init__(self, dataset, batch_size): self.sampler = torch.utils.data.sampler.SequentialSampler(dataset) self.batch_size = batch_size def __iter__(self): data = [] for idx in self.sampler: data.append(idx) batch_num = int(len(data) / self.batch_size) if len(data) % self.batch_size != 0: batch_num += 1 batch_order = list(range(batch_num)) random.shuffle(batch_order) batch = [] for batch_id in batch_order: write_out("Accessing minibatch #" + str(batch_id)) for i in range(self.batch_size): if i+(batch_id*self.batch_size) < len(data): batch.append(data[i+(batch_id*self.batch_size)]) yield batch batch = [] def __len__(self): length = 0; for idx in self.sampler: length += 1 return length def label_list_to_topology(labels): if isinstance(labels, list): labels = torch.LongTensor(labels) unique, count = torch.unique_consecutive(labels, return_counts=True) top_list = [torch.LongTensor((0, int(labels[0])))] prev_count = 0 for i in range(1, unique.size(0)): prev_count += int(count[i-1]) top_list.append(torch.LongTensor((prev_count, int(unique[i])))) return top_list def remapped_labels_hmm_to_orginal_labels(labels): for idx, pl in enumerate(labels): if pl >= 5 and pl < 45: labels[idx] = 0 if pl >= 45 and pl < 85: labels[idx] = 1 if pl >= 85: labels[idx] = 2 if isinstance(labels, list): labels = torch.LongTensor(labels) return labels def original_labels_to_fasta(label_list): sequence = "" for label in label_list: if label == 0: sequence = sequence + "M" if label == 1: sequence = sequence + "M" if label == 2: sequence = sequence + "S" if label == 3: sequence = sequence + "I" if label == 4: sequence = sequence + "O" if label == 5: sequence = sequence + "-" return sequence def get_predicted_type_from_labels(labels): labels = list([int(i) for i in labels]) if 0 in labels or 1 in labels: if 2 in labels: return 1 else: return 0 else: if 2 in labels: return 2 else: return 3 def is_topologies_equal(topology_a, topology_b, minimum_seqment_overlap=5): if len(topology_a) != len(topology_b): return False for idx, (position_a, label_a) in enumerate(topology_a): if label_a != topology_b[idx][1]: return False if label_a == 0 or label_a == 1: overlap_segment_start = max(topology_a[idx][0],topology_b[idx][0]) overlap_segment_end = min(topology_a[idx+1][0],topology_b[idx+1][0]) if overlap_segment_end-overlap_segment_start < minimum_seqment_overlap: return False return True def parse_3line_format(lines): i = 0 prot_list = [] while(i < len(lines)): if lines[i].strip() is "": i += 1 continue prot_name_comment = lines[i] type_string = None cluster_id = None if prot_name_comment.__contains__(">"): i += 1 prot_name = prot_name_comment.split("|")[0].split(">")[1] type_string = prot_name_comment.split("|")[1] cluster_id = int(prot_name_comment.split("|")[2]) else: # assume this is data prot_name = "> Unknown Protein Name" prot_aa_list = lines[i].upper() i += 1 if len(prot_aa_list) > 6000: print("Discarding protein",prot_name,"as length larger than 6000:",len(prot_aa_list)) if i < len(lines) and not lines[i].__contains__(">"): i += 1 else: if i < len(lines) and not lines[i].__contains__(">"): prot_topology_list = lines[i].upper() i += 1 if prot_topology_list.__contains__("S"): if prot_topology_list.__contains__("M"): type_id = 1 assert type_string == "SP+TM" else: type_id = 2 assert type_string == "SP" else: if prot_topology_list.__contains__("M"): type_id = 0 assert type_string == "TM" else: type_id = 3 assert type_string == "GLOBULAR" else: type_id = None prot_topology_list = None prot_list.append((prot_name, prot_aa_list, prot_topology_list, type_id, cluster_id)) return prot_list def parse_datafile_from_disk(file): lines = list([line.strip() for line in open(file)]) return parse_3line_format(lines) def calculate_partitions(partitions_count, cluster_partitions, types): partition_distribution = torch.ones((partitions_count, len(torch.unique(types))), dtype=torch.long) partition_assignments = torch.zeros(cluster_partitions.shape[0],dtype=torch.long) for i in torch.unique(cluster_partitions): cluster_positions = (cluster_partitions == i).nonzero() cluster_types = types[cluster_positions] unique_types_in_cluster, type_count = torch.unique(cluster_types, return_counts=True) tmp_distribution = partition_distribution.clone() tmp_distribution[:,unique_types_in_cluster] += type_count relative_distribution = partition_distribution.double()/tmp_distribution.double() min_relative_distribution_group = torch.argmin(torch.sum(relative_distribution,dim=1)) partition_distribution[min_relative_distribution_group,unique_types_in_cluster] += type_count partition_assignments[cluster_positions] = min_relative_distribution_group write_out("Loaded data into the following partitions") write_out("[[ TM SP+TM SP Glob]") write_out(partition_distribution-torch.ones(partition_distribution.shape,dtype=torch.long)) return partition_assignments def load_data_from_disk(filename, partition_rotation=0): print("Loading data from disk...") data = parse_datafile_from_disk(filename) data_unzipped = list(zip(*data)) partitions = calculate_partitions( cluster_partitions=torch.LongTensor(np.array(data_unzipped[4])), types=torch.LongTensor(np.array(data_unzipped[3])), partitions_count=5) train_set = [] val_set = [] test_set = [] for idx, sample in enumerate(data): partition = int(partitions[idx]) # in range 0-4 rotated = (partition + partition_rotation) % 5 if int(rotated) <= 2: train_set.append(sample) elif int(rotated) == 3: val_set.append(sample) else: test_set.append(sample) print("Data splited as:", len(train_set), "train set", len(val_set), "validation set", len(test_set), "test set") return train_set, val_set, test_set def normalize_confusion_matrix(confusion_matrix): confusion_matrix = confusion_matrix.astype(np.float64) for i in range(4): sum = int(confusion_matrix[i].sum()) if sum != 0: confusion_matrix[4][i] /= sum * 0.01 # 0.01 to convert to percentage for k in range(5): if sum != 0: confusion_matrix[i][k] /= sum * 0.01 # 0.01 to convert to percentage else: confusion_matrix[i][k] = math.nan return confusion_matrix.round(2)
openprotein-master
experiments/tmhmm3/tm_util.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. import os import pickle from .tm_models import * from .tm_util import * from models import * from training import train_model from util import write_out, set_experiment_id, load_model_from_disk import numpy as np import hashlib def run_experiment(parser, use_gpu): parser.add_argument('--minibatch-size-validation', dest='minibatch_size_validation', type=int, default=50, help='Size of each minibatch during evaluation.') parser.add_argument('--hidden-size', dest='hidden_size', type=int, default=64, help='Hidden size.') parser.add_argument('--learning-rate', dest='learning_rate', type=float, default=0.001, help='Learning rate to use during training.') parser.add_argument('--cv-partition', dest='cv_partition', type=int, default=0, help='Run a particular cross validation rotation.') parser.add_argument('--model-mode', dest='model_mode', type=int, default=3, help='Which model to use.') parser.add_argument('--input-data', dest='input_data', type=str, default='data/raw/TMHMM3.train.3line.latest', help='Path of input data file.') parser.add_argument('--pre-trained-model-paths', dest='pre_trained_model_paths', type=str, default=None, help='Paths of pre-trained models.') args, unknown = parser.parse_known_args() result_matrices = np.zeros((5, 5), dtype=np.int64) if args.model_mode == 0: model_mode = TMHMM3Mode.LSTM elif args.model_mode == 1: model_mode = TMHMM3Mode.LSTM_CRF elif args.model_mode == 2: model_mode = TMHMM3Mode.LSTM_CRF_HMM elif args.model_mode == 3: model_mode = TMHMM3Mode.LSTM_CRF_MARG elif args.model_mode == 4: model_mode = TMHMM3Mode.LSTM_CTC else: print("ERROR: No model defined") print("Using model:", model_mode) embedding = "BLOSUM62" use_marg_prob = False all_prediction_data = [] for cv_partition in [0, 1, 2, 3, 4]: # prepare data sets train_set, val_set, test_set = load_data_from_disk(filename=args.input_data, partition_rotation=cv_partition) # topology data set train_set_TOPOLOGY = list(filter(lambda x: x[3] is 0 or x[3] is 1, train_set)) val_set_TOPOLOGY = list(filter(lambda x: x[3] is 0 or x[3] is 1, val_set)) test_set_TOPOLOGY = list(filter(lambda x: x[3] is 0 or x[3] is 1, test_set)) if not args.silent: print("Loaded ", len(train_set), "training,", len(val_set), "validation and", len(test_set), "test samples") print("Processing data...") pre_processed_path = "data/preprocessed/preprocessed_data_"+str(hashlib.sha256(args.input_data.encode()).hexdigest())[:8]+"_cv" + str(cv_partition) + ".pickle" if not os.path.isfile(pre_processed_path): input_data_processed = list([TMDataset.from_disk(set, use_gpu) for set in [train_set, val_set, test_set, train_set_TOPOLOGY, val_set_TOPOLOGY, test_set_TOPOLOGY]]) pickle.dump(input_data_processed, open(pre_processed_path, "wb")) input_data_processed = pickle.load(open(pre_processed_path, "rb")) train_preprocessed_set = input_data_processed[0] validation_preprocessed_set = input_data_processed[1] test_preprocessed_set = input_data_processed[2] train_preprocessed_set_TOPOLOGY = input_data_processed[3] validation_preprocessed_set_TOPOLOGY = input_data_processed[4] test_preprocessed_set_TOPOLOGY = input_data_processed[5] print("Completed preprocessing of data...") train_loader = tm_contruct_dataloader_from_disk(train_preprocessed_set, args.minibatch_size, balance_classes=True) validation_loader = tm_contruct_dataloader_from_disk(validation_preprocessed_set, args.minibatch_size_validation, balance_classes=True) test_loader = tm_contruct_dataloader_from_disk(test_preprocessed_set if args.evaluate_on_test else validation_preprocessed_set, args.minibatch_size_validation) train_loader_TOPOLOGY = tm_contruct_dataloader_from_disk(train_preprocessed_set_TOPOLOGY, int( args.minibatch_size / 2)) # use smaller minibatch size for topology validation_loader_TOPOLOGY = tm_contruct_dataloader_from_disk(validation_preprocessed_set_TOPOLOGY, args.minibatch_size_validation) type_predictor_model_path = None if args.pre_trained_model_paths is None: for (experiment_id, train_data, validation_data) in [ ("TRAIN_TYPE_CV" + str(cv_partition) + "-" + str(model_mode) + "-HS" + str(args.hidden_size) + "-F" + str(args.input_data.split(".")[-2]), train_loader, validation_loader), ("TRAIN_TOPOLOGY_CV" + str(cv_partition) + "-" + str(model_mode) + "-HS" + str(args.hidden_size) + "-F" + str(args.input_data.split(".")[-2]), train_loader_TOPOLOGY, validation_loader_TOPOLOGY)]: type_predictor = None if type_predictor_model_path is not None: type_predictor = load_model_from_disk(type_predictor_model_path, force_cpu=False) model = TMHMM3( embedding, args.hidden_size, use_gpu, model_mode, use_marg_prob, type_predictor) model_path = train_model(data_set_identifier=experiment_id, model=model, train_loader=train_data, validation_loader=validation_data, learning_rate=args.learning_rate, minibatch_size=args.minibatch_size, eval_interval=args.eval_interval, hide_ui=args.hide_ui, use_gpu=use_gpu, minimum_updates=args.minimum_updates) # let the GC collect the model del model write_out(model_path) # if we just trained a type predictor, save it for later if "TRAIN_TYPE" in experiment_id: type_predictor_model_path = model_path else: # use the pre-trained model model_path = args.pre_trained_model_paths.split(",")[cv_partition] # test model write_out("Testing model...") model = load_model_from_disk(model_path, force_cpu=False) loss, json_data, prediction_data = model.evaluate_model(test_loader) all_prediction_data.append(model.post_process_prediction_data(prediction_data)) result_matrix = np.array(json_data['confusion_matrix']) result_matrices += result_matrix write_out(result_matrix) set_experiment_id("TEST-" + str(model_mode) + "-HS" + str(args.hidden_size) + "-F" + str(args.input_data.split(".")[-2]), args.learning_rate, args.minibatch_size) write_out(result_matrices) write_prediction_data_to_disk("\n".join(all_prediction_data))
openprotein-master
experiments/tmhmm3/__init__.py
# This file is part of the TMHMM3 project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. from enum import Enum import torch.autograd as autograd import torch.nn as nn import openprotein from experiments.tmhmm3.tm_util import * from pytorchcrf.torchcrf import CRF from util import write_out, get_experiment_id import tensorflow as tf import os # seed random generator for reproducibility torch.manual_seed(1) class TMHMM3(openprotein.BaseModel): def __init__(self, embedding, hidden_size, use_gpu, model_mode, use_marg_prob, type_predictor_model): super(TMHMM3, self).__init__(embedding, use_gpu) # initialize model variables num_tags = 5 num_labels = 5 self.max_signal_length = 67 if model_mode == TMHMM3Mode.LSTM_CRF_HMM: num_tags += 2 * 40 + self.max_signal_length elif model_mode == TMHMM3Mode.LSTM_CRF_MARG: num_tags = num_tags * 4 # 4 different types #num_labels = num_tags # 4 different types elif model_mode == TMHMM3Mode.LSTM_CTC: num_tags += 1 # add extra class for blank num_labels += 1 self.hidden_size = hidden_size self.use_gpu = use_gpu self.use_marg_prob = use_marg_prob self.model_mode = model_mode self.embedding = embedding self.embedding_function = nn.Embedding(24, self.get_embedding_size()) self.bi_lstm = nn.LSTM(self.get_embedding_size(), self.hidden_size, num_layers=1, bidirectional=True) self.hidden_to_labels = nn.Linear(self.hidden_size * 2, num_labels) # * 2 for bidirectional crf_start_mask = torch.ones(num_tags).byte() crf_end_mask = torch.ones(num_tags).byte() if model_mode == TMHMM3Mode.LSTM_CRF_HMM: allowed_transitions = [ (3, 3), (4, 4), (3, 5), (4, 45)] for i in range(5, 45 - 1): allowed_transitions.append((i, i + 1)) if i > 8 and i < 43: allowed_transitions.append((8, i)) allowed_transitions.append((44, 4)) for i in range(45, 85 - 1): allowed_transitions.append((i, i + 1)) if i > 48 and i < 83: allowed_transitions.append((48, i)) allowed_transitions.append((84, 3)) for i in range(85, 151): allowed_transitions.append((i, i + 1)) allowed_transitions.append((2, i)) allowed_transitions.append((2, 151)) allowed_transitions.append((2, 4)) allowed_transitions.append((151, 4)) crf_start_mask[2] = 0 crf_start_mask[3] = 0 crf_start_mask[4] = 0 crf_end_mask[3] = 0 crf_end_mask[4] = 0 elif model_mode == TMHMM3Mode.LSTM_CRF_MARG: allowed_transitions = [ (0, 0), (1, 1), (3, 3), (4, 4), (3, 0), (0, 4), (4, 1), (1, 3), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (8, 5), (5, 9), (9, 6), (6, 8), (7, 9), (12, 12), (14, 14), (12, 14), (18, 18), ] crf_start_mask[3] = 0 crf_start_mask[4] = 0 crf_start_mask[7] = 0 crf_start_mask[8] = 0 crf_start_mask[9] = 0 crf_start_mask[12] = 0 crf_start_mask[18] = 0 crf_end_mask[3] = 0 crf_end_mask[4] = 0 crf_end_mask[8] = 0 crf_end_mask[9] = 0 crf_end_mask[14] = 0 crf_end_mask[18] = 0 else: allowed_transitions = [ (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (3, 0), (0, 4), (4, 1), (1, 3), (2, 4)] crf_start_mask[2] = 0 crf_start_mask[3] = 0 crf_start_mask[4] = 0 crf_end_mask[3] = 0 crf_end_mask[4] = 0 self.allowed_transitions = allowed_transitions self.crfModel = CRF(num_tags) self.type_classifier = type_predictor_model self.type_tm_classier = None self.type_sp_classier = None crf_transitions_mask = torch.ones((num_tags, num_tags)).byte() self.label_01loss_values = [] self.type_01loss_values = [] self.topology_01loss_values = [] # if on GPU, move state to GPU memory if self.use_gpu: self.embedding_function = self.embedding_function.cuda() self.crfModel = self.crfModel.cuda() self.bi_lstm = self.bi_lstm.cuda() self.hidden_to_labels = self.hidden_to_labels.cuda() crf_transitions_mask = crf_transitions_mask.cuda() crf_start_mask = crf_start_mask.cuda() crf_end_mask = crf_end_mask.cuda() # compute mask matrix from allow transitions list for i in range(num_tags): for k in range(num_tags): if (i, k) in self.allowed_transitions: crf_transitions_mask[i][k] = 0 # generate masked transition parameters crf_start_transitions, crf_end_transitions, crf_transitions = \ self.generate_masked_crf_transitions( self.crfModel, (crf_start_mask, crf_transitions_mask, crf_end_mask) ) # initialize CRF self.initialize_crf_parameters(self.crfModel, start_transitions=crf_start_transitions, end_transitions=crf_end_transitions, transitions=crf_transitions) def initialize_crf_parameters(self, crfModel, start_transitions=None, end_transitions=None, transitions=None) -> None: """Initialize the transition parameters. The parameters will be initialized randomly from a uniform distribution between -0.1 and 0.1, unless given explicitly as an argument. """ if start_transitions is None: nn.init.uniform(crfModel.start_transitions, -0.1, 0.1) else: crfModel.start_transitions.data = start_transitions if end_transitions is None: nn.init.uniform(crfModel.end_transitions, -0.1, 0.1) else: crfModel.end_transitions.data = end_transitions if transitions is None: nn.init.uniform(crfModel.transitions, -0.1, 0.1) else: crfModel.transitions.data = transitions def generate_masked_crf_transitions(self, crf_model, transition_mask): start_transitions_mask, transitions_mask, end_transition_mask = transition_mask start_transitions = crf_model.start_transitions.data.clone() end_transitions = crf_model.end_transitions.data.clone() transitions = crf_model.transitions.data.clone() if start_transitions_mask is not None: start_transitions.masked_fill_(start_transitions_mask, -100000000) if end_transition_mask is not None: end_transitions.masked_fill_(end_transition_mask, -100000000) if transitions_mask is not None: transitions.masked_fill_(transitions_mask, -100000000) return start_transitions, end_transitions, transitions def get_embedding_size(self): return 24 # bloom matrix has size 24 def flatten_parameters(self): self.bi_lstm.flatten_parameters() def encode_amino_acid(self, letter): if self.embedding == "BLOSUM62": # blosum encoding if not globals().get('blosum_encoder'): blosum = \ """4,-1,-2,-2,0,-1,-1,0,-2,-1,-1,-1,-1,-2,-1,1,0,-3,-2,0,-2,-1,0,-4 -1,5,0,-2,-3,1,0,-2,0,-3,-2,2,-1,-3,-2,-1,-1,-3,-2,-3,-1,0,-1,-4 -2,0,6,1,-3,0,0,0,1,-3,-3,0,-2,-3,-2,1,0,-4,-2,-3,3,0,-1,-4 -2,-2,1,6,-3,0,2,-1,-1,-3,-4,-1,-3,-3,-1,0,-1,-4,-3,-3,4,1,-1,-4 0,-3,-3,-3,9,-3,-4,-3,-3,-1,-1,-3,-1,-2,-3,-1,-1,-2,-2,-1,-3,-3,-2,-4 -1,1,0,0,-3,5,2,-2,0,-3,-2,1,0,-3,-1,0,-1,-2,-1,-2,0,3,-1,-4 -1,0,0,2,-4,2,5,-2,0,-3,-3,1,-2,-3,-1,0,-1,-3,-2,-2,1,4,-1,-4 0,-2,0,-1,-3,-2,-2,6,-2,-4,-4,-2,-3,-3,-2,0,-2,-2,-3,-3,-1,-2,-1,-4 -2,0,1,-1,-3,0,0,-2,8,-3,-3,-1,-2,-1,-2,-1,-2,-2,2,-3,0,0,-1,-4 -1,-3,-3,-3,-1,-3,-3,-4,-3,4,2,-3,1,0,-3,-2,-1,-3,-1,3,-3,-3,-1,-4 -1,-2,-3,-4,-1,-2,-3,-4,-3,2,4,-2,2,0,-3,-2,-1,-2,-1,1,-4,-3,-1,-4 -1,2,0,-1,-3,1,1,-2,-1,-3,-2,5,-1,-3,-1,0,-1,-3,-2,-2,0,1,-1,-4 -1,-1,-2,-3,-1,0,-2,-3,-2,1,2,-1,5,0,-2,-1,-1,-1,-1,1,-3,-1,-1,-4 -2,-3,-3,-3,-2,-3,-3,-3,-1,0,0,-3,0,6,-4,-2,-2,1,3,-1,-3,-3,-1,-4 -1,-2,-2,-1,-3,-1,-1,-2,-2,-3,-3,-1,-2,-4,7,-1,-1,-4,-3,-2,-2,-1,-2,-4 1,-1,1,0,-1,0,0,0,-1,-2,-2,0,-1,-2,-1,4,1,-3,-2,-2,0,0,0,-4 0,-1,0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-2,-1,1,5,-2,-2,0,-1,-1,0,-4 -3,-3,-4,-4,-2,-2,-3,-2,-2,-3,-2,-3,-1,1,-4,-3,-2,11,2,-3,-4,-3,-2,-4 -2,-2,-2,-3,-2,-1,-2,-3,2,-1,-1,-2,-1,3,-3,-2,-2,2,7,-1,-3,-2,-1,-4 0,-3,-3,-3,-1,-2,-2,-3,-3,3,1,-2,1,-1,-2,-2,0,-3,-1,4,-3,-2,-1,-4 -2,-1,3,4,-3,0,1,-1,0,-3,-4,0,-3,-3,-2,0,-1,-4,-3,-3,4,1,-1,-4 -1,0,0,1,-3,3,4,-2,0,-3,-3,1,-1,-3,-1,0,-1,-3,-2,-2,1,4,-1,-4 0,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-2,0,0,-2,-1,-1,-1,-1,-1,-4 -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,1""".replace('\n', ',') blosum_matrix = np.fromstring(blosum, sep=",").reshape(24,24) blosum_key = "A,R,N,D,C,Q,E,G,H,I,L,K,M,F,P,S,T,W,Y,V,B,Z,X,U".split(",") key_map = {} for idx, value in enumerate(blosum_key): key_map[value] = list([int(v) for v in blosum_matrix[idx].astype('int')]) globals().__setitem__("blosum_encoder", key_map) return globals().get('blosum_encoder')[letter] elif self.embedding == "ONEHOT": # one hot encoding one_hot_key = "A,R,N,D,C,Q,E,G,H,I,L,K,M,F,P,S,T,W,Y,V,B,Z,X,U".split(",") arr = [] for idx, k in enumerate(one_hot_key): if k == letter: arr.append(1) else: arr.append(0) return arr elif self.embedding == "PYTORCH": key_id = "A,R,N,D,C,Q,E,G,H,I,L,K,M,F,P,S,T,W,Y,V,B,Z,X,U".split(",") for idx, k in enumerate(key_id): if k == letter: return idx def embed(self, prot_aa_list): embed_list = [] for aa_list in prot_aa_list: t = list([self.encode_amino_acid(aa) for aa in aa_list]) if self.embedding == "PYTORCH": t = torch.LongTensor(t) else: t= torch.FloatTensor(t) if self.use_gpu: t = t.cuda() embed_list.append(t) return embed_list def init_hidden(self, minibatch_size): # number of layers (* 2 since bidirectional), minibatch_size, hidden size initial_hidden_state = torch.zeros(1 * 2, minibatch_size, self.hidden_size) initial_cell_state = torch.zeros(1 * 2, minibatch_size, self.hidden_size) if self.use_gpu: initial_hidden_state = initial_hidden_state.cuda() initial_cell_state = initial_cell_state.cuda() self.hidden_layer = (autograd.Variable(initial_hidden_state), autograd.Variable(initial_cell_state)) def _get_network_emissions(self, input_sequences): batch_sizes = torch.LongTensor(list([i.size(0) for i in input_sequences])) pad_seq_embed = torch.nn.utils.rnn.pad_sequence(input_sequences) minibatch_size = len(input_sequences) self.init_hidden(minibatch_size) bi_lstm_out, self.hidden_layer = self.bi_lstm(pad_seq_embed, self.hidden_layer) emissions = self.hidden_to_labels(bi_lstm_out) if self.model_mode == TMHMM3Mode.LSTM_CRF_HMM: inout_select = torch.LongTensor([0]) outin_select = torch.LongTensor([1]) signal_select = torch.LongTensor([2]) if self.use_gpu: inout_select = inout_select.cuda() outin_select = outin_select.cuda() signal_select = signal_select.cuda() inout = torch.index_select(emissions, 2, autograd.Variable(inout_select)) outin = torch.index_select(emissions, 2, autograd.Variable(outin_select)) signal = torch.index_select(emissions, 2, autograd.Variable(signal_select)) emissions = torch.cat((emissions, inout.expand(-1, len(batch_sizes), 40), outin.expand(-1, len(batch_sizes), 40), signal.expand(-1, len(batch_sizes), self.max_signal_length)), 2) elif self.model_mode == TMHMM3Mode.LSTM_CRF_MARG: emissions = emissions.repeat(1,1,4) return emissions, batch_sizes def batch_sizes_to_mask(self, batch_sizes): mask = torch.autograd.Variable(torch.t(torch.ByteTensor( [[1] * int(batch_size) + [0] * (int(batch_sizes[0]) - int(batch_size)) for batch_size in batch_sizes] ))) if self.use_gpu: mask = mask.cuda() return mask def compute_loss(self, training_minibatch): _, labels_list, remapped_labels_list_crf_hmm, remapped_labels_list_crf_marg, prot_type_list, prot_topology_list, prot_name_list, original_aa_string, original_label_string = training_minibatch minibatch_size = len(labels_list) if self.model_mode == TMHMM3Mode.LSTM_CRF_MARG: labels_to_use = remapped_labels_list_crf_marg elif self.model_mode == TMHMM3Mode.LSTM_CRF_HMM: labels_to_use = remapped_labels_list_crf_hmm else: labels_to_use = labels_list input_sequences = [autograd.Variable(x) for x in self.embed(original_aa_string)] if self.model_mode == TMHMM3Mode.LSTM_CTC: # CTC loss emissions, batch_sizes = self._get_network_emissions(input_sequences) output = torch.nn.functional.log_softmax(emissions, dim=2) topologies = list([torch.LongTensor(list([label for (idx, label) in label_list_to_topology(a)])) for a in labels_list]) if self.use_gpu: topologies = list([a.cuda() for a in topologies]) targets, target_lengths = torch.nn.utils.rnn.pad_sequence(topologies).transpose(0,1), list([a.size()[0] for a in topologies]) ctc_loss = nn.CTCLoss(blank=5) return ctc_loss(output, targets, tuple(batch_sizes), tuple(target_lengths)) else: actual_labels = torch.nn.utils.rnn.pad_sequence([autograd.Variable(l) for l in labels_to_use]) emissions, batch_sizes = self._get_network_emissions(input_sequences) if self.model_mode == TMHMM3Mode.LSTM: prediction = emissions.transpose(0,1).contiguous().view(-1, emissions.size(-1)) target = actual_labels.transpose(0,1).contiguous().view(-1, 1) losses = -torch.gather(nn.functional.log_softmax(prediction), dim=1, index=target).view(*actual_labels.transpose(0,1).size()) mask_expand = torch.range(0, batch_sizes.data.max() - 1).long().unsqueeze(0).expand(batch_sizes.size(0), batch_sizes.data.max()) if self.use_gpu: mask_expand = mask_expand.cuda() batch_sizes = batch_sizes.cuda() mask = mask_expand < batch_sizes.unsqueeze(1).expand_as(mask_expand) loss = (losses * mask.float()).sum() / batch_sizes.float().sum() else: loss = -1 * self.crfModel(emissions, actual_labels, mask=self.batch_sizes_to_mask(batch_sizes)) / minibatch_size if float(loss) > 100000: for idx, batch_size in enumerate(batch_sizes): last_label = None for i in range(batch_size): label = int(actual_labels[i][idx]) write_out(str(label) + ",", end='') if last_label is not None and (last_label, label) not in self.allowed_transitions: write_out("Error: invalid transition found") write_out((last_label, label)) exit() last_label = label write_out(" ") return loss def forward(self, input_sequences, forced_types=None): emissions, batch_sizes = self._get_network_emissions(input_sequences) if self.model_mode == TMHMM3Mode.LSTM_CTC or self.model_mode == TMHMM3Mode.LSTM: output = torch.nn.functional.log_softmax(emissions, dim=2) _, predicted_labels = output[:,:,0:5].max(dim=2) predicted_labels = list([list(map(int,x[:batch_sizes[idx]])) for idx, x in enumerate(predicted_labels.transpose(0,1))]) predicted_labels = list(torch.cuda.LongTensor(l) if self.use_gpu else torch.LongTensor(l) for l in predicted_labels) predicted_topologies = list(map(label_list_to_topology, predicted_labels)) if forced_types is None and self.model_mode == TMHMM3Mode.LSTM_CTC: tf_output = tf.placeholder(tf.float32, shape=emissions.size()) tf_batch_sizes = tf.placeholder(tf.int32, shape=(emissions.size()[1])) beam_decoded, _ = tf.nn.ctc_beam_search_decoder(tf_output, sequence_length=tf_batch_sizes, beam_width=10) decoded_topology = tf.sparse_tensor_to_dense(beam_decoded[0]) # beam search is much faster on the CPU, disable GPU for this part config = tf.ConfigProto( device_count={'GPU': 0} ) with tf.Session(config=config) as tf_session: tf.global_variables_initializer().run() decoded_topology = tf_session.run(decoded_topology, feed_dict={tf_output: output.detach().cpu().numpy(), tf_batch_sizes: batch_sizes}) predicted_types = torch.LongTensor(list(map(get_predicted_type_from_labels, decoded_topology))) else: predicted_types = torch.LongTensor(list(map(get_predicted_type_from_labels, predicted_labels))) else: mask = self.batch_sizes_to_mask(batch_sizes) labels_predicted = list(torch.cuda.LongTensor(l) if self.use_gpu else torch.LongTensor(l) for l in self.crfModel.decode(emissions, mask=mask)) if self.model_mode == TMHMM3Mode.LSTM_CRF_HMM: predicted_labels = list(map(remapped_labels_hmm_to_orginal_labels, labels_predicted)) predicted_types = torch.LongTensor(list(map(get_predicted_type_from_labels, predicted_labels))) elif self.model_mode == TMHMM3Mode.LSTM_CRF_MARG: alpha = self.crfModel._compute_log_alpha(emissions, mask, run_backwards=False) z = alpha[alpha.size(0)-1] + self.crfModel.end_transitions type = z.view((-1, 4, 5)) type = self.logsumexp(type, dim=2) max, predicted_types = torch.max(type, dim=1) predicted_labels = list([l % 5 for l in labels_predicted]) # remap else: predicted_labels = labels_predicted predicted_types = torch.LongTensor(list(map(get_predicted_type_from_labels, predicted_labels))) if self.use_gpu: predicted_types = predicted_types.cuda() predicted_topologies = list(map(label_list_to_topology, predicted_labels)) # if all O's, change to all I's (by convention) for idx, labels in enumerate(predicted_labels): if torch.eq(labels, 4).all(): predicted_labels[idx] = labels - 1 return predicted_labels, predicted_types if forced_types is None else forced_types, predicted_topologies def evaluate_model(self, data_loader): validation_loss_tracker = [] validation_type_loss_tracker = [] validation_topology_loss_tracker = [] confusion_matrix = np.zeros((5,5), dtype=np.int64) protein_names = [] protein_aa_strings = [] protein_label_actual = [] protein_label_prediction = [] for i, minibatch in enumerate(data_loader, 0): validation_loss_tracker.append(self.compute_loss(minibatch).detach()) _, labels_list, _, _, prot_type_list, prot_topology_list, prot_name_list, original_aa_string, original_label_string = minibatch input_sequences = [x for x in self.embed(original_aa_string)] predicted_labels, predicted_types, predicted_topologies = self(input_sequences) protein_names.extend(prot_name_list) protein_aa_strings.extend(original_aa_string) protein_label_actual.extend(original_label_string) # if we're using an external type predictor if self.type_classifier is not None: predicted_labels_type_classifer, predicted_types_type_classifier, predicted_topologies_type_classifier = self.type_classifier(input_sequences) for idx, actual_type in enumerate(prot_type_list): predicted_type = predicted_types[idx] predicted_topology = predicted_topologies[idx] predicted_labels_for_protein = predicted_labels[idx] if self.type_classifier is not None: if predicted_type != predicted_types_type_classifier[idx]: # we must always use the type predicted by the type predictor if available predicted_type = predicted_types_type_classifier[idx] predicted_topology = predicted_topologies_type_classifier[idx] predicted_labels_for_protein = predicted_labels_type_classifer[idx] prediction_topology_match = is_topologies_equal(prot_topology_list[idx], predicted_topology, 5) if actual_type == predicted_type: validation_type_loss_tracker.append(0) # if we guessed the type right for SP+GLOB or GLOB, we count the topology as correct if actual_type == 2 or actual_type == 3 or prediction_topology_match: validation_topology_loss_tracker.append(0) confusion_matrix[actual_type][4] += 1 else: validation_topology_loss_tracker.append(1) confusion_matrix[actual_type][predicted_type] += 1 # if the type was correctly guess 2 or 3 by the type classifier, use its topology prediction if (actual_type == 2 or actual_type == 3) and self.type_classifier is not None: protein_label_prediction.append(predicted_labels_type_classifer[idx]) else: protein_label_prediction.append(predicted_labels_for_protein) else: confusion_matrix[actual_type][predicted_type] += 1 validation_type_loss_tracker.append(1) validation_topology_loss_tracker.append(1) protein_label_prediction.append(predicted_labels_for_protein) write_out(confusion_matrix) loss = float(torch.stack(validation_loss_tracker).mean()) type_loss = float(torch.FloatTensor(validation_type_loss_tracker).mean().detach()) topology_loss = float(torch.FloatTensor(validation_topology_loss_tracker).mean().detach()) self.type_01loss_values.append(type_loss) self.topology_01loss_values.append(topology_loss) if get_experiment_id() is not None and "TYPE" in get_experiment_id(): # optimize for type validation_loss = type_loss else: # optimize for topology validation_loss = topology_loss data = {} data['type_01loss_values'] = self.type_01loss_values data['topology_01loss_values'] = self.topology_01loss_values data['confusion_matrix'] = confusion_matrix.tolist() return validation_loss, data, (protein_names, protein_aa_strings, protein_label_actual, protein_label_prediction) def post_process_prediction_data(self, prediction_data): data = [] for (name, aa_string, actual, prediction) in zip(*prediction_data): data.append("\n".join([">" + name, aa_string, actual, original_labels_to_fasta(prediction)])) return "\n".join(data) def logsumexp(self, data, dim): return data.max(dim)[0] + torch.log(torch.sum(torch.exp(data - data.max(dim)[0].unsqueeze(dim)), dim)) class TMHMM3Mode(Enum): LSTM = 1 LSTM_CRF = 2 LSTM_CRF_HMM = 3 LSTM_CRF_MARG = 4 LSTM_CTC = 5
openprotein-master
experiments/tmhmm3/tm_models.py
# This file is part of the OpenProtein project. # # @author Jeppe Hallgren # # For license information, please see the LICENSE file in the root directory. from preprocessing import process_raw_data from models import * from training import train_model def run_experiment(parser, use_gpu): # parse experiment specific command line arguments parser.add_argument('--learning-rate', dest='learning_rate', type=float, default=0.01, help='Learning rate to use during training.') args, unknown = parser.parse_known_args() # pre-process data process_raw_data(use_gpu, force_pre_processing_overwrite=False) # run experiment training_file = "data/preprocessed/sample.txt.hdf5" validation_file = "data/preprocessed/sample.txt.hdf5" model = ExampleModel(21, args.minibatch_size, use_gpu=use_gpu) # embed size = 21 train_loader = contruct_dataloader_from_disk(training_file, args.minibatch_size) validation_loader = contruct_dataloader_from_disk(validation_file, args.minibatch_size) train_model_path = train_model(data_set_identifier="TRAIN", model=model, train_loader=train_loader, validation_loader=validation_loader, learning_rate=args.learning_rate, minibatch_size=args.minibatch_size, eval_interval=args.eval_interval, hide_ui=args.hide_ui, use_gpu=use_gpu, minimum_updates=args.minimum_updates) print(train_model_path)
openprotein-master
experiments/example/__init__.py
""" pNeRF algorithm for parallelized conversion from torsion (dihedral) angles to Cartesian coordinates implemented with PyTorch. Reference implementation in tensorflow by Mohammed AlQuraishi: https://github.com/aqlaboratory/pnerf/blob/master/pnerf.py Paper (preprint) by Mohammed AlQuraishi: https://www.biorxiv.org/content/early/2018/08/06/385450 PyTorch implementation by Felix Opolka """ import math import collections import numpy as np import torch import torch.nn.functional as F # Constants NUM_DIMENSIONS = 3 NUM_DIHEDRALS = 3 BOND_LENGTHS = np.array([145.801, 152.326, 132.868], dtype=np.float32) BOND_ANGLES = np.array([2.124, 1.941, 2.028], dtype=np.float32) def dihedral_to_point(dihedral, use_gpu, bond_lengths=BOND_LENGTHS, bond_angles=BOND_ANGLES): """ Takes triplets of dihedral angles (phi, psi, omega) and returns 3D points ready for use in reconstruction of coordinates. Bond lengths and angles are based on idealized averages. :param dihedral: [NUM_STEPS, BATCH_SIZE, NUM_DIHEDRALS] :return: Tensor containing points of the protein's backbone atoms. Shape [NUM_STEPS x NUM_DIHEDRALS, BATCH_SIZE, NUM_DIMENSIONS] """ num_steps = dihedral.shape[0] batch_size = dihedral.shape[1] r_cos_theta = torch.tensor(bond_lengths * np.cos(np.pi - bond_angles)) r_sin_theta = torch.tensor(bond_lengths * np.sin(np.pi - bond_angles)) if use_gpu: r_cos_theta = r_cos_theta.cuda() r_sin_theta = r_sin_theta.cuda() point_x = r_cos_theta.view(1, 1, -1).repeat(num_steps, batch_size, 1) point_y = torch.cos(dihedral) * r_sin_theta point_z = torch.sin(dihedral) * r_sin_theta point = torch.stack([point_x, point_y, point_z]) point_perm = point.permute(1, 3, 2, 0) point_final = point_perm.contiguous().view(num_steps*NUM_DIHEDRALS, batch_size, NUM_DIMENSIONS) return point_final def point_to_coordinate(points, use_gpu, num_fragments=6): """ Takes points from dihedral_to_point and sequentially converts them into coordinates of a 3D structure. Reconstruction is done in parallel by independently reconstructing num_fragments and the reconstituting the chain at the end in reverse order. The core reconstruction algorithm is NeRF, based on DOI: 10.1002/jcc.20237 by Parsons et al. 2005. The parallelized version is described in https://www.biorxiv.org/content/early/2018/08/06/385450. :param points: Tensor containing points as returned by `dihedral_to_point`. Shape [NUM_STEPS x NUM_DIHEDRALS, BATCH_SIZE, NUM_DIMENSIONS] :param num_fragments: Number of fragments in which the sequence is split to perform parallel computation. :return: Tensor containing correctly transformed atom coordinates. Shape [NUM_STEPS x NUM_DIHEDRALS, BATCH_SIZE, NUM_DIMENSIONS] """ # Compute optimal number of fragments if needed total_num_angles = points.shape[0] # NUM_STEPS x NUM_DIHEDRALS if num_fragments is None: num_fragments = int(math.sqrt(total_num_angles)) # Initial three coordinates (specifically chosen to eliminate need for # extraneous matmul) Triplet = collections.namedtuple('Triplet', 'a, b, c') batch_size = points.shape[1] init_matrix = np.array([[-np.sqrt(1.0 / 2.0), np.sqrt(3.0 / 2.0), 0], [-np.sqrt(2.0), 0, 0], [0, 0, 0]], dtype=np.float32) init_matrix = torch.from_numpy(init_matrix) if use_gpu: init_matrix = init_matrix.cuda() init_coords = [row.repeat([num_fragments * batch_size, 1]) .view(num_fragments, batch_size, NUM_DIMENSIONS) for row in init_matrix] init_coords = Triplet(*init_coords) # NUM_DIHEDRALS x [NUM_FRAGS, BATCH_SIZE, NUM_DIMENSIONS] # Pad points to yield equal-sized fragments padding = ((num_fragments - (total_num_angles % num_fragments)) % num_fragments) # (NUM_FRAGS x FRAG_SIZE) - (NUM_STEPS x NUM_DIHEDRALS) points = F.pad(points, (0, 0, 0, 0, 0, padding)) # [NUM_FRAGS x FRAG_SIZE, BATCH_SIZE, NUM_DIMENSIONS] points = points.view(num_fragments, -1, batch_size, NUM_DIMENSIONS) # [NUM_FRAGS, FRAG_SIZE, BATCH_SIZE, NUM_DIMENSIONS] points = points.permute(1, 0, 2, 3) # [FRAG_SIZE, NUM_FRAGS, BATCH_SIZE, NUM_DIMENSIONS] # Extension function used for single atom reconstruction and whole fragment # alignment def extend(prev_three_coords, point, multi_m): """ Aligns an atom or an entire fragment depending on value of `multi_m` with the preceding three atoms. :param prev_three_coords: Named tuple storing the last three atom coordinates ("a", "b", "c") where "c" is the current end of the structure (i.e. closest to the atom/ fragment that will be added now). Shape NUM_DIHEDRALS x [NUM_FRAGS/0, BATCH_SIZE, NUM_DIMENSIONS]. First rank depends on value of `multi_m`. :param point: Point describing the atom that is added to the structure. Shape [NUM_FRAGS/FRAG_SIZE, BATCH_SIZE, NUM_DIMENSIONS] First rank depends on value of `multi_m`. :param multi_m: If True, a single atom is added to the chain for multiple fragments in parallel. If False, an single fragment is added. Note the different parameter dimensions. :return: Coordinates of the atom/ fragment. """ bc = F.normalize(prev_three_coords.c - prev_three_coords.b, dim=-1) n = F.normalize(torch.cross(prev_three_coords.b - prev_three_coords.a, bc), dim=-1) if multi_m: # multiple fragments, one atom at a time m = torch.stack([bc, torch.cross(n, bc), n]).permute(1, 2, 3, 0) else: # single fragment, reconstructed entirely at once. s = point.shape + (3,) m = torch.stack([bc, torch.cross(n, bc), n]).permute(1, 2, 0) m = m.repeat(s[0], 1, 1).view(s) coord = torch.squeeze(torch.matmul(m, point.unsqueeze(3)), dim=3) + prev_three_coords.c return coord # Loop over FRAG_SIZE in NUM_FRAGS parallel fragments, sequentially # generating the coordinates for each fragment across all batches coords_list = [None] * points.shape[0] # FRAG_SIZE x [NUM_FRAGS, BATCH_SIZE, NUM_DIMENSIONS] prev_three_coords = init_coords for i in range(points.shape[0]): # Iterate over FRAG_SIZE coord = extend(prev_three_coords, points[i], True) coords_list[i] = coord prev_three_coords = Triplet(prev_three_coords.b, prev_three_coords.c, coord) coords_pretrans = torch.stack(coords_list).permute(1, 0, 2, 3) # Loop backwards over NUM_FRAGS to align the individual fragments. For each # next fragment, we transform the fragments we have already iterated over # (coords_trans) to be aligned with the next fragment coords_trans = coords_pretrans[-1] for i in reversed(range(coords_pretrans.shape[0]-1)): # Transform the fragments that we have already iterated over to be # aligned with the next fragment `coords_trans` transformed_coords = extend(Triplet(*[di[i] for di in prev_three_coords]), coords_trans, False) coords_trans = torch.cat([coords_pretrans[i], transformed_coords], 0) coords = F.pad(coords_trans[:total_num_angles-1], (0, 0, 0, 0, 1, 0)) return coords
openprotein-master
pnerf/pnerf.py
from setuptools import setup, find_packages setup( name = 'point-transformer-pytorch', packages = find_packages(), version = '0.1.5', license='MIT', description = 'Point Transformer - Pytorch', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', url = 'https://github.com/lucidrains/point-transformer-pytorch', keywords = [ 'artificial intelligence', 'transformers', 'attention mechanism', 'point clouds' ], install_requires=[ 'einops>=0.3', 'torch>=1.6' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
point-transformer-pytorch-main
setup.py
import torch from torch import nn, einsum from einops import repeat # helpers def exists(val): return val is not None def max_value(t): return torch.finfo(t.dtype).max def batched_index_select(values, indices, dim = 1): value_dims = values.shape[(dim + 1):] values_shape, indices_shape = map(lambda t: list(t.shape), (values, indices)) indices = indices[(..., *((None,) * len(value_dims)))] indices = indices.expand(*((-1,) * len(indices_shape)), *value_dims) value_expand_len = len(indices_shape) - (dim + 1) values = values[(*((slice(None),) * dim), *((None,) * value_expand_len), ...)] value_expand_shape = [-1] * len(values.shape) expand_slice = slice(dim, (dim + value_expand_len)) value_expand_shape[expand_slice] = indices.shape[expand_slice] values = values.expand(*value_expand_shape) dim += value_expand_len return values.gather(dim, indices) # classes class PointTransformerLayer(nn.Module): def __init__( self, *, dim, pos_mlp_hidden_dim = 64, attn_mlp_hidden_mult = 4, num_neighbors = None ): super().__init__() self.num_neighbors = num_neighbors self.to_qkv = nn.Linear(dim, dim * 3, bias = False) self.pos_mlp = nn.Sequential( nn.Linear(3, pos_mlp_hidden_dim), nn.ReLU(), nn.Linear(pos_mlp_hidden_dim, dim) ) self.attn_mlp = nn.Sequential( nn.Linear(dim, dim * attn_mlp_hidden_mult), nn.ReLU(), nn.Linear(dim * attn_mlp_hidden_mult, dim), ) def forward(self, x, pos, mask = None): n, num_neighbors = x.shape[1], self.num_neighbors # get queries, keys, values q, k, v = self.to_qkv(x).chunk(3, dim = -1) # calculate relative positional embeddings rel_pos = pos[:, :, None, :] - pos[:, None, :, :] rel_pos_emb = self.pos_mlp(rel_pos) # use subtraction of queries to keys. i suppose this is a better inductive bias for point clouds than dot product qk_rel = q[:, :, None, :] - k[:, None, :, :] # prepare mask if exists(mask): mask = mask[:, :, None] * mask[:, None, :] # expand values v = repeat(v, 'b j d -> b i j d', i = n) # determine k nearest neighbors for each point, if specified if exists(num_neighbors) and num_neighbors < n: rel_dist = rel_pos.norm(dim = -1) if exists(mask): mask_value = max_value(rel_dist) rel_dist.masked_fill_(~mask, mask_value) dist, indices = rel_dist.topk(num_neighbors, largest = False) v = batched_index_select(v, indices, dim = 2) qk_rel = batched_index_select(qk_rel, indices, dim = 2) rel_pos_emb = batched_index_select(rel_pos_emb, indices, dim = 2) mask = batched_index_select(mask, indices, dim = 2) if exists(mask) else None # add relative positional embeddings to value v = v + rel_pos_emb # use attention mlp, making sure to add relative positional embedding first sim = self.attn_mlp(qk_rel + rel_pos_emb) # masking if exists(mask): mask_value = -max_value(sim) sim.masked_fill_(~mask[..., None], mask_value) # attention attn = sim.softmax(dim = -2) # aggregate agg = einsum('b i j d, b i j d -> b i d', attn, v) return agg
point-transformer-pytorch-main
point_transformer_pytorch/point_transformer_pytorch.py
import torch from torch import nn, einsum from einops import repeat, rearrange # helpers def exists(val): return val is not None def max_value(t): return torch.finfo(t.dtype).max def batched_index_select(values, indices, dim = 1): value_dims = values.shape[(dim + 1):] values_shape, indices_shape = map(lambda t: list(t.shape), (values, indices)) indices = indices[(..., *((None,) * len(value_dims)))] indices = indices.expand(*((-1,) * len(indices_shape)), *value_dims) value_expand_len = len(indices_shape) - (dim + 1) values = values[(*((slice(None),) * dim), *((None,) * value_expand_len), ...)] value_expand_shape = [-1] * len(values.shape) expand_slice = slice(dim, (dim + value_expand_len)) value_expand_shape[expand_slice] = indices.shape[expand_slice] values = values.expand(*value_expand_shape) dim += value_expand_len return values.gather(dim, indices) # classes class MultiheadPointTransformerLayer(nn.Module): def __init__( self, *, dim, heads = 4, dim_head = 64, pos_mlp_hidden_dim = 64, attn_mlp_hidden_mult = 4, num_neighbors = None ): super().__init__() self.heads = heads inner_dim = dim_head * heads self.num_neighbors = num_neighbors self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False) self.to_out = nn.Linear(inner_dim, dim) self.pos_mlp = nn.Sequential( nn.Linear(3, pos_mlp_hidden_dim), nn.ReLU(), nn.Linear(pos_mlp_hidden_dim, inner_dim) ) attn_inner_dim = inner_dim * attn_mlp_hidden_mult self.attn_mlp = nn.Sequential( nn.Conv2d(inner_dim, attn_inner_dim, 1, groups = heads), nn.ReLU(), nn.Conv2d(attn_inner_dim, inner_dim, 1, groups = heads), ) def forward(self, x, pos, mask = None): n, h, num_neighbors = x.shape[1], self.heads, self.num_neighbors # get queries, keys, values q, k, v = self.to_qkv(x).chunk(3, dim = -1) # split out heads q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), (q, k, v)) # calculate relative positional embeddings rel_pos = rearrange(pos, 'b i c -> b i 1 c') - rearrange(pos, 'b j c -> b 1 j c') rel_pos_emb = self.pos_mlp(rel_pos) # split out heads for rel pos emb rel_pos_emb = rearrange(rel_pos_emb, 'b i j (h d) -> b h i j d', h = h) # use subtraction of queries to keys. i suppose this is a better inductive bias for point clouds than dot product qk_rel = rearrange(q, 'b h i d -> b h i 1 d') - rearrange(k, 'b h j d -> b h 1 j d') # prepare mask if exists(mask): mask = rearrange(mask, 'b i -> b i 1') * rearrange(mask, 'b j -> b 1 j') # expand values v = repeat(v, 'b h j d -> b h i j d', i = n) # determine k nearest neighbors for each point, if specified if exists(num_neighbors) and num_neighbors < n: rel_dist = rel_pos.norm(dim = -1) if exists(mask): mask_value = max_value(rel_dist) rel_dist.masked_fill_(~mask, mask_value) dist, indices = rel_dist.topk(num_neighbors, largest = False) indices_with_heads = repeat(indices, 'b i j -> b h i j', h = h) v = batched_index_select(v, indices_with_heads, dim = 3) qk_rel = batched_index_select(qk_rel, indices_with_heads, dim = 3) rel_pos_emb = batched_index_select(rel_pos_emb, indices_with_heads, dim = 3) if exists(mask): mask = batched_index_select(mask, indices, dim = 2) # add relative positional embeddings to value v = v + rel_pos_emb # use attention mlp, making sure to add relative positional embedding first attn_mlp_input = qk_rel + rel_pos_emb attn_mlp_input = rearrange(attn_mlp_input, 'b h i j d -> b (h d) i j') sim = self.attn_mlp(attn_mlp_input) # masking if exists(mask): mask_value = -max_value(sim) mask = rearrange(mask, 'b i j -> b 1 i j') sim.masked_fill_(~mask, mask_value) # attention attn = sim.softmax(dim = -2) # aggregate v = rearrange(v, 'b h i j d -> b i j (h d)') agg = einsum('b d i j, b i j d -> b i d', attn, v) # combine heads return self.to_out(agg)
point-transformer-pytorch-main
point_transformer_pytorch/multihead_point_transformer_pytorch.py
from point_transformer_pytorch.point_transformer_pytorch import PointTransformerLayer from point_transformer_pytorch.multihead_point_transformer_pytorch import MultiheadPointTransformerLayer
point-transformer-pytorch-main
point_transformer_pytorch/__init__.py
from setuptools import setup, find_packages setup( name = 'esbn-pytorch', packages = find_packages(), version = '0.0.4', license='MIT', description = 'Emergent Symbol Binding Network - Pytorch', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', url = 'https://github.com/lucidrains/ESBN-pytorch', keywords = [ 'artificial intelligence', 'deep learning', 'neuro-symbolic', 'abstract reasoning', 'memory' ], install_requires=[ 'torch>=1.6', 'einops>=0.3' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
ESBN-pytorch-main
setup.py
from esbn_pytorch.esbn_pytorch import ESBN
ESBN-pytorch-main
esbn_pytorch/__init__.py
import torch from functools import partial from torch import nn, einsum from einops import repeat, rearrange # helpers def exists(val): return val is not None def safe_cat(t, el, dim = 0): if not exists(t): return el return torch.cat((t, el), dim = dim) def map_fn(fn, *args, **kwargs): def inner(*arr): return map(lambda t: fn(t, *args, **kwargs), arr) return inner # classes class ESBN(nn.Module): def __init__( self, *, value_dim = 64, key_dim = 64, hidden_dim = 512, output_dim = 4, encoder = None ): super().__init__() self.h0 = torch.zeros(hidden_dim) self.c0 = torch.zeros(hidden_dim) self.k0 = torch.zeros(key_dim + 1) self.rnn = nn.LSTMCell(key_dim + 1, hidden_dim) self.to_gate = nn.Linear(hidden_dim, 1) self.to_key = nn.Linear(hidden_dim, key_dim) self.to_output = nn.Linear(hidden_dim, output_dim) self.encoder = nn.Sequential( nn.Conv2d(3, 32, kernel_size = 4, stride = 2), nn.ReLU(), nn.Conv2d(32, 64, kernel_size = 4, stride = 2), nn.ReLU(), nn.Conv2d(64, 64, kernel_size = 4, stride = 2), nn.Flatten(1), nn.Linear(4 * 64, value_dim) ) if not exists(encoder) else encoder self.to_confidence = nn.Linear(1, 1) def forward(self, images): b = images.shape[1] Mk = None Mv = None hx, cx, kx, k0 = map_fn(repeat, 'd -> b d', b = b)(self.h0, self.c0, self.k0, self.k0) out = [] for ind, image in enumerate(images): is_first = ind == 0 z = self.encoder(image) hx, cx = self.rnn(kx, (hx, cx)) y, g, kw = self.to_output(hx), self.to_gate(hx), self.to_key(hx) if is_first: kx = k0 else: # attention sim = einsum('b n d, b d -> b n', Mv, z) wk = sim.softmax(dim = -1) # calculate confidence sim, wk = map_fn(rearrange, 'b n -> b n ()')(sim, wk) ck = self.to_confidence(sim).sigmoid() # concat confidence to memory keys # then weighted sum of all memory keys by attention of memory values kx = g.sigmoid() * (wk * torch.cat((Mk, ck), dim = -1)).sum(dim = 1) kw, z = map_fn(rearrange, 'b d -> b () d')(kw, z) Mk = safe_cat(Mk, kw, dim = 1) Mv = safe_cat(Mv, z, dim = 1) out.append(y) return torch.stack(out)
ESBN-pytorch-main
esbn_pytorch/esbn_pytorch.py
from setuptools import setup, find_packages setup( name = 'pixel-level-contrastive-learning', packages = find_packages(), version = '0.1.1', license='MIT', description = 'Pixel-Level Contrastive Learning', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', url = 'https://github.com/lucidrains/pixel-level-contrastive-learning', keywords = ['self-supervised learning', 'artificial intelligence'], install_requires=[ 'einops', 'torch>=1.6', 'kornia>=0.4.0' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
pixel-level-contrastive-learning-main
setup.py
import math import copy import random from functools import wraps, partial from math import floor import torch from torch import nn, einsum import torch.nn.functional as F from kornia import augmentation as augs from kornia import filters, color from einops import rearrange # helper functions def identity(t): return t def default(val, def_val): return def_val if val is None else val def rand_true(prob): return random.random() < prob def singleton(cache_key): def inner_fn(fn): @wraps(fn) def wrapper(self, *args, **kwargs): instance = getattr(self, cache_key) if instance is not None: return instance instance = fn(self, *args, **kwargs) setattr(self, cache_key, instance) return instance return wrapper return inner_fn def get_module_device(module): return next(module.parameters()).device def set_requires_grad(model, val): for p in model.parameters(): p.requires_grad = val def cutout_coordinates(image, ratio_range = (0.6, 0.8)): _, _, orig_h, orig_w = image.shape ratio_lo, ratio_hi = ratio_range random_ratio = ratio_lo + random.random() * (ratio_hi - ratio_lo) w, h = floor(random_ratio * orig_w), floor(random_ratio * orig_h) coor_x = floor((orig_w - w) * random.random()) coor_y = floor((orig_h - h) * random.random()) return ((coor_y, coor_y + h), (coor_x, coor_x + w)), random_ratio def cutout_and_resize(image, coordinates, output_size = None, mode = 'nearest'): shape = image.shape output_size = default(output_size, shape[2:]) (y0, y1), (x0, x1) = coordinates cutout_image = image[:, :, y0:y1, x0:x1] return F.interpolate(cutout_image, size = output_size, mode = mode) # augmentation utils class RandomApply(nn.Module): def __init__(self, fn, p): super().__init__() self.fn = fn self.p = p def forward(self, x): if random.random() > self.p: return x return self.fn(x) # exponential moving average class EMA(): def __init__(self, beta): super().__init__() self.beta = beta def update_average(self, old, new): if old is None: return new return old * self.beta + (1 - self.beta) * new def update_moving_average(ema_updater, ma_model, current_model): for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()): old_weight, up_weight = ma_params.data, current_params.data ma_params.data = ema_updater.update_average(old_weight, up_weight) # loss fn def loss_fn(x, y): x = F.normalize(x, dim=-1, p=2) y = F.normalize(y, dim=-1, p=2) return 2 - 2 * (x * y).sum(dim=-1) # classes class MLP(nn.Module): def __init__(self, chan, chan_out = 256, inner_dim = 2048): super().__init__() self.net = nn.Sequential( nn.Linear(chan, inner_dim), nn.BatchNorm1d(inner_dim), nn.ReLU(), nn.Linear(inner_dim, chan_out) ) def forward(self, x): return self.net(x) class ConvMLP(nn.Module): def __init__(self, chan, chan_out = 256, inner_dim = 2048): super().__init__() self.net = nn.Sequential( nn.Conv2d(chan, inner_dim, 1), nn.BatchNorm2d(inner_dim), nn.ReLU(), nn.Conv2d(inner_dim, chan_out, 1) ) def forward(self, x): return self.net(x) class PPM(nn.Module): def __init__( self, *, chan, num_layers = 1, gamma = 2): super().__init__() self.gamma = gamma if num_layers == 0: self.transform_net = nn.Identity() elif num_layers == 1: self.transform_net = nn.Conv2d(chan, chan, 1) elif num_layers == 2: self.transform_net = nn.Sequential( nn.Conv2d(chan, chan, 1), nn.BatchNorm2d(chan), nn.ReLU(), nn.Conv2d(chan, chan, 1) ) else: raise ValueError('num_layers must be one of 0, 1, or 2') def forward(self, x): xi = x[:, :, :, :, None, None] xj = x[:, :, None, None, :, :] similarity = F.relu(F.cosine_similarity(xi, xj, dim = 1)) ** self.gamma transform_out = self.transform_net(x) out = einsum('b x y h w, b c h w -> b c x y', similarity, transform_out) return out # a wrapper class for the base neural network # will manage the interception of the hidden layer output # and pipe it into the projecter and predictor nets class NetWrapper(nn.Module): def __init__( self, *, net, projection_size, projection_hidden_size, layer_pixel = -2, layer_instance = -2 ): super().__init__() self.net = net self.layer_pixel = layer_pixel self.layer_instance = layer_instance self.pixel_projector = None self.instance_projector = None self.projection_size = projection_size self.projection_hidden_size = projection_hidden_size self.hidden_pixel = None self.hidden_instance = None self.hook_registered = False def _find_layer(self, layer_id): if type(layer_id) == str: modules = dict([*self.net.named_modules()]) return modules.get(layer_id, None) elif type(layer_id) == int: children = [*self.net.children()] return children[layer_id] return None def _hook_pixel(self, _, __, output): setattr(self, 'hidden_pixel', output) def _hook_instance(self, _, __, output): setattr(self, 'hidden_instance', output) def _register_hook(self): pixel_layer = self._find_layer(self.layer_pixel) instance_layer = self._find_layer(self.layer_instance) assert pixel_layer is not None, f'hidden layer ({self.layer_pixel}) not found' assert instance_layer is not None, f'hidden layer ({self.layer_instance}) not found' pixel_layer.register_forward_hook(self._hook_pixel) instance_layer.register_forward_hook(self._hook_instance) self.hook_registered = True @singleton('pixel_projector') def _get_pixel_projector(self, hidden): _, dim, *_ = hidden.shape projector = ConvMLP(dim, self.projection_size, self.projection_hidden_size) return projector.to(hidden) @singleton('instance_projector') def _get_instance_projector(self, hidden): _, dim = hidden.shape projector = MLP(dim, self.projection_size, self.projection_hidden_size) return projector.to(hidden) def get_representation(self, x): if not self.hook_registered: self._register_hook() _ = self.net(x) hidden_pixel = self.hidden_pixel hidden_instance = self.hidden_instance self.hidden_pixel = None self.hidden_instance = None assert hidden_pixel is not None, f'hidden pixel layer {self.layer_pixel} never emitted an output' assert hidden_instance is not None, f'hidden instance layer {self.layer_instance} never emitted an output' return hidden_pixel, hidden_instance def forward(self, x): pixel_representation, instance_representation = self.get_representation(x) instance_representation = instance_representation.flatten(1) pixel_projector = self._get_pixel_projector(pixel_representation) instance_projector = self._get_instance_projector(instance_representation) pixel_projection = pixel_projector(pixel_representation) instance_projection = instance_projector(instance_representation) return pixel_projection, instance_projection # main class class PixelCL(nn.Module): def __init__( self, net, image_size, hidden_layer_pixel = -2, hidden_layer_instance = -2, projection_size = 256, projection_hidden_size = 2048, augment_fn = None, augment_fn2 = None, prob_rand_hflip = 0.25, moving_average_decay = 0.99, ppm_num_layers = 1, ppm_gamma = 2, distance_thres = 0.7, similarity_temperature = 0.3, alpha = 1., use_pixpro = True, cutout_ratio_range = (0.6, 0.8), cutout_interpolate_mode = 'nearest', coord_cutout_interpolate_mode = 'bilinear' ): super().__init__() DEFAULT_AUG = nn.Sequential( RandomApply(augs.ColorJitter(0.8, 0.8, 0.8, 0.2), p=0.8), augs.RandomGrayscale(p=0.2), RandomApply(filters.GaussianBlur2d((3, 3), (1.5, 1.5)), p=0.1), augs.RandomSolarize(p=0.5), augs.Normalize(mean=torch.tensor([0.485, 0.456, 0.406]), std=torch.tensor([0.229, 0.224, 0.225])) ) self.augment1 = default(augment_fn, DEFAULT_AUG) self.augment2 = default(augment_fn2, self.augment1) self.prob_rand_hflip = prob_rand_hflip self.online_encoder = NetWrapper( net = net, projection_size = projection_size, projection_hidden_size = projection_hidden_size, layer_pixel = hidden_layer_pixel, layer_instance = hidden_layer_instance ) self.target_encoder = None self.target_ema_updater = EMA(moving_average_decay) self.distance_thres = distance_thres self.similarity_temperature = similarity_temperature self.alpha = alpha self.use_pixpro = use_pixpro if use_pixpro: self.propagate_pixels = PPM( chan = projection_size, num_layers = ppm_num_layers, gamma = ppm_gamma ) self.cutout_ratio_range = cutout_ratio_range self.cutout_interpolate_mode = cutout_interpolate_mode self.coord_cutout_interpolate_mode = coord_cutout_interpolate_mode # instance level predictor self.online_predictor = MLP(projection_size, projection_size, projection_hidden_size) # get device of network and make wrapper same device device = get_module_device(net) self.to(device) # send a mock image tensor to instantiate singleton parameters self.forward(torch.randn(2, 3, image_size, image_size, device=device)) @singleton('target_encoder') def _get_target_encoder(self): target_encoder = copy.deepcopy(self.online_encoder) set_requires_grad(target_encoder, False) return target_encoder def reset_moving_average(self): del self.target_encoder self.target_encoder = None def update_moving_average(self): assert self.target_encoder is not None, 'target encoder has not been created yet' update_moving_average(self.target_ema_updater, self.target_encoder, self.online_encoder) def forward(self, x, return_positive_pairs = False): shape, device, prob_flip = x.shape, x.device, self.prob_rand_hflip rand_flip_fn = lambda t: torch.flip(t, dims = (-1,)) flip_image_one, flip_image_two = rand_true(prob_flip), rand_true(prob_flip) flip_image_one_fn = rand_flip_fn if flip_image_one else identity flip_image_two_fn = rand_flip_fn if flip_image_two else identity cutout_coordinates_one, _ = cutout_coordinates(x, self.cutout_ratio_range) cutout_coordinates_two, _ = cutout_coordinates(x, self.cutout_ratio_range) image_one_cutout = cutout_and_resize(x, cutout_coordinates_one, mode = self.cutout_interpolate_mode) image_two_cutout = cutout_and_resize(x, cutout_coordinates_two, mode = self.cutout_interpolate_mode) image_one_cutout = flip_image_one_fn(image_one_cutout) image_two_cutout = flip_image_two_fn(image_two_cutout) image_one_cutout, image_two_cutout = self.augment1(image_one_cutout), self.augment2(image_two_cutout) proj_pixel_one, proj_instance_one = self.online_encoder(image_one_cutout) proj_pixel_two, proj_instance_two = self.online_encoder(image_two_cutout) image_h, image_w = shape[2:] proj_image_shape = proj_pixel_one.shape[2:] proj_image_h, proj_image_w = proj_image_shape coordinates = torch.meshgrid( torch.arange(image_h, device = device), torch.arange(image_w, device = device) ) coordinates = torch.stack(coordinates).unsqueeze(0).float() coordinates /= math.sqrt(image_h ** 2 + image_w ** 2) coordinates[:, 0] *= proj_image_h coordinates[:, 1] *= proj_image_w proj_coors_one = cutout_and_resize(coordinates, cutout_coordinates_one, output_size = proj_image_shape, mode = self.coord_cutout_interpolate_mode) proj_coors_two = cutout_and_resize(coordinates, cutout_coordinates_two, output_size = proj_image_shape, mode = self.coord_cutout_interpolate_mode) proj_coors_one = flip_image_one_fn(proj_coors_one) proj_coors_two = flip_image_two_fn(proj_coors_two) proj_coors_one, proj_coors_two = map(lambda t: rearrange(t, 'b c h w -> (b h w) c'), (proj_coors_one, proj_coors_two)) pdist = nn.PairwiseDistance(p = 2) num_pixels = proj_coors_one.shape[0] proj_coors_one_expanded = proj_coors_one[:, None].expand(num_pixels, num_pixels, -1).reshape(num_pixels * num_pixels, 2) proj_coors_two_expanded = proj_coors_two[None, :].expand(num_pixels, num_pixels, -1).reshape(num_pixels * num_pixels, 2) distance_matrix = pdist(proj_coors_one_expanded, proj_coors_two_expanded) distance_matrix = distance_matrix.reshape(num_pixels, num_pixels) positive_mask_one_two = distance_matrix < self.distance_thres positive_mask_two_one = positive_mask_one_two.t() with torch.no_grad(): target_encoder = self._get_target_encoder() target_proj_pixel_one, target_proj_instance_one = target_encoder(image_one_cutout) target_proj_pixel_two, target_proj_instance_two = target_encoder(image_two_cutout) # flatten all the pixel projections flatten = lambda t: rearrange(t, 'b c h w -> b c (h w)') target_proj_pixel_one, target_proj_pixel_two = list(map(flatten, (target_proj_pixel_one, target_proj_pixel_two))) # get total number of positive pixel pairs positive_pixel_pairs = positive_mask_one_two.sum() # get instance level loss pred_instance_one = self.online_predictor(proj_instance_one) pred_instance_two = self.online_predictor(proj_instance_two) loss_instance_one = loss_fn(pred_instance_one, target_proj_instance_two.detach()) loss_instance_two = loss_fn(pred_instance_two, target_proj_instance_one.detach()) instance_loss = (loss_instance_one + loss_instance_two).mean() if positive_pixel_pairs == 0: ret = (instance_loss, 0) if return_positive_pairs else instance_loss return ret if not self.use_pixpro: # calculate pix contrast loss proj_pixel_one, proj_pixel_two = list(map(flatten, (proj_pixel_one, proj_pixel_two))) similarity_one_two = F.cosine_similarity(proj_pixel_one[..., :, None], target_proj_pixel_two[..., None, :], dim = 1) / self.similarity_temperature similarity_two_one = F.cosine_similarity(proj_pixel_two[..., :, None], target_proj_pixel_one[..., None, :], dim = 1) / self.similarity_temperature loss_pix_one_two = -torch.log( similarity_one_two.masked_select(positive_mask_one_two[None, ...]).exp().sum() / similarity_one_two.exp().sum() ) loss_pix_two_one = -torch.log( similarity_two_one.masked_select(positive_mask_two_one[None, ...]).exp().sum() / similarity_two_one.exp().sum() ) pix_loss = (loss_pix_one_two + loss_pix_two_one) / 2 else: # calculate pix pro loss propagated_pixels_one = self.propagate_pixels(proj_pixel_one) propagated_pixels_two = self.propagate_pixels(proj_pixel_two) propagated_pixels_one, propagated_pixels_two = list(map(flatten, (propagated_pixels_one, propagated_pixels_two))) propagated_similarity_one_two = F.cosine_similarity(propagated_pixels_one[..., :, None], target_proj_pixel_two[..., None, :], dim = 1) propagated_similarity_two_one = F.cosine_similarity(propagated_pixels_two[..., :, None], target_proj_pixel_one[..., None, :], dim = 1) loss_pixpro_one_two = - propagated_similarity_one_two.masked_select(positive_mask_one_two[None, ...]).mean() loss_pixpro_two_one = - propagated_similarity_two_one.masked_select(positive_mask_two_one[None, ...]).mean() pix_loss = (loss_pixpro_one_two + loss_pixpro_two_one) / 2 # total loss loss = pix_loss * self.alpha + instance_loss ret = (loss, positive_pixel_pairs) if return_positive_pairs else loss return ret
pixel-level-contrastive-learning-main
pixel_level_contrastive_learning/pixel_level_contrastive_learning.py
from pixel_level_contrastive_learning.pixel_level_contrastive_learning import PPM, PixelCL
pixel-level-contrastive-learning-main
pixel_level_contrastive_learning/__init__.py
from setuptools import setup, find_packages setup( name = 'byol-pytorch', packages = find_packages(exclude=['examples']), version = '0.6.0', license='MIT', description = 'Self-supervised contrastive learning made simple', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', url = 'https://github.com/lucidrains/byol-pytorch', keywords = [ 'self-supervised learning', 'artificial intelligence' ], install_requires=[ 'torch>=1.6', 'torchvision>=0.8' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
byol-pytorch-master
setup.py
from byol_pytorch.byol_pytorch import BYOL
byol-pytorch-master
byol_pytorch/__init__.py
import copy import random from functools import wraps import torch from torch import nn import torch.nn.functional as F from torchvision import transforms as T # helper functions def default(val, def_val): return def_val if val is None else val def flatten(t): return t.reshape(t.shape[0], -1) def singleton(cache_key): def inner_fn(fn): @wraps(fn) def wrapper(self, *args, **kwargs): instance = getattr(self, cache_key) if instance is not None: return instance instance = fn(self, *args, **kwargs) setattr(self, cache_key, instance) return instance return wrapper return inner_fn def get_module_device(module): return next(module.parameters()).device def set_requires_grad(model, val): for p in model.parameters(): p.requires_grad = val # loss fn def loss_fn(x, y): x = F.normalize(x, dim=-1, p=2) y = F.normalize(y, dim=-1, p=2) return 2 - 2 * (x * y).sum(dim=-1) # augmentation utils class RandomApply(nn.Module): def __init__(self, fn, p): super().__init__() self.fn = fn self.p = p def forward(self, x): if random.random() > self.p: return x return self.fn(x) # exponential moving average class EMA(): def __init__(self, beta): super().__init__() self.beta = beta def update_average(self, old, new): if old is None: return new return old * self.beta + (1 - self.beta) * new def update_moving_average(ema_updater, ma_model, current_model): for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()): old_weight, up_weight = ma_params.data, current_params.data ma_params.data = ema_updater.update_average(old_weight, up_weight) # MLP class for projector and predictor def MLP(dim, projection_size, hidden_size=4096): return nn.Sequential( nn.Linear(dim, hidden_size), nn.BatchNorm1d(hidden_size), nn.ReLU(inplace=True), nn.Linear(hidden_size, projection_size) ) def SimSiamMLP(dim, projection_size, hidden_size=4096): return nn.Sequential( nn.Linear(dim, hidden_size, bias=False), nn.BatchNorm1d(hidden_size), nn.ReLU(inplace=True), nn.Linear(hidden_size, hidden_size, bias=False), nn.BatchNorm1d(hidden_size), nn.ReLU(inplace=True), nn.Linear(hidden_size, projection_size, bias=False), nn.BatchNorm1d(projection_size, affine=False) ) # a wrapper class for the base neural network # will manage the interception of the hidden layer output # and pipe it into the projecter and predictor nets class NetWrapper(nn.Module): def __init__(self, net, projection_size, projection_hidden_size, layer = -2, use_simsiam_mlp = False): super().__init__() self.net = net self.layer = layer self.projector = None self.projection_size = projection_size self.projection_hidden_size = projection_hidden_size self.use_simsiam_mlp = use_simsiam_mlp self.hidden = {} self.hook_registered = False def _find_layer(self): if type(self.layer) == str: modules = dict([*self.net.named_modules()]) return modules.get(self.layer, None) elif type(self.layer) == int: children = [*self.net.children()] return children[self.layer] return None def _hook(self, _, input, output): device = input[0].device self.hidden[device] = flatten(output) def _register_hook(self): layer = self._find_layer() assert layer is not None, f'hidden layer ({self.layer}) not found' handle = layer.register_forward_hook(self._hook) self.hook_registered = True @singleton('projector') def _get_projector(self, hidden): _, dim = hidden.shape create_mlp_fn = MLP if not self.use_simsiam_mlp else SimSiamMLP projector = create_mlp_fn(dim, self.projection_size, self.projection_hidden_size) return projector.to(hidden) def get_representation(self, x): if self.layer == -1: return self.net(x) if not self.hook_registered: self._register_hook() self.hidden.clear() _ = self.net(x) hidden = self.hidden[x.device] self.hidden.clear() assert hidden is not None, f'hidden layer {self.layer} never emitted an output' return hidden def forward(self, x, return_projection = True): representation = self.get_representation(x) if not return_projection: return representation projector = self._get_projector(representation) projection = projector(representation) return projection, representation # main class class BYOL(nn.Module): def __init__( self, net, image_size, hidden_layer = -2, projection_size = 256, projection_hidden_size = 4096, augment_fn = None, augment_fn2 = None, moving_average_decay = 0.99, use_momentum = True ): super().__init__() self.net = net # default SimCLR augmentation DEFAULT_AUG = torch.nn.Sequential( RandomApply( T.ColorJitter(0.8, 0.8, 0.8, 0.2), p = 0.3 ), T.RandomGrayscale(p=0.2), T.RandomHorizontalFlip(), RandomApply( T.GaussianBlur((3, 3), (1.0, 2.0)), p = 0.2 ), T.RandomResizedCrop((image_size, image_size)), T.Normalize( mean=torch.tensor([0.485, 0.456, 0.406]), std=torch.tensor([0.229, 0.224, 0.225])), ) self.augment1 = default(augment_fn, DEFAULT_AUG) self.augment2 = default(augment_fn2, self.augment1) self.online_encoder = NetWrapper(net, projection_size, projection_hidden_size, layer=hidden_layer, use_simsiam_mlp=not use_momentum) self.use_momentum = use_momentum self.target_encoder = None self.target_ema_updater = EMA(moving_average_decay) self.online_predictor = MLP(projection_size, projection_size, projection_hidden_size) # get device of network and make wrapper same device device = get_module_device(net) self.to(device) # send a mock image tensor to instantiate singleton parameters self.forward(torch.randn(2, 3, image_size, image_size, device=device)) @singleton('target_encoder') def _get_target_encoder(self): target_encoder = copy.deepcopy(self.online_encoder) set_requires_grad(target_encoder, False) return target_encoder def reset_moving_average(self): del self.target_encoder self.target_encoder = None def update_moving_average(self): assert self.use_momentum, 'you do not need to update the moving average, since you have turned off momentum for the target encoder' assert self.target_encoder is not None, 'target encoder has not been created yet' update_moving_average(self.target_ema_updater, self.target_encoder, self.online_encoder) def forward( self, x, return_embedding = False, return_projection = True ): assert not (self.training and x.shape[0] == 1), 'you must have greater than 1 sample when training, due to the batchnorm in the projection layer' if return_embedding: return self.online_encoder(x, return_projection = return_projection) image_one, image_two = self.augment1(x), self.augment2(x) online_proj_one, _ = self.online_encoder(image_one) online_proj_two, _ = self.online_encoder(image_two) online_pred_one = self.online_predictor(online_proj_one) online_pred_two = self.online_predictor(online_proj_two) with torch.no_grad(): target_encoder = self._get_target_encoder() if self.use_momentum else self.online_encoder target_proj_one, _ = target_encoder(image_one) target_proj_two, _ = target_encoder(image_two) target_proj_one.detach_() target_proj_two.detach_() loss_one = loss_fn(online_pred_one, target_proj_two.detach()) loss_two = loss_fn(online_pred_two, target_proj_one.detach()) loss = loss_one + loss_two return loss.mean()
byol-pytorch-master
byol_pytorch/byol_pytorch.py
import os import argparse import multiprocessing from pathlib import Path from PIL import Image import torch from torchvision import models, transforms from torch.utils.data import DataLoader, Dataset from byol_pytorch import BYOL import pytorch_lightning as pl # test model, a resnet 50 resnet = models.resnet50(pretrained=True) # arguments parser = argparse.ArgumentParser(description='byol-lightning-test') parser.add_argument('--image_folder', type=str, required = True, help='path to your folder of images for self-supervised learning') args = parser.parse_args() # constants BATCH_SIZE = 32 EPOCHS = 1000 LR = 3e-4 NUM_GPUS = 2 IMAGE_SIZE = 256 IMAGE_EXTS = ['.jpg', '.png', '.jpeg'] NUM_WORKERS = multiprocessing.cpu_count() # pytorch lightning module class SelfSupervisedLearner(pl.LightningModule): def __init__(self, net, **kwargs): super().__init__() self.learner = BYOL(net, **kwargs) def forward(self, images): return self.learner(images) def training_step(self, images, _): loss = self.forward(images) return {'loss': loss} def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=LR) def on_before_zero_grad(self, _): if self.learner.use_momentum: self.learner.update_moving_average() # images dataset def expand_greyscale(t): return t.expand(3, -1, -1) class ImagesDataset(Dataset): def __init__(self, folder, image_size): super().__init__() self.folder = folder self.paths = [] for path in Path(f'{folder}').glob('**/*'): _, ext = os.path.splitext(path) if ext.lower() in IMAGE_EXTS: self.paths.append(path) print(f'{len(self.paths)} images found') self.transform = transforms.Compose([ transforms.Resize(image_size), transforms.CenterCrop(image_size), transforms.ToTensor(), transforms.Lambda(expand_greyscale) ]) def __len__(self): return len(self.paths) def __getitem__(self, index): path = self.paths[index] img = Image.open(path) img = img.convert('RGB') return self.transform(img) # main if __name__ == '__main__': ds = ImagesDataset(args.image_folder, IMAGE_SIZE) train_loader = DataLoader(ds, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS, shuffle=True) model = SelfSupervisedLearner( resnet, image_size = IMAGE_SIZE, hidden_layer = 'avgpool', projection_size = 256, projection_hidden_size = 4096, moving_average_decay = 0.99 ) trainer = pl.Trainer( gpus = NUM_GPUS, max_epochs = EPOCHS, accumulate_grad_batches = 1, sync_batchnorm = True ) trainer.fit(model, train_loader)
byol-pytorch-master
examples/lightning/train.py
from setuptools import setup, find_packages setup( name = 'perceiver-pytorch', packages = find_packages(), version = '0.8.8', license='MIT', description = 'Perceiver - Pytorch', long_description_content_type = 'text/markdown', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', url = 'https://github.com/lucidrains/perceiver-pytorch', keywords = [ 'artificial intelligence', 'deep learning', 'transformer', 'attention mechanism' ], install_requires=[ 'einops>=0.3', 'torch>=1.6' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
perceiver-pytorch-main
setup.py
import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat from perceiver_pytorch.perceiver_pytorch import exists, default, cache_fn, fourier_encode, PreNorm, FeedForward, Attention # helpers class Residual(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x, **kwargs): return x + self.fn(x, **kwargs) class GRUGating(nn.Module): def __init__(self, dim, fn): super().__init__() self.dim = dim self.fn = fn self.gru = nn.GRUCell(dim, dim) def forward(self, x, **kwargs): b, dim = x.shape[0], self.dim y = self.fn(x, **kwargs) gated_output = self.gru( rearrange(y, '... d -> (...) d'), rearrange(x, '... d -> (...) d') ) gated_output = rearrange(gated_output, '(b n) d -> b n d', b = b) return gated_output # main class class Perceiver(nn.Module): def __init__( self, *, num_freq_bands, depth, max_freq, input_channels = 3, input_axis = 2, num_latents = 512, latent_dim = 512, cross_heads = 1, latent_heads = 8, cross_dim_head = 64, latent_dim_head = 64, num_classes = 1000, attn_dropout = 0., ff_dropout = 0., weight_tie_layers = False ): super().__init__() self.input_axis = input_axis self.max_freq = max_freq self.num_freq_bands = num_freq_bands input_dim = input_axis * ((num_freq_bands * 2) + 1) + input_channels self.latents = nn.Parameter(torch.randn(num_latents, latent_dim)) get_cross_attn = lambda: GRUGating(latent_dim, PreNorm(latent_dim, Attention(latent_dim, input_dim, heads = cross_heads, dim_head = cross_dim_head, dropout = attn_dropout), context_dim = input_dim)) get_latent_attn = lambda: GRUGating(latent_dim, PreNorm(latent_dim, Attention(latent_dim, heads = latent_heads, dim_head = latent_dim_head, dropout = attn_dropout))) get_cross_ff = lambda: Residual(PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout))) get_latent_ff = lambda: Residual(PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout))) get_cross_attn, get_cross_ff, get_latent_attn, get_latent_ff = map(cache_fn, (get_cross_attn, get_cross_ff, get_latent_attn, get_latent_ff)) self.layers = nn.ModuleList([]) for i in range(depth): should_cache = i > 0 and weight_tie_layers cache_args = {'_cache': should_cache} self.layers.append(nn.ModuleList([ get_cross_attn(**cache_args), get_cross_ff(**cache_args), get_latent_attn(**cache_args), get_latent_ff(**cache_args) ])) self.to_logits = nn.Sequential( nn.LayerNorm(latent_dim), nn.Linear(latent_dim, num_classes) ) def forward(self, data, mask = None): b, *axis, _, device = *data.shape, data.device assert len(axis) == self.input_axis, 'input data must have the right number of axis' # calculate fourier encoded positions in the range of [-1, 1], for all axis axis_pos = list(map(lambda size: torch.linspace(-1., 1., steps = size, device = device), axis)) pos = torch.stack(torch.meshgrid(*axis_pos, indexing = 'ij'), dim = -1) enc_pos = fourier_encode(pos, self.max_freq, self.num_freq_bands) enc_pos = rearrange(enc_pos, '... n d -> ... (n d)') enc_pos = repeat(enc_pos, '... -> b ...', b = b) # concat to channels of data and flatten axis data = torch.cat((data, enc_pos), dim = -1) data = rearrange(data, 'b ... d -> b (...) d') x = repeat(self.latents, 'n d -> b n d', b = b) for cross_attn, cross_ff, latent_attn, latent_ff in self.layers: x = cross_attn(x, context = data, mask = mask) x = cross_ff(x) x = latent_attn(x) x = latent_ff(x) x = x.mean(dim = -2) return self.to_logits(x)
perceiver-pytorch-main
perceiver_pytorch/gated.py
from math import pi, log from functools import wraps import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat # helpers def exists(val): return val is not None def default(val, d): return val if exists(val) else d def cache_fn(f): cache = None @wraps(f) def cached_fn(*args, _cache = True, **kwargs): if not _cache: return f(*args, **kwargs) nonlocal cache if cache is not None: return cache cache = f(*args, **kwargs) return cache return cached_fn # structured dropout, more effective than traditional attention dropouts def dropout_seq(seq, mask, dropout): b, n, *_, device = *seq.shape, seq.device logits = torch.randn(b, n, device = device) if exists(mask): logits = logits.masked_fill(~mask, -torch.finfo(logits.dtype).max) keep_prob = 1. - dropout num_keep = max(1, int(keep_prob * n)) keep_indices = logits.topk(num_keep, dim = 1).indices batch_indices = torch.arange(b, device = device) batch_indices = rearrange(batch_indices, 'b -> b 1') seq = seq[batch_indices, keep_indices] if exists(mask): seq_counts = mask.sum(dim = -1) seq_keep_counts = torch.ceil(seq_counts * keep_prob).int() keep_mask = torch.arange(num_keep, device = device) < rearrange(seq_keep_counts, 'b -> b 1') mask = mask[batch_indices, keep_indices] & keep_mask return seq, mask # helper classes class PreNorm(nn.Module): def __init__(self, dim, fn, context_dim = None): super().__init__() self.fn = fn self.norm = nn.LayerNorm(dim) self.norm_context = nn.LayerNorm(context_dim) if exists(context_dim) else None def forward(self, x, **kwargs): x = self.norm(x) if exists(self.norm_context): context = kwargs['context'] normed_context = self.norm_context(context) kwargs.update(context = normed_context) return self.fn(x, **kwargs) class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim = -1) return x * F.gelu(gates) class FeedForward(nn.Module): def __init__(self, dim, mult = 4): super().__init__() self.net = nn.Sequential( nn.Linear(dim, dim * mult * 2), GEGLU(), nn.Linear(dim * mult, dim) ) def forward(self, x): return self.net(x) class Attention(nn.Module): def __init__(self, query_dim, context_dim = None, heads = 8, dim_head = 64): super().__init__() inner_dim = dim_head * heads context_dim = default(context_dim, query_dim) self.scale = dim_head ** -0.5 self.heads = heads self.to_q = nn.Linear(query_dim, inner_dim, bias = False) self.to_kv = nn.Linear(context_dim, inner_dim * 2, bias = False) self.to_out = nn.Linear(inner_dim, query_dim) def forward(self, x, context = None, mask = None): h = self.heads q = self.to_q(x) context = default(context, x) k, v = self.to_kv(context).chunk(2, dim = -1) q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h = h), (q, k, v)) sim = einsum('b i d, b j d -> b i j', q, k) * self.scale if exists(mask): mask = rearrange(mask, 'b ... -> b (...)') max_neg_value = -torch.finfo(sim.dtype).max mask = repeat(mask, 'b j -> (b h) () j', h = h) sim.masked_fill_(~mask, max_neg_value) # attention, what we cannot get enough of attn = sim.softmax(dim = -1) out = einsum('b i j, b j d -> b i d', attn, v) out = rearrange(out, '(b h) n d -> b n (h d)', h = h) return self.to_out(out) # main class class PerceiverIO(nn.Module): def __init__( self, *, depth, dim, queries_dim, logits_dim = None, num_latents = 512, latent_dim = 512, cross_heads = 1, latent_heads = 8, cross_dim_head = 64, latent_dim_head = 64, weight_tie_layers = False, decoder_ff = False, seq_dropout_prob = 0. ): super().__init__() self.seq_dropout_prob = seq_dropout_prob self.latents = nn.Parameter(torch.randn(num_latents, latent_dim)) self.cross_attend_blocks = nn.ModuleList([ PreNorm(latent_dim, Attention(latent_dim, dim, heads = cross_heads, dim_head = cross_dim_head), context_dim = dim), PreNorm(latent_dim, FeedForward(latent_dim)) ]) get_latent_attn = lambda: PreNorm(latent_dim, Attention(latent_dim, heads = latent_heads, dim_head = latent_dim_head)) get_latent_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim)) get_latent_attn, get_latent_ff = map(cache_fn, (get_latent_attn, get_latent_ff)) self.layers = nn.ModuleList([]) cache_args = {'_cache': weight_tie_layers} for i in range(depth): self.layers.append(nn.ModuleList([ get_latent_attn(**cache_args), get_latent_ff(**cache_args) ])) self.decoder_cross_attn = PreNorm(queries_dim, Attention(queries_dim, latent_dim, heads = cross_heads, dim_head = cross_dim_head), context_dim = latent_dim) self.decoder_ff = PreNorm(queries_dim, FeedForward(queries_dim)) if decoder_ff else None self.to_logits = nn.Linear(queries_dim, logits_dim) if exists(logits_dim) else nn.Identity() def forward( self, data, mask = None, queries = None ): b, *_, device = *data.shape, data.device x = repeat(self.latents, 'n d -> b n d', b = b) cross_attn, cross_ff = self.cross_attend_blocks # structured dropout (as done in perceiver AR https://arxiv.org/abs/2202.07765) if self.training and self.seq_dropout_prob > 0.: data, mask = dropout_seq(data, mask, self.seq_dropout_prob) # cross attention only happens once for Perceiver IO x = cross_attn(x, context = data, mask = mask) + x x = cross_ff(x) + x # layers for self_attn, self_ff in self.layers: x = self_attn(x) + x x = self_ff(x) + x if not exists(queries): return x # make sure queries contains batch dimension if queries.ndim == 2: queries = repeat(queries, 'n d -> b n d', b = b) # cross attend from decoder queries to latents latents = self.decoder_cross_attn(queries, context = x) # optional decoder feedforward if exists(self.decoder_ff): latents = latents + self.decoder_ff(latents) # final linear out return self.to_logits(latents) # Perceiver LM example class PerceiverLM(nn.Module): def __init__( self, *, dim, num_tokens, max_seq_len, **kwargs ): super().__init__() self.token_emb = nn.Embedding(num_tokens, dim) self.pos_emb = nn.Embedding(max_seq_len, dim) self.perceiver_io = PerceiverIO( dim = dim, queries_dim = dim, logits_dim = num_tokens, **kwargs ) def forward( self, x, mask = None ): n, device = x.shape[1], x.device x = self.token_emb(x) pos_emb = self.pos_emb(torch.arange(n, device = device)) pos_emb = rearrange(pos_emb, 'n d -> () n d') x = x + pos_emb logits = self.perceiver_io(x, mask = mask, queries = x) return logits
perceiver-pytorch-main
perceiver_pytorch/perceiver_io.py
import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat from perceiver_pytorch.perceiver_pytorch import exists, default, cache_fn, fourier_encode, PreNorm, FeedForward, Attention # linear attention class LinearAttention(nn.Module): def __init__( self, dim, *, heads = 4, dim_head = 64, dropout = 0. ): super().__init__() inner_dim = heads * dim_head self.heads = heads self.scale = dim_head ** -0.5 self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False) self.to_out = nn.Sequential( nn.Linear(inner_dim, dim), nn.Dropout(dropout) ) def forward(self, x, mask = None): h = self.heads q, k, v = self.to_qkv(x).chunk(3, dim = -1) q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h = h), (q, k, v)) q = q * self.scale q, k = q.softmax(dim = -1), k.softmax(dim = -2) if exists(mask): k.masked_fill_(mask, 0.) context = einsum('b n d, b n e -> b d e', q, k) out = einsum('b d e, b n d -> b n e', context, v) out = rearrange(out, ' (b h) n d -> b n (h d)', h = h) return self.to_out(out) # main class class Perceiver(nn.Module): def __init__( self, *, num_freq_bands, depth, max_freq, input_channels = 3, input_axis = 2, num_latents = 512, latent_dim = 512, cross_heads = 1, latent_heads = 8, cross_dim_head = 64, latent_dim_head = 64, num_classes = 1000, attn_dropout = 0., ff_dropout = 0., weight_tie_layers = False, fourier_encode_data = True ): super().__init__() self.input_axis = input_axis self.max_freq = max_freq self.num_freq_bands = num_freq_bands self.fourier_encode_data = fourier_encode_data input_dim = input_channels if fourier_encode_data: input_dim += input_axis * ((num_freq_bands * 2) + 1) + input_channels self.latents = nn.Parameter(torch.randn(num_latents, latent_dim)) self.data_proj = nn.Linear(input_dim, input_dim) get_cross_attn = lambda: PreNorm(latent_dim, Attention(latent_dim, input_dim, heads = cross_heads, dim_head = cross_dim_head, dropout = attn_dropout), context_dim = input_dim) get_cross_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout)) get_input_attn = lambda: PreNorm(input_dim, LinearAttention(input_dim, dropout = attn_dropout)) get_rev_cross_attn = lambda: PreNorm(input_dim, Attention(input_dim, latent_dim, heads = cross_heads, dim_head = cross_dim_head, dropout = attn_dropout), context_dim = latent_dim) get_rev_cross_ff = lambda: PreNorm(input_dim, FeedForward(input_dim, dropout = ff_dropout)) get_latent_attn = lambda: PreNorm(latent_dim, Attention(latent_dim, heads = latent_heads, dim_head = latent_dim_head, dropout = attn_dropout)) get_latent_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout)) get_cross_attn, get_cross_ff, get_rev_cross_attn, get_rev_cross_ff, get_input_attn, get_latent_attn, get_latent_ff = map(cache_fn, (get_cross_attn, get_cross_ff, get_rev_cross_attn, get_rev_cross_ff, get_input_attn, get_latent_attn, get_latent_ff)) self.layers = nn.ModuleList([]) for i in range(depth): should_cache = i > 0 and weight_tie_layers cache_args = {'_cache': should_cache} self.layers.append(nn.ModuleList([ get_cross_attn(**cache_args), get_cross_ff(**cache_args), get_rev_cross_attn(**cache_args), get_rev_cross_ff(**cache_args), get_input_attn(**cache_args), get_latent_attn(**cache_args), get_latent_ff(**cache_args) ])) self.to_logits = nn.Sequential( nn.LayerNorm(latent_dim), nn.Linear(latent_dim, num_classes) ) def forward(self, data, mask = None): b, *axis, _, device = *data.shape, data.device assert len(axis) == self.input_axis, 'input data must have the right number of axis' if self.fourier_encode_data: # calculate fourier encoded positions in the range of [-1, 1], for all axis axis_pos = list(map(lambda size: torch.linspace(-1., 1., steps = size, device = device), axis)) pos = torch.stack(torch.meshgrid(*axis_pos, indexing = 'ij'), dim = -1) enc_pos = fourier_encode(pos, self.max_freq, self.num_freq_bands) enc_pos = rearrange(enc_pos, '... n d -> ... (n d)') enc_pos = repeat(enc_pos, '... -> b ...', b = b) # concat to channels of data and flatten axis data = torch.cat((data, enc_pos), dim = -1) data = rearrange(data, 'b ... d -> b (...) d') data = self.data_proj(data) x = repeat(self.latents, 'n d -> b n d', b = b) for i, (cross_attn, cross_ff, rev_cross_attn, rev_cross_ff, input_attn, latent_attn, latent_ff) in enumerate(self.layers): is_last = i == (len(self.layers) - 1) x = cross_attn(x, context = data, mask = mask) + x x = cross_ff(x) + x if not is_last: data = input_attn(data, mask = mask) + data data = rev_cross_attn(data, context = x) + data data = rev_cross_ff(data) + data x = latent_attn(x) + x x = latent_ff(x) + x x = x.mean(dim = -2) return self.to_logits(x)
perceiver-pytorch-main
perceiver_pytorch/experimental.py
from perceiver_pytorch.perceiver_pytorch import Perceiver from perceiver_pytorch.perceiver_io import PerceiverIO, PerceiverLM
perceiver-pytorch-main
perceiver_pytorch/__init__.py
from math import pi, log from functools import wraps import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat from einops.layers.torch import Reduce # helpers def exists(val): return val is not None def default(val, d): return val if exists(val) else d def cache_fn(f): cache = dict() @wraps(f) def cached_fn(*args, _cache = True, key = None, **kwargs): if not _cache: return f(*args, **kwargs) nonlocal cache if key in cache: return cache[key] result = f(*args, **kwargs) cache[key] = result return result return cached_fn def fourier_encode(x, max_freq, num_bands = 4): x = x.unsqueeze(-1) device, dtype, orig_x = x.device, x.dtype, x scales = torch.linspace(1., max_freq / 2, num_bands, device = device, dtype = dtype) scales = scales[(*((None,) * (len(x.shape) - 1)), Ellipsis)] x = x * scales * pi x = torch.cat([x.sin(), x.cos()], dim = -1) x = torch.cat((x, orig_x), dim = -1) return x # helper classes class PreNorm(nn.Module): def __init__(self, dim, fn, context_dim = None): super().__init__() self.fn = fn self.norm = nn.LayerNorm(dim) self.norm_context = nn.LayerNorm(context_dim) if exists(context_dim) else None def forward(self, x, **kwargs): x = self.norm(x) if exists(self.norm_context): context = kwargs['context'] normed_context = self.norm_context(context) kwargs.update(context = normed_context) return self.fn(x, **kwargs) class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim = -1) return x * F.gelu(gates) class FeedForward(nn.Module): def __init__(self, dim, mult = 4, dropout = 0.): super().__init__() self.net = nn.Sequential( nn.Linear(dim, dim * mult * 2), GEGLU(), nn.Linear(dim * mult, dim), nn.Dropout(dropout) ) def forward(self, x): return self.net(x) class Attention(nn.Module): def __init__(self, query_dim, context_dim = None, heads = 8, dim_head = 64, dropout = 0.): super().__init__() inner_dim = dim_head * heads context_dim = default(context_dim, query_dim) self.scale = dim_head ** -0.5 self.heads = heads self.to_q = nn.Linear(query_dim, inner_dim, bias = False) self.to_kv = nn.Linear(context_dim, inner_dim * 2, bias = False) self.dropout = nn.Dropout(dropout) self.to_out = nn.Linear(inner_dim, query_dim) def forward(self, x, context = None, mask = None): h = self.heads q = self.to_q(x) context = default(context, x) k, v = self.to_kv(context).chunk(2, dim = -1) q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h = h), (q, k, v)) sim = einsum('b i d, b j d -> b i j', q, k) * self.scale if exists(mask): mask = rearrange(mask, 'b ... -> b (...)') max_neg_value = -torch.finfo(sim.dtype).max mask = repeat(mask, 'b j -> (b h) () j', h = h) sim.masked_fill_(~mask, max_neg_value) # attention, what we cannot get enough of attn = sim.softmax(dim = -1) attn = self.dropout(attn) out = einsum('b i j, b j d -> b i d', attn, v) out = rearrange(out, '(b h) n d -> b n (h d)', h = h) return self.to_out(out) # main class class Perceiver(nn.Module): def __init__( self, *, num_freq_bands, depth, max_freq, input_channels = 3, input_axis = 2, num_latents = 512, latent_dim = 512, cross_heads = 1, latent_heads = 8, cross_dim_head = 64, latent_dim_head = 64, num_classes = 1000, attn_dropout = 0., ff_dropout = 0., weight_tie_layers = False, fourier_encode_data = True, self_per_cross_attn = 1, final_classifier_head = True ): """The shape of the final attention mechanism will be: depth * (cross attention -> self_per_cross_attn * self attention) Args: num_freq_bands: Number of freq bands, with original value (2 * K + 1) depth: Depth of net. max_freq: Maximum frequency, hyperparameter depending on how fine the data is. freq_base: Base for the frequency input_channels: Number of channels for each token of the input. input_axis: Number of axes for input data (2 for images, 3 for video) num_latents: Number of latents, or induced set points, or centroids. Different papers giving it different names. latent_dim: Latent dimension. cross_heads: Number of heads for cross attention. Paper said 1. latent_heads: Number of heads for latent self attention, 8. cross_dim_head: Number of dimensions per cross attention head. latent_dim_head: Number of dimensions per latent self attention head. num_classes: Output number of classes. attn_dropout: Attention dropout ff_dropout: Feedforward dropout weight_tie_layers: Whether to weight tie layers (optional). fourier_encode_data: Whether to auto-fourier encode the data, using the input_axis given. defaults to True, but can be turned off if you are fourier encoding the data yourself. self_per_cross_attn: Number of self attention blocks per cross attn. final_classifier_head: mean pool and project embeddings to number of classes (num_classes) at the end """ super().__init__() self.input_axis = input_axis self.max_freq = max_freq self.num_freq_bands = num_freq_bands self.fourier_encode_data = fourier_encode_data fourier_channels = (input_axis * ((num_freq_bands * 2) + 1)) if fourier_encode_data else 0 input_dim = fourier_channels + input_channels self.latents = nn.Parameter(torch.randn(num_latents, latent_dim)) get_cross_attn = lambda: PreNorm(latent_dim, Attention(latent_dim, input_dim, heads = cross_heads, dim_head = cross_dim_head, dropout = attn_dropout), context_dim = input_dim) get_cross_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout)) get_latent_attn = lambda: PreNorm(latent_dim, Attention(latent_dim, heads = latent_heads, dim_head = latent_dim_head, dropout = attn_dropout)) get_latent_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout)) get_cross_attn, get_cross_ff, get_latent_attn, get_latent_ff = map(cache_fn, (get_cross_attn, get_cross_ff, get_latent_attn, get_latent_ff)) self.layers = nn.ModuleList([]) for i in range(depth): should_cache = i > 0 and weight_tie_layers cache_args = {'_cache': should_cache} self_attns = nn.ModuleList([]) for block_ind in range(self_per_cross_attn): self_attns.append(nn.ModuleList([ get_latent_attn(**cache_args, key = block_ind), get_latent_ff(**cache_args, key = block_ind) ])) self.layers.append(nn.ModuleList([ get_cross_attn(**cache_args), get_cross_ff(**cache_args), self_attns ])) self.to_logits = nn.Sequential( Reduce('b n d -> b d', 'mean'), nn.LayerNorm(latent_dim), nn.Linear(latent_dim, num_classes) ) if final_classifier_head else nn.Identity() def forward( self, data, mask = None, return_embeddings = False ): b, *axis, _, device, dtype = *data.shape, data.device, data.dtype assert len(axis) == self.input_axis, 'input data must have the right number of axis' if self.fourier_encode_data: # calculate fourier encoded positions in the range of [-1, 1], for all axis axis_pos = list(map(lambda size: torch.linspace(-1., 1., steps=size, device=device, dtype=dtype), axis)) pos = torch.stack(torch.meshgrid(*axis_pos, indexing = 'ij'), dim = -1) enc_pos = fourier_encode(pos, self.max_freq, self.num_freq_bands) enc_pos = rearrange(enc_pos, '... n d -> ... (n d)') enc_pos = repeat(enc_pos, '... -> b ...', b = b) data = torch.cat((data, enc_pos), dim = -1) # concat to channels of data and flatten axis data = rearrange(data, 'b ... d -> b (...) d') x = repeat(self.latents, 'n d -> b n d', b = b) # layers for cross_attn, cross_ff, self_attns in self.layers: x = cross_attn(x, context = data, mask = mask) + x x = cross_ff(x) + x for self_attn, self_ff in self_attns: x = self_attn(x) + x x = self_ff(x) + x # allow for fetching embeddings if return_embeddings: return x # to logits return self.to_logits(x)
perceiver-pytorch-main
perceiver_pytorch/perceiver_pytorch.py
import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat from perceiver_pytorch.perceiver_pytorch import exists, default, cache_fn, fourier_encode, PreNorm, FeedForward, Attention # latent mixer def Mixer(seq_len, mult = 4, dropout = 0.): return nn.Sequential( nn.Conv1d(seq_len, seq_len * mult, 1), nn.GELU(), nn.Dropout(dropout), nn.Conv1d(seq_len * mult, seq_len, 1) ) # main class class Perceiver(nn.Module): def __init__( self, *, num_freq_bands, depth, max_freq, input_channels = 3, input_axis = 2, num_latents = 512, latent_dim = 512, cross_heads = 1, latent_heads = 8, cross_dim_head = 64, latent_dim_head = 64, num_classes = 1000, attn_dropout = 0., ff_dropout = 0., weight_tie_layers = False, **kwargs ): super().__init__() self.input_axis = input_axis self.max_freq = max_freq self.num_freq_bands = num_freq_bands input_dim = input_axis * ((num_freq_bands * 2) + 1) + input_channels self.latents = nn.Parameter(torch.randn(num_latents, latent_dim)) get_cross_attn = lambda: PreNorm(latent_dim, Attention(latent_dim, input_dim, heads = cross_heads, dim_head = cross_dim_head, dropout = attn_dropout), context_dim = input_dim) get_latent_attn = lambda: PreNorm(latent_dim, Mixer(num_latents, dropout = ff_dropout)) get_cross_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout)) get_latent_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout)) get_cross_attn, get_cross_ff, get_latent_attn, get_latent_ff = map(cache_fn, (get_cross_attn, get_cross_ff, get_latent_attn, get_latent_ff)) self.layers = nn.ModuleList([]) for i in range(depth): should_cache = i > 0 and weight_tie_layers cache_args = {'_cache': should_cache} self.layers.append(nn.ModuleList([ get_cross_attn(**cache_args), get_cross_ff(**cache_args), get_latent_attn(**cache_args), get_latent_ff(**cache_args) ])) self.to_logits = nn.Sequential( nn.LayerNorm(latent_dim), nn.Linear(latent_dim, num_classes) ) def forward(self, data, mask = None): b, *axis, _, device = *data.shape, data.device assert len(axis) == self.input_axis, 'input data must have the right number of axis' # calculate fourier encoded positions in the range of [-1, 1], for all axis axis_pos = list(map(lambda size: torch.linspace(-1., 1., steps = size, device = device), axis)) pos = torch.stack(torch.meshgrid(*axis_pos, indexing = 'ij'), dim = -1) enc_pos = fourier_encode(pos, self.max_freq, self.num_freq_bands) enc_pos = rearrange(enc_pos, '... n d -> ... (n d)') enc_pos = repeat(enc_pos, '... -> b ...', b = b) # concat to channels of data and flatten axis data = torch.cat((data, enc_pos), dim = -1) data = rearrange(data, 'b ... d -> b (...) d') x = repeat(self.latents, 'n d -> b n d', b = b) for cross_attn, cross_ff, latent_attn, latent_ff in self.layers: x = cross_attn(x, context = data, mask = mask) + x x = cross_ff(x) + x x = latent_attn(x) + x x = latent_ff(x) + x x = x.mean(dim = -2) return self.to_logits(x)
perceiver-pytorch-main
perceiver_pytorch/mixed_latents.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import sys import re import os import os.path import argparse import numpy as np import numpy.random as npr import deepbind_util as util import cPickle import scipy import shutil # Warning: The multiprocessing module may be used indirectly, so do not put any # unintentional statements outside of main(). datadir = "../data/encode" seq_suffix = ".seq.gz" def main(): util.enable_reversecomplement() args = loadargs() models = loadmodels(args) trdata = None tedata = None tfids = load_tfids(args) for tfid in tfids: if "calib" in args.steps: print "-------------- calib:", tfid, "--------------" trdata = load_traindata(tfid, args) util.calibrate(models, trdata, args.calibdir, nfold=args.nfold, ncalib=args.ncalib) if "train" in args.steps: print "-------------- train:", tfid, "--------------" trdata = load_traindata(tfid, args) util.train(models, trdata, args.calibdir, args.finaldir, nfold=1, ntrial=args.ntrial) if "test" in args.steps: tedata = load_testdata(tedata, tfids, args) util.save_metrics(tedata, "test", args.finaldir) if "report" in args.steps: tedata = load_testdata(tedata, tfids, args) util.save_featuremaps(tedata, args.finaldir, args.reportdir, maxrows=100000) util.save_report(args.finaldir, args.reportdir, tfids) ######################################################################### def load_tfids(args): targetnames = sorted([filename.replace("_AC"+seq_suffix,"") for filename in os.listdir(datadir) if filename.endswith("_AC"+seq_suffix)]) chunktargets = util.getchunktargets(args, targetnames) return chunktargets ################################# def loadargs(): args = argparse.ArgumentParser(description="Generate the ENCODE experiments.") args.add_argument("mode", type=str, help="Either \"top\" (train top 500 odd, test top 500 even) or \"all\" (train top 500 even + all after 1000, test top 500 even).") args = util.parseargs("encode", args) args.calibdir = args.calibdir.replace(args.outdir, args.outdir+"/"+args.mode) args.finaldir = args.finaldir.replace(args.outdir, args.outdir+"/"+args.mode) args.reportdir = args.reportdir.replace(args.outdir,args.outdir+"/"+args.mode) args.outdir = args.outdir+"/"+args.mode return args ################################# def loadmodels(args): models = util.loadmodels(args, "cfg/classification") if args.mode == "top": for name in models.keys(): models[name]['trainer'].max_steps = 10000 # training on top 500 never seems to need more than 10000 steps, since it's a small training set for cfg in models.itervalues(): cfg["model"].conv_seq[0].fsize = 24 # Override default max motif length return models ################################# def load_traindata(tfid, args): print "load_traindata: %s"%tfid maxrows = 10000 if args.quick else None minrows = 100000 trdata = util.load_seq("%s/%s_AC%s" % (datadir,tfid,seq_suffix), minrows=minrows, maxrows=maxrows) trdata.targetnames = [tfid] if args.mode == "top": trdata = trdata[:500] # Only top 500 even peaks (A); top 500 odd (B) are stored in the corresponding _B.seq.gz file elif args.mode == "all": pass # Top 500 even (A) plus everything else (C) else: quit("Unrecognized mode \"%s\". Expected \"top\" or \"all\".") return trdata ################################# def load_testdata(tedata, tfids, args): if tedata is not None: return tedata if "encode" in datadir: maxrows = 10000 elif "chip" in datadir: maxrows = 10000 else: maxrows = None all_tedata = {} for tfid in tfids: print "load_testdata: %s ..."%tfid, tedata = util.load_seq("%s/%s_B%s" % (datadir,tfid,seq_suffix), minrows=10000, maxrows=maxrows) tedata.targetnames = [tfid] all_tedata[tfid] = tedata print "done" return all_tedata if __name__=="__main__": #util.disable_multiprocessing() main()
DeepBind-master
code/deepbind_train_encode.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import sys import os import re import os.path sys.path.append("libs/kangaroo") sys.path.append("libs/deepity") sys.path.append("libs/smat/py") import math import time import glob import shutil import numpy as np import numpy.random as npr import random import kangaroo import deepity import itertools import argparse import cPickle import smat import scipy import scipy.stats datasource = kangaroo.datasource train = kangaroo.train loadcfg = kangaroo.loadcfg calibrate = kangaroo.calibrate acgt2ord = kangaroo.util.acgt2ord ord2acgt = kangaroo.util.ord2acgt revcomp = kangaroo.util.revcomp makepath = kangaroo.util.makepath predict = kangaroo.predict calc_metrics = deepity.calc_metrics globals = kangaroo.globals load_metrics = deepity.load_metrics save_gradientmaps = kangaroo.save_gradientmaps def set_devices(devices): kangaroo.globals.set_devices(devices) ##################### generate PFMs ###################### def ord2mask_b(x): """ Convert a vector of length N with integral values in range {0,1,2,3} into an Nx4 numpy array, where for example "2" is represented by row [0,0,1,0]. """ mask = np.zeros((x.size,4)) for i in range(x.size): if x[0,i] <= 3: mask[i,x[0,i]] = 1 elif x[0,i] == 255: mask[i,:] = 0.25*np.ones((4,)) return mask def compute_pfms(data, filter_len=20, num_permut=1000, rev_comp=True): nf, num = data.shape pfms = [0.0001*np.ones((filter_len,4)) for i in range(nf)] counts = [0 for _ in range(nf)] for i in xrange(num): seq = ord2mask_b(acgt2ord('N'*(filter_len-1) + data[0,i][0] + 'N'*(filter_len-1))) for j in range(nf): if data[j,i][1] <= 0: continue max_ind = data[j,i][2] idx_st = max_ind idx_sp = max_ind + filter_len pfms[j] += seq[idx_st:idx_sp,:] counts[j] += 1 info = np.zeros((filter_len, nf)) ic = np.zeros((nf,)) for j in range(nf): for k in range(pfms[j].shape[0]): pfms[j][k,:] /= np.sum(pfms[j][k,:]) info[k,j] = 2 + np.sum(pfms[j][k,:] * np.log2(pfms[j][k,:])) ic[j] = np.sum(info[:,j].ravel()) pfm_st, pfm_sp = trim_pfm(info[:,j].ravel()) pfms[j] = pfms[j][pfm_st:pfm_sp,:] ic[j] = 0 for k in range(pfms[j].shape[0]): ic[j] += 2 + np.sum(pfms[j][k,:] * np.log2(pfms[j][k,:])) kl_dist, pval = pfm_kl_dist(pfms, ic, num_permut, rev_comp) return pfms, ic, kl_dist, pval, counts + [num] def trim_pfm(info): max_ic = np.max(info) ic_threshold = np.max([0.1*max_ic, 0.1]); w = info.shape[0] pfm_st = 0 pfm_sp = w for i in range(w): if info[i] < ic_threshold: pfm_st += 1 else: break for inf in reversed(info): if inf < ic_threshold: pfm_sp -= 1 else: break return pfm_st, pfm_sp def rev_com_mask(p): q = p.copy() q = q[::-1,:] q = q[:,::-1] return q def kldist(p, q): return np.sum(p*np.log(p/q)) #r, c = p.shape #kl = 0 #for i in range(r): # for j in range(c): # kl += p[i,j]*np.log(p[i,j]/q[i,j]) #return kl def compute_kl(p, q): lp = p.shape[0] lq = q.shape[0] padding = 0.25*np.ones((lp-1,4)) q = np.vstack((padding, q, padding)) dist = np.inf for k in range(lq+lp-1): tq = q[k:k+lp,:] tkl = kldist(p, tq) if tkl < dist: dist = tkl return dist/lp def pfm_kl_dist(pfms, ic, num_permut, rev_comp): nf = len(pfms) dist = np.zeros((nf, nf)) pval = np.ones((nf, nf)) for i,vp in enumerate(pfms): for j,vq in enumerate(pfms): p = vp.copy() q = vq.copy() if j <= i: continue if ic[i] * ic[j] == 0: dist[i,j] = -1 dist[j,i] = -1 continue if q.shape[0] < p.shape[0]: q, p = p, q dist[i,j] = compute_kl(p, q) if rev_comp: q_rev_com = rev_com_mask(q) rev_dist = compute_kl(p, q_rev_com) if rev_dist < dist[i,j]: dist[i,j] = rev_dist if num_permut > 0: for _ in range(num_permut): tp = p.copy() p_row = np.random.permutation(tp.shape[0]) p_col = np.random.permutation(tp.shape[1]) tp = tp[p_row,:] tp = tp[:,p_col] if rev_comp: p_dist = np.min([compute_kl(tp, q), compute_kl(tp, q_rev_com)]) else: p_dist = compute_kl(tp, q) if p_dist <= dist[i,j]: pval[i,j] += 1 pval[i,j] /= num_permut pval[j,i] = pval[i,j] dist[j,i] = dist[i,j] return dist, pval ####################### doublet_shuffle ############################### # This implementation is based on Altschul and Erickson's Algorithm # for shuffling a sequence while preserving the doublet frequency # Babak Alipanahi # Jan 24, 2014 # University of Toronto # form the graph from sequence def form_seq_graph(seq): graph = {} for i, s in enumerate(seq[:-1]): if s not in graph: graph[s] = [] graph[s].append(seq[i+1]) return graph # sample a random last edge graph def sample_le_graph(graph, last_nt): le_graph = {} for vx in graph: le_graph[vx] = [] if vx not in last_nt: le_graph[vx].append(random.choice(graph[vx])) return le_graph # check whether there exists an Eulerian walk # from seq[0] to seq[-1] in the shuffled # sequence def check_le_graph(le_graph, last_nt): for vx in le_graph: if vx not in last_nt: if not find_path(le_graph, vx, last_nt): return False return True # function from: http://www.python.org/doc/essays/graphs/ # check whether there is a path between two nodes in a # graph def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if not graph.has_key(start): return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None # generate a new seq graph based on the last edge graph # while randomly permuting all other edges def form_new_graph(graph, le_graph, last_nt): new_graph = {} for vx in graph: new_graph[vx] = [] temp_edges = graph[vx] if vx not in last_nt: temp_edges.remove(le_graph[vx][0]) random.shuffle(temp_edges) for ux in temp_edges: new_graph[vx].append(ux) if vx not in last_nt: new_graph[vx].append(le_graph[vx][0]) return new_graph # walk through the shuffled graph and make the # new sequence def form_shuffled_seq(new_graph, init_nt, len_seq): is_done = False new_seq = init_nt while not is_done: last_nt = new_seq[-1] new_seq += new_graph[last_nt][0] new_graph[last_nt].pop(0) if len(new_seq) >= len_seq: is_done = True return new_seq # verify the nucl def verify_counts(seq, shuf_seq): kmers = {} # Forming the k-mer library kmer_range = range(1,3) for k in kmer_range: for tk in itert.product('ACGTN', repeat=k): tkey = ''.join(i for i in tk) kmers[tkey] = [0,0] kmers[seq[0]][0] = 1 kmers[shuf_seq[0]][1] = 1 for k in kmer_range: for l in range(len(seq)-k+1): tkey = seq[l:l+k] kmers[tkey][0] += 1 tkey = shuf_seq[l:l+k] kmers[tkey][1] += 1 for tk in kmers: if kmers[tk][0] != kmers[tk][1]: return False return True _preprocess_seq = ['N']*256; _preprocess_seq[ord('a')] = _preprocess_seq[ord('A')] = 'A'; # Map A => A _preprocess_seq[ord('c')] = _preprocess_seq[ord('C')] = 'C'; # Map C => C _preprocess_seq[ord('g')] = _preprocess_seq[ord('G')] = 'G'; # Map G => G _preprocess_seq[ord('t')] = _preprocess_seq[ord('T')] = 'T'; # Map T => T _preprocess_seq[ord('u')] = _preprocess_seq[ord('U')] = 'T'; # Map U => T _preprocess_seq = "".join(_preprocess_seq) def preprocess_seq(seq): return seq.translate(_preprocess_seq) def doublet_shuffle(seq, verify=False): seq = preprocess_seq(seq) last_nt = seq[-1] graph = form_seq_graph(seq) # sample a random last edge graph is_ok = False while not is_ok: le_graph = sample_le_graph(graph, last_nt) # check the last edge graph is_ok = check_le_graph(le_graph, last_nt) new_graph = form_new_graph(graph, le_graph, last_nt) shuf_seq = form_shuffled_seq(new_graph, seq[0], len(seq)) if verify: assert(verify_counts(seq, shuf_seq)) return shuf_seq def kmer_former(seq, kmerlen): kmers = {} for j in range(len(seq) - kmerlen + 1): tkey = seq[j:j+kmerlen] if tkey not in kmers: kmers[tkey] = True return kmers def verify_kmer(shuf_seq, kmers, kmerlen): for j in range(len(shuf_seq) - kmerlen + 1): tkey = shuf_seq[j:j+kmerlen] if tkey in kmers: return False return True ######################## AUC ###################### def calc_tpc_fpc_curve(z, y): assert len(z) == len(y) # Sort by decreasing score order = np.argsort(z, axis=0, kind="mergesort")[::-1].ravel() z = z[order] y = y[order] # Accumulate the true positives with decreasing threshold tpc = y.cumsum() fpc = 1 + np.arange(len(y)).astype(y.dtype) - tpc return tpc, fpc def calc_auc(z, y, want_curve=False): tpc, fpc = calc_tpc_fpc_curve(z, y) # If curve doesn't have point at x=0, explicitly insert one if fpc[0] != 0: tpc = np.r_[0,tpc] fpc = np.r_[0,fpc] # If one of the classes was empty, return NaN if fpc[-1] == 0 or tpc[-1] == 0: return np.nan # Convert sums to rates tpr = tpc / tpc[-1] fpr = fpc / fpc[-1] # Calculate area under the curve using trapezoidal rule auc = np.trapz(tpr, fpr, axis=0) if want_curve: curve = np.hstack([fpr.reshape((-1,1)),tpr.reshape((-1,1))]) return auc,curve return auc def calc_pr_curve(z, y): tpc, fpc = calc_tpc_fpc_curve(z, y) assert not (fpc[-1] == 0 or tpc[-1] == 0) precision = tpc / (tpc + fpc) recall = tpc / tpc[-1] curve = np.hstack([recall.reshape((-1,1)),precision.reshape((-1,1))]) return curve def bootstrap_auc(z, y, ntrial=100): n = len(y) aucs = [] for t in range(ntrial): sample = npr.randint(0,n,n) zt = z[sample].copy().reshape((-1,1)) yt = y[sample].copy().reshape((-1,1)) auc = calc_auc(zt,yt) if np.isnan(auc): return np.nan, np.nan # If any of the samples returned NaN, the whole bootstrap result is NaN aucs.append(auc) return np.mean(aucs),np.std(aucs) ##################### IUPAC translation #################### iupac = { "R" : "AG", "Y" : "CT", "S" : "GC", "W" : "AT", "K" : "GT", "M" : "AC", "B" : "CGT", "D" : "AGT", "H" : "ACT", "V" : "ACG", "N" : "ACGT" } def iupac2re(seq): for code in iupac: seq = seq.replace(code, "[%s]"%iupac[code]) return seq ######################################################################### def parseargs(appname, args, shorthandids=None): args.add_argument("steps", type=str, help="Either 'all', or a Comma-separated list of calib,train,test,report. Default is all.") args.add_argument("id", type=str, nargs="*", metavar="LIST", help="Explicit list of ids to train") args.add_argument("-d","--device", type=str, default="0", help="GPUs permitted to use, e.g. \"0,1,2\". Default is \"0\".") args.add_argument("-c","--chunk", type=str, default=None, help="For spreading job across multiple workstations. Saying \"2/3\" divides the work into 3 chunks and makes this process responsible for the second chunk.") args.add_argument("-q","--quick", action="store_true", default=False, help="Quick mode. Only trains/tests a few models, and only on a subset of the data rows.") args = args.parse_args() if args.steps == "all": args.steps = "calib,train,test,report" args.steps = args.steps.split(",") args.outdir = "../out/"+appname args.device = [int(id) for id in args.device.split(",")] kangaroo.globals.set_devices(args.device) args.calibdir = args.outdir+"/calib" args.finaldir = args.outdir+"/final" args.reportdir = args.outdir+"/report" args.testdir = args.outdir+"/test" if shorthandids: for id in args.id: if id in shorthandids: args.id.remove(id) args.id.extend(shorthandids[id]) args.nfold = 2 if args.quick else 3 args.ncalib = 3 if args.quick else 30 args.ntrial = 2 if args.quick else 6 args.id = list(set(args.id)) return args ################################# def loadmodels(args, modeldir): # Load one trainer for everything if args.quick: trainer = kangaroo.loadcfg("cfg/trainers/quick.cfg") else: trainer = kangaroo.loadcfg("cfg/trainers/default.cfg") models = {} if args.quick: modelnames = ("M1",) else: modelnames = ("M1","M2") # Load several types of models and pair them up with the trainer. for name in modelnames: model = kangaroo.loadcfg("%s/%s.cfg" % (modeldir,name)) models[name] = { "model" : model, "trainer" : trainer } return models ################################# def getchunktargets(args, targetnames): chunknames = [name for name in targetnames] if args.id: chunknames = [name for name in targetnames if any(re.search(id,name) for id in args.id)] if args.chunk: chunkidx = int(args.chunk.split("/")[0]) numchunk = int(args.chunk.split("/")[1]) assert chunkidx >= 1 and chunkidx <= numchunk splits = [int(x) for x in np.linspace(0, len(chunknames), numchunk+1)] #print splits lo = splits[chunkidx-1] hi = splits[chunkidx] if lo == hi: quit("Chunk is empty (no columns). Quitting.") print "Chunk %s working on columns %d..%d out of %d" % (args.chunk, lo+1, hi, len(chunknames)) chunknames = chunknames[lo:hi] #idxs = [i for i in idxs if not os.path.exists("out/rnac/A/final/%s"%targetnames[i])] #print [targetnames[i] for i in idxs] return chunknames ################################# def save_metrics(data, groupname, outdir, modeldir=None): if modeldir is None: modeldir = outdir if not isinstance(data,dict): data = { id : data.astargets([id]) for id in data.targetnames } pred = kangaroo.predict(data, modeldir, outdir) for targetname in data.keys(): z = pred[targetname].ravel() y = data[targetname].Y.ravel() rowidx = data[targetname].rowidx _update_metrics(outdir, targetname, groupname, rowidx, z, y) check_repeat_correlation = False if check_repeat_correlation: for targetname in data.keys(): z = pred[targetname].ravel() y = data[targetname].Y.ravel() s = [data[targetname].X_seq[i] for i in range(len(data[targetname]))] # Only get the bound examples. z = [s[i] for i in range(len(data[targetname])) if y[i] != 0] s = [s[i] for i in range(len(data[targetname])) if y[i] != 0] class revcomp_str(object): def __init__(self, s): self.s = s; def __eq__(self, other): return self.s == other.s or self.s == revcomp(other.s) # For each percentile, count the number of repeats print targetname order = np.argsort(z) for denom in reversed([2,8,32,128,512,2048]): top_s = [s[i] for i in order[len(order)//denom:]] top_unique = set([revcomp(top_s[i]) for i in range(len(top_s))]) nall = float(len(top_s)) nunique = float(len(top_unique)) percent_repeat = 100*(nall - nunique) / nall print " top %.4f%% (n=%d)\t=> %.2f%% repeats" % (100./denom, nall, percent_repeat) def _update_metrics(outdir, targetname, groupname, rowidx, z, y, aucthresh=(.5,.5)): modeldir = outdir+"/"+targetname # Load current predictions with np.load(modeldir+"/predict.npz") as f: predict_npz = { name : f[name] for name in f.keys() } # Add prediction group group = predict_npz["groups"][()].setdefault(groupname,{}) group["I"] = rowidx group["Z"] = z.reshape((-1,1)) if y is not None: group["Y"] = y.reshape((-1,1)) # Save predictions np.savez_compressed(modeldir+"/predict.npz", **predict_npz) deepity.call_dumpviz(modeldir+"/predict.npz") # Load current metrics metrics = deepity.load_metrics(modeldir+"/metrics.txt") metrics[groupname] = deepity.calc_metrics(z, y, aucthresh=aucthresh) deepity.save_metrics(modeldir+"/metrics.txt", metrics) """ with open("%s/%s/predict.tsv" % (outdir,targetname),"w") as f: f.write("RowIndex\tPredict") if y is not None: assert len(z) == len(y) f.write("\tTarget") yfmt = "\t%d" if np.all(y.astype(np.int32) == y) else "\t%.4f" f.write("\n") for i in range(len(z)): f.write("%d\t%.4f" % (rowidx[i],z[i])) if y is not None: f.write(yfmt % y[i]) f.write("\n")""" def disable_softmax(): kangaroo.globals.flags.push("disable_softmax",True) def enable_softmax(): kangaroo.globals.flags.pop("disable_softmax") ################################# def save_featuremaps(data, modeldir, outdir, maxrows=1000000): if not isinstance(data,dict): data = { id : data.astargets([id]) for id in data.targetnames } disable_softmax() pred = kangaroo.predict(data, modeldir, outdir) # Find a list of rows, in order of decreasing confidence, and with all # duplicate sequences deleted for name, Z in pred.iteritems(): Y = data[name].Y.ravel() allidx = [] allseq = set() roworder = np.argsort(-Z.ravel()) for i in range(len(roworder)): s = data[name].X_seq[roworder[i]] #if s in allseq: # continue allidx.append(roworder[i]) allseq.add(s) if maxrows and len(allidx) >= maxrows: break # Now actually dump the featuremaps for all the rows specified print "Generating feature maps...", datasub = data[name][allidx] kangaroo.globals.set_multiprocessing(False) # Needed to get back collected values in globals; uugh if "reverse_complement" in kangaroo.globals.flags: kangaroo.globals.flags.push("collect_Zmask",True) kangaroo.globals.flags.push("collect_featuremaps",True) kangaroo.globals.flags.push("disable_relu",True) kangaroo.predict(datasub, modeldir, outdir) kangaroo.globals.flags.pop("disable_relu") fmaps = kangaroo.globals.flags.pop("collect_featuremaps") Zmask = kangaroo.globals.flags.pop("collect_Zmask").ravel() if "reverse_complement" in kangaroo.globals.flags else None kangaroo.globals.set_multiprocessing(True) seqs = [] for i in range(len(datasub)): s = datasub.sequences[i][0] seqs.append(s) if "reverse_complement" in kangaroo.globals.flags: seqs.append(revcomp(s)) if "reverse_complement" in kangaroo.globals.flags: # Remove the strand that was not used for prediction fmaps = [fmaps[i] for i in range(len(fmaps)) if Zmask[i]] seqs = [seqs[i] for i in range(len(seqs)) if Zmask[i]] filter_len = fmaps[0].shape[1] - len(seqs[0]) + 1 # Make tuples of (sequence, max_value, max_index) for each featuremap pfmargs = [] for k in range(fmaps[0].shape[0]): pfmarg = [(seqs[i], float(np.max(fmaps[i][k])), int(np.argmax(fmaps[i][k]))) for i in range(len(seqs))] pfmargs.append(pfmarg) pfmargs = np.array(pfmargs, dtype='a%d,f4,i4' % max(len(seqs[i]) for i in range(len(seqs)))) print "done" #np.savez_compressed(outdir + "/%s.pfm_info.npz"%(name), pfmargs=pfmargs) # Compute PFMs from the pfmargs array print "Computing PFMs for %s..." % name, pfms, ic, kl_dist, pval, counts = compute_pfms(pfmargs, filter_len=filter_len, num_permut=500, rev_comp=False) print "done" makepath(outdir) with open(outdir + "/%s.pfms.pkl"%(name),"wb") as f: cPickle.dump({"pfms" : pfms, "ic" : ic, "kl_dist" : kl_dist, "pval" : pval, "counts" : counts}, f) enable_softmax() ################################# def retrain(models, data, calibdir, finaldir, nfold=1, ntrial=1): kangaroo.globals.flags.push("disable_softmax",True) for trial in range(10): Z = kangaroo.predict(data, finaldir, finaldir)["bound"] I0 = [i for i in range(len(data)) if data.Y[i] < .5] I1 = [i for i in range(len(data)) if data.Y[i] > .5] #threshold = np.mean(Z[I1].ravel()) - 4*np.std(Z[I1].ravel()) #threshold = np.percentile(Z[I0].ravel(), 95) threshold = np.percentile(Z[I1].ravel(), 1) numshuffle = 0 for i in I0: if Z[i] > threshold: data.sequences[i][0] = doublet_shuffle(data.sequences[i][0]) data.X_seq[i] = data.sequences[i][0] numshuffle += 1 numshuffle_pct = float(numshuffle)/len(I0)*100 print "retrain trial %d: had to shuffle %.1f%% unbound sequences" % (trial, numshuffle_pct) if numshuffle <= .0001*len(I0): break kangaroo.globals.flags.pop("disable_softmax") kangaroo.train(models, data, calibdir, finaldir, nfold=nfold, ntrial=ntrial) return ################################# def train_without_outliers(cfgs, data, calibdir, outdir, ntrial=1, auxfilter=None): # Same as kangaroo.train, except this version trains twice: once with all # the data, and again with worst outliers 'removed'. # Step 1. Train with all training data #kangaroo.train(cfgs, data, calibdir, outdir, nfold=1, ntrial=ntrial, auxfilter=auxfilter) # Step 2. Load predictions on the training data, and remove% # the examples that were misclassified the worst. if not isinstance(data,dict): data = { id : data.astargets([id]) for id in data.targetnames } kangaroo.globals.flags.push("disable_softmax",True) pred = kangaroo.predict(data, outdir, outdir) for targetname in sorted(data.targetnames): for name, Z in pred.iteritems(): Y = data[name].Y.ravel() allidx = [] allseq = set() roworder = np.argsort(-Z.ravel()) ################################# def disable_multiprocessing(): kangaroo.globals.set_multiprocessing(False) #smat.set_default_dtype(smat.float64) ################################# def enable_reversecomplement(force=False): kangaroo.globals.flags.push("reverse_complement", "force" if force else True ) def reversecomplement_enabled(): return "reverse_complement" in kangaroo.globals.flags ################################# def shufseq(s): return "".join([s[i] for i in npr.permutation(len(s))]) def randpad(seq, padsize): if not padsize: return seq n = len(seq) j = npr.randint(0, padsize) return randseq(j, j) + seq + randseq(padsize-j, padsize-j) class _augment_seqdata(object): def __init__(self, minrows, padsize): self.minrows = minrows self.padsize = padsize def __call__(self, data): nrows = max(self.minrows, len(data)) if self.minrows else len(data) data = data[[i//2 % len(data) for i in range(nrows*2)]] for i in range(0,nrows*2,2): seq = data.sequences[i][0] seq = randpad(seq, self.padsize) shuf = doublet_shuffle(seq) data.sequences[i] = [seq] data.sequences[i+1] = [shuf] data.X_seq[i] = seq data.X_seq[i+1] = shuf data.Y[i+1] = 0 return data def load_seq(filename, minrows=None, maxrows=None, padsize=None): if maxrows: minrows = min(maxrows, minrows) data = datasource.fromtxt(filename, None, None, maxrows=maxrows) # Duplicate all the data as many times as needed to provide a match # for each background sequence if minrows: data.augmented = _augment_seqdata(minrows, padsize) return data ################################# def randseq(minlen, maxlen, p=None): size = npr.randint(minlen, maxlen+1) if p is None: return ord2acgt(npr.randint(0, 4, size)) return ord2acgt(npr.choice([0,1,2,3], size=size, p=p)) ###################################################### def save_report(modeldir, reportdir, tfids, index_metric="auc", rna=False): makepath(reportdir) index_html = open(reportdir+"/index.html",'w') index_html.write("<html><head><title>Training report</title></head><body>\n") index_html.write("<table cellspacing=0 cellpadding=5 border=1>\n") index_html.write("<tr><th>Name</th><th>train %s</th><th>test %s</th></tr>\n" % (index_metric, index_metric)) performance_txt = open(reportdir+"/performance.txt",'w') performance_txt.write("\ttrain.%s\ttest.%s\n" % (index_metric, index_metric)) for tfid in tfids: print tfid makepath(reportdir+"/"+tfid) # Load PFMs, convert them to logo images, and dump them to the report directory logos = [] if os.path.exists(reportdir+"/%s.pfms.pkl"%tfid): with open(reportdir+"/%s.pfms.pkl"%tfid) as f: _ = cPickle.load(f) pfms = _["pfms"] ics = _["ic"] counts = _["counts"] pfm_order = np.argsort(-ics) for j in pfm_order: pfm = pfms[j] ic = ics[j] if ic <= 0: continue pfm_rev = np.fliplr(np.flipud(pfm)) logo_filename = "%s/%s/pfm%02d" % (reportdir, tfid, len(logos)) logos.append((j, os.path.basename(logo_filename)+"_fwd.png", ic, counts[j])) logo_fwd = deepity.tape2logo.tape2logo(pfm.T, height=50, letterwidth=10, bufferzoom=4, vmax=1.0, style="seqlogo", rna=rna) logo_rev = deepity.tape2logo.tape2logo(pfm_rev.T, height=50, letterwidth=10, bufferzoom=4, vmax=1.0, style="seqlogo", rna=rna) scipy.misc.imsave(logo_filename+"_fwd.png", logo_fwd) scipy.misc.imsave(logo_filename+"_rev.png", logo_rev) # Load train/test metrics so we can print them in the HTML report metrics_file = "%s/%s/metrics.txt" % (modeldir, tfid) metrics = deepity.load_metrics(metrics_file) # Add row for this TF in main index.html index_html.write("<tr>\n") index_html.write("<td><a href=\"%s/index.html\">%s</a></td>\n" % (tfid, tfid)) train_performance = "" test_performance = "" if index_metric=="auc": if "train" in metrics: index_html.write("<td>%s &plusmn; %s</td>\n" % (metrics["train"]["auc.mean"], metrics["train"]["auc.std"])) train_performance = metrics["train"]["auc.mean"] if "test" in metrics: index_html.write("<td><b>%s</b> &plusmn; %s</td>\n" % (metrics["test"]["auc.mean"], metrics["test"]["auc.std"])) test_performance = metrics["test"]["auc.mean"] elif index_metric=="pearson": if "train" in metrics: index_html.write("<td>%s (p=%s)</td>\n" % (metrics["train"]["pearson.r"], metrics["train"]["pearson.p"])) train_performance = metrics["train"]["pearson.r"] if "test" in metrics: index_html.write("<td><b>%s</b> (p=%s)</td>\n" % (metrics["test"]["pearson.r"], metrics["test"]["pearson.p"])) train_performance = metrics["test"]["pearson.r"] index_html.write("</tr>\n") performance_txt.write("%s\t%s\t%s\n" % (tfid, train_performance, test_performance)) # Build page showing filters and sequence logos for this specific TF tf_html = open(reportdir+"/"+tfid+"/index.html", 'w') tf_html.write("<html><head><title>Training report - %s</title></head><body>\n" % tfid) tf_html.write("<h2>%s</h2>\n" % tfid) # tf_html.write("<a href=\"../gmaps/%s/index.html\">gradient maps</a>)<hr/>\n"%(tfid,tfid)) tf_html.write(""" <script language="javascript"> function toggle_strand() { var pfms = document.getElementsByClassName('pfm') for (var i = 0; i < pfms.length; i++) if (pfms[i].src.search("_fwd") != -1) pfms[i].src = pfms[i].src.replace("_fwd","_rev"); else if (pfms[i].src.search("_rev") != -1) pfms[i].src = pfms[i].src.replace("_rev","_fwd"); } </script></head><body> """) with open(metrics_file) as f: metrics_text = f.read() tf_html.write("<pre>%s</pre>\n"% metrics_text) if os.path.exists(modeldir+"/%s/predict.scatter-train.png" % tfid): tf_html.write("<br/>Distribution of training predictions:<br/><img src=\"../../final/%s/predict.scatter-train.png\"/>\n" % tfid) # Then generate a table for the complete model tfdir = modeldir+"/"+tfid if logos: tf_html.write("<hr/><h3>Feature Logos</h3>\n") tf_html.write("<input type=\"button\" value=\"toggle strand\" onclick=\"toggle_strand();\"/><br/>") tf_html.write("<table cellspacing=0 cellpadding=4 border=0>\n") for filter_index, logo, ic, count in logos: tf_html.write("<tr><td>%d</td><td><img src=\"%s\" class=\"pfm\"/></td><td>%.1f bits,</td><td> %d activations</td></tr>" % (filter_index, logo, ic, count)) tf_html.write("</table><br/><br/>\n") # Now show the actual model. ''' shutil.copy(tfdir_final[0]+"/fold0.report/filters_.conv_seq(0).color.png", basedir+"report/%s/final_filters.png" % (tfid)) shutil.copy(tfdir_final[0]+"/fold0.report/filters_.conv_seq(0).logo.png", basedir+"report/%s/final_logos.png" % (tfid)) shutil.copy(tfdir_final[0]+"/fold0.report/filters_.conv_seq(1).png", basedir+"report/%s/final_biases.png" % (tfid)) shutil.copy(tfdir_final[0]+"/fold0.report/filters_.combiner.png", basedir+"report/%s/final_weights.png" % (tfid)) os.system("convert %sreport/%s/final_filters.png -rotate -90 %sreport/%s/final_filters_rot.png" % (basedir,tfid,basedir,tfid)) ''' tf_html.write("<hr/><h3>Actual DeepBind model</h3>\n") if os.path.exists(tfdir + "/model.conv_seq(1).color.png"): tf_html.write("Filters:<br/>\n") tf_html.write("<img src=\"../../final/%s/model.conv_seq(1).color.png\"/><br/>\n" % tfid) if os.path.exists(tfdir + "/model.combiner.png"): tf_html.write("<br/>Combiner layer:<br/>\n") tf_html.write("<img src=\"../../final/%s/model.combiner.png\"/><br/>\n" % tfid) tf_html.write("</body></html>\n") index_html.write("</table>\n") index_html.write("</body></html>\n") index_html.close()
DeepBind-master
code/deepbind_util.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import os import os.path import argparse import gzip import numpy as np import deepbind_util as util # Warning: The multiprocessing module may be used indirectly, so do not put any # unintentional statements outside of main(). def main(): args = loadargs() models = loadmodels(args) trdata = None util.globals.flags.push("clamp_targets", True) # Clamp the top .995 percentile of target values, to avoid extremely large targets (e.g. 00038/MBNL suffers from this) util.globals.flags.push("normalize_targets", True) # Make the targets have unit variance if "calib" in args.steps: trdata = load_traindata(trdata, args) util.calibrate(models, trdata, args.calibdir, nfold=args.nfold, ncalib=args.ncalib, allfolds=True) if "train" in args.steps: trdata = load_traindata(trdata, args) util.train(models, trdata, args.calibdir, args.finaldir, nfold=1, ntrial=args.ntrial) if "test" in args.steps: save_test_predictions(args) if "report" in args.steps: save_pfms(args) ids, _ = get_chunktargets(args) ids = sorted(ids) util.save_report(args.finaldir, args.reportdir, ids, index_metric="pearson", rna=True) ######################################################################### # Baseline AUCs computed beforehand, by applying RNAcompete PFMs to the in vivo test data sets and summing/maxing/averaging the per-position scores rnac_all_aucs ="""Protein File RNAcompete ID direct max avg sum len direct.std max.std avg.std sum.std len.std RBM4 RBM4.txt RNCMPT00052 nan 0.57954 0.53739 0.59715 0.68759 nan 0.01316 0.01179 0.01116 0.01185 RBM4 RBM4.txt RNCMPT00113 nan 0.57840 0.53501 0.60088 0.68759 nan 0.01395 0.01253 0.01129 0.01185 FUS FUS.txt RNCMPT00018 nan 0.26564 0.25616 0.39401 0.50894 nan 0.01001 0.00706 0.01116 0.00798 CPEB4 CPEB4.txt RNCMPT00158 nan 0.46494 0.51228 0.45046 0.30682 nan 0.01787 0.01636 0.01699 0.01312 PUM2 PUM2.txt RNCMPT00046 nan 0.92388 0.93771 0.93146 0.48923 nan 0.00570 0.00514 0.00533 0.01019 PUM2 PUM2.txt RNCMPT00101 nan 0.91999 0.93490 0.92761 0.48923 nan 0.00599 0.00518 0.00549 0.01019 PUM2 PUM2.txt RNCMPT00102 nan 0.92309 0.93684 0.92996 0.48923 nan 0.00556 0.00455 0.00517 0.01019 PUM2 PUM2.txt RNCMPT00103 nan 0.92704 0.93744 0.93271 0.48923 nan 0.00556 0.00548 0.00568 0.01019 PUM2 PUM2.txt RNCMPT00104 nan 0.93297 0.93929 0.93711 0.48923 nan 0.00505 0.00525 0.00503 0.01019 PUM2 PUM2.txt RNCMPT00105 nan 0.91665 0.92218 0.91714 0.48923 nan 0.00616 0.00607 0.00628 0.01019 HuR ELAVL1_Hafner.txt RNCMPT00274 nan 0.80117 0.81005 0.80901 0.50492 nan 0.00766 0.00784 0.00760 0.00867 HuR ELAVL1_Lebedeva.txt RNCMPT00274 nan 0.80521 0.82457 0.80981 0.50640 nan 0.00509 0.00434 0.00491 0.01020 HuR ELAVL1_MNASE.txt RNCMPT00274 nan 0.81389 0.82680 0.82515 0.50907 nan 0.00927 0.00912 0.00902 0.00873 HuR ELAVL1_Mukharjee.txt RNCMPT00274 nan 0.88430 0.89534 0.89195 0.50741 nan 0.00291 0.00251 0.00245 0.00562 FMR1 FMR1_RIP_top1K.txt RNCMPT00016 nan 0.76716 0.75601 0.89024 0.81773 nan 0.01173 0.01059 0.00754 0.01080 FMR1 FMR1_table2a_top1K.txt RNCMPT00016 nan 0.56646 0.59232 0.59202 0.49905 nan 0.01074 0.01077 0.01125 0.01624 FMR1 FMR1_table2a_top5K.txt RNCMPT00016 nan 0.57225 0.59665 0.59672 0.49990 nan 0.00679 0.00625 0.00634 0.00498 FMR1 FMR1_table2b_top1K.txt RNCMPT00016 nan 0.56580 0.59210 0.59223 0.50034 nan 0.01480 0.01520 0.01524 0.01267 FMR1 FMR1_table2b_top5K.txt RNCMPT00016 nan 0.55623 0.57975 0.57952 0.49705 nan 0.00476 0.00475 0.00478 0.00714 QKI QKI.txt RNCMPT00047 nan 0.92322 0.93431 0.93004 0.50657 nan 0.00611 0.00593 0.00576 0.01082 SRSF1 SFRS1.txt RNCMPT00106 nan 0.85875 0.87453 0.87285 0.54262 nan 0.01365 0.01363 0.01384 0.02879 SRSF1 SFRS1.txt RNCMPT00107 nan 0.85443 0.86763 0.86887 0.54262 nan 0.01640 0.01597 0.01555 0.02879 SRSF1 SFRS1.txt RNCMPT00108 nan 0.84777 0.85921 0.85865 0.54262 nan 0.01782 0.01638 0.01690 0.02879 SRSF1 SFRS1.txt RNCMPT00109 nan 0.84414 0.85777 0.85645 0.54262 nan 0.01754 0.01659 0.01711 0.02879 SRSF1 SFRS1.txt RNCMPT00110 nan 0.79507 0.81253 0.81173 0.54262 nan 0.01474 0.01493 0.01425 0.02879 SRSF1 SFRS1.txt RNCMPT00163 nan 0.86275 0.87639 0.87327 0.54262 nan 0.01372 0.01296 0.01290 0.02879 Vts1p Vts1p.txt RNCMPT00082 nan 0.67892 0.68584 0.68750 0.56794 nan 0.01679 0.01765 0.01601 0.02029 Vts1p Vts1p.txt RNCMPT00111 nan 0.68317 0.69048 0.69310 0.56794 nan 0.01815 0.02086 0.01746 0.02029 HNRNPA2B1 hnRNPA2B1.txt RNCMPT00024 nan 0.54903 0.56342 0.56330 0.49990 nan 0.00959 0.01012 0.01000 0.00921 MBNL1 Mbnl1_B6Brain.txt RNCMPT00038 nan 0.61514 0.62822 0.62443 0.50256 nan 0.00614 0.00593 0.00599 0.00849 MBNL1 Mbnl1_B6Heart.txt RNCMPT00038 nan 0.60240 0.61387 0.61421 0.52043 nan 0.01131 0.01098 0.01126 0.01359 MBNL1 Mbnl1_B6Muscle.txt RNCMPT00038 nan 0.60721 0.61079 0.61372 0.51123 nan 0.02156 0.02032 0.02063 0.01794 MBNL1 Mbnl1_B129Brain.txt RNCMPT00038 nan 0.58529 0.59620 0.59205 0.49597 nan 0.00416 0.00431 0.00413 0.00369 MBNL1 Mbnl1_C2C12.txt RNCMPT00038 nan 0.67202 0.68331 0.67960 0.50211 nan 0.00207 0.00213 0.00205 0.00269 PTBP1 PTBP1.txt RNCMPT00268 nan 0.73912 0.77290 0.74726 0.51303 nan 0.00812 0.00741 0.00797 0.00916 PTBP1 PTBP1.txt RNCMPT00269 nan 0.73258 0.76753 0.74049 0.51303 nan 0.00769 0.00737 0.00754 0.00916 LIN28 LIN28_hES_3UTR.txt RNCMPT00036 nan 0.64158 0.66601 0.64597 0.49502 nan 0.00391 0.00440 0.00385 0.00364 LIN28 LIN28_hES_3UTR.txt RNCMPT00162 nan 0.61623 0.63471 0.61896 0.49502 nan 0.00508 0.00574 0.00511 0.00364 LIN28 LIN28_hES_coding_exons.txt RNCMPT00036 nan 0.61977 0.63383 0.62368 0.51739 nan 0.00737 0.00775 0.00789 0.00587 LIN28 LIN28_hES_coding_exons.txt RNCMPT00162 nan 0.59463 0.60173 0.59540 0.51739 nan 0.00739 0.00747 0.00753 0.00587 LIN28 LIN28_v5_3UTR.txt RNCMPT00036 nan 0.62030 0.63684 0.62011 0.48639 nan 0.00871 0.00824 0.00843 0.01021 LIN28 LIN28_v5_3UTR.txt RNCMPT00162 nan 0.64040 0.65904 0.64265 0.48639 nan 0.00873 0.00834 0.00889 0.01021 LIN28 LIN28_v5_coding_exons.txt RNCMPT00036 nan 0.59787 0.60869 0.59829 0.49904 nan 0.00947 0.00996 0.00914 0.00765 LIN28 LIN28_v5_coding_exons.txt RNCMPT00162 nan 0.61716 0.62985 0.61869 0.49904 nan 0.01133 0.01165 0.01068 0.00765 MSI1 MSI.txt RNCMPT00176 nan 0.63872 0.85384 0.61312 0.35007 nan 0.05670 0.03968 0.05180 0.05094 HNRNPA1 hnRNPA1.txt RNCMPT00023 nan 0.63787 0.66090 0.66060 0.49896 nan 0.01842 0.01709 0.01739 0.01959 SHEP SHEP_bg3_normal.txt RNCMPT00068 nan 0.68478 0.59950 0.78179 0.80603 nan 0.02868 0.03654 0.01885 0.01860 SHEP SHEP_bg3_normal.txt RNCMPT00174 nan 0.67722 0.56947 0.77837 0.80603 nan 0.02655 0.03655 0.01767 0.01860 SHEP SHEP_bg3_normal.txt RNCMPT00175 nan 0.68777 0.60964 0.78866 0.80603 nan 0.02748 0.03319 0.01870 0.01860 SHEP SHEP_bg3_stringent.txt RNCMPT00068 nan 0.65654 0.61508 0.75189 0.76043 nan 0.02804 0.02777 0.02695 0.03001 SHEP SHEP_bg3_stringent.txt RNCMPT00174 nan 0.67423 0.59333 0.75680 0.76043 nan 0.02515 0.02641 0.02562 0.03001 SHEP SHEP_bg3_stringent.txt RNCMPT00175 nan 0.66576 0.62182 0.75435 0.76043 nan 0.02719 0.02632 0.02765 0.03001 SHEP SHEP_kc_normal.txt RNCMPT00068 nan 0.58452 0.66421 0.60800 0.48666 nan 0.02354 0.02042 0.02061 0.01753 SHEP SHEP_kc_normal.txt RNCMPT00174 nan 0.60444 0.68226 0.61162 0.48666 nan 0.01583 0.01687 0.01707 0.01753 SHEP SHEP_kc_normal.txt RNCMPT00175 nan 0.60845 0.68181 0.62068 0.48666 nan 0.01919 0.01680 0.01763 0.01753 SHEP SHEP_kc_stringent.txt RNCMPT00068 nan 0.57643 0.66430 0.58256 0.44887 nan 0.02101 0.02489 0.02209 0.01979 SHEP SHEP_kc_stringent.txt RNCMPT00174 nan 0.56663 0.65829 0.56107 0.44887 nan 0.02144 0.02681 0.02334 0.01979 SHEP SHEP_kc_stringent.txt RNCMPT00175 nan 0.57928 0.66535 0.58411 0.44887 nan 0.02430 0.02639 0.02401 0.01979 IGF2BP2 IGF2BP1-3.txt RNCMPT00033 nan 0.58948 0.60332 0.57859 0.49313 nan 0.00662 0.00529 0.00624 0.00703 TARDBP TARDBP_iCLIP.txt RNCMPT00076 nan 0.69432 0.76630 0.74933 0.50791 nan 0.00441 0.00413 0.00402 0.00548 TARDBP TARDBP_RIP.txt RNCMPT00076 nan 0.51319 0.51618 0.50674 0.48739 nan 0.01787 0.01786 0.01817 0.02001 TAF15 TAF15.txt RNCMPT00018 nan 0.27793 0.26921 0.39900 0.50233 nan 0.01085 0.01096 0.01464 0.01268 TIA1 TIA1.txt RNCMPT00077 nan 0.77897 0.80216 0.78685 0.46814 nan 0.00993 0.00899 0.01005 0.01164 TIA1 TIA1.txt RNCMPT00165 nan 0.79207 0.80957 0.79501 0.46814 nan 0.01001 0.00883 0.00975 0.01164 TIAL1 TIAL1.txt RNCMPT00077 nan 0.79665 0.82024 0.80884 0.49757 nan 0.00544 0.00530 0.00569 0.01029 TIAL1 TIAL1.txt RNCMPT00165 nan 0.81188 0.82708 0.81648 0.49757 nan 0.00540 0.00484 0.00516 0.01029 LARK Lark_shared.txt RNCMPT00035 nan 0.60496 0.55183 0.63621 0.69572 nan 0.05016 0.05038 0.05092 0.04579 LARK Lark_shared.txt RNCMPT00097 nan 0.62910 0.58226 0.65882 0.69572 nan 0.05477 0.05532 0.05376 0.04579 LARK Lark_shared.txt RNCMPT00124 nan 0.63998 0.59298 0.68235 0.69572 nan 0.05991 0.05948 0.05403 0.04579 LARK Lark_union.txt RNCMPT00035 nan 0.64096 0.59872 0.66861 0.69956 nan 0.02697 0.02756 0.02547 0.02800 LARK Lark_union.txt RNCMPT00097 nan 0.65407 0.60527 0.66818 0.69956 nan 0.02743 0.02961 0.02634 0.02800 LARK Lark_union.txt RNCMPT00124 nan 0.63400 0.58167 0.66941 0.69956 nan 0.02865 0.03266 0.02820 0.02800""".split("\n") # Generate test AUCs on in vivo data invivo_ids = { "PUM2" : ([ 46,101,102,103,104,105],["PUM2"]), "SRSF1" : ([106,107,108,109,110,163],["SFRS1"]), #"FUS" : ([19,88,89,90], ["FUS"]), #"TAF15" : ([19,88,89,90], ["TAF15"]), "FUS" : ([18], ["FUS"]), "TAF15" : ([18], ["TAF15"]), "SHEP" : ([68,174,175], ["SHEP_bg3_normal","SHEP_bg3_stringent","SHEP_kc_normal","SHEP_kc_stringent"]), "Vts1p" : ([82,111], ["Vts1p"]), "HuR" : ([274], ["ELAVL1_Hafner","ELAVL1_Lebedeva","ELAVL1_MNASE","ELAVL1_Mukharjee"]), "LARK" : ([35,97,124], ["Lark_shared","Lark_union"]), "QKI" : ([47], ["QKI"]), "FMR1" : ([16], ["FMR1_RIP_top1K","FMR1_table2a_top1K","FMR1_table2a_top5K","FMR1_table2b_top1K","FMR1_table2b_top5K"]), "TIA1" : ([77,165], ["TIA1"]), "TIAL1" : ([77,165], ["TIAL1"]), "TARDBP" : ([76], ["TARDBP_iCLIP","TARDBP_RIP"]), "PTBP1" : ([268,269], ["PTBP1"]), "HNRNPA1" : ([23], ["hnRNPA1"]), "LIN28" : ([36,162], ["LIN28_hES_3UTR","LIN28_hES_coding_exons","LIN28_v5_3UTR","LIN28_v5_coding_exons"]), "MSI1" : ([176], ["MSI"]), "RBM4" : ([52,113], ["RBM4"]), "IGF2BP2" : ([33], ["IGF2BP1-3"]), "HNRNPA2B1" : ([24], ["hnRNPA2B1"]), "MBNL1" : ([38], ["Mbnl1_B6Brain","Mbnl1_B6Heart","Mbnl1_B6Muscle","Mbnl1_B129Brain","Mbnl1_C2C12"]), "CPEB4" : ([158], ["CPEB4"]), } all_invivo_ids = sorted(sum([value[0] for value in invivo_ids.itervalues()],[])) shorthandids = { #"invivo_sub" : ["RNCMPT00016", "RNCMPT00111", "RNCMPT00038", "RNCMPT00105", "RNCMPT00274", "RNCMPT00076", "RNCMPT00107", "RNCMPT00176", "RNCMPT00269", "RNCMPT00023"], "invivo_sub" : ["RNCMPT00268", "RNCMPT00076", "RNCMPT00038", "RNCMPT00023"], "invivo" : ["RNCMPT%05d"%id for id in all_invivo_ids ], } def loadargs(): # Give names to specific groups of RNAcompete ids args = argparse.ArgumentParser(description="Generate the RNAcompete experiments.") args.add_argument("mode", type=str, help="Either \"A\" (train A, test B), \"B\" (train B, test A), or \"AB\" (train AB, test invivo).") args = util.parseargs("rnac", args, shorthandids=shorthandids) args.calibdir = args.calibdir.replace(args.outdir, args.outdir+"/"+args.mode) args.finaldir = args.finaldir.replace(args.outdir, args.outdir+"/"+args.mode) args.reportdir = args.reportdir.replace(args.outdir,args.outdir+"/"+args.mode) args.outdir = args.outdir+"/"+args.mode return args ################################# def loadmodels(args): models = util.loadmodels(args, modeldir="cfg/regression/allpool") return models ################################# def get_chunktargets(args): # Determine which targetnames we're responsible for targetnames = gzip.open("../data/rnac/targets.tsv.gz").readline().rstrip().split("\t") chunktargets = util.getchunktargets(args, targetnames) chunkcols = [i for i in range(len(targetnames)) if targetnames[i] in chunktargets] return chunktargets, chunkcols def load_traindata(trdata, args): if trdata is not None: return trdata # Training data was already loaded in earlier step. # In quick mode, only load a subset of the data maxrows = 10000 if args.quick else None chunktargets, chunkcols = get_chunktargets(args) # Load only a specific fold if args.mode == "A": trdata = util.datasource.fromtxt("../data/rnac/sequences.tsv.gz", None, "../data/rnac/targets.tsv.gz", targetcols=chunkcols, foldfilter="A", maxrows=maxrows) elif args.mode == "B": trdata = util.datasource.fromtxt("../data/rnac/sequences.tsv.gz", None, "../data/rnac/targets.tsv.gz", targetcols=chunkcols, foldfilter="B", maxrows=maxrows) elif args.mode == "AB": trdata = util.datasource.fromtxt("../data/rnac/sequences.tsv.gz", None, "../data/rnac/targets.tsv.gz", targetcols=chunkcols, foldfilter="AB", maxrows=maxrows) else: quit("Unrecognized mode") return trdata ################################# def save_test_predictions(args): # In quick mode, only load a subset of the data maxrows = 10000 if args.quick else None chunktargets, chunkcols = get_chunktargets(args) tedata = {} abs_auc = lambda x: max(x, 1-x) if args.mode == "AB": invivo_data_dir = "../data/rnac/invivo" util.makepath(args.testdir+"/invivo") aucdump = open(args.testdir+"/invivo/deepbind_all.txt","w") aucdump.write("Protein\tFile\tModel\tauc\tauc.mean\tauc.std\n") for invivo_id in invivo_ids.keys(): rnac_ids, invivo_files = invivo_ids[invivo_id] rnac_names = ["RNCMPT%05d" % id for id in rnac_ids] rnac_names = [name for name in rnac_names if name in chunktargets] if not rnac_names: continue for invivo_file in invivo_files: if not os.path.exists(invivo_data_dir + "/" + invivo_file + ".txt"): continue print "File %s using models %s..." % (invivo_file, ",".join(rnac_names)) # Convert the invivo sequence file into a format that predict.py expects, # i.e. with a Fold ID, Event ID, and Sequence column. data = util.datasource.fromtxt(invivo_data_dir+"/" + invivo_file + ".txt[1]", None, invivo_data_dir+"/" + invivo_file + ".txt[0]", sequencenames=["bound","seq"], targetnames=["bound"] ) # First generate predictions based on "trivial" features for this particular invivo file sequences = [row[0] for row in data.sequences] labels = data.targets predictions = {} predictions["len"] = np.asarray([len(s) for s in sequences],np.float32).reshape((-1,1)) predictions["A"] = np.asarray([s.upper().count("A") / float(len(s)) for s in sequences], np.float32).reshape((-1,1)) predictions["C"] = np.asarray([s.upper().count("C") / float(len(s)) for s in sequences], np.float32).reshape((-1,1)) predictions["G"] = np.asarray([s.upper().count("G") / float(len(s)) for s in sequences], np.float32).reshape((-1,1)) predictions["T"] = np.asarray([(s.upper().count("U")+s.upper().count("T")) / float(len(s)) for s in sequences], np.float32).reshape((-1,1)) predictions["GC"] = predictions["G"] + predictions["C"] # Next, generate predictions for each model on this same data file data.targetnames = rnac_names data.Y = np.repeat(data.Y, len(rnac_names), 1) data.Ymask = np.repeat(data.Ymask, len(rnac_names), 1) data.targets = data.Y.copy() #pred = util.predict(data, "../data/rnac/pfms", args.reportdir, scan=20) pred = util.predict(data, args.finaldir, args.reportdir, scan=20) predictions.update(pred) # Dump all performance stats to the file for pname in sorted(predictions.keys(), key=lambda x: x if "RNCMPT" not in x else " "+x): # Make sure RNCMPT items go first in each group, for readability of all_aucs.txt # Calculate the AUC of this particular prediction, of this particular model, # on this particular invivo file. z = predictions[pname].ravel() y = np.array(labels).ravel() metrics = util.calc_metrics(z, y) # Write out a row indicating performance of each model on this file aucdump.write("%s\t%s\t%s\t%.4f\t%.4f\t%.6f\n" % (invivo_id, invivo_file, pname, metrics["auc"], metrics["auc.mean"], metrics["auc.std"])) aucdump.close() # Re-open the AUC dump file, pull out all experiments associated with a single protein, # and collect only the best of each type all_aucs = {} with open(args.testdir+"/invivo/deepbind_all.txt") as f: f.readline() # discard header line for line in f: protein_name, invivo_file, model_name, auc, auc_mean, auc_std = line.rstrip().split("\t") model_suffix = ".deepbind" if "RNCMPT" in model_name else "" if model_name == "GC": continue all_aucs.setdefault(protein_name,[]).append({"file" : invivo_file, "model" : model_name+model_suffix, "auc" : float(auc), "auc.mean" : float(auc_mean), "auc.std" : float(auc_std)}) # Open the rnac_all.txt and pull out the AUCs for the PFMs from the RNAcompete paper # The rnac_all.txt file is in a different format, for legacy reasons head = rnac_all_aucs[0].rstrip().split("\t") lines = [line.rstrip().split("\t") for line in rnac_all_aucs[1:]] cols = { item : head.index(item) for item in head } for line in lines: protein_name = line[0] for scantype in ("max","sum","avg","direct"): invivo_file = line[1].rsplit(".",1)[0] model_name = line[2]+"."+scantype auc = "nan" auc_mean = line[cols[scantype]] auc_std = line[cols[scantype+".std"]] if protein_name in all_aucs: all_aucs[protein_name].append({"file" : invivo_file, "model" : model_name+".rnac", "auc" : float(auc), "auc.mean" : float(auc_mean), "auc.std" : float(auc_std)}) for scantype in ("direct","max","sum","avg"): for modeltype in ("deepbind","rnac"): with open(args.testdir+"/invivo/%s_best_%s.txt" % (modeltype, scantype),"w") as f: f.write("Protein\tFile") f.write("\t"+"\t".join(["deeputil.model","deeputil.auc","deeputil.auc.mean","deeputil.auc.std"])) f.write("\t"+"\t".join(["rnac.model", "rnac.auc", "rnac.auc.mean", "rnac.auc.std"])) f.write("\t"+"\t".join(["trivial.model", "trivial.auc", "trivial.auc.mean", "trivial.auc.std"])) f.write("\n") for protein in sorted(all_aucs.keys()): trials = all_aucs[protein] # For this particular protein, first find the best row based on non-trivial models, # e.g. among RNCMPTXXXXX.direct and RNCMPTXXXXX.max, while ignoring "A" and "len" best = None for trial in trials: if trial["model"].endswith(scantype+"."+modeltype): if best is None or trial["auc.mean"] > best["auc.mean"]: best = trial # Also find the best trivial feature associated with this file best_trivial = None for trial in trials: if trial["file"] == best["file"] and "RNCMPT" not in trial["model"]: if best_trivial is None or abs_auc(trial["auc.mean"]) > abs_auc(best_trivial["auc.mean"]): best_trivial = trial # Also find the best competing feature associated with this file best_other = None if modeltype == "rnac": other_scantype = "max" elif modeltype == "deepbind": other_scantype = "avg" else: other_scantype = scantype for trial in trials: if trial["file"] == best["file"] and ("."+other_scantype+".") in trial["model"] and not trial["model"].endswith(other_scantype+"."+modeltype): if best_other is None or trial["auc.mean"] > best_other["auc.mean"]: best_other = trial best_deepbind = best if modeltype == "deepbind" else best_other best_rnac = best if modeltype == "rnac" else best_other f.write("%s\t%s\t" % (protein, best["file"])) f.write("%s\t%.4f\t%.4f\t%.6f\t" % (best_deepbind["model"], best_deepbind["auc"], best_deepbind["auc.mean"], best_deepbind["auc.std"])) f.write("%s\t%.4f\t%.4f\t%.6f\t" % (best_rnac["model"], best_rnac["auc"], best_rnac["auc.mean"], best_rnac["auc.std"])) f.write("%s\t%.4f\t%.4f\t%.6f\n" % (best_trivial["model"], abs_auc(best_trivial["auc"]), abs_auc(best_trivial["auc.mean"]), best_trivial["auc.std"])) elif args.mode in ("A","B"): # Generate predictions on PBM probes from test set (i.e. if mode="A", the training set was "A" so the test set is "B") print "Loading PBM data...", testfold = "A" if args.mode == "B" else "B" pbmdata = util.datasource.fromtxt("../data/rnac/sequences.tsv.gz", None, "../data/rnac/targets.tsv.gz", targetcols=[0], foldfilter=testfold, maxrows=maxrows) print "done" util.makepath(args.testdir+"/pbm") for targetname in chunktargets: print targetname pbmdata.targetnames = [targetname] predictions = util.predict(pbmdata, args.finaldir, args.reportdir, include=[targetname]) Z = predictions[targetname].ravel() with gzip.open(args.testdir+"/pbm/%s-DB-%s.txt.gz"%(targetname, testfold), "w") as f: for z in Z: f.write("%.4f\n"%z) else: quit("Unrecognized mode") ################################# def save_pfms(args): maxrows = 10000 if args.quick else None chunktargets, chunkcols = get_chunktargets(args) print "Loading PBM data...", if args.mode == "A": testfold = "B" elif args.mode == "B": testfold = "A" else: testfold = "AB" pbmdata = util.datasource.fromtxt("../data/rnac/sequences.tsv.gz", None, "../data/rnac/targets.tsv.gz", targetcols=chunkcols, foldfilter=testfold, maxrows=maxrows) print "done" util.save_featuremaps(pbmdata, args.finaldir, args.reportdir) if __name__=="__main__": #util.disable_multiprocessing() main()
DeepBind-master
code/deepbind_train_rnac.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import sys import argparse import numpy as np from os import listdir from os.path import join sys.path.append("libs/smat/py") from smat import * # change the activation function, cane be [logistic|tanh|relu] activation_func = "relu" # change to the desired GPU (if not default) picked_device = None if picked_device is not None: set_backend_options(device=picked_device) # change to dt64 for double precision dt = float32 set_default_dtype(dt) data_root = '../data/deepfind/' print "Started DeepFind: scoring SNVs in promoters using DeepBind predictions" print "Training DeepFind using", get_backend_info().device ############################################################################## # Neural Network ############################################################################## # Evaluate our 1-layer neural network using weights W1,W2 above. # Returns final outputs and, if targets Y are given, returns gradients as well. def nnet_eval(X, Y=None, mode="sigmoid"): global W1,W2,b1,b2 #**************************************************************** # Forward propagate minibatch inputs X to generate predictions Z2 A1 = dot(X, W1) + b1 Z1 = f(A1) # Z1 = outputs for layer 1 if Y is not None: if dropoutrate > 0: mask = bernoulli(Z1.shape, 1 - dropoutrate, dtype=dt) Z1 *= mask else: Z1 *= 1 - dropoutrate A2 = dot(Z1, W2) + b2 Z2 = logistic(A2) # Z2 = output if Y is None: if mode == "sigmoid": return Z2 # If no gradient requested, just return the predictions else: return A2 # If no gradient requested, just return the predictions before passing the sigmoid #**************************************************************** # Backward propagate error between Z2 and targets Y D2 = (Z2-Y)/X.shape[0] # Backprop prediction error as delta to layer 2 D1 = df(Z1)*dot_nt(D2, W2) # Backprop layer 2 deltas to layer 1 if dropoutrate > 0: D1 *= mask # Apply the dropout mask # Compute gradient of training error w.r.t. network weights dW2 = dot_tn(Z1, D2) + l2norm*W2 db2 = sum(D2, axis=0) # Gradient w.r.t. W2 dW1 = dot_tn(X , D1) + l2norm*W1 db1 = sum(D1, axis=0) # Gradient w.r.t. W1 return Z2,dW1,dW2,db1,db2 # Return predictions and gradients # Activation functions if activation_func == "logistic": def f(A): return 1./(1+exp(-A)) # logistic sigmoid activation function, returns Z=logistic(A) def df(Z): return Z-Z**2 # derivative d/dx(logistic)(x) = logistic(x)-logistic(x)^2 elif activation_func == "tanh": def f(A): return tanh(A) # tanh sigmoid activation function, returns Z=tanh(A) def df(Z): return 1-Z**2 # derivative d/dx(tanh)(x) = 1-tanh(x)^2 elif activation_func == "relu": def f(A): return maximum(0, A) # 'rectified linear' (relu) activation function, returns Z=max(0,A) def df(Z): return sign(Z) # derivative d/dx(relu)(x) = sign(max(0,x)) else: quit("Unrecognized activation function \"%s\"." % activation_func) # Set neural network's weights to small random values def randweights(n, m): return rand(n, m)*0.002-0.001 # initialize to small values [-0.001,0.001] ############################################################################## # Functions for PRINTING ############################################################################## def calc_auc(z, y, want_curve = False): """Given predictions z and 0/1 targets y, computes AUC with optional ROC curve""" z = z.ravel() y = y.ravel() assert len(z) == len(y) # Remove any pair with NaN in y m = ~np.isnan(y) y = y[m] z = z[m] assert np.all(np.logical_or(y==0, y==1)), "Cannot calculate AUC for non-binary targets" order = np.argsort(z,axis=0)[::-1].ravel() # Sort by decreasing order of prediction strength z = z[order] y = y[order] npos = np.count_nonzero(y) # Total number of positives. nneg = len(y)-npos # Total number of negatives. if nneg == 0 or npos == 0: return (np.nan,None) if want_curve else 1 n = len(y) fprate = np.zeros((n+1,1)) tprate = np.zeros((n+1,1)) ntpos,nfpos = 0.,0. for i,yi in enumerate(y): if yi: ntpos += 1 else: nfpos += 1 tprate[i+1] = ntpos/npos fprate[i+1] = nfpos/nneg auc = float(np.trapz(tprate,fprate,axis=0)) if want_curve: curve = np.hstack([fprate,tprate]) return auc, curve return auc def error_rate(X, Y): Z = np.vstack([nnet_eval(tX).asnumpy() for tX in X]) L = np.vstack([tY.asnumpy() for tY in Y]) return calc_auc(Z,L) def print_status(epoch=None): update_interval = 25 if epoch is None or epoch > 0: # Only print status every 5 epochs. time_per_epoch = toc() / update_interval test_error = error_rate(Xvd, Yvd) status_msg = "start: " if epoch is None else ("epoch[%03d]:"% (epoch+1)) time_msg = "(%.2fs/epoch)" % time_per_epoch if epoch is not None else "" if epoch is None or (epoch+1) % update_interval == 0: train_error = error_rate(Xtr, Ytr) print "\t%s %.2f%% train auc, %.2f%% validation auc %s" % (status_msg, 100*train_error, 100*test_error, time_msg) sys.stdout.flush() tic() return test_error ############################################################################## # Functions for loading DATA ############################################################################## add_cons = True # add conservation information add_feats = True # add dist to TSS and is_transversion features add_tfs = True # add predictions from TFs for wildtype and mutant do_masking = True # match genes of positive and negative sets # input files and directories pos_dir = join(data_root, 'tfs_simulated') neg_dir = join(data_root, 'tfs_derived') cons_pos_file = join(data_root, 'simulated_cons.npz') cons_neg_file = join(data_root, 'derived_cons.npz') mask_file = join(data_root, 'matching_mask.npz') pos_feat_file = join(data_root, 'simulated_feats.npz') neg_feat_file = join(data_root, 'derived_feats.npz') tfs_to_consider = join(data_root, 'TFs_to_consider.txt') with open(tfs_to_consider) as fh: considered_files = [line.strip('\r\n') for line in fh] # function for loading the TF predictions in NPZ files def load_data(save_dir, considered_files=None): files = listdir(save_dir) factor_names = [] if considered_files is None: dim = 2*(len(files)) else: dim = 2*(len(considered_files)) cnt = 0 for file_name in sorted(files): # ignore the TFs that are not picked if considered_files is not None and file_name[:-4] not in considered_files: continue factor_names.append(file_name[:-4]) # remove the .npz suffix with np.load(join(save_dir, file_name)) as data: p = data['pred'] if cnt == 0: # initiliaze the feature matrix X = np.empty((p.shape[0]/2,dim)) X[:,2*cnt] = p[::2] # wild type predictions X[:,2*cnt+1] = p[1::2] - p[::2] # mutant - wildtype predictions cnt += 1 return X, factor_names print "*******************************************************************" print 'Loading the data...' # Loading Training data pX, pfactors = load_data(pos_dir, considered_files) nX, nfactors = load_data(neg_dir, considered_files) print 'Adding prediction for %d TFs' % len(pfactors) for pf, nf in zip(pfactors, nfactors): if not pf == nf: print 'Mismatched TFs!' # Combine psoitive and negative sets X = np.vstack([pX, nX]) Y = np.vstack([np.ones((pX.shape[0],1)), np.zeros((nX.shape[0],1))]) # Add conservation if add_cons: print 'Adding conservation' with np.load(cons_pos_file) as data: pC = data['cons'] with np.load(cons_neg_file) as data: nC = data['cons'] C = np.vstack((pC, nC)) # add conservation information to TF features X = np.hstack((X, C)) # Add two features: transversion_flag for mutations # and the normalized distance to the closest TSS in (0, 1] if add_feats: print 'Adding two extra features' with np.load(pos_feat_file) as data: pF = data['feats'] with np.load(neg_feat_file) as data: nF = data['feats'] X = np.hstack([X, np.vstack([pF, nF])]) # Applying the mask and matching the genes in the # simulated and derived alleles if do_masking: print 'Matching genes' with np.load(mask_file) as data: c_mask = np.hstack([data['pos_mask'], data['neg_mask']]) X = X[c_mask] Y = Y[c_mask] num, dim = X.shape print 'Data is loaded\nsample size: %d, dimensions:%d' % (num, dim) # randomly permuting the data np.random.seed(1234) shuffled_idx = np.random.permutation(num) X[:] = X[shuffled_idx] Y[:] = Y[shuffled_idx] # Setting up cross-validation indices num_fold = 5 sp = np.linspace(0, num, num_fold+1).astype(np.int) splits = np.empty((num_fold, 2), dtype=np.int) for i in range(num_fold): splits[i,:] = [sp[i], sp[i+1]] def split_data(splits, fold_id, num_fold): all_splits = set(np.arange(num_fold)) ts = np.mod(num_fold-1+fold_id, num_fold) vd = np.mod(num_fold-2+fold_id, num_fold) tr = list(all_splits - set([ts, vd])) idx_ts = np.arange(splits[ts,0],splits[ts,1]) idx_vd = np.arange(splits[vd,0],splits[vd,1]) idx_tr = np.arange(splits[tr[0],0],splits[tr[0],1]) for i in range(1, len(tr)): idx_tr = np.hstack([idx_tr, np.arange(splits[tr[i],0],splits[tr[i],1])]) return idx_tr, idx_vd, idx_ts # Perform cross validation on the data # Parameters of SGD training batchsize = 128 num_epoch = 250 learn_rate = 5e-4 momentum = 0.90 dropoutrate = 0.5 layersize1 = 200 # Number of neurons in first layer outputsize = 1 # 2 classes, 1 sigmoid l2norm = 1e-6 inputsize = dim # Holding folds' information perfs = list() test_auc = list() tic("total time") Y_hat = np.empty(num) for fold_id in range(num_fold): best_va_auc = 0. test_fold = np.mod(num_fold-1+fold_id, num_fold)+1 print "*******************************************************************" print "Training a neural network and testing on fold %d" % (test_fold) tic("fold time") temp_perfs = list() # weights and biases and their momentums W1 = randweights(inputsize, layersize1); b1 = randweights(1, layersize1) W2 = randweights(layersize1, outputsize); b2 = randweights(1, outputsize) mW1 = zeros_like(W1); mb1 = zeros_like(b1) mW2 = zeros_like(W2); mb2 = zeros_like(b2) # form the GPU based testing and trainng sets # Uploading the Training data to GPU idx_tr, idx_vd, idx_ts = split_data(splits, fold_id, num_fold) num_tr = idx_tr.shape[0] num_ts = idx_ts.shape[0] num_vd = idx_vd.shape[0] Xtr = None; Xts = None; Xvd = None Ytr = None; Yts = None; Yvd = None Xtr = [asarray(X[idx_tr[i:np.min([i+batchsize, num_tr])]], dtype=dt) for i in range(0, num_tr, batchsize)] Ytr = [asarray(Y[idx_tr[i:np.min([i+batchsize, num_tr])]], dtype=dt) for i in range(0, num_tr, batchsize)] Xts = [asarray(X[idx_ts[i:np.min([i+batchsize, num_ts])]], dtype=dt) for i in range(0, num_ts, batchsize)] Yts = [asarray(Y[idx_ts[i:np.min([i+batchsize, num_ts])]], dtype=dt) for i in range(0, num_ts, batchsize)] Xvd = [asarray(X[idx_vd[i:np.min([i+batchsize, num_vd])]], dtype=dt) for i in range(0, num_vd, batchsize)] Yvd = [asarray(Y[idx_vd[i:np.min([i+batchsize, num_vd])]], dtype=dt) for i in range(0, num_vd, batchsize)] print_status() tic("training time") ############################################################################## # TRAINING LOOP ############################################################################## # Start training! for epoch in range(num_epoch): nb = len(Xtr) # number of minibatches rand_b = np.random.permutation(nb) for j in range(nb): i = rand_b[j] tX = Xtr[i] tY = Ytr[i] # Generate predictions Z, along with # per-layer gradient based on targets Y Z,dW1,dW2,db1,db2 = nnet_eval(tX, tY) # Gradient step with very basic momentum for P,dP,mP in zip(( W1, W2, b1, b2), (dW1, dW2, db1, db2), (mW1, mW2, mb1, mb2)): dP *= -learn_rate mP *= momentum mP += dP P += mP # store the parameters at each epoch va_auc = print_status(epoch) if va_auc > best_va_auc: best_params = [W1.copy(), W2.copy(), b1.copy(), b2.copy()] best_va_auc = va_auc temp_perfs.append(va_auc) W1, W2, b1, b2 = best_params t_Yts_hat = np.vstack([nnet_eval(tX, mode='presigmoid').asnumpy() for tX in Xts]) t_Yts = Y[idx_ts] test_auc.append(100*calc_auc(t_Yts_hat, t_Yts)) print "\nFold %d test AUC: %.2f, fold running time = %.1fs" % (test_fold, test_auc[-1], toc("fold time")) print "*******************************************************************" perfs.append(temp_perfs) print "Average Test AUC: %.2f, Total running time = %.1fs" % (np.mean(test_auc), toc("total time"))
DeepBind-master
code/deepfind.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import sys import re import os import os.path import argparse import numpy as np import numpy.random as npr import deepbind_util as util import cPickle import scipy import shutil # Warning: The multiprocessing module may be used indirectly, so do not put any # unintentional statements outside of main(). datadir = "../data/selex" def main(): util.enable_reversecomplement() args = loadargs() models = loadmodels(args) trdata = None tedata = None tfids = load_tfids(args) for tfid in tfids: if "calib" in args.steps: print "-------------- calib:", tfid, "--------------" set_motif_lengths(args, models, tfid) trdata = load_traindata(tfid, args) util.calibrate(models, trdata, args.calibdir, nfold=args.nfold, ncalib=args.ncalib, allfolds=False) if "train" in args.steps: print "-------------- train:", tfid, "--------------" set_motif_lengths(args, models, tfid) trdata = load_traindata(tfid, args) util.train(models, trdata, args.calibdir, args.finaldir, nfold=1, ntrial=args.ntrial) if "test" in args.steps: tedata = load_testdata(tedata, tfids, args) util.save_metrics(tedata, "test", args.finaldir) if "report" in args.steps: tedata = load_testdata(tedata, tfids, args) util.save_featuremaps(tedata, args.finaldir, args.reportdir) util.save_report(args.finaldir, args.reportdir, tfids) ######################################################################### def load_tfids(args): targetnames = sorted(list(set([filename.split(".")[0].rsplit("_",1)[0] for filename in os.listdir(datadir) if not os.path.isdir(datadir+"/"+filename)]))) chunktargets = util.getchunktargets(args, targetnames) return chunktargets ################################# def loadargs(): global datadir args = argparse.ArgumentParser(description="Generate the HT-SELEX experiments.") args.add_argument("--jolma", action="store_true", default=False, help="Use this flag to train on the HT-SELEX cycles selected by Jolma et al., rather than the cycles selected by Alipanahi et al.") args = util.parseargs("selex", args) if args.jolma: args.calibdir = args.outdir+"/jolma/calib" args.finaldir = args.outdir+"/jolma/final" args.reportdir = args.outdir+"/jolma/report" args.testdir = args.outdir+"/jolma/test" datadir = datadir + "/jolma" else: args.calibdir = args.outdir+"/best/calib" args.finaldir = args.outdir+"/best/final" args.reportdir = args.outdir+"/best/report" args.testdir = args.outdir+"/best/test" datadir = datadir + "/best" return args ################################# def loadmodels(args): models = util.loadmodels(args, "cfg/classification") return models ################################# def set_motif_lengths(args, models, tfid): seqpatt = tfid.split("_")[-3] ligandlen = re.findall("(\d+)N", seqpatt) if not ligandlen: quit("Could not parse ligand length from tfid %s" % tfid) ligandlen = int(ligandlen[0]) filterlens = { 14 : 14, 20 : 20, 30 : 24, 40 : 32, } filterlen = filterlens[ligandlen] print "Using filter size %d" % filterlen for cfg in models.itervalues(): cfg["model"].conv_seq[0].fsize = filterlen ################################# def load_traindata(tfid, args): print "load_traindata: %s"%tfid maxrows = 10000 if args.quick else None trdata = util.load_seq("%s/%s_A.seq.gz" % (datadir,tfid), minrows=100000, maxrows=maxrows) trdata.targetnames = [tfid] return trdata ################################# def load_testdata(tedata, tfids, args, maxrows = None): if tedata is not None: return tedata if maxrows is None: maxrows = 10000 if args.quick else None tedata = {} for tfid in tfids: print "load_testdata: %s ..."%tfid, tedata[tfid] = util.datasource.fromtxt("%s/%s_B.seq.gz" % (datadir,tfid), None, None, maxrows=maxrows) tedata[tfid].targetnames = [tfid] print "done" return tedata ################################# if __name__=="__main__": #util.disable_multiprocessing() main()
DeepBind-master
code/deepbind_train_selex.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import sys import re import os import os.path import argparse import numpy as np import numpy.random as npr import gzip import csv import cPickle import deepbind_util as util import deepity import scipy import shutil # Warning: The multiprocessing module may be used indirectly, so do not put any # unintentional statements outside of main(). def main(): util.enable_reversecomplement() args = loadargs() models = loadmodels(args) tfgroups = load_tfgroups(args) util.globals.flags.push("normalize_targets", True) for tfgroup in tfgroups: trdata = None if len(tfgroup["ids"]) == 0: print "No TFs to train on microarray %s"%tfgroup["train_fold"] continue if "calib" in args.steps: trdata = load_pbmdata(trdata, tfgroup["ids"], tfgroup["train_fold"], args, remove_probe_bias=True) util.calibrate(models, trdata, args.calibdir, nfold=args.nfold, ncalib=args.ncalib, allfolds=True) if "train" in args.steps: trdata = load_pbmdata(trdata, tfgroup["ids"], tfgroup["train_fold"], args, remove_probe_bias=True) util.train(models, trdata, args.calibdir, args.finaldir, nfold=1, ntrial=args.ntrial, metric_key="pearson.r") for tfgroup in tfgroups: tedata = None newids = [] for id in tfgroup["ids"]: if os.path.exists(args.outdir+"/final/"+id+"/model.pkl"): newids.append(id) else: print "WARNING: did not find model for %s, skipping" % id tfgroup["ids"] = newids if len(tfgroup["ids"]) == 0: print "No TFs to test on microarray %s"%tfgroup["train_fold"] continue if "test" in args.steps: tedata = load_pbmdata(tedata, tfgroup["ids"], tfgroup["test_fold"], args, remove_probe_bias=False) save_test_performance(tedata, tfgroup["ids"], tfgroup["test_fold"], args) if "report" in args.steps: tedata = load_pbmdata(tedata, tfgroup["ids"], tfgroup["test_fold"], args, remove_probe_bias=False) util.save_featuremaps(tedata, args.finaldir, args.reportdir) if "report" in args.steps: all_tfids = sum([tfgroup["ids"] for tfgroup in tfgroups],[]) save_report(args.finaldir, args.reportdir, all_tfids, index_metric="pearson") save_pbm_performance_table(args, all_tfids) if "chip" in args.steps: all_tfids = sum([tfgroup["ids"] for tfgroup in tfgroups],[]) save_chip_performance_table(args, all_tfids) ######################################################################### def load_tfgroups(args): with open("../data/dream5/pbm/tfids.txt") as f: tfids = sorted([line.rstrip("\r\n") for line in f.readlines()]) # Narrow down the list of ids based on which chunk we've been asked to compute tfids = util.getchunktargets(args, tfids) # Group the TF ids into those that are trained on A versus those that are trained on B tfgroups = [ {"ids" : list(set(tfids).intersection(["C_%d"%(i+1) for i in range(20)] + ["TF_%d"%(i+1) for i in range( 0,33)])), "train_fold" : "A", "test_fold" : "B" }, {"ids" : list(set(tfids).intersection( ["TF_%d"%(i+1) for i in range(33,66)])), "train_fold" : "B", "test_fold" : "A" }] return tfgroups ################################# def loadargs(): args = argparse.ArgumentParser(description="Generate the DREAM5 PBM and/or CHIP experiments.") args = util.parseargs("dream5", args) return args ################################# def loadmodels(args): models = util.loadmodels(args, "cfg/regression/maxpool") for cfg in models.itervalues(): cfg["model"].conv_seq[0].fsize = 24 # Override default max motif length return models ################################# def load_probe_biases(): if not os.path.exists("../data/dream5/pbm/probe_biases.npz"): # First find which rows belong to which microarray (A or B) with gzip.open("../data/dream5/pbm/sequences.tsv.gz") as f: f.readline() foldids = [line[0] for line in f] rowidx = { "A" : [i for i in range(len(foldids)) if foldids[i] == "A"], "B" : [i for i in range(len(foldids)) if foldids[i] == "B"] } # Then load the targets and split the rows into rows for A and rows for B with gzip.open("../data/dream5/pbm/targets.tsv.gz") as f: reader = csv.reader(f, delimiter='\t') colnames = reader.next() targets = np.array([[float(x) for x in row] for row in reader]) biases = {} for foldid in ("A","B"): # For this microarray (A or B), calculate a multiplicative bias # for each one of its individual probes (rows). microarray_measurements = targets[rowidx[foldid]] bias = [] for i in range(len(microarray_measurements)): probe_measurements = microarray_measurements[i,:].ravel() if np.all(np.isnan(probe_measurements)): bias.append(np.nan) else: bias.append(np.median(probe_measurements[~np.isnan(probe_measurements)])) biases[foldid] = np.array(bias) np.savez("../data/dream5/pbm/probe_biases.npz", **biases) with np.load("../data/dream5/pbm/probe_biases.npz") as f: biases = { key : f[key] for key in f.keys() } return biases ################################# def load_pbmdata(trdata, tfids, fold, args, remove_probe_bias=False): if trdata is not None: return trdata # Training data was already loaded in earlier step. maxrows = 10000 if args.quick else None # Determine which targetnames we're responsible for targetnames = gzip.open("../data/dream5/pbm/targets.tsv.gz").readline().rstrip().split("\t") targetcols = [i for i in range(len(targetnames)) if targetnames[i] in tfids] data = util.datasource.fromtxt("../data/dream5/pbm/sequences.tsv.gz", None, "../data/dream5/pbm/targets.tsv.gz", targetcols=targetcols, foldfilter=fold, maxrows=maxrows) if remove_probe_bias: # Remove per-probe multiplicative bias biases = load_probe_biases()[fold].reshape((-1,1)) data.targets /= biases data.Y /= biases return data ################################# def save_test_performance(data, tfids, fold, args): print "Predicting...", tfids # Generate predictions for each model predictions = util.predict(data, args.finaldir, args.reportdir) print "done" for tfname in predictions: print tfname Z = predictions[tfname] # Restore the original (unpreprocessed) scale and normalization of the predictions # Then add the opposite microarray's estimated probe value to each probe with open(args.finaldir + "/" + tfname +"/preprocessors.pkl") as f: normalizer = cPickle.load(f)['targets'][0] Z *= normalizer.scales[0] Z += normalizer.biases[0] # Add per-probe multiplicative bias to predictions probe_biases = load_probe_biases()[fold].reshape((-1,1)) if args.quick: probe_biases = probe_biases[:len(Z),:] M = ~np.isnan(probe_biases) Z[M] *= probe_biases[M] #with open("predictions/%s_%s.tsv" % (tfname, {"A":"B","B":"A"}[foldid]), 'w') as f: # f.writelines([str(x)+"\n" for x in Z.ravel()]) z = Z.ravel() y = data.Y[:,data.targetnames.index(tfname)].ravel() rowidx = data.rowidx.ravel() mask = ~np.isnan(y) zscore4 = np.std(y[mask])*4+np.mean(y[mask]) util._update_metrics(args.finaldir, tfname, "test", rowidx, z, y, aucthresh=(zscore4,zscore4)) ################################# def save_pbm_performance_table(args, tfids): metric_keys = ["pearson.r","spearman.r","pearson.p","spearman.p","auc","auc.mean"] with open(args.reportdir+"/performance_pbm.txt", "w") as f: f.write("protein\t%s\n" % "\t".join(metric_keys)) for tfid in ["TF_%d" % i for i in range(1,67)]: f.write(tfid) if tfid in tfids: metrics = util.load_metrics(args.finaldir+"/"+tfid+"/metrics.txt") for key in metric_keys: f.write("\t%s" % metrics["test"].get(key,np.nan)) f.write("\n") return ################################# def save_chip_performance_table(args, tfids): with open(args.reportdir+"/performance_chipseq.txt", "w") as f: f.write("Background\tFile\tauc.mean\tauc.std\n") chipseqids = ["TF_%d"%i for i in [23,25,31,40,44]] for tfid in chipseqids: if tfid not in tfids: continue for windowsize in [51,100]: for background in ["dinuc", "full_genomic", "genomic"]: seqfile = "../data/dream5/chipseq/%s_CHIP_%d_%s.seq" % (tfid, windowsize, background) invivodata = util.datasource.fromtxt(seqfile+"[0]", None, seqfile+"[1]", sequencenames=["seq"], targetnames=[tfid]) invivodata.targetnames = [tfid] predictions = util.predict(invivodata, args.finaldir, args.reportdir, include=[tfid]) z = predictions[tfid].ravel() y = invivodata.Y.ravel() metrics = util.calc_metrics(z, y) s = "%s\t%s\t%.3f\t%.3f\n" % (background, seqfile, metrics['auc.mean'], metrics['auc.std']) print s, f.write(s) ################################# def save_report(modeldir, reportdir, tfids, index_metric="auc"): util.makepath(reportdir) index_html = open(reportdir+"/index.html",'w') index_html.write("<html><head><title>Training report</title></head><body>\n") index_html.write("<table cellspacing=0 cellpadding=5 border=1>\n") index_html.write("<tr><th>Name</th><th>train %s</th><th>test %s</th></tr>\n" % (index_metric, index_metric)) for tfid in ["TF_%d" % i for i in range(1,67)]: if tfid not in tfids: continue print tfid util.makepath(reportdir+"/"+tfid) # Load PFMs, convert them to logo images, and dump them to the report directory with open(reportdir+"/%s.pfms.pkl"%tfid) as f: _ = cPickle.load(f) pfms = _["pfms"] ics = _["ic"] counts = _["counts"] pfm_order = np.argsort(-ics) logos = [] for j in pfm_order: pfm = pfms[j] ic = ics[j] if ic <= 0: continue pfm_rev = np.fliplr(np.flipud(pfm)) logo_fwd = deepity.tape2logo.tape2logo(pfm.T, height=50, letterwidth=10, bufferzoom=4, vmax=1.0, style="seqlogo", rna=False) logo_rev = deepity.tape2logo.tape2logo(pfm_rev.T, height=50, letterwidth=10, bufferzoom=4, vmax=1.0, style="seqlogo", rna=False) logo_filename = "%s/%s/pfm%02d" % (reportdir, tfid, len(logos)) scipy.misc.imsave(logo_filename+"_fwd.png", logo_fwd) scipy.misc.imsave(logo_filename+"_rev.png", logo_rev) logos.append((j, os.path.basename(logo_filename)+"_fwd.png", ic, counts[j])) # Load train/test metrics so we can print them in the HTML report metrics_file = "%s/%s/metrics.txt" % (modeldir, tfid) metrics = deepity.load_metrics(metrics_file) # Add row for this TF in main index.html index_html.write("<tr>\n") index_html.write("<td><a href=\"%s/index.html\">%s</a></td>\n" % (tfid, tfid)) if index_metric=="auc": index_html.write("<td>%s &plusmn; %s</td>\n" % (metrics["train"]["auc.mean"], metrics["train"]["auc.std"])) index_html.write("<td><b>%s</b> &plusmn; %s</td>\n" % (metrics["test"]["auc.mean"], metrics["test"]["auc.std"])) elif index_metric=="pearson": index_html.write("<td>%s (p=%s)</td>\n" % (metrics["train"]["pearson.r"], metrics["train"]["pearson.p"])) index_html.write("<td><b>%s</b> (p=%s)</td>\n" % (metrics["test"]["pearson.r"], metrics["test"]["pearson.p"])) index_html.write("</tr>\n") # Build page showing filters and sequence logos for this specific TF tf_html = open(reportdir+"/"+tfid+"/index.html", 'w') tf_html.write("<html><head><title>Training report - %s</title></head><body>\n" % tfid) tf_html.write("<h2>%s</h2>\n" % tfid) # tf_html.write("<a href=\"../gmaps/%s/index.html\">gradient maps</a>)<hr/>\n"%(tfid,tfid)) tf_html.write(""" <script language="javascript"> function toggle_strand() { var pfms = document.getElementsByClassName('pfm') for (var i = 0; i < pfms.length; i++) if (pfms[i].src.search("_fwd") != -1) pfms[i].src = pfms[i].src.replace("_fwd","_rev"); else if (pfms[i].src.search("_rev") != -1) pfms[i].src = pfms[i].src.replace("_rev","_fwd"); } </script></head><body> """) with open(metrics_file) as f: metrics_text = f.read() tf_html.write("<pre>%s</pre>\n"% metrics_text) if os.path.exists(modeldir+"/%s/predict.scatter-test.png" % tfid): tf_html.write("<table cellspacing=0 cellpadding=0 style=\"display:inline;margin-right:20px;\"><tr><td align=center>TEST predictions</td></tr><tr><td><img src=\"../../final/%s/predict.scatter-test.png\"/></td></tr></table>\n" % tfid) if os.path.exists(modeldir+"/%s/predict.scatter-train.png" % tfid): tf_html.write("<table cellspacing=0 cellpadding=0 style=\"display:inline\"><tr><td align=center>TRAINING predictions</td></tr><tr><td><img src=\"../../final/%s/predict.scatter-train.png\"/></td></tr></table>\n" % tfid) # Then generate a table for the complete model tfdir = modeldir+"/"+tfid tf_html.write("<hr/><h3>Feature Logos</h3>\n") tf_html.write("<input type=\"button\" value=\"toggle strand\" onclick=\"toggle_strand();\"/><br/>") tf_html.write("<table cellspacing=0 cellpadding=4 border=0>\n") for filter_index, logo, ic, count in logos: tf_html.write("<tr><td>%d</td><td><img src=\"%s\" class=\"pfm\"/></td><td>%.1f bits,</td><td> %d activations</td></tr>" % (filter_index, logo, ic, count)) tf_html.write("</table><br/><br/>\n") # Now show the actual model. ''' shutil.copy(tfdir_final[0]+"/fold0.report/filters_.conv_seq(0).color.png", basedir+"report/%s/final_filters.png" % (tfid)) shutil.copy(tfdir_final[0]+"/fold0.report/filters_.conv_seq(0).logo.png", basedir+"report/%s/final_logos.png" % (tfid)) shutil.copy(tfdir_final[0]+"/fold0.report/filters_.conv_seq(1).png", basedir+"report/%s/final_biases.png" % (tfid)) shutil.copy(tfdir_final[0]+"/fold0.report/filters_.combiner.png", basedir+"report/%s/final_weights.png" % (tfid)) os.system("convert %sreport/%s/final_filters.png -rotate -90 %sreport/%s/final_filters_rot.png" % (basedir,tfid,basedir,tfid)) ''' tf_html.write("<hr/><h3>Actual DeepBind model</h3>\n") if os.path.exists(tfdir + "/model.conv_seq(1).color.png"): tf_html.write("Filters:<br/>\n") tf_html.write("<img src=\"../../final/%s/model.conv_seq(1).color.png\"/><br/>\n" % tfid) if os.path.exists(tfdir + "/model.combiner.png"): tf_html.write("<br/>Combiner layer:<br/>\n") tf_html.write("<img src=\"../../final/%s/model.combiner.png\"/><br/>\n" % tfid) tf_html.write("</body></html>\n") index_html.write("</table>\n") index_html.write("</body></html>\n") index_html.close() if __name__=="__main__": #util.disable_multiprocessing() main()
DeepBind-master
code/deepbind_train_dream5.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # # DO NOT IMPORT THIS MODULE # It is meant to be spawned by report.py as a separate process, # in order to avoid problems using matplotlib from within child # processes of the multiprocessing module # (crashing on exit; instability in subsequent child processes) import os import os.path import sys import copy import glob import re import numpy as np import argparse import tape2logo from PIL import Image from PIL import ImageDraw from PIL import ImageFont import time import matplotlib matplotlib.rcParams.update({'font.size': 9, 'font.family': 'sans serif', 'text.usetex' : False, 'figure.max_num_figures' : 100}) if (not os.environ.has_key("DISPLAY")) and (not os.environ.has_key("HOMEDRIVE")): matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter from matplotlib import colors as colors from matplotlib import cm from matplotlib.figure import Figure gridimg_pal_RedBlue = matplotlib.colors.LinearSegmentedColormap('RedBlue', { 'red': ((0.00, 0.0, 0.0), (0.50, 1.0, 1.0), (1.00, 1.0, 1.0)), 'green': ((0.00, 0.0, 0.0), (0.50, 1.0, 1.0), (1.00, 0.0, 0.0)), 'blue': ((0.00, 1.0, 1.0), (0.50, 1.0, 1.0), (1.00, 0.0, 0.0)), },gamma =1.0)(np.arange(256)) gridimg_pal = np.asarray(gridimg_pal_RedBlue[:,:3]*255, dtype=np.uint8) gridimg_pal_Red = matplotlib.colors.LinearSegmentedColormap('Red', { 'red': ((0.00, 1.0, 1.0), (1.00, 1.0, 1.0)), 'green': ((0.00, 1.0, 1.0), (1.00, 0.0, 0.0)), 'blue': ((0.00, 1.0, 1.0), (1.00, 0.0, 0.0)), },gamma =1.0)(np.arange(256)) gridimg_pal_positive = np.asarray(gridimg_pal_Red[:,:3]*255, dtype=np.uint8) _image_grid_font = ImageFont.truetype(os.path.abspath(os.path.dirname(__file__))+"/arial.ttf", 9) #_image_grid_font = ImageFont.load_default() import scipy import scipy.misc import scipy.stats import warnings #warnings.simplefilter('error', UserWarning) def calc_auc(z,y, want_curve = False): assert len(z) == len(y) m = ~np.isnan(y) y = y[m] z = z[m] ymin = y.min() ymax = y.max() lo = (0.02-0) / (1.0 - 0.0) * (ymax-ymin) + ymin hi = (0.10-0) / (1.0 - 0.0) * (ymax-ymin) + ymin mlo = y<=lo mhi = y>=hi y[mlo] = 0 y[mhi] = 1 y[np.logical_and(mlo,mhi)] = np.nan m = ~np.isnan(y) y = y[m] z = z[m] order = np.argsort(z,axis=0)[::-1].ravel() # Sort by decreasing order of prediction strength z = z[order] y = y[order] npos = np.count_nonzero(y) # Total number of positives. nneg = len(y)-npos # Total number of negatives. if nneg == 0 or npos == 0: return (1,None) if want_curve else 1 n = len(y) fprate = np.zeros((n+1,1)) tprate = np.zeros((n+1,1)) ntpos,nfpos = 0.,0. for i,yi in enumerate(y): if yi: ntpos += 1 else: nfpos += 1 tprate[i+1] = ntpos/npos fprate[i+1] = nfpos/nneg auc = np.trapz(tprate,fprate,axis=0) if want_curve: curve = np.hstack([fprate,tprate]) return auc,curve return auc def makepath(dir): """ Makes a complete path if it does not exist already. Does not remove any existing files. Fixes periodic failure of os.makedirs on Windows. """ if os.path.exists(dir): return dir retries = 8 while retries >= 0: try: time.sleep(0.001) os.makedirs(dir) retries = -1 except Exception, e: if retries == 0: raise else: retries -= 1 return dir ##################################################################### class filter_images(object): def __init__(self,F,per_image_scale=False,symmetric_range=True): assert len(F.shape) == 3 # (size_y,size_x,num_filters) # Get information about shape and range of filter elements self.vmean = F.reshape((F.shape[0],-1)).mean(axis=1).reshape((-1,1,1)) self.vmin = F.reshape((F.shape[0],-1)).min(axis=1).reshape((-1,1,1)) self.vmax = F.reshape((F.shape[0],-1)).max(axis=1).reshape((-1,1,1)) if symmetric_range: self.vmax = np.maximum(abs(self.vmin),abs(self.vmax)) self.vmin = -self.vmax self.vranges = [(F[i,:,:].min(), F[i,:,:].max()) for i in range(F.shape[0])] # Convert filters to images self.raw = F I = F.copy() if per_image_scale: I -= self.vmin I *= 1./(self.vmax-self.vmin) else: I -= self.vmin.min() I *= 1./(self.vmax.max()-self.vmin.min()) I = np.maximum(0,I) I = np.minimum(1,I) I *= 255 I = np.uint8(I) self.images = I def __len__(self): return self.images.shape[0] def __getitem__(self,i): return self.images[i,:,:] def __iter__(self): return [self.images[i,:,:] for i in range(len(self))].__iter__() def zoom(self, factor): self.images = np.repeat(self.images,factor,1) self.images = np.repeat(self.images,factor,2) def zoom_smooth(self, factor): I = self.images Z = np.zeros((I.shape[0],I.shape[1]*factor,I.shape[2]*factor), dtype=I.dtype) for i in range(len(I)): img = Image.fromarray(I[i]) img = img.resize((int(img.size[0]*factor),int(img.size[1]*factor)), Image.ANTIALIAS) Z[i,:,:] = np.array(img) self.images = Z def L2RGB(I,cmap): I = scipy.misc.toimage(I, pal=cmap).convert("RGB") return np.array(I) def addborder(I, color=0): I = np.vstack([color*np.ones_like(I[:1,:,:]), I, color*np.ones_like(I[:1,:,:])]) I = np.hstack([color*np.ones_like(I[:,:1,:]), I, color*np.ones_like(I[:,:1,:])]) return I def image_grid(fimgs, maxwd = 6000, maxht = 5000, cmap=None, fade=False, positive=False): I = fimgs.images max_vmax = fimgs.vmax.max() min_vmin = fimgs.vmin.min() if cmap is None: cmap = np.repeat(np.arange(256).reshape((-1,1)),3) n,fht,fwd = I.shape[:3] # n = number of features if fwd > maxwd or fht > maxht: print "image larger than maximum size allowed" return None is_logo = (len(I.shape) == 4) #if not is_logo: fwd += 2 # border fht += 2 # border idwd = 20 decwd = 12 txtwd = 48 wd = idwd+decwd+fwd+txtwd ht = fht maxrows = min(int(maxht-1)//(ht+1), n) # How many images can stack on top of each other? (-1 / +3 because of 1 pixel border and 1 pixel cell padding) maxcols = min(int(maxwd-1)//(wd+1), (n+maxrows-1)//maxrows) # Start from a blank white image G = np.ones(((ht+1)*maxrows-1,(wd+1)*maxcols-1,3),dtype=I.dtype) if G.dtype == np.uint8: G *= 255 # Copy each image into a spot in the grid for i in range(n): col = i // maxrows row = i % maxrows if col >= maxcols: break x0 = col*(wd+1) y0 = row*(ht+1) if is_logo: F = I[i,:,:,:].copy() else: F = L2RGB(I[i,:,:], cmap) F = addborder(F) rmin,rmax = fimgs.vranges[i] mid = ht//2 hi = int((mid-1) * float(max(0, rmax)) / abs(max_vmax) + 0.5) lo = int((mid-1) * float(max(0,-rmin)) / abs(min_vmin) + 0.5) if not positive else 0 #if positive: # F[1:-1,1:-1] = 255-F[1:-1,1:-1] if fade and hi <= 1 and lo <= 1: F = 192 + F//4 # Fade out anything that's extremely weak, so that user's attention is drawn to the other filters. img = np.hstack([255*np.ones((ht,idwd,3),np.uint8), F, 255*np.ones((ht,decwd+txtwd,3),np.uint8)]) # Draw a little vertical bar thingy to visually indicate magnitude of range # relative to other filters img[mid-hi:mid, idwd+fwd+3:idwd+fwd+decwd-3,:] = np.asarray([255,0,0]).reshape((1,1,3)) img[mid+1:mid+1+lo, idwd+fwd+3:idwd+fwd+decwd-3,:] = np.asarray([0,0,255]).reshape((1,1,3)) #img[mid,idwd+fwd+2:idwd+fwd+decwd-2,:] *= (1-max(float(rmax) / abs(max_vmax),float(-rmin) / abs(min_vmin)))**0.8 img = Image.fromarray(img) # convert to Image so that we can use ImageDraw draw = ImageDraw.Draw(img) draw.text((0,2),"%3d"%i,(200,200,200),font=_image_grid_font) if rmax != rmin and not positive: draw.text((idwd+decwd+F.shape[1]+0, 2),"%+.3f"%rmax,0,font=_image_grid_font) draw.text((idwd+decwd+F.shape[1]+2,13),"%+.3f"%rmin,0,font=_image_grid_font) else: draw.text((idwd+decwd+F.shape[1]+2, 2),"%+.3f"%rmax,0,font=_image_grid_font) img = np.array(img) # convert back to numpy G[y0:y0+ht,x0:x0+wd,:] = img return G def fimgs2logos(fimgs, finalheight, finalletterwidth): filters = fimgs.raw nfilter,_,fsize = filters.shape # n = number of filters logos = 255*np.ones((nfilter,finalheight,fsize*finalletterwidth,3), np.uint8) limgs = copy.deepcopy(fimgs) limgs.images = logos for k in range(nfilter): logos[k,:,:,:] = tape2logo.tape2logo(filters[k,:,:], finalheight, finalletterwidth, 5) return limgs def reverse_complement_weights(W): W = W[:,:,::-1] W = W[:,[3,2,1,0],:] return W ######################################################## def unpack(npzfile, zoom): entries = np.load(npzfile)['entries'] outdir = os.path.splitext(npzfile)[0] makepath(outdir) dpi = 80.0 # First dump filter images if "images" in entries[-1]: for name,weights in entries[-1]["images"].iteritems(): name = "filters_"+name.replace("[","(").replace("]",")") is_conv = (".conv_" in name and weights.shape[-1] > 1) # convnet filters treated differently. # First, generate if is_conv: # Save colourized filters fimgs = filter_images(weights, per_image_scale=True) fimgs.zoom(max(1,12//fimgs.images.shape[1])) fimgs.zoom_smooth(4) fimgs.zoom_smooth(0.5) #fimgs.zoom(max(1,24//fimgs.images.shape[1])) scipy.misc.imsave(outdir+"/"+name+".color.png",image_grid(fimgs, cmap=gridimg_pal, fade=True)) # Save black and white filters #fimgs = filter_images(weights, per_image_scale=True) #fimgs.zoom(max(1,24//fimgs.images.shape[1])) #scipy.misc.imsave(outdir+"/"+name+".png",image_grid(fimgs, fade=True)) logoheight, letterwd = 41, 6 weights -= (np.sort(weights, axis=1)[:,1:2,:] + np.sort(weights, axis=1)[:,2:3,:])/2 #weights -= np.sort(weights, axis=1)[:,1:2,:] # Subtract off the second-smallest value in each column #weights -= weights.min(axis=1).reshape((weights.shape[0],1,weights.shape[2])); logoheight = 24 logoheight = int(round(zoom*logoheight)) letterwd = int(round(zoom*letterwd)) fwdlogo = fimgs2logos(filter_images(weights, per_image_scale=True), logoheight, letterwd) revlogo = fimgs2logos(filter_images(reverse_complement_weights(weights), per_image_scale=True), logoheight, letterwd) fwdlogo = image_grid(fwdlogo, fade=True) revlogo = image_grid(revlogo, fade=True) fwdtitle = Image.fromarray(255*np.ones((20,fwdlogo.shape[1],3),np.uint8)); ImageDraw.Draw(fwdtitle).text((20,2),"actual",(0,0,0),font=_image_grid_font) revtitle = Image.fromarray(255*np.ones((20,revlogo.shape[1],3),np.uint8)); ImageDraw.Draw(revtitle).text((20,2),"reverse complement",(0,0,0),font=_image_grid_font) scipy.misc.imsave(outdir+"/"+name+".logo.png", np.hstack([np.vstack([np.array(fwdtitle), fwdlogo]), np.vstack([np.array(revtitle), revlogo])])) else: # Save colourized weight maps fimgs = filter_images(weights, per_image_scale=False) fimgs.zoom(max(1,12//fimgs.images.shape[1])) scipy.misc.imsave(outdir+"/"+name+".png",image_grid(fimgs, cmap=gridimg_pal)) # Then dump loss plots if "tloss" in entries[-1]: fig = plt.figure(figsize=(300/dpi,200/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=False) ax = fig.add_axes([0.1,0.08,.88,.88]) colours = [[0.0,0.0,0.0], # train [0.0,0.7,0.4], # validate [1.0,0.0,0.0]] # test (if any) styles = ['-','-','-'] ax.set_autoscale_on(False) ax.set_xlabel("step") ax.set_ylabel("loss") ax.grid(True,which='major',axis='y',linestyle=':',color=[0.2,0.2,0.2]) ax.grid(True,which='minor',axis='y',linestyle=':',color=[0.8,0.8,0.8]) xval = np.asarray([entry["step"] for entry in entries]) yval_t = np.asarray([entry["tloss"] for entry in entries]) yval_v = np.asarray([entry["vloss"] for entry in entries]) if "vloss" in entries[-1] else None xmax = xval.max() ymin = yval_t.min() ymax = yval_t.max() ax.semilogy(xval,yval_t,color=colours[0],linestyle=styles[0],label="tloss") if yval_v is not None: ymin = min(ymin,yval_v.min()) ymax = min(ymax,yval_v.max()) ax.semilogy(xval,yval_v,color=colours[1],linestyle=styles[1],label="vloss") ymin = max(ymin,1e-8) # Just update the axis limits, since this isn't done ymax = max(ymax,1e-8+ymin) # automatically when you modify the line data directly. ymax = min(ymax,ymin*10.1) ax.set_xlim(0,xmax) ax.set_ylim(ymin,ymax) ax.legend() ax.set_xlim(0,xmax*1.1) ax.set_ylim([10**np.floor(np.log10(ymin)),10**np.ceil(np.log10(ymax))]) fig.savefig(outdir+"/loss.png",dpi=dpi) #fig.savefig(outdir+"/loss.pdf",dpi=dpi) del fig plt.close() # Then dump the prediction/target scatterplots for foldname in ("t","v"): if not foldname+"Z" in entries[-1]: continue xval = entries[-1][foldname+"Y"] yval = entries[-1][foldname+"Z"] for i in range(entries[-1]["tY"].shape[1]): xval_i = xval[:,i:i+1] yval_i = yval[:,i:i+1] fig = plt.figure(figsize=(300/dpi,300/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=False) ax = fig.add_axes([0.14,0.14,.74,.74]) ybar = fig.add_axes([0.89, 0.14, 0.11, 0.74]) keep = ~np.isnan(xval_i) xval_i = xval_i[keep] yval_i = yval_i[keep] lo = min(xval_i.min(),yval_i.min()) hi = max(xval_i.max(),yval_i.max()) aximg = ax.hist2d(xval_i,yval_i,bins=50,range=[[lo-.05,hi+.05],[lo-.05,hi+.05]],cmap=cm.hot,cmin=1)[3] ybar.hist(yval_i, bins=30, orientation='horizontal', histtype='bar', cumulative=False, color=[0.0,0.0,1.0], range=[lo-0.05, hi+0.05], edgecolor="none") ybar.set_ylim([lo-0.05, hi+0.05]) ybar.axis("off") ax.set_xlabel("target") ax.set_ylabel("prediction") fig.savefig(outdir+"/predict_%02d_%s.png"%(i,foldname),dpi=dpi) #fig.savefig(outdir+"/predict_%02d%s.pdf"%(i,foldname),dpi=dpi) del fig plt.close() # Finally, write AUCs for foldname in ("t","v"): if not foldname+"Z" in entries[-1]: continue x = entries[-1][foldname+"Y"] z = entries[-1][foldname+"Z"] for i in range(entries[-1]["tY"].shape[1]): y_i = x[:,i:i+1] z_i = z[:,i:i+1] auc,curve = calc_auc(z_i,y_i,want_curve=True) if curve is not None: xval = curve[:,0] yval = curve[:,1] fig = plt.figure(figsize=(300/dpi,300/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=False) ax = fig.add_axes([0.18,0.1,.8,.8]) ax.plot(xval,yval,'-r') ax.set_xlabel("FP rate") ax.set_ylabel("TP rate") fig.savefig(outdir+"/predict_%02d_%s_auc.png"%(i,foldname),dpi=dpi) #fig.savefig(outdir+"/predict_%02d_%s_auc.pdf"%(i,foldname),dpi=dpi) del fig plt.close() args = argparse.ArgumentParser(description="Unpack a \"foldX.report.npz\" file and generate visualizations of its contents (filters, predictions, etc)") args.add_argument("path", type=str, help="A report.npz file, or a directory to search.") args.add_argument("-z","--zoom", type=float, default=1, help="Zoom factor relative to default size; for generating print-quality bitmaps.") args = args.parse_args() if not os.path.exists(args.path): quit("Cannot find file \"%s\"."%args.path) if os.path.isdir(args.path): for dirpath, dirnames, filenames in os.walk(args.path): for filename in filenames: if len(re.findall("fold.\.report\.npz", filename)) > 0: unpack(os.path.join(dirpath, filename), args.zoom) else: unpack(args.path,args.zoom)
DeepBind-master
code/libs/deepity/deepity/report_plotter.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import os import gc import re import sys import copy import time import random import tempfile import logging import cPickle as cp import multiprocessing import subprocess import deepity import numpy as np import numpy.random as npr import smat as sm import scipy import scipy.stats from . import std from . import hpsearch as hp from . import _io_ from . import util from .data import datasource from . import globals from .report import training_report, calc_auc, bootstrap_auc import node as _node import trainer as _trainer class _object_factory_from_file(object): def __init__(self,filename,fieldname=None): self.filename = filename self.fieldname = fieldname def __call__(self): obj = _io_.load(self.filename) if self.fieldname and isinstance(obj,dict): return obj[self.fieldname] return obj def _create_model(model_proto, hparams): model = copy.deepcopy(model_proto) for key,val in hparams.iteritems(): prefix,path = key.split(":") # look for hparams named "model:..." if prefix == "model": nodepath,attrname = path.rsplit(".",1) node = model.find(nodepath) if hasattr(node,"set_"+attrname): getattr(node,"set_"+attrname)(model,val) # call model.set_xxx(val) else: setattr(node,attrname,val) return model def _create_trainer(trainer_proto, hparams): trainer = copy.deepcopy(trainer_proto) for key,val in hparams.iteritems(): prefix,attrname = key.split(":") # look for hparams named "trainer:..." if prefix == "trainer": if hasattr(trainer,"set_"+attrname): getattr(trainer,"set_"+attrname)(model,val) # call trainer.set_xxx(val) else: setattr(trainer,attrname,val) return trainer def _slice_hparams(hparams, inst): h = copy.deepcopy(hparams) for key in h.keys(): h[key] = h[key][inst] return h def load_hparams_result(filename): with open(filename,'r') as f: lines = f.readlines() params = {} result = 0.0 for line in lines: # Look for validation performance matches = re.findall("# metric = (\S+)", line) if len(matches) > 0: result = float(matches[0]) continue # Add hparam name, value = re.findall(" *(\S+) += (\S+)", line)[0] if name in [":cfgname"]: params[name] = value else: params[name] = float(value) return hp.sample(params, result) def save_hparams_result(filename, hparams_result, metric_key): util.makepath(os.path.dirname(filename)) with open(filename,'w') as f: if metric_key: f.write("# metric = %f (%s)\n" % (hparams_result.metrics[metric_key], metric_key)) f.write(hparams2str(hparams_result.params)) def _save_model_inst(filename, inst, model, hparams): m = copy.deepcopy(model) sm.sync() # Slice the trainable weights m.slice_inst(inst) # Also slice the hyperparams, and replace corresponding 'arrayed' # attributes in the model with their scalar (sliced element) counterpart. h = _slice_hparams(hparams,inst) for key,val in h.iteritems(): prefix,path = key.split(":") # look for hparams named "model:..." if prefix != "model": continue nodepath,attrname = path.rsplit(".",1) node = m.find(nodepath) if hasattr(node,"set_"+attrname): getattr(node,"set_"+attrname)(model,val) # call model.set_xxx(val) else: setattr(node,attrname,val) # Dump the model util.makepath(os.path.dirname(filename)) with open(filename,'wb') as f: cp.dump(m,f) sm.sync() # Make sure we wait until the sarrays are all dumped def gen_predictions(model, data): # We must feed each sequence through the model several times # by applying the model repeatedly on sliding a window along the sequence. # That generates a prediction map, from which we can take max, sum, etc. predictions = [] gmaps = {} batches = data.asbatches(batchsize=128, reshuffle=False) for batch in batches: args = batch.input_data() args["want_bprop_inputs"] = False if isinstance(model.Z.origin().node,std.softmaxnode): args["bprop_inputs_loss"] = std.nll() else: args["bprop_inputs_loss"] = std.mse() outputs = model.eval(**args) Z = outputs['Z'].asnumpy() Zmask = outputs.get('Zmask',None) if Zmask is not None: Zmask = Zmask.asnumpy() Z = Z[Zmask.ravel()] predictions.append(Z) # Concatenate all numpy arrays if they're the same size predictions = np.vstack(predictions) return predictions def getinstdir(outdir, targetname, trialnum, foldid): if isinstance(outdir,str): return outdir outdir = [_ for _ in outdir] # Make a copy that we can substitute elements in args = {"target" : targetname, "trial" : trialnum, "fold" : foldid} for i,item in enumerate(outdir): if isinstance(item, tuple): name, patt = item if args[name] is None: outdir[i] = None else: outdir[i] = patt % args[name] instdir = "/".join([part for part in outdir if part is not None]) return instdir def load_metrics(filename): metrics = {} with open(filename) as f: groupnames = f.readline().rstrip().split() for line in f: line = line.rstrip().split() for i,val in enumerate(line[1:]): metrics.setdefault(groupnames[i],{})[line[0]] = val return metrics def save_metrics(outfile, metrics): with open(outfile,"w") as f: groupnames = sorted(metrics.keys()) fieldnames = set() for groupname in groupnames: for fieldname in metrics[groupname].keys(): fieldnames.add(fieldname) fieldnames = sorted(list(fieldnames)) f.write(" "*14+"\t".join(groupnames) + "\n") rows = {} for groupname in groupnames: for fieldname in fieldnames: fieldval = metrics[groupname].setdefault(fieldname, np.nan) if not isinstance(fieldval,np.ndarray): if isinstance(fieldval, float): fmt = "%.2e" if fieldname.endswith(".p") else "%.6f" fieldval = fmt%fieldval rows.setdefault(fieldname,[]).append(str(fieldval)) f.writelines([fieldname + " "*max(0,14-len(fieldname)) + "\t".join(rows[fieldname]) +"\n" for fieldname in fieldnames]) def call_dumpviz(dumpdir): subprocess.Popen(["python", os.path.dirname(__file__)+"/dumpviz.py", dumpdir]) ########################################## class hypertrain_worker(object): """ Given a dataset and specific hyperparameters, this object will simply train a model (an array of models) and return the validation error (array of validation errors). """ def __init__(self, worker_id, model_proto, trainer_proto, datasrc, nfold, allfolds, outdir, report_class, devices, verbose, default_dtype, global_flags, auxfilter, mode, dumpviz): self.worker_id = worker_id # All the data subsets in 'trainset' will be merged into a single fold. self.model_proto = model_proto self.trainer_proto = trainer_proto self.datasrc = datasrc # Load a copy of the dataset into this worker process. self.nfold = nfold self.allfolds = allfolds self.outdir = outdir self.mode = mode self.aucrange = (0.5,0.5) # threshold for making AUCs out of non-binary targets, presumed to be in range [0,1] self.report_class = report_class self.auxfilter = auxfilter self.dumpviz = dumpviz globals.flags.copy_from(global_flags) # If we've been called from a new process, create a separate log file. # Otherwise everything is logged into the original log file. if multiprocessing.current_process().name != "MainProcess": logdir = getinstdir(outdir,None,None,None) worker_logfile = os.path.join(logdir,"hypertrain_worker%d.log" % worker_id) globals.set_logging(worker_logfile,level=verbose,echo=False) logging.info("\n----------------------------- %s -----------------------------" % time.strftime("%y-%m-%d %H-%M-%S",time.localtime())) # Configure deepity to use this worker's GPU device. logging.info("worker %d starting on device %d using %s" % (worker_id,devices[worker_id],sm.get_default_dtype().__name__)) rseed = int((time.time()*100000 + worker_id) % 2000) globals.reset_backend(device=devices[worker_id], seed=rseed) random.seed(rseed) sm.set_default_dtype(default_dtype) npr.seed(rseed) # Seed this process's random number generator, for reproducibility sm.sync() # Prepare the datasource to serve data. self.datasrc.open() def __del__(self): self.datasrc.close() self.datasrc = None gc.collect() # Clear out the cruft and make sure the backend can be destroyed sm.sync() sm.destroy_backend() def __call__(self, hparams, task_ids, sample_ids): # Determine what kind of targets we want to train on data = self.datasrc.astargets(task_ids) # Copies of arbitrary targets data = data[:] # Copy so that when we normalize etc we don't affect the original data # Normalize the targets. For logisitic-output models this means # scaling targets to [0,1]. For other models this means scaling # targets to have mean=0, variance=1. data.requirements = self.model_proto.data_requirements() #print np.percentile(data.Y[data.Ymask].ravel(), [99, 99.99, 99.995, 99.999]) #print data.Y.size, int(data.Y.size*(100-99.95)/100) if "clamp_targets" in globals.flags: data.clamp_extremes(0.0,99.95) if "normalize_targets" in globals.flags: data.normalize_targets() #data.arcsinhtransform_targets() if self.mode != 'calib': # If we're not in calibration mode, then there's no need for multiple checkpoints # -- just keep the last checkpoint so that it can be dumped to disk #del hparams["trainer:checkpoints"] self.trainer_proto.checkpoints = 1 # Shuffle the individual rows of data, always the same random shuffle # and therefore always the same random split each time the code is run. data.shuffle() # Create a callback handler to collect predictions and evaluate final performance checkpoints = self.report_class() # Perform k-fold cross validation (k=nfold), training with one fold held out at a time. for foldid in range(self.nfold): checkpoints.setfold(foldid) # Tell the checkpoint # Create a new model and trainer with the given hyperparams model = _create_model(self.model_proto, hparams) trainer = _create_trainer(self.trainer_proto, hparams) # Split the data into training and validation sets trdata, vadata = data.split(foldid, self.nfold-1) trdata = trdata.augmented(trdata) datasets = { "train" : trdata } if vadata: vadata = vadata.augmented(vadata) datasets["validate"] = vadata if self.auxfilter: datasets["validate_aux"] = vadata[[i for i in range(len(vadata)) if vadata.foldids[i] in self.auxfilter]] for dset in datasets.values(): dset.requirements = model.data_requirements() #if not checkpoint_callback: # trainer.viz_steps = False # Disable periodic updates if no reports # Train the model and remember how well it performed. trainer.train(model, datasets, checkpoints) if self.mode == 'train' and self.nfold > 1: entries = checkpoints.curr() metrics = self.calc_metrics(entries) self.save_model(model, hparams, task_ids, sample_ids, foldid) self.save_metrics(metrics, task_ids, sample_ids, foldid) self.save_predictions(entries, task_ids, sample_ids, foldid) self.call_dumpviz(task_ids, sample_ids, foldid) # If we`re only supposed to try one fold, then don`t bother looping over the other splits if not self.allfolds: break # Consolidate the separate folds, and dump them if need be entries = checkpoints.combined() # Calculate the performance stats associated with each target metrics = self.calc_metrics(entries) # Save the current model and predictions if self.mode == 'train': self.save_predictions(entries, task_ids, sample_ids, None) self.save_metrics(metrics, task_ids, sample_ids, None) if self.nfold == 1: self.save_model(model, hparams, task_ids, sample_ids, None) self.save_preprocessors(data, task_ids, sample_ids, None) #self.call_dumpviz(task_ids, sample_ids, None) # Return a new hparams object with the performance incorporated hpsearch_result = self.add_hparam_metrics(hparams, metrics) return hpsearch_result def save_model(self, model, hparams, task_ids, sample_ids, foldid): for i, taskid in enumerate(task_ids): dumpdir = getinstdir(self.outdir, taskid, sample_ids[i], foldid) util.makepath(dumpdir) # Slice out model i and save it to disk _save_model_inst(dumpdir+"/model.pkl", i, model, hparams) def save_predictions(self, entries, task_ids, sample_ids, foldid): for i, taskid in enumerate(task_ids): dumpdir = getinstdir(self.outdir, taskid, sample_ids[i], foldid) util.makepath(dumpdir) # Save out the predictions for model i assert len(entries[i]) == 1, "Bug. Expected only a single unique 'step' in the list of entries" groups = entries[i].values()[0] np.savez_compressed(dumpdir+"/predict.npz", targetname=np.asarray(taskid, dtype=object), groups=np.asarray(groups, dtype=object)) def save_metrics(self, metrics, task_ids, sample_ids, foldid): for i, taskid in enumerate(task_ids): dumpdir = getinstdir(self.outdir, taskid, sample_ids[i], foldid) util.makepath(dumpdir) # Save out the predictions for model i assert len(metrics[i]) == 1, "Bug. Expected only a single unique 'step' in the list of entries" groups = metrics[i].values()[0] save_metrics(dumpdir+"/metrics.txt", groups) def call_dumpviz(self, task_ids, sample_ids, foldid): if not self.dumpviz: return for i, taskid in enumerate(task_ids): dumpdir = getinstdir(self.outdir, taskid, sample_ids[i], foldid) call_dumpviz(dumpdir) def save_preprocessors(self, data, task_ids, sample_ids, foldid): for i, taskid in enumerate(task_ids): dumpdir = getinstdir(self.outdir, taskid, sample_ids[i], foldid) data.dump_preprocessors(dumpdir, slice(i,i+1)) def add_hparam_metrics(self, hparams, metrics): groupkey = "validate" if "validate" in metrics[0].values()[0] else "train" hpsearch_result = {} for i in metrics: for step in metrics[i]: hparams_i = { key : val[i] for key,val in hparams.iteritems() } hparams_i["trainer:max_steps"] = step metrics_i = metrics[i][step][groupkey] hpsearch_result.setdefault(i,[]).append((hparams_i, metrics_i)) # Thus tuple is returned to hpsearch return hpsearch_result """ if "vloss" in stats and stats["vloss"] is not None: loss.append(stats["vloss"]) auc.append(stats["vauc"]) else: loss.append(stats["tloss"]) auc.append(stats["tauc"]) if self.testfilter is not None: tidx = [i for i in range(len(vdata)) if vdata.foldids[i] in self.testfilter] tdata = vdata[tidx] tpred = gen_predictions(model, tdata) testauc,teststd = bootstrap_auc(tpred.ravel(), tdata.Y.ravel(), ntrial=20) flogfile = self.outdir + "/%s_%04d/fold%d.log" % (task_ids[0], sample_ids[0], foldid) with open(flogfile) as fh: flog = fh.readlines() flog[-1] = flog[-1].rstrip() + "\ttestAUC=%.3f (%f)\n" % (testauc,teststd) with open(flogfile,"w") as fh: fh.writelines(flog) testaucs.append((testauc, teststd)) if report: reports.append(report) report.dump(want_html=True) #report.dump(want_html=self.want_html) # Dump each model to a separate file for inst in range(len(sample_ids)): filename = self.outdir + ("/%s_%04d/fold%d.model.pkl" % (task_ids[inst], sample_ids[inst], foldid)) _save_model_inst(filename, inst, model, hparams) """ #break """" if reports != []: # Dump the separate (individual) hyperparams that were used for each instance trained for inst in range(len(sample_ids)): dumpdir = self.outdir + ("/%s_%04d/" % (task_ids[inst], sample_ids[inst])) vloss = self.validation_performance[task_ids[inst]] if self.validation_performance else None _dump_hparams(dumpdir, _slice_hparams(hparams,inst), vloss) tdata.dump_preprocessors(dumpdir, slice(inst,inst+1)) merged = self.report_class.merge_reports(self.outdir + "/%(task_id)s_%(sample_id)04d/final.log", task_ids, sample_ids, reports) #merged.dump(want_html=self.want_html) merged.dump() if testaucs: flogfile = self.outdir + "/%s_%04d/final.log" % (task_ids[0], sample_ids[0]) with open(flogfile) as fh: flog = fh.readlines() testauc = sum([_auc for _auc, _std in testaucs]) / len(testaucs) teststd = sum([_std for _auc, _std in testaucs]) / len(testaucs) flog[-1] = flog[-1].rstrip() + "\ttestAUC=%.3f (%f)\n" % (testauc,teststd) with open(flogfile,"w") as fh: fh.writelines(flog) # Average the loss over each fold loss = np.mean(np.asarray(loss),axis=0) auc = np.mean(np.asarray(auc),axis=0) # Dump each average loss and corresponding hyperparameters into a log file for inst in range(len(sample_ids)): util.makepath(self.outdir+"/hpsearch") with open(self.outdir+"/hpsearch/%s.log"%task_ids[inst],"a") as f: f.write("%.6f\t%.4f\t%s\n"%(loss[inst], auc[inst], hparams2str( _slice_hparams(hparams,inst) ).replace("\n",";")) ) """ sm.sync() # Return a list of objective values, one per search_id values = [float(x) for x in loss] return values def calc_metrics(self, entries): metrics = {} for taskidx in entries: for step in entries[taskidx]: for group in entries[taskidx][step]: entry = entries[taskidx][step][group] Z = entry["Z"] Y = entry["Y"] # Start computing stats metric = metrics.setdefault(taskidx,{}).setdefault(step,{}).setdefault(group,{}) metric["loss"] = entry["L"] if Z.shape[1] == 1: metric.update(deepity.calc_metrics(Z.ravel(), Y.ravel(), self.aucrange)) return metrics def hparams2str(params): txt = "" for key in sorted(params.keys()): value = params[key] if isinstance(value, np.ndarray) and value.size > 10: value = "ndarray" txt += " %s = %s\n" % (key + " "*max(0,20-len(key)),value) return txt ####################################### def hypertrain(model, trainer, data, nfold=2, allfolds=True, outdir=None, nsample=20, devices=None, verbose=None, report_class=None, auxfilter=None): if report_class is None: report_class = training_report # Create the output directory if it doesn't already exist. if outdir is None: outdir = join(tempfile.gettempdir(),"hypertrain") # Define the search space space = _get_hypertrain_searchspace(model, trainer) # Perform the search, returning the best parameters in the search space. logging.info("calibrating...") samples = hp.search(space, objective = hypertrain_worker, objective_initargs = (model,trainer,data,nfold,allfolds,outdir,report_class,devices,False,sm.get_default_dtype(),globals.flags,auxfilter,"calib",False), task_ids = data.targetnames, nsample = nsample, nprocess = len(devices), nsample_per_process = 15, print_progress = True) logging.info("...calibrating done") return samples ########################################### def train(model, trainer, data, hparams=None, hparams_metric=None, nfold=1, outdir=None, nsample=1, devices=None, verbose=None, report_class=None, auxfilter=None, dumpviz=True): if report_class is None: report_class = training_report if hparams: for targetname in data.targetnames: for sample in range(nsample): for fold in range(nfold): save_hparams_result(getinstdir(outdir, targetname, sample, fold)+"/calib.txt", hparams[targetname], hparams_metric) space = _get_fixed_searchspace(model, trainer, data.targetnames, hparams) #space = _get_hypertrain_searchspace(model, trainer) #if space and not hparams: # raise ValueError("The given model has undetermined hyperparamters. Must call hypertrain first.") # Replace the randomly sampled hparams with fixed values specified by 'hparams' #for pname in space._pdefs.iterkeys(): # pbest = np.asarray([hparams[task_id].params[pname] for task_id in data.targetnames]) # space._pdefs[pname] = hp.fixed(pbest, pname) #print "assigning hparam",pname,"<-",pbest final_outdir = outdir logging.info("train...") hp.search(space, objective = hypertrain_worker, objective_initargs = (model,trainer,data,nfold,True,final_outdir,report_class,devices,verbose,sm.get_default_dtype(),globals.flags,auxfilter,"train",dumpviz), task_ids = data.targetnames, nsample = nsample, nsample_per_process = 2,#len(data.targetnames), # Hack: only train numtargets models at a time, to ensure that when nsample>1 the next sample gets a different minibatch order nprocess = len(devices)) logging.info("...train done") ####################################################### def _get_fixed_searchspace(model, trainer, targetnames, hparams): pdefs = [] if hparams: # Convert the hparams list-of-dictionaries (all dictionaries having same key) # into a single dictionary-of-lists hpvec = {} for targetname in targetnames: sample = hparams[targetname] for pkey in sample.params: hpvec.setdefault(pkey,[]).append(sample.params[pkey]) for key in hpvec: pdefs.append(hp.fixed(np.array(hpvec[key]), key)) space = hp.space(pdefs) return space def _get_hypertrain_searchspace(model, trainer): # First, collect all hparams by visiting the model's dependency graph model_hparams = [] def collect_hparam(path,attr): if isinstance(attr,hp.paramdef): attr.name = "model:" + path # model:...path model_hparams.append(attr) model.visit(collect_hparam) # Next, ask the trainer for its hyperparams, and put a "trainer." prefix on the name of each one # so that they don't conflict with model_hparams trainer_hparams = [] for name,attr in trainer.__dict__.iteritems(): if isinstance(attr,hp.paramdef): attr.name = "trainer:" + name # trainer:...path trainer_hparams.append(attr) # Return a search space built from model and trainer hyperparams return hp.space(trainer_hparams + model_hparams)
DeepBind-master
code/libs/deepity/deepity/hypertrain.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import os import time import tempfile ################################################# def splitlist(x,n): m = len(x) return [x[i:min(m,i+m//n)] for i in range(0,m,m//n)] ################################################# def makepath(dir): """ Makes a complete path if it does not exist already. Does not remove any existing files. Fixes periodic failure of os.makedirs on Windows. """ if os.path.exists(dir): return dir retries = 8 while retries >= 0: try: time.sleep(0.001) os.makedirs(dir) retries = -1 except Exception, e: if retries == 0: raise else: retries -= 1 return dir ################################################# def hashed_filename(filename,**kwargs): # The cache is a temporary file that is hashed based on args+variant, # i.e. if we only want cols 1,2,3 for example, that will go into a different # temporary file than if we were asked for cols 2,3,4. filebase = os.path.basename(os.path.splitext(filename)[0]) args_hash = abs(hash(";".join(["%s=%s" % (key,val) for key,val in kwargs.iteritems()]))) cachepath = os.path.join(tempfile.gettempdir(),"%s.hash%s" % (filebase,args_hash)) return cachepath ################################################# # MATLAB-like tic/toc _tics = {None: 0.0} def tic(id=None): global _tics now = time.time() _tics[id] = now return now def toc(id=None): global _tics now = time.time() return now - _tics[id]
DeepBind-master
code/libs/deepity/deepity/util.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import os import sys import logging import util import copy #################################### class global_flags(object): def __init__(self): self._flags = {} def copy_from(self, other): self._flags = copy.deepcopy(other._flags) def __contains__(self, name): if name in self._flags: return len(self._flags[name]) > 0 return False def __getitem__(self, name): return self.get(name) def get(self, name, default_value=None): if name in self: return self._flags[name][-1] return default_value def push(self, name, value): if name in self._flags: self._flags[name].append(value) else: self._flags[name] = [value] def pop(self, name): assert name in self._flags val = self._flags[name].pop() if len(self._flags[name]) == 0: del self._flags[name] return val flags = global_flags() _allow_multiprocessing = True def set_multiprocessing(enabled): global _allow_multiprocessing _allow_multiprocessing = enabled def reset_backend(**kwargs): import smat smat.reset_backend(**kwargs) def set_logging(file = None, level = None, echo = True, logger = None): if logger is None: logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.handlers = [] # Clear any existing handlers if echo: # The stdout handler should only print what the user has requested shandler = logging.StreamHandler() shandler.setFormatter(logging.Formatter("%(message)s")) if level == 0: shandler.setLevel(logging.ERROR) elif level == 1: shandler.setLevel(logging.INFO) elif level == 2: shandler.setLevel(logging.DEBUG) logger.addHandler(shandler) if file is not None: # The file handler should always write full debug logging util.makepath(os.path.dirname(file)) fhandler = logging.FileHandler(file,'w') fhandler.setFormatter(logging.Formatter("%(message)s")) fhandler.setLevel(logging.DEBUG) logger.addHandler(fhandler)
DeepBind-master
code/libs/deepity/deepity/globals.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import time import logging import smat as sm import numpy as np import numpy.random as npr from . import _ext from .trainer import trainer from .std import trainable from .gradcheck import gradcheck from . import globals from .plug import disconnect import report as _report class sgd(trainer): """ Stochastic (mini-batch) gradient descent with momentum. """ def __init__(self, rate = 0.05, rate_decay = 1.0, #0.99998, momentum = 0.85, nesterov = True, batchsize = 64, max_epochs = 20, max_steps = 10000, viz_steps = 10000, checkpoints = 1, checkpoint_save = True, weight_decay_start = 100, lossfunc = None, gradcheck = False): self.rate = rate self.rate_decay = rate_decay self.momentum = momentum self.nesterov = nesterov self.batchsize = batchsize self.max_epochs = max_epochs self.max_steps = max_steps self.viz_steps = viz_steps self.checkpoints = checkpoints self.checkpoint_save = checkpoint_save self.weight_decay_start = weight_decay_start self.gradcheck = gradcheck self.lossfunc = lossfunc self._report_tbatches = None self._report_vbatches = None self._last_drate_step = None self._last_drate_scale = None self._last_mrate_step = None self._last_mrate_scale = None self._last_report_step = None self._last_report_time = None def _train(self, trainable_plugs, cost, datasets, checkpoint_callback): self.force_single_value("rate_decay","nesterov","batchsize","max_steps","max_epochs") # Ask tdata for an object that serves mini-batches batchsets = {name : data.asbatches(self.batchsize, reshuffle=False) for name, data in datasets.iteritems()} tbatches = batchsets["train"] vbatches = batchsets.get("validate", None) # Allocate and bind trainable parameters to the cost object P,dP,mP,drate,mrate,trnodes = self._train_setup(trainable_plugs, cost) bprop_trainable = lambda: cost.bprop_trainable(trnodes, tbatches.next()) if self.gradcheck: gradcheck(trnodes,cost,tbatches.next()) def enforce_constraints(): for trnode in trnodes: trnode.enforce_constraints() enforce_constraints() #sm.sync() #print "START" #t0 = time.time() #self.max_steps = 1000 globals.flags.push("weight_decay_start", self.weight_decay_start) # Main training loop. max_steps = int(min(self.max_steps, self.max_epochs*len(tbatches))) checkpoints = [int(max_steps*float(cp)/self.checkpoints) for cp in range(1, self.checkpoints+1)] self._report_progress(0, cost, tbatches, vbatches) for step in xrange(max_steps): globals.flags.push("step", step) globals.flags.push("train_mode",True) # Compute learning rate and momentum for this particular step self._update_drate(step, drate) self._update_mrate(step, mrate) # Report our current performance #self._report_step(step, cost, tbatches, vbatches, report) # Step the parameters P, and also momentum vector mP _ext.gradstep(P, dP, drate, mP, mrate, grad=bprop_trainable, nesterov=self.nesterov) enforce_constraints() globals.flags.pop("train_mode") # Report our current performance if step+1 in checkpoints: self._report_progress(step+1, cost, tbatches, vbatches) checkpoint_callback(step=step+1, cost=cost, datasets=batchsets) globals.flags.pop("step") globals.flags.pop("weight_decay_start") #sm.sync() #print "STOP. Time = ", time.time()-t0 #quit() # Report the final performance on ALL batches #globals.flags.push("store_featuremaps",True) #tloss,vloss,tauc,vauc = self._report_performance(step, cost, tbatches, vbatches, None, report) #globals.flags.pop("store_featuremaps") # Affix the final trainable node weights to the inputs of each # corresponding plug on the actual model; then we can throw away # the outer 'cost' node and just leave the trained/fixed model. self._train_teardown(trnodes, cost) #stats = {} #stats["tloss"] = tloss #stats["vloss"] = vloss #stats["tauc"] = tauc #stats["vauc"] = vauc #return stats def _report_progress(self, step, cost, tbatches, vbatches): max_printwidth = 112 if step == 0: header = "\n " for name in tbatches[0].targetnames: header += " " header += name[:13] + " "*max(0,13-len(name)) print header[:max_printwidth] logging.info(header) # Get a subset of batch indices that we'll estimate our performance on trstats = _report._calc_performance_stats(cost, tbatches[:100]) vastats = _report._calc_performance_stats(cost, vbatches[:100]) if vbatches is not None else None txt = "%06d: " % step if vastats: txt += " ".join(["%.4f/%.4f" % (trloss, valoss) for trloss, valoss in zip(trstats["L"], vastats["L"])]) else: txt += " ".join(["%.4f" % (trloss) for trloss in trstats["L"]]) print txt[:max_printwidth] logging.info(txt) ''' def _report_step(self, step, cost, tbatches, vbatches, report): update_frequency = self.viz_steps if (not update_frequency) or (step % update_frequency != 0):# and step != 0: return sm.sync() now = time.time() time_per_step = None if self._last_report_step is not None: time_per_step = (now-self._last_report_time)/(step-self._last_report_step)/cost.ninst # Get a subset of batch indices that we'll estimate our performance on if self._report_tbatches is None: self._report_tbatches = npr.permutation(len(tbatches))[:max(1,len(tbatches)//10)] if vbatches is not None: if self._report_vbatches is None: self._report_vbatches = npr.permutation(len(vbatches))[:max(1,len(vbatches)//10)] self._report_performance(step, cost, [tbatches[i] for i in self._report_tbatches], [vbatches[i] for i in self._report_vbatches] if vbatches is not None else None, time_per_step, report) #print "report time = %f" % (time.time() - now) self._last_report_step = step self._last_report_time = time.time() def _report_performance(self, step, cost, tdata, vdata, time_per_step, report): if report: tloss, vloss, tauc, vauc = report.update(step, cost, tdata, vdata) else: tloss,tZ,tY,tI = _report._calc_performance_stats(cost,tdata) vloss,vZ,vY,vI = _report._calc_performance_stats(cost,vdata) if vdata is not None else (None,None,None,None) tauc = None vauc = None if tdata[0].Y.shape[1] == len(tloss): tauc = np.array([_report.calc_auc(tZ[:,i],tY[:,i]) for i in range(tZ.shape[1])]) vauc = np.array([_report.calc_auc(vZ[:,i],vY[:,i]) for i in range(vZ.shape[1])]) if vdata is not None else None for i in range(cost.ninst): txt = "%03d:%06d:\t t=%f" % (i,step,float(tloss[i])) if vloss is not None: txt += " v=%f" % float(vloss[i]) txt += " r=%.4f" % ((self.rate if np.isscalar(self.rate) else self.rate[i] )*self._last_drate_scale) txt += " m=%.2f" % ((self.momentum if np.isscalar(self.momentum) else self.momentum[i])*self._last_mrate_scale) if i == 0 and time_per_step: txt += " ms=%.3f" % (1000*time_per_step) print txt logging.info(txt) return tloss,vloss,tauc,vauc ''' def _update_drate(self, step, drate): # Periodically re-scale the drate vector, depending on how much it's supposed # to have changed since the last time we re-scaled it. if True or "disable_rate_schedule" in globals.flags: self._last_drate_step = step self._last_drate_scale=1. return i0,i1 = self._last_drate_step, step s0 = max(self.rate_decay ** i0,0.2) * (1-.75*(3./(i0+4))) if i0 is not None else 1 s1 = max(self.rate_decay ** i1,0.2) * (1-.75*(3./(i1+4))) reldiff = abs(s1-s0)/min(s1,s0) if reldiff >= .10 or (i1-i0 > 50): #drate *= s1/s0 self._last_drate_step = step self._last_drate_scale = s1 #print "step %d drate_scale = %.3f" % (step,s1) def _update_mrate(self, step, mrate): if True or "disable_rate_schedule" in globals.flags: self._last_mrate_step = step self._last_mrate_scale=1. return i0,i1 = self._last_mrate_step, step s0 = (1-4./(i0+5)) if i0 is not None else 1 s1 = (1-4./(i1+5)) reldiff = abs(s1-s0)/min(s1,s0) if reldiff >= .10 or (i1-i0 > 50): #mrate *= s1/s0 self._last_mrate_step = step self._last_mrate_scale = s1 #print "step %d mrate_scale = %.3f" % (step,s1) def _train_setup(self, trainable_plugs, cost): # For each trainable plug, figure out how many weights it needs. sizes = [ np.prod(p.shape)*cost.ninst for p in trainable_plugs ] offsets = np.asarray(np.cumsum([0] + [ size for size in sizes ]),np.uint32) # Allocate giant contiguous arrays for P, dP, and mP P = sm.zeros((offsets[-1],1)) dP = sm.zeros_like(P) mP = sm.zeros_like(P) # Per-inst learn rates / momentum rates go here. # Giant contiguous array maps to same indicies as in P, dP, mP drate = sm.zeros_like(P) mrate = sm.zeros_like(P) trnodes = [] # For each plug, create a trainable node that is bound to # a chunk of our P (parameter) and dP (gradient) vectors, where the node can for i,tplug in enumerate(trainable_plugs): # Grow the actual shape of the trainable parameters, using the # axis specified by the trainable plug. shape = list(tplug.shape) shape[tplug.inst_axis] *= tplug.node.ninst # Allocate a new trainable node, and connect it to the plug trnode = trainable(P[offsets[i]:offsets[i+1]].reshape(tuple(shape)), dP[offsets[i]:offsets[i+1]].reshape(tuple(shape))) trnode >> tplug trnodes.append(trnode) # Assign instance-specific learning rates and momentum rates # to each corresponding element in the giant drate/mrate vectors if tplug.inst_axis == 0: k = np.prod(tplug.shape) else: k = tplug.shape[1] dratevec = drate[offsets[i]:offsets[i+1]] mratevec = mrate[offsets[i]:offsets[i+1]] _ext.madd_bcast(sm.ones_like(dratevec),self.rate,k,dratevec) _ext.madd_bcast(sm.ones_like(mratevec),self.momentum,k,mratevec) # Also initialize elements of P based on the trainable plug's initialization scale, # which can be different for each individual instance Pvec = P[offsets[i]:offsets[i+1]] initval = tplug.origin().node.init if isinstance(initval, np.ndarray) and initval.ndim == 3: # Specific initialization of individual filters Pvec[:] = sm.asarray(np.require(np.rollaxis(initval,1),requirements="C").reshape((-1,1))) else: # Random initialization _ext.madd_bcast(sm.randn(Pvec.shape[0],Pvec.shape[1]), initval,k,Pvec) if hasattr(tplug.origin().node,'init_mu'): initmu_val = tplug.origin().node.init_mu if isinstance(initmu_val, list): # Specific initialization of individual bias elements initmu_val = np.tile(initmu_val,tplug.origin().node.ninst) Pvec[:] = sm.asarray(initmu_val).reshape(Pvec.shape) else: _ext.madd_bcast(sm.ones_like(Pvec), tplug.origin().node.init_mu,k,Pvec) # Add shift return (P,dP,mP,drate,mrate,trnodes) def _train_teardown(self, trnodes, cost): for trnode in trnodes: trplug = trnode.Z.dsts[0] disconnect(trnode.Z,trplug) trplug.fpval = trnode.P
DeepBind-master
code/libs/deepity/deepity/sgd.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # from .node import node,supernode from .plug import plug,connect,disconnect from .data import datasource,resident_datasource,make_predictions,count_errors,shuffled_repeat_iter from .sgd import sgd from .hypertrain import hypertrain,train,load_hparams_result,save_hparams_result,getinstdir,call_dumpviz, load_metrics, save_metrics from .trainer import trainer from .report import calc_auc, bootstrap_auc, calc_metrics from .globals import reset_backend,set_logging import _io_ as io
DeepBind-master
code/libs/deepity/deepity/__init__.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import os import sys import time import signal import logging import exceptions import traceback import warnings import multiprocessing import numpy as np import numpy.random as npr from os.path import exists,dirname,join from . import globals class local_dummy_pool(object): class job_handle(object): def __init__(self, objective, args): self.objective = objective self.args = args def get(self, timeout): args = self.args return _call_objective(*args) def __init__(self, objective, initargs): _init_objective(objective, initargs, 1) def apply_async(self, objective, args): return self.job_handle(objective, args) def close(self): pass def join(self): pass def terminate(self): pass ################################################# def _makepath(dir): """ Makes a complete path if it does not exist already. Does not remove any existing files. Fixes periodic failure of os.makedirs on Windows. """ if os.path.exists(dir): return dir retry = True while retry: try: time.sleep(0.001) os.makedirs(dir) except WindowsError, e: if e.errno != 13: # eaccess raise else: retry = False return dir ################################################# class paramdef(object): def __init__(self,name,dtype): self.name = name self.dtype = dtype class choice(paramdef): """A discrete choice, taken from a list of choices, e.g. [-1,0,1] or ['a','b','c']""" def __init__(self,choices,name=None): assert len(choices) > 0 self.choices = np.asarray(choices) super(choice,self).__init__(name,self.choices.dtype) def sample(self,task_idx,sample_ids): return np.asarray([self.choices[npr.randint(0,len(self.choices))] for id in sample_ids]) class uniform(paramdef): """A float interval [lo,hi) sampled uniformly.""" def __init__(self,lo,hi,name=None): assert lo <= hi super(uniform,self).__init__(name,np.float32) self.lo = lo self.hi = hi def sample(self,task_idx,sample_ids): return np.asarray([float(npr.rand()*(self.hi-self.lo) + self.lo) for id in sample_ids]) class loguniform(paramdef): """A float interval [lo,hi) sampled as 10**uniform(log10(lo),log10(hi)).""" def __init__(self,lo,hi,name=None): assert lo <= hi super(loguniform,self).__init__(name,np.float32) self.lo = lo self.hi = hi def sample(self,task_idx,sample_ids): lo = np.log10(self.lo) hi = np.log10(self.hi) return np.asarray([10**(npr.rand()*(hi-lo) + lo) for id in sample_ids]) class powuniform(paramdef): """A float interval [lo,hi) sampled as lo+(hi-lo)*uniform(0,1)**p for 0 < p <= 1""" def __init__(self,lo,hi,p,name=None): assert lo <= hi assert 0 < p and p <= 1 super(powuniform,self).__init__(name,np.float32) self.lo = lo self.hi = hi self.p = p def sample(self,task_idx,sample_ids): lo = self.lo hi = self.hi p = self.p return np.asarray([float((npr.rand()**p)*(hi-lo) + lo) for id in sample_ids]) class fixed(paramdef): """ Used during training of "final" models; allows a specific vector of params to be used, presumeably the best parameters from an earlier hyperparameter search. """ def __init__(self,values,name=None): super(fixed,self).__init__(name,values.dtype) self.values = values def sample(self,task_idx,sample_ids): return self.values[task_idx] ################################################# class space(object): """ A search space is just a collection of paramdefs. The sample() function is a convenient way to sample from all paramdefs. """ def __init__(self,paramdefs=None): self._pdefs = {} self.update(paramdefs) def pnames(self): return self._pdefs.keys() def update(self,paramdefs): for p in paramdefs: assert isinstance(p,paramdef), "Expected list of paramdef instances." self._pdefs.update({ p.name : p for p in paramdefs }) self.__dict__.update(self._pdefs) def __len__(self): return len(self._pdefs) def __iter__(self): return self._pdefs.itervalues() def __getitem__(self,i): return self._pdefs[i] def empty(self): return len(self) == 0 def sample(self,task_ids,sample_ids): return { name : p.sample(task_ids,sample_ids) for name,p in self._pdefs.iteritems() } ################################################# class sample(object): """ A hyperparameter search sample. """ def __init__(self,params,metrics): self.params = params self.metrics = metrics ################################################# class sampleset(object): """ A list of (params,result) pairs, where - params is a dictionary of hyperparameter values used to generate the sample. - result is the performance using those hyperparameters. The (params,result) values are echoed to a text file (JSON format) and can also be loaded from the same file. """ def __init__(self,space): self.space = space self._samples = [] def add(self,params,metrics): self._samples.append(sample(params,metrics)) def __len__(self): return len(self._samples) def __getitem__(self,i): return self._samples[i] def __iter__(self): return self._samples.__iter__() def get_all(self): """Returns the entire list of samples.""" # SIMPLE VERSION (one parameter per value) return self._samples def get_best_sample(samples, metrickey, wantmax=False): """Returns the best params from the entire list of samples.""" # SIMPLE VERSION (one parameter per value) assert len(samples) > 0, "Cannot call get_best on an empty sampleset." best = None for i in range(len(samples)): if not np.isnan(samples[i].metrics[metrickey]): if best is None: best = i else: a = samples[i].metrics[metrickey] b = samples[best].metrics[metrickey] if (wantmax and a > b) or (a < b and not wantmax): best = i return samples[best] ################################################# # _search_objective # Each process gets its own copy of this variable, and it is # instantiated when global _search_objective global _search_objective_init_err # Sets up the _search_objective global variable so that, # in the future, calling _eval_objective(params) will invoke # _search_objective(params). We need the _eval_objective # "wrapper" so that _search_objective can be a class instance, # because multiprocessing cannot pickle a class instance as an # entry point for a task -- it can only pickle a global function. def _init_objective(objective,objective_args,nprocess): global _search_objective global _search_objective_init_err _search_objective = None _search_objective_init_err = None sys.exc_clear() try: if globals._allow_multiprocessing: signal.signal(signal.SIGINT, signal.SIG_IGN) if isinstance(objective, type): process = multiprocessing.current_process() if "-" in process.name: process_type,process_id = process.name.split("-") # Get unique 1-base "process_id", which gets larger every time a new pool is created worker_id = (int(process_id)-1) % nprocess # Get unique 0-based "worker_id" index, always in range {0,...,nprocess-1} else: worker_id = 0 _search_objective = objective(worker_id, *objective_args) else: _search_objective = objective except BaseException as err: _search_objective = None # or else multiprocessing.Pool will get stuck trying to initialize traceback_str = traceback.format_exc() _search_objective_init_err = (err,traceback_str) logging.info(err.message + "\n" + traceback_str) # Do not allow the error to propagate during _call_objective, if not globals._allow_multiprocessing: raise # A global function entry-point for calling _search_objective # from a multiprocessing task def _call_objective(params,task_ids,sample_ids): global _search_objective global _search_objective_init_err sys.exc_clear() if _search_objective_init_err: return _search_objective_init_err try: # Return the params too incase they were modified by _search_objective # (this can happen when _search_objective has to force certain param vectors # to have the same uniform value for this particular sample. result = _search_objective(params, task_ids, sample_ids) except BaseException as err: _search_objective = None # or else multiprocessing.Pool will get stuck trying to initialize traceback_str = traceback.format_exc() logging.info(err.message + "\n" + traceback_str) # Do not allow the error to propagate during _call_objective, if not globals._allow_multiprocessing: raise return (err,traceback_str) return (params,result) ################################################# def _search_random(space, objective, objective_initargs, nsample, task_ids, pool, samples, nsample_per_process, print_progress=False): # Max number of samples to evaluate in each 'job' for the multiprocessing pool # TODO: THIS NUMBER IS VERY IMPORTANT, and should be chosen BASED ON MEMORY USAGE # of the MODEL. Right now set by hand :( :( :( ntask = len(task_ids) nsample_per_job = min(nsample_per_process, nsample*ntask) # Ask the pool of subprocesses to evaluate the objective jobs = [] for s in range(0,nsample*ntask,nsample_per_job): job_sample_ids = range(s, min(s+nsample_per_job, nsample*ntask)) job_task_idx = [(i % ntask) for i in job_sample_ids] job_task_ids = [task_ids[i] for i in job_task_idx] job_params = space.sample(job_task_idx, job_sample_ids) job_handle = pool.apply_async(_call_objective, (job_params,job_task_ids,job_sample_ids)) jobs.append((job_task_ids, job_handle)) # Wait for all the results to complete, and store each within its corresponding sampleset jobs_complete = 0 start_time = time.time() for job_task_ids,job_handle in jobs: jobret = job_handle.get(1000000) # huge timeout is workaround for multiprocessing bug where a KeyboardInterrupt causes everything to hang if isinstance(jobret[0], Exception): worker_exception, traceback_str = jobret quit("Error in Worker...\n" + worker_exception.message + "\n" + traceback_str) params,results = jobret for i in results: for params_i, metrics_i in results[i]: samples[job_task_ids[i]].add(params_i, metrics_i) # Store a (params,result) sample for this objective #for i in range(len(job_task_ids)): # params_i = { key : val[i] for key,val in params.iteritems() } # samples[job_task_ids[i]].add(params_i,results[i]) # Store a (params,result) sample for this objective jobs_complete += 1 if print_progress: percent_complete = float(jobs_complete) / len(jobs) print "------- %.1f%% complete -------" % (100 * percent_complete) sys.stdout.flush() ################################################# def search(space, objective, objective_initargs = None, strategy = "random", nsample = 20, nsample_per_process = 10, task_ids = None, nprocess = None, print_progress = False): """ Minimize 'objective' over the given search space. If objective is a class type, then an instance of that class will be created with __init__(worker_id,**initargs) passed to the constructor """ # Each objective can be multi-task, where ntask # Each task gets "nsample" random parameters global _search_objective # Create a pool of processes. # If no processes were requested, just use a thread instead (multiprocessing.dummy) # to avoid some of the limitations of multiprocessing (pickling, pipes, etc). if not globals._allow_multiprocessing: warnings.warn("PerformanceWarning: multiprocessing is disabled; all jobs will be run from main process.") pool = local_dummy_pool(objective=objective, initargs=objective_initargs) else: pool = multiprocessing.Pool(processes=nprocess, initializer=_init_objective, initargs=(objective,objective_initargs,nprocess)) samples = { id : sampleset(space) for id in task_ids } try: # Perform the actual search according to the selected strategy. if "random" in strategy.split(): _search_random(space, objective, objective_initargs, nsample, task_ids, pool, samples, nsample_per_process, print_progress) # TODO: other strategies like tree parzen window except: pool.terminate() pool.join() _search_objective = None raise else: pool.close() # Terminate the subprocesses pool.join() _search_objective = None return { task_id : s.get_all() for task_id,s in samples.iteritems() }
DeepBind-master
code/libs/deepity/deepity/hpsearch.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import node # circular import ref ok because we only access node module inside functions ########################################################################## # Plugs take value 'null' when they are uninitialized, rather than None, # so that there is no confusion in cases where a node sets an output plug to None class plug_null(object): def __nonzero__(self): return False # Behave like None during tests class plug(object): """ A plug on a dependency graph node. See iplug and oplug. """ def __init__(self,node,name=None,shape=None): self._shape = shape self.name = name self.node = node # Node this plug belongs to. self.srcs = [] # Upstream plugs self.dsts = [] # Downstream plugs self._fpval = plug_null # Last value forward-propagated through this plug. self._bpval = plug_null # Last value backward-propagated through this plug. self._shape = None # Shape constraints on this plug's potential values self.inst_axis = 1 # Which axis of _shape grows when there are multiple 'instances' on the plug; by default, it's columns self.trainable = True def has_src(self): return len(self.srcs) > 0 def has_dst(self): return len(self.dsts) > 0 def has_upstream(self): """Returns whether there's an upstream plug with a computed value.""" if len(self.srcs) == 0: return self.is_oplug() for src in self.srcs: if src.has_upstream(): return True return False @property def path(self): return self.node.path + "."+self.name def rename(self,newname): del self.node.__dict__[self.name] self.name = newname self.node.__dict__[newname] = self def origin(self): """A supernode plug's origin is its corresponding 'real' plug (on a non-supernode)""" # If we're attached to an actual node, then return ourselves if not isinstance(self.node,node.supernode): return self # If we're an iplug on a supernode, ask our dst plug for its origin if self.is_iplug(): return self.dsts[0].origin() # Otherwise, we're an oplug on a supernode, so ask our src plug for it's origin return self.srcs[0].origin() @property def shape(self): """ The shape of a plug's value, as a tuple (nrow,ncol), even if no plug value has been assigned yet. If nrow or ncol is None, then that dimension's size is undefined (e.g. nrow = None when nrow varies with minibatch size). """ if self._shape is None: self._calc_shape([]) # Try to calculate shape return self._shape @shape.setter def shape(self,shape): self._shape = shape @property def fpval(self): """Pull _fpval from all src plugs.""" if self._fpval is plug_null: if self.has_src(): for src in self.srcs: if self._fpval is plug_null: self._fpval = src.fpval # 1. First time, get a reference (no copy) elif src is self.srcs[1]: self._fpval = self._fpval + src.fpval # 2. Second time, make a new sum else: self._fpval += src.fpval # 3. Third+ time, add directly to new value elif self.is_oplug(): self.node.fprop() else: #raise AssertionError("unreachable code") self._fpval = None return self._fpval @property def bpval(self): """Pull _bpval from all dst plugs.""" if self._bpval is plug_null: if self.has_dst(): for dst in self.dsts: if self._bpval is plug_null: self._bpval = dst.bpval # 1. First time, get a reference (no copy) elif dst is self.dsts[1]: self._bpval = self._bpval + dst.bpval # 2. Second time, make a new sum else: self._bpval += dst.bpval # 3. Third+ time, add directly to new value elif self.is_iplug(): self.node.bprop() else: raise AssertionError("unreachable code") return self._bpval @fpval.setter def fpval(self,value): """Directly set the value forward propagated by this input plug (e.g. int, float, numpy array, etc.)""" self._fpval = value; self._check_shape() @bpval.setter def bpval(self,value): """Directly set the value backward propagated by this output plug""" assert not self.has_dst(), "Cannot directly set bpval on plug with downstream connection." assert self._bpval is plug_null, "Must call node.clear() before setting new value on a plug." self._bpval = value; self._check_shape() def _check_shape(self): if self.shape and hasattr(self._fpval,"shape"): assert len(self._fpval.shape) == len(self.shape), "Value dimension does not match plug dimension." for ss,vs in zip(self.shape,self._fpval.shape): if ss: # If shape[i] is None, don't enforce any shape assert vs >= ss , "Value shape is too small for plug shape." assert vs % ss == 0 , "Value shape does not broadcast to plug shape." def _calc_shape(self,visited): if self._shape is not None: return True # Don't backtrack. if self in visited: return False # If any of our immediate srcs/dsts have a well-defined shape, then # our shape must match theirs. for p in self.srcs+self.dsts: if p._calc_shape(visited+[self]): self._shape = p._shape assert self.inst_axis == p.inst_axis #print "%s._calc_shape() succeeded: %s" % (self.path,str(self._shape)) return True # Otherwise, ask the node to propagate shapes and see if it managed # to determine a shape for us. self.node.calc_shapes(visited+[self]) if self._shape: return True def _add_src(self,src): self.srcs.append(src) self._validate() def _add_dst(self,dst): self.dsts.append(dst) self._validate() def is_iplug(self): return self in self.node.iplugs def is_oplug(self): return self in self.node.oplugs def _validate(self): for p in self.srcs+self.dsts: assert isinstance(p,plug), "Src/dst must be of type plug, not \"%s\"" % type(p) if isinstance(self.node,node.supernode): if self.is_iplug(): assert len(self.dsts) <= 1, "Supernode iplug can only have one dst" else: assert len(self.srcs) <= 1, "Supernode oplug can only have one src" else: if self.is_iplug(): assert len(self.dsts) == 0, "Node iplug cannot have dst" else: assert len(self.srcs) == 0, "Node oplug cannot have src" # Functions to allow easier connect(X,Y) syntax. # Allows things like X >> Y, Y << X where Y is a plug # and X is a plug or a literal. def __lshift__(self,other): connect(other,self); return self def __rshift__(self,other): connect(self,other); return other def __rlshift__(self,other): connect(self,other); return other def __rrshift__(self,other): connect(other,self); return self ########################################################################## def connect(src,dst): """ Connects src to dst. - src can be an iplug, a node, or a value (float, ndarray, sarray) - dst can be an oplug, or a node If src is a node, its first output plug is used. If dst is a node, its first input plug is used. Once connected, any change to src's value will be propagated to dst and thereby to all dst's downstream dependents. Note that operators "src >> dst" and "dst << src" are equivalent to calling this function. """ # If src/dst is a node, then assume the user wants to connect # the first src.oplugs[0] to dst.iplugs[0] as convenient shorthand if isinstance(src,node.node): src = src.oplugs[0] if isinstance(dst,node.node): dst = dst.iplugs[0] # Connect the two plugs. src._add_dst(dst) dst._add_src(src) def disconnect(src,dst): if isinstance(src,node.node): src = src.oplugs[0] if isinstance(dst,node.node): dst = dst.iplugs[0] src.dsts.remove(dst) dst.srcs.remove(src)
DeepBind-master
code/libs/deepity/deepity/plug.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import os import os.path import numpy as np from PIL import Image from PIL import ImageDraw from PIL import ImageFont _logo_fonts = { "Arial" : ImageFont.truetype(os.path.abspath(os.path.dirname(__file__))+"/arial.ttf", 200), "ArialBold" : ImageFont.truetype(os.path.abspath(os.path.dirname(__file__))+"/arialbd.ttf", 200), "Courier" : ImageFont.truetype(os.path.abspath(os.path.dirname(__file__))+"/cour.ttf", 200) } _lettercache_unsized = {} _lettercache = {} def _autocrop(I): I = np.array(I) # Cut out all the rows/columns that are all white I = I[np.where(np.any(I[:,:,:3].min(axis=1)!=255,axis=1))[0],:,:] # Crop vertical I = I[:,np.where(np.any(I[:,:,:3].min(axis=0)!=255,axis=1))[0],:] # Crop horizontal # Add white border. Helps avoid edge artifacts when resizing down with anti-aliasing pad1 = 255*np.ones_like(I[:1,:,:]); pad1[:,:,3] = 0 I = np.vstack([pad1, I, pad1]) pad2 = 255*np.ones_like(I[:,:3,:]); pad2[:,:,3] = 0 I = np.hstack([pad2, I, pad2]) return Image.fromarray(I) uparrow_chr = u'\u25B2' def _get_letterimg_unsized(letter, font): global _lettercache_unsized global _logo_fonts colors = { "A" : (0,200,0), "C" : (0,0,200), "G" : (235,140,0), "T" : (200,0,0), "U" : (200,0,0), "N" : (128,128,128), uparrow_chr : (128,128,128) } assert letter in colors, "Unrecognized letter" assert font in _logo_fonts, "Unrecognized font" if (letter,font) not in _lettercache_unsized: # Draw full-sized versions of this letter letterimg = 255*np.ones((256,256,4), np.uint8) letterimg[:,:,3] = 0 # Transparent by default letterimg = Image.fromarray(letterimg) draw = ImageDraw.Draw(letterimg) draw.text((1,1), letter, colors[letter], font=_logo_fonts[font]) letterimg = _autocrop(letterimg) _lettercache_unsized[(letter,font)] = letterimg return _lettercache_unsized[(letter,font)] def get_letterimg(letter, width, height, font="ArialBold"): global _lettercache assert width and height # If we've never been asked for a letter of this width/zheight before, # then we use Image.resize to generate a new one. if (letter,width,height,font) not in _lettercache: letterimg = _get_letterimg_unsized(letter, font) letterimg = letterimg.resize((width, height), Image.ANTIALIAS) _lettercache[(letter,width,height,font)] = np.array(letterimg).reshape((height,width,4)) return _lettercache[(letter,width,height,font)] def tape2logo(tape, height=51, letterwidth=6, bufferzoom=4, refseq=None, vmax=None, style=None, rna=False, transparent=False, complement=False): # Styles "stack" "grow" "growclip" "growfade" "bars" "bar" tapedim,tapelen = tape.shape # n = number of filters if tapedim != 4: raise NotImplementedError("Expected tape with 4 rows") if vmax is not None: tape = np.maximum(-vmax, np.minimum(vmax, tape)) zheight = height*bufferzoom zletterwidth = letterwidth*bufferzoom mid1 = (zheight-bufferzoom)//2 mid2 = (zheight-bufferzoom)//2 + bufferzoom if refseq: assert len(refseq) == tapelen refseq_height = int(letterwidth*bufferzoom*1.1) # Create an up-arrow image arrowheight = int(refseq_height*0.15) uparrow_img = get_letterimg(uparrow_chr, zletterwidth//2, arrowheight, font="Arial") pad1 = 255*np.ones((arrowheight, zletterwidth//4, 4)) pad1[:,:,3] = 0 uparrow_img = np.hstack([pad1, uparrow_img]) pad2 = 255*np.ones((arrowheight, zletterwidth-uparrow_img.shape[1], 4)) pad2[:,:,3] = 0 uparrow_img = np.hstack([uparrow_img, pad2]) mid1 -= refseq_height//2+2*bufferzoom mid2 = mid1+refseq_height+4*bufferzoom positive_only = bool(np.all(tape.ravel() >= 0)) or (style in ("grow", "growfade","bar")) if positive_only: mid1 = zheight mid2 = zheight translate = { "A":"A", "C":"C", "G":"G", "T":"T", "U":"U", "N":"N" } if complement: translate = { "A":"T", "C":"G", "G":"C", "T":"A", "U":"A", "N":"N" } lettertable = ["A","C","G","U" if rna else "T"] barcolors = { "A" : (128,220,128), "C" : (128,128,220), "G" : (245,200,90), "T" : (220,128,128), "U" : (220,128,128), "N" : (192,192,192) } def make_lettercol(t, colheight, reverse): # Only show letters with positive coefficient in f idx = [i for i in range(4) if t[i] > 0] # Put largest positive value first in "above", and put largest negative value last in "below" idx = sorted(idx, key=lambda i: t[i]) # Calculate the individual zheight of each letter in pixels zheights = [int(round(t[i]/sum(t[idx])*colheight)) for i in idx] idx = [i for i,h in zip(idx,zheights) if h > 0] zheights = [h for h in zheights if h > 0] # While the stack of letters is too tall, remove pixel rows from the smallest-zheight entries #print sum(zheights) - mid1 while sum(zheights) > mid1: zheights[-1] -= 1 if zheights[-1] == 0: zheights.pop() idx.pop() # Make the individual images, reversing their order if so requested imgs = [get_letterimg(lettertable[i], zletterwidth, h) for i,h in zip(idx, zheights)] if reverse: imgs = [img for img in reversed(imgs)] return np.vstack(imgs) if imgs else np.empty((0, zletterwidth, 4)) if style == "seqlogo": assert positive_only L = 255*np.ones((zheight,tapelen*zletterwidth,4), np.uint8) L[:,:,3] = 0 # Transparent for j in range(tapelen): bits = 2 + np.sum(tape[:,j] * np.log2(tape[:,j])) letterimg = make_lettercol( tape[:,j], mid1 * bits/2., reverse=True) L[mid1-letterimg.shape[0]:mid1,j*zletterwidth:(j+1)*zletterwidth,:] = letterimg # Rescale it down to the original requested size L = np.array(Image.fromarray(L).resize((tapelen*letterwidth, height), Image.ANTIALIAS)) if not transparent: L[:,:,3] = 255 # full opacity return L pos_tape = np.maximum(1e-16, tape) neg_tape = np.maximum(1e-16,-tape) pos_colheights = pos_tape.max(axis=0) neg_colheights = neg_tape.max(axis=0) #max_colheight = np.maximum(pos_colheights, neg_colheights).max() #max_colheight = (pos_colheights + neg_colheights).max() max_colheight = neg_colheights.max() #neg_colheights = np.minimum(max_colheight,neg_colheights) pos_colheights /= max_colheight neg_colheights /= max_colheight # If we've been told to scale everything relative to a certain maximum, then adjust our scales accordinly if vmax: pos_colheights *= pos_tape.max() / vmax neg_colheights *= neg_tape.max() / vmax L = 255*np.ones((zheight,tapelen*zletterwidth,4), np.uint8) L[:,:,3] = 0 # Start transparent # For each column of the filter, generate a stack of letters for the logo for j in range(tapelen): if style in (None,"stack"): # Generate the stack of letters that goes above, and below, the dividing ling aboveimg = make_lettercol( tape[:,j], mid1 * pos_colheights[j], reverse=True) belowimg = make_lettercol(-tape[:,j], mid1 * neg_colheights[j], reverse=False) if not positive_only else None # Insert the stacked images into column j of the logo image L[mid1-aboveimg.shape[0]:mid1,j*zletterwidth:(j+1)*zletterwidth,:] = aboveimg if not positive_only: L[mid2:mid2+belowimg.shape[0],j*zletterwidth:(j+1)*zletterwidth,:] = belowimg if refseq: letterimg = get_letterimg(refseq[j], zletterwidth, refseq_height, font="ArialBold") L[mid1+2*bufferzoom:mid2-2*bufferzoom,j*zletterwidth:(j+1)*zletterwidth,:] = letterimg elif style == "growclip": # Grow the height of each letter based on binding zletterheight = int(mid1 * neg_colheights[j]) if zletterheight: letterimg = get_letterimg(refseq[j] if refseq else "N", zletterwidth, zletterheight, font="ArialBold") L[mid1-letterimg.shape[0]:mid1,j*zletterwidth:(j+1)*zletterwidth,:] = letterimg elif style == "refseq": letterimg = get_letterimg(refseq[j], zletterwidth, refseq_height, font="Arial") L[mid1-letterimg.shape[0]:mid1,j*zletterwidth:(j+1)*zletterwidth,:] = letterimg elif style == "growfade" or style == "grow": # Grow the height of each letter based on binding arrowpad_top = 3*bufferzoom arrowpad_btm = 4*bufferzoom arrowheight_padded = 0#arrowheight+arrowpad_top+arrowpad_btm growheight = int((mid1-arrowheight_padded-refseq_height) * neg_colheights[j]) fademin = refseq_height fademax = refseq_height+0.333*(mid1-arrowheight_padded-refseq_height) zletterheight = refseq_height + growheight fade = max(0, min(0.85, (fademax-zletterheight)/(fademax-fademin))) letterimg = get_letterimg(translate[refseq[j]] if refseq else "N", zletterwidth, zletterheight, font="ArialBold") if style == "growfade": letterimg = letterimg*(1-fade) + 255*fade mid0 = mid1-letterimg.shape[0] L[mid0:mid1,j*zletterwidth:(j+1)*zletterwidth,:] = letterimg[::-1,::] if complement else letterimg """ #aboveimg = make_lettercol(tape[:,j], (mid1-bufferzoom*2) * pos_colheights[j], reverse=True) #intensity = max(0, min(1.0, (pos_colheights[j]-0.4*refseq_height/mid1)/(1.5*refseq_height/mid1))) #aboveimg = aboveimg*intensity + 255*(1-intensity) tapej = tape[:,j].copy() tapej[tapej < 0.10*abs(tape).max()] = 0.0 #if pos_colheights[j] >= 0.15*max(pos_colheights.max(),neg_colheights[j].max()): if np.any(tapej > 0): aboveimg = make_lettercol(tapej, (mid1-bufferzoom*3) * pos_colheights[j], reverse=True) aboveimg = np.minimum(255,aboveimg*0.61 + 255*0.4) assert mid0-arrowheight-arrowpad_btm >= 0 assert mid0-arrowheight_padded-aboveimg.shape[0] >= 0 L[mid0-arrowheight-arrowpad_btm:mid0-arrowpad_btm,j*zletterwidth:(j+1)*zletterwidth,:] = uparrow_img L[mid0-arrowheight_padded-aboveimg.shape[0]:mid0-arrowheight_padded,j*zletterwidth:(j+1)*zletterwidth,:] = aboveimg #grey = aboveimg.mean(axis=2).reshape(aboveimg.shape[:2]+(1,)) #aboveimg[:,:,:] = np.minimum(255,grey.astype(np.float32)*160./grey.min()) #L[mid0-arrowpad_btm-aboveimg.shape[0]:mid0-arrowpad_btm,j*zletterwidth:(j+1)*zletterwidth,:] = aboveimg """ elif style == "bar": assert refseq, "style topbar needs refseq" # Put the refseq letter, with fixed height letterimg = get_letterimg(refseq[j], zletterwidth, refseq_height, font="Arial") L[mid1-letterimg.shape[0]:mid1,j*zletterwidth:(j+1)*zletterwidth,:] = letterimg # Draw a bar plot along the top based on neg_colheights barheight = int((mid1-refseq_height-2*bufferzoom) * neg_colheights[j]) L[mid1-letterimg.shape[0]-barheight-2*bufferzoom:mid1-letterimg.shape[0]-2*bufferzoom,j*zletterwidth:(j+1)*zletterwidth,:] = np.array(barcolors[refseq[j]]).reshape((1,1,4)) elif style == "bars": assert refseq, "style topbar needs refseq" # Put the refseq letter, with fixed height letterimg = get_letterimg(refseq[j], zletterwidth, refseq_height, font="Arial") L[mid1+2*bufferzoom:mid2-2*bufferzoom,j*zletterwidth:(j+1)*zletterwidth,:] = letterimg # Draw a bar plot along the top based on neg_colheights aboveheight = int(mid1 * neg_colheights[j]) belowheight = int(mid1 * pos_colheights[j]) L[mid1-aboveheight:mid1,j*zletterwidth:(j+1)*zletterwidth,:] = np.array(barcolors[refseq[j]]).reshape((1,1,4)) L[mid2:mid2+belowheight,j*zletterwidth:(j+1)*zletterwidth,:] = np.array(barcolors[refseq[j]]).reshape((1,1,4)) else: raise NotImplementedError("Unrecognzied style type") if style in (None, "stack") and not refseq: # Put a horizontal line across the middle of this logo L[mid1:mid1+bufferzoom,:,:] = 100 if not positive_only: L[mid2-bufferzoom:mid2,:,:] = 100 if not transparent: L[:,:,3] = 255 # full opacity # Rescale it down to the original requested size L = np.array(Image.fromarray(L).resize((tapelen*letterwidth, height), Image.ANTIALIAS)) if complement: L = L[::-1,:,:] # vertical flip return L
DeepBind-master
code/libs/deepity/deepity/tape2logo.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import logging import warnings import numpy as np from .node import node,supernode from .plug import plug,disconnect from .std import mse,nll,hinge,trainable from .std.elemwise import logistic from .std.softmax import softmax from . import globals class costsum(node): def __init__(self): super(costsum,self).__init__(["X"],["cost"]) def _fprop(self, X): return X # The incoming values were already accumulated at input plug X, automatically, so nothing to do def _bprop(self): return 1 # Each incoming value def _calc_shapes(self, cost): self.cost._shape = (1,1) class trainer(object): class cost(supernode): def __init__(self, model, lossfunc): self.model = model self.costsum = costsum() # First set up subgraph "model -> loss -> costsum" if isinstance(model.Z.origin().node,softmax): self.loss = nll() # If user ended model with a softmax, make loss nll implicitly elif lossfunc == "hinge": self.loss = hinge() else: self.loss = mse() # Otherwise, minimize MSE loss self.model.Z >> self.loss >> self.costsum # Find all "cost" oplugs and make sure they get summed at the output for p in model.oplugs: if p.name.startswith("cost"): p >> self.costsum super(trainer.cost,self).__init__([self.model,self.loss,self.costsum]) def disconnect(self): for src in self.iplugs: if src.has_dst(): dst = src.dsts[0] if dst.node is self.model: disconnect(src,dst) dst.fpval = src.fpval for p in self.model.oplugs: if p.name.startswith("cost"): disconnect(p,self.costsum) disconnect(self.model.Z,self.loss) def eval_loss(self, batches): if batches is None: return None loss = None for batch in batches: # For each data attribute, set its value on the corresponding plug for attrname in batch.data_attrs(): if hasattr(self, attrname): getattr(self, attrname).fpval = getattr(batch, attrname) else: warnings.warn("Data has attribute \"%s\", but model does not; that particular input will be ignored." % attrname) # Pull the final loss value for this minibatch batch_loss = self.loss.loss.fpval.asnumpy().ravel() if loss is None: loss = np.zeros_like(batch_loss) loss += batch_loss # Clear all stored values in the dependency graph, effectively resetting it self.clear() for attrname in batch.data_attrs(): if hasattr(self, attrname): getattr(self, attrname).fpval = None loss /= len(batches) return loss def eval_model(self, batches): if batches is None: return None Z = [] for batch in batches: # For each data attribute, set its value on the corresponding plug for attrname in batch.data_attrs(): if hasattr(self, attrname): getattr(self, attrname).fpval = getattr(batch, attrname) else: warnings.warn("Data has attribute \"%s\", but model does not; that particular input will be ignored." % attrname) # Pull the final loss value for this minibatch Z.append(self.model.Z.fpval.asnumpy()) # Clear all stored values in the dependency graph, effectively resetting it self.clear() for attrname in batch.data_attrs(): if hasattr(self, attrname): getattr(self, attrname).fpval = None return np.vstack(Z) def bprop_trainable(self, trnodes, datasrc): # For each data attribute, set its value on the corresponding plug for attrname in datasrc.data_attrs(): if hasattr(self, attrname): getattr(self, attrname).fpval = getattr(datasrc, attrname) #else: # warnings.warn("Data has attribute \"%s\", but model does not; that particular input will be ignored." % attrname) # Set the initial bpvalue to be simply 1 self.cost.bpval = 1 # Tell each trainable node to update its dP value globals.flags.push("bprop_mode",True) for trnode in trnodes: trnode.bprop() globals.flags.pop("bprop_mode") # Clear all the stored values in the dependency graph, effectively resetting it self.clear() for attrname in datasrc.data_attrs(): if hasattr(self, attrname): getattr(self, attrname).fpval = None def train(self, model, datasets, checkpoint_callback): tdata = datasets["train"] ninst = len(tdata.targetnames) cost = trainer.cost(model, self.lossfunc) cost.set_ninstance(ninst) # Set the shape of all model inputs for attrname in tdata.input_attrs(): #assert hasattr(cost,attrname), "Data has input named \"%s\", but model does not" % attrname if hasattr(cost, attrname): getattr(cost, attrname).shape = (None,tdata.attrdim(attrname)) else: logging.warn("Data has input named \"%s\", but model does not" % attrname) # Assert that all model outputs match the size of the corresponding targets, if any for attrname in tdata.output_attrs(): assert hasattr(cost,attrname), "Data has output named \"%s\", but model does not" % attrname #assert getattr(cost,attrname).shape[1] == tdata.attrdim(attrname)/ninst, "Model's output attribute \"%s\" (dim=%d) doesn't match corresponding target dimension (dim=%d)" % (attrname,getattr(cost,attrname).shape[1],tdata.attrdim(attrname)/ninst) # Collect all input plugs on the cost function that are not # determined by the data inputs/targets trainable_plugs = [ p for p in cost.iplugs if (p.origin().trainable and p.shape and p.name not in tdata.data_attrs()) ] # Call subclass to do the actual training self._train(trainable_plugs, cost, datasets, checkpoint_callback) cost.disconnect() model._parent = None def force_single_value(self,*attrnames): for attrname in attrnames: attr = getattr(self,attrname) if isinstance(attr,np.ndarray): if any(attr != attr[0]): logging.info("forcing parameter \"%s\" to single value %s" % (attrname,str(np.asscalar(attr[0])))) attr[:] = attr[0] setattr(self,attrname,np.asscalar(attr[0]))
DeepBind-master
code/libs/deepity/deepity/trainer.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # from .plug import plug,connect,plug_null from .data import datasource from . import globals import re import smat as sm import numpy as np try: from hpsearch import paramdef except: class dummy_type(object): pass paramdef = dummy_type class node(object): """ A dependency graph node. Each node must provide two functions: _fprop: compute the value of each output plug, using the input plugs _bprop: compute the delta of each input plug, using the input plugs and delta of each output plug For example, a "Z = tanh(X)" node would be implemented as: class tanh_node(node): def __init__(self): node.__init__(["X"],["Z"]) # Create iplug X and oplug Z def _fprop(self,X): return tanh(X) # Compute Z from X def _bprop(self,Z,dZ): return dZ*(1-Z**2) # Compute dX from Z and dZ # (Note: tanh'(X) = 1-tanh(X)^2 = 1-Z^2) """ def __init__(self,iplugs,oplugs,name=None): self.name = name self.ninst = 1 self._parent = None # Weakref to parent (the @parent property automatically derefs) # Add plugs directly specified by subclass self.iplugs = [plug(self,pname) for pname in iplugs] self.oplugs = [plug(self,pname) for pname in oplugs] # For convenience, add each plug as a named attribute, to facilitate "self.X" self.__dict__.update({ plug.name : plug for plug in self.iplugs }) self.__dict__.update({ plug.name : plug for plug in self.oplugs }) @property def parent(self): return self._parent @property def path(self): if not self._parent: return "" # Iterate over our other parent's children and identify our path relative to that parent for i,child in enumerate(self.parent): if child is self: # The path to a child is, by default, "path[i]" where i is the child's index relpath = "["+str(i)+"]" # However, if the child is also an attribute, like .foo, then path is "path.foo" for name,attr in self.parent.__dict__.iteritems(): if self is attr: relpath = "."+name break break return self.parent.path + relpath def _visit(self,path,callback): # Visit ourself first. callback(path,self) # Visit all our own attributes, *except* any nodes (let supernode deal with them if need be) for name,attr in self.__dict__.iteritems(): if isinstance(attr,(plug,paramdef)): newval = callback(path+"."+name,attr) if newval is not None: setattr(self,name,newval) def visit(self,callback): """ Visits each plug of the node, and each child of the node, invoking callback(path,object) for each one. For example, if 'node' is a "dropout" node, then node.visit would call: callback(".X",node.X) # visit the input plug X callback(".Z",node.Z) # visit the output plug Z callback(".rate",node.rate) # visit the dropout rate (a scalar) If 'node' were a supernode, such as a chain([bias,dropout]), then node.visit would call callback(".X",node.X) # visit supernode's input plug X (which will have dst bias.X) callback(".Z",node.Z) # visit supernode's output plug X (which will have src dropout.Z) callback("[0]",node.children[0]) # visit first child node callback("[0].X",node.children[0].X) # visit first child's input plug X callback("[0].b",node.children[0].b) # visit first child's bias plug b (i.e. trainable weights) callback("[0].Z",node.children[0].Z) # visit first child's output plug Z callback("[1]",node.children[1]) # ... callback("[1].X",node.children[1].X) callback("[1].Z",node.children[1].Z) callback("[1].rate",node.children[1].rate) """ self._visit("",callback) def set_ninstance(self,ninst): def set_ninst(path,obj): if isinstance(obj,node): obj.ninst = ninst self.visit(set_ninst) def _set_ninstance(self,ninst): raise NotImplementedError("Subclass should implement _set_ninstance.") def slice_inst(self,inst): # First, ask each internal node to pull its _fpval and slice out # the parameters for instance number 'inst'. # The internal nodes may pull their _fpval from supernode plugs. def do_slice_inst(path,obj): if isinstance(obj,node): obj._slice_inst(inst) obj.ninst = 1 self.visit(do_slice_inst) # Second, a supernode parameter plug may still have def replace_with_origin(path,obj): if isinstance(obj,plug) and isinstance(obj.node,supernode): if obj.origin() is not obj and obj.origin()._fpval is not None: obj.fpval = obj.origin()._fpval self.visit(replace_with_origin) def _slice_inst(self,inst): return # by default, do nothing def find(self,path): """Returns the node or attribute specified by the path, relative to this node""" if path == "": return self assert path.startswith(".") return getattr(self,path[1:]) def find_and_set(self,path,val): """Sets the node or attribute specified by the path, relative to this node""" if "." not in path: setattr(path, val) assert path.startswith(".") return getattr(self, path[1:]) def requirements(self): # Return a dictionary of "requirements" that the external program should # make sure that the data accomodates. Each node has the opportunity to list # some requirement for the input data, such as data being padded. # Each requirement is in the form { "a.b.requirement_name" : requirement_value } reqs = {} def add_reqs(path,obj): if isinstance(obj,node): reqs.update({ (path+"."+key) : val for key,val in obj._requirements().iteritems() }) self.visit(add_reqs) return reqs def _requirements(self): return {} def data_requirements(self): reqs = self.requirements() padding = max([0]+[val for key,val in reqs.items() if key.endswith("sequence_padding")]) target = [val for key,val in reqs.items() if key.endswith("target")] assert len(target) <= 1 if target: target = target[0] return { 'target' : target, 'padding' : padding } def calc_shapes(self,visited): if self in visited: return argnames = self._calc_shapes.__code__.co_varnames[1:self._calc_shapes.__code__.co_argcount] inputs = { name : getattr(self,name) for name in argnames } for iplug in inputs.itervalues(): iplug._calc_shape(visited+[self]) self._calc_shapes(**inputs) #for iplug in inputs.itervalues(): #if iplug._shape is not None: #print "%s._calc_shape() succeeded: %s" % (iplug.path,str(iplug._shape)) def _calc_shapes(self): raise NotImplementedError("Subclass should implement _calc_shapes.") def clear(self): def clear_plug(path,obj): if isinstance(obj,plug): if obj.has_src() or obj.is_oplug(): obj._fpval = plug_null # Clear all fprop values except input plugs with a fixed (external) value set on them obj._bpval = plug_null self.visit(clear_plug) def fprop(self): """ Calculate the value of all output plugs based on the current iplugs. """ for oplug in self.oplugs: assert oplug._fpval is plug_null, "fprop on a node can only be called while it's output fpvals are undefined" # If the subclass of this object defined # def _fprop(self,X,Y): # ... # then we want to automatically pull the value stored by plugs X and Y # and pass those values as _fprop's arguments. argnames = self._fprop.__code__.co_varnames[1:self._fprop.__code__.co_argcount] inputs = { } for argname in argnames: p = getattr(self,argname) assert p in self.iplugs, "_fprop cannot request parameter %s, as its value has not been determined yet" % argname inputs[argname] = p.fpval # Call subclass _fprop implementation and get a list of outputs outputs = self._fprop(**inputs) if not isinstance(outputs,tuple): outputs = (outputs,) # Move each output to the corresponding oplug for oplug,fpval in zip(self.oplugs,outputs): oplug._fpval = fpval def bprop(self): """ Calculate 'delta' for each input plug. For example, if iplugs=[X] and oplugs=[Z], then bprop should compute dX from X,Z,dZ. """ for iplug in self.iplugs: assert iplug._bpval is plug_null, "bprop on a node can only be called while it's input bpvals are undefined" # If the subclass of this object defined # def _bprop(self,X,Z,dZ): # ... # then we want to automatically call # self._bprop(X._fpval,Z._fpval,Z._bpval) # argnames = self._bprop.__code__.co_varnames[1:self._bprop.__code__.co_argcount] inputs = {} for argname in argnames: if argname.startswith("d") and hasattr(self,argname[1:]): # If the plug is dZ, then substitute with Z.bpval p = getattr(self,argname[1:]) assert p in self.oplugs, "_bprop cannot request parameter %s, as its value has not been determined yet" % argname inputs[argname] = p.bpval else: # Otherwise, simply use Z.fpval p = getattr(self,argname) inputs[argname] = p.fpval # Call subclass _bprop implementation and get a list of deltas outputs = self._bprop(**inputs) if not isinstance(outputs,tuple): outputs = (outputs,) # Copy each output to the corresponding iplug's delta value for iplug,bpval in zip(self.iplugs,outputs): iplug._bpval = bpval def _fprop(self): raise NotImplementedError("Cannot propagate through node.") def _bprop(self): raise NotImplementedError("Cannot back-propagate through node.") def eval(self,**kwargs): want_clear = kwargs.pop('clear',True) want_bprop_inputs = kwargs.pop('want_bprop_inputs',False) bprop_inputs_loss = kwargs.pop('bprop_inputs_loss',None) self.clear() globals.flags.push("want_bprop_inputs",want_bprop_inputs) globals.flags.push("bprop_mode",want_bprop_inputs) # For each keyword, set the corresponding plug's value for key,val in kwargs.iteritems(): getattr(self,key).fpval = val # Pull the final loss value for this minibatch result = { p.name : p.fpval for p in self.oplugs } # If needed, also pull the backprop'd input deltas and include them in the result if want_bprop_inputs or bprop_inputs_loss: # First set up special backprop values: "Z" (the prediction) backpropagates a negative value # All other output plugs (e.g. costs) backpropagate zero. for p in self.oplugs: if p.name == "Z": bprop_inputs_loss.batchmean = False # Disable scaling gradient by minibatch size bprop_inputs_loss.Z.fpval = result["Z"] bprop_inputs_loss.Y.fpval = sm.zeros_like(result["Z"]) #bprop_inputs_loss.Y.fpval = -1.*sm.ones_like(result["Z"]) p._bpval = bprop_inputs_loss.Z.bpval result['Zmask'] = bprop_inputs_loss.Zmask._fpval # Only backprop gradient of target #0, not the other targets if p._bpval.shape[1] > 1: p._bpval[:,1:] = sm.zeros_like(p._bpval[:,1:]) #p._bpval = -result["Z"] #p._bpval = -sm.ones_like(result["Z"]) else: p._bpval = sm.zeros((0,0)) # Now backpropagate to each input, and store the result if want_bprop_inputs: result.update({ "d"+p.name : p.bpval for p in self.iplugs if p.name in kwargs}) globals.flags.pop("want_bprop_inputs") globals.flags.pop("bprop_mode") # Clear all stored values in the dependency graph, effectively resetting it if want_clear: self.clear() for key in kwargs.iterkeys(): getattr(self,key).fpval = plug_null return result # Functions to allow easier connect(X,Y) syntax. # Allows things like X >> Y, Y << X where Y is a node # and X is a node or a literal. def __lshift__(self,other): connect(other,self); return self def __rshift__(self,other): connect(self,other); return other def __rlshift__(self,other): connect(self,other); return other def __rrshift__(self,other): connect(other,self); return self ##################################################################### class supernode(node): """ A supernode wraps a subgraph with a simple interface. All of this node's inputs are forwarded internal inputs, likewise all its outputs are and forwarded from internal outputs. """ def __init__(self,children,name=None): self._children = children for child in children: child._parent = self # Collect all unconnected plugs so that we can expose # corresponding external plugs on the supernode iplugs = [plug for child in children for plug in child.iplugs if not plug.has_src()] oplugs = [plug for child in children for plug in child.oplugs if not plug.has_dst()] # Figure out what the external name for each internal plug should be, # e.g. two internal plugs named "W" get renamed "W0" and "W1". iplug_names = self._calc_plug_names(iplugs) oplug_names = self._calc_plug_names(oplugs) # Call node constructor to initialize our own plugs. super(supernode,self).__init__(iplug_names,oplug_names,name) # Connect each external plug to its internal counterpart for src,dst in zip(self.iplugs,iplugs): src >> dst; src.inst_axis = dst.inst_axis for src,dst in zip(oplugs,self.oplugs): src >> dst; dst.inst_axis = src.inst_axis @staticmethod def _calc_plug_names(plugs): # If two internal plugs are named R, for example, then their external # counterparts get named R0,R1 raw_names = [plug.name for plug in plugs] new_names = [] for i,name in enumerate(raw_names): while (raw_names+new_names).count(name) > 1: name = name + str(raw_names[:i].count(name)) # R,R becomes R0,R1 new_names.append(name) return new_names def _visit(self,path,callback): # First visit all our own attributes super(supernode,self)._visit(path,callback) # Next, iterate over our other immediate children and recursively call _visit for i,child in enumerate(self): # The path to a child is, by default, "path[i]" where i is the child's index childpath = "["+str(i)+"]" # However, if the child is also an attribute, like .foo, then path is "path.foo" for name,attr in self.__dict__.iteritems(): if attr is child: childpath = "."+name break child._visit(path+childpath,callback) def _set_ninstance(self,ninst): return # Do nothing on the supernode itself. Let set_ninstance visit all our children automatically. def find(self,path): """Returns the node or attribute specified by the path, relative to this node""" if path == "": return self # If path is "[i]...", then call children[i].find(...) match = re.search("^\[(\d+)\](.*)",path) if match: return self._children[int(match.group(1))].find(match.group(2)) # If path is ".name", then return getattr(self,name) match = re.search("^\.(\w+)$",path) if match: return getattr(self,match.group(1)) # If path is ".name..." then 'name' must be a child node, and we return getattr(self,name).find(...) match = re.search("^\.(\w+)(.+)",path) if match: return getattr(self,match.group(1)).find(match.group(2)) def __iter__(self): return self._children.__iter__() def __getitem__(self,i): return self._children[i] def __len__(self): return len(self._children) def calc_shapes(self,visited): return # Do nothing def fprop(self): return # Do nothing def bprop(self): return # Do nothing def _fprop(self): return # Do nothing def _bprop(self): return # Do nothing def slice_inst(self,inst): super(supernode,self).slice_inst(inst)
DeepBind-master
code/libs/deepity/deepity/node.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import time import logging import numpy as np import numpy.random as npr from .std import trainable from . import globals def gradcheck(trnodes,cost,datasrc,maxtime=2,rtol=1e-5,atol=1e-4): """ Checks the computation of grad() against numerical gradient. If any component of the numerical gradient does not match, an AssertionError is raised with information about the problem. """ # Collect each trainable node in the dependency graph if len(trnodes) == 0: return # No trainable nodes, means zero-dimensional gradient # trnodes[0].P[:] = 0 print "gradient check (dtype=%s)..." % str(trnodes[0].P.dtype) globals.flags.push("train_mode",False) # Update the dP value of each trainable node, so that it contains # the symbolic gradient for that trainable node's parameters cost.bprop_trainable(trnodes,datasrc) # Compute components numeric gradient by starting from the symbolic gradient # and then checking several weight components by central-difference failures = {} data = datasrc.data() # Loop over each for trnode in trnodes: # Get the parameter vector P, and also the symbolic gradient that was computed at the beginning P = trnode.P.ravel() # Keep as sarray dP = trnode.dP.asnumpy().ravel() # Download # Decide on step size and what order to perturb the parameters of this trainable node step = 1e-8 if P.dtype == np.float64 else 1e-4 #order = npr.permutation(len(P)) # Use same permutation every time for consistency in output order = np.arange(len(P)) # For the time allotted, perturb each parameter and evaluate the cost starttime = time.time() numcheck,mincheck = 0,min(len(order),50) for i in order: # Temporarily perturb weight i by 'step' and evaluate the new cost at each position x = float(P[i]) P[i] = x-step; c0 = np.sum(cost.eval(**data)["cost"].asnumpy()); P[i] = x+step; c1 = np.sum(cost.eval(**data)["cost"].asnumpy()); P[i] = x # Compute the numeric gradient for paraneter i, and check its closeness to symbolic gradient dc_num = float(c1-c0)/float(2*step) dc_sym = dP[i] if not np.allclose(dc_num,dc_sym,rtol=rtol,atol=atol) or not np.allclose(dc_sym,dc_num,rtol=rtol,atol=atol): if trnode not in failures: failures[trnode] = [] failures[trnode].append((i,dc_num,dc_sym)) # Quit early if we ran out of time for this particular node numcheck += 1 if time.time()-starttime >= maxtime and numcheck >= mincheck: break globals.flags.pop("train_mode") # No errors? Then simply return if len(failures) == 0: logging.info("gradient check PASSED") return msg = "...gradient check FAILED\n" for trnode,items in failures.iteritems(): msg += " %s FAILED at weights:\n" % (trnode.Z.dsts[0].origin().path) # Sort by index items.sort(cmp=lambda x,y: int(x[0]-y[0])) count = 0 for index,dc_num,dc_sym in items: msg += "\t\t[%d] num: %.8f sym: %.8f\n" % (index,dc_num,dc_sym) count += 1 if count > 8: msg += "\t\t...\n" break for trnode in trnodes: if trnode not in failures: msg += " %s SUCCEEDED\n" % (trnode.Z.dsts[0].origin().path) logging.info("gradient check FAILED") logging.info(msg) raise AssertionError(msg)
DeepBind-master
code/libs/deepity/deepity/gradcheck.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import os import os.path import copy import numpy as np import numpy.random as npr import smat as sm import gc from .util import makepath from .data import make_predictions from . import globals import scipy import scipy.stats import subprocess import warnings #warnings.simplefilter('error', UserWarning) #################################################################### def calc_auc(z, y, want_curve = False): assert len(z) == len(y) #m = ~np.isnan(y) #y = y[m] #z = z[m] #ymin = y.min() #ymax = y.max() #lo = (0.02-0) / (1.0 - 0.0) * (ymax-ymin) + ymin #hi = (0.10-0) / (1.0 - 0.0) * (ymax-ymin) + ymin #mlo = y<=lo #mhi = y>=hi #y[mlo] = 0 #y[mhi] = 1 #y[np.logical_and(mlo,mhi)] = np.nan #m = ~np.isnan(y) #y = y[m] #z = z[m] # Sort by decreasing score order = np.argsort(z, axis=0, kind="mergesort")[::-1].ravel() z = z[order] y = y[order] # Accumulate the true positives with decreasing threshold tpr = y.cumsum() fpr = 1 + np.arange(len(y)).astype(y.dtype) - tpr # If curve doesn't have point at x=0, explicitly insert one if fpr[0] != 0: tpr = np.r_[0,tpr] fpr = np.r_[0,fpr] # If one of the classes was empty, return NaN if fpr[-1] == 0 or tpr[-1] == 0: return (np.nan,None) if want_curve else np.nan # Convert sums to rates tpr = tpr / tpr[-1] fpr = fpr / fpr[-1] # Calculate area under the curve using trapezoidal rule auc = np.trapz(tpr,fpr,axis=0) # Done! if want_curve: curve = np.hstack([fpr,tpr]) return auc,curve return auc ''' #auc1 = auc npos = np.count_nonzero(y) # Total number of positives. nneg = len(y)-npos # Total number of negatives. if nneg == 0 or npos == 0: return (np.nan,None) if want_curve else np.nan n = len(y) fprate = np.zeros((n+1,1)) tprate = np.zeros((n+1,1)) ntpos,nfpos = 0.,0. for i,yi in enumerate(y): if yi: ntpos += 1 else: nfpos += 1 tprate[i+1] = ntpos/npos fprate[i+1] = nfpos/nneg auc = np.trapz(tprate,fprate,axis=0) if want_curve: curve = np.hstack([fprate,tprate]) return auc,curve return auc''' ######################################################################### def bootstrap_auc(z, y, ntrial=10): n = len(y) aucs = [] for t in range(ntrial): sample = npr.randint(0,n,n) zt = z[sample].copy().reshape((-1,1)) yt = y[sample].copy().reshape((-1,1)) auc = calc_auc(zt,yt) if np.isnan(auc): return np.nan, np.nan # If any of the samples returned NaN, the whole bootstrap result is NaN aucs.append(auc) return np.mean(aucs),np.std(aucs) ##################################################################### def calc_metrics(z, y, aucthresh=(0.5,0.5)): metric = {} # Compute correlations using all non-NaN values M = ~np.isnan(y) z = z[M] y = y[M] metric["pearson.r"], metric["pearson.p"] = scipy.stats.pearsonr(z,y) metric["spearman.r"], metric["spearman.p"] = scipy.stats.spearmanr(z,y) if np.any(y < aucthresh[0]) and np.any(y >= aucthresh[1]): # Compute percentiles of positive and negative sets: #if np.sum(y < aucthresh[0]) > 1 and np.sum(y > .5) > 1: # negmu,negstd = np.mean(z[y<.5]), np.std(z[y<.5]) # posmu,posstd = np.mean(z[y>.5]), np.std(z[y>.5]) # numer = posmu-negmu # denom = posstd+negstd # metric["gapratio"] = (numer / denom) if denom else np.nan # Convert y to binary using the aucrange threshold lo, hi = aucthresh Mlo = y< lo Mhi = y>=hi y[Mlo] = 0 y[Mhi] = 1 M = np.logical_or(Mlo,Mhi) y = y[M] z = z[M] # Calculate AUC stats metric["auc"] = calc_auc(z, y) metric["auc.mean"], metric["auc.std"] = bootstrap_auc(z, y, 20) return metric ##################################################################### def _calc_performance_stats(cost, batches): Z = [] Y = [] L = [] rowidx = [] for batch in batches: args = { key : val for key,val in batch.data().items() if hasattr(cost,key) } cost.eval(clear=False,**args) Zi = cost.loss.Z.fpval.asnumpy() Yi = sm.asnumpy(batch.Y) Li = cost.loss.loss.fpval.asnumpy() rowidx_i = sm.asnumpy(batch.rowidx) if hasattr(batch,"rowidx") else None # Deal with possibility that only a subset of predictions contributed to the loss, due to some test performed after prediction (e.g. max of sequence and reverse_complement of sequence) if cost.Zmask.fpval is not None: Zmask = cost.Zmask.fpval.asnumpy() Zi = np.hstack([Zi[Zmask[:,col],col].reshape((-1,1)) for col in range(Zi.shape[1])]) Yi = np.hstack([Yi[Zmask[:,col],col].reshape((-1,1)) for col in range(Yi.shape[1])]) if rowidx_i is not None: rowidx_i = rowidx_i[Zmask[:,0],0].reshape((-1,1)) Z.append(Zi) Y.append(Yi) L.append(Li) if rowidx_i is not None: rowidx.append(rowidx_i) cost.clear() Z = np.vstack(Z) Y = np.vstack(Y) L = np.vstack(L) L = np.mean(L,axis=0) rowidx = np.vstack(rowidx) if rowidx else None return { "L" : L, "Z" : Z, "Y" : Y, "I" : rowidx } #return (L,Z,Y,rowidx) ##################################################### class training_report(object): ''' class subreport(object): def __init__(self,filename): self.filename = filename makepath(os.path.dirname(filename)) self.logfile = open(filename,'w') self.entries = [] def update(self, step, model, tloss, tZ, tY, tI, vloss, vZ, vY, vI, **kwargs): if tI is not None: p = np.argsort(tI.ravel()) tZ = tZ[p,:] tY = tY[p,:] tI = tI[p,:] if vI is not None: p = np.argsort(vI.ravel()) vZ = vZ[p,:] vY = vY[p,:] vI = vI[p,:] # Build a short string describing the current state txt = "" if step is not None: txt += "%06d:" % step if tloss is not None: txt += "\t tloss=%.8f" % tloss if vloss is not None: txt += "\t vloss=%.8f" % vloss for key,val in kwargs.iteritems(): txt += "\t%s=%s\t " % tloss for i in range(tY.shape[1]): tZi = tZ[:,i:i+1] tYi = tY[:,i:i+1] tMi = ~np.isnan(tYi) tpearson = scipy.stats.pearsonr(tZi[tMi],tYi[tMi]) tspearman = scipy.stats.spearmanr(tZi[tMi],tYi[tMi]) tauc = bootstrap_auc(tZi[tMi],tYi[tMi]) txt += "\t tp%02d=%.3f (%g)" % (i,tpearson[0],tpearson[1]) txt += "\t ts%02d=%.3f (%g)" % (i,tspearman[0],tspearman[1]) txt += "\t ta%02d=%.3f (%g)" % (i,tauc[0],tauc[1]) if vY is not None: vZi = vZ[:,i:i+1] vYi = vY[:,i:i+1] vMi = ~np.isnan(vYi) vpearson = scipy.stats.pearsonr(vZi[vMi],vYi[vMi]) vspearman = scipy.stats.spearmanr(vZi[vMi],vYi[vMi]) vauc = bootstrap_auc(vZi[vMi],vYi[vMi]) txt += "\t vp%02d=%.3f (%g)" % (i,vpearson[0],vpearson[1]) txt += "\t vs%02d=%.3f (%g)" % (i,vspearman[0],vspearman[1]) txt += "\t va%02d=%.3f (%g)" % (i,vauc[0],vauc[1]) # If such state was provided, append it to our file. if txt != "": mode = "w" if self.entries == [] else "a" with open(self.filename,mode) as f: f.write(txt+"\n") images = self.extract_filters(model) if "store_featuremaps" in globals.flags else None entry = {} if step is not None: entry['step'] = step if tloss is not None: entry['tloss'] = tloss if tloss is not None: entry['tauc'] = tauc if tZ is not None: entry['tZ'] = tZ if tY is not None: entry['tY'] = tY if tI is not None: entry['tI'] = tI if vloss is not None: entry['vloss'] = vloss if vloss is not None: entry['vauc'] = vauc if vZ is not None: entry['vZ'] = vZ if vY is not None: entry['vY'] = vY if vI is not None: entry['vI'] = vI if images is not None: entry['images'] = images entry.update(kwargs) self.entries.append(entry) @staticmethod def extract_filters(model): # Extract any filters from the dependency graph nodes, and # convert them to images. if not model: return None filters = {} def collect_filters(path,obj): if hasattr(obj,"getfilters"): F = obj.getfilters() if F is not None: filters[path] = F model.visit(collect_filters) return filters if len(filters) > 0 else None def dump(self, want_html=False, want_anim=False): # Don't just dump the status text -- also dump all weights, in an archive if want_html: prefix = os.path.splitext(self.filename)[0] np.savez_compressed(prefix+".report.npz", entries=np.asarray(self.entries[-1:],dtype=object)) # Fire off a separate process that will generate filter/prediction plots # using matplotlib; this should be done in a separate process so as to avoid # instability with matplotlib/tk in the multiprocess hyperparameter search subprocess.Popen(["python", os.path.dirname(__file__)+"/report_plotter.py", prefix+".report.npz"]) ''' ############################### def __init__(self, aucrange=(0.5,0.5)): """auclo and auchi can be used to explicitly threshold a non-binary target Y""" self.aucrange = aucrange self.foldid = 0 self.entries = {} # An "entry" is identified by indices entries[task][step][dataset]. # Each entry entry[quantity][foldid] # is the quantity for the specific foldid, where quantity is something like 'Z' or 'Y' and foldid is some integer like 0,1,2 # self.subreports = [self.subreport(logfile_pattern % {"sample_id" : sample_id, "task_id" : task_id}) # for (task_id,sample_id) in zip(task_ids,sample_ids)] def setfold(self, foldid): self.foldid = foldid ############################### @staticmethod def _get_submodel(model, index): submodel = copy.deepcopy(cost.model) sm.sync() submodel.slice_inst(index) sm.sync() return submodel ############################### def __call__(self, step, cost, datasets): """ Record the performance of each submodel (of 'cost') at this particular step. """ # Compute all loss values L, predictions Z, targets Y, and original row indices I both tdata, and for vdata for name, data in datasets.iteritems(): stats = _calc_performance_stats(cost, data) # Figure out how many output dimensions (columns of Y) belong to each target. assert stats["L"].size == len(data.curr().targetnames) assert stats["Y"].shape[1] % stats["L"].size == 0 Ydim = stats["Y"].shape[1] // stats["L"].size # Split up the columns for i, targetname in enumerate(data.curr().targetnames): # Store the loss, predictions Z, and targets Y for model i entry = self.entries.setdefault(i,{}).setdefault(step,{}) entry.setdefault(name,{}).setdefault("L",[]).append(float(stats["L"][i])) entry.setdefault(name,{}).setdefault("Z",[]).append(stats["Z"][:,i*Ydim:(i+1)*Ydim]) entry.setdefault(name,{}).setdefault("Y",[]).append(stats["Y"][:,i*Ydim:(i+1)*Ydim]) entry.setdefault(name,{}).setdefault("I",[]).append(stats["I"]) ############################### def combined(self): combined = {} for taskidx in self.entries: for step in self.entries[taskidx]: for group in self.entries[taskidx][step]: entry = self.entries[taskidx][step][group] combined_entry = combined.setdefault(taskidx,{}).setdefault(step,{}).setdefault(group,{}) combined_entry["L"] = np.mean(entry["L"]) combined_entry["Z"] = np.vstack(entry["Z"]) combined_entry["Y"] = np.vstack(entry["Y"]) combined_entry["I"] = np.vstack(entry["I"]) return combined ############################### def curr(self): curr = {} for taskidx in self.entries: for step in self.entries[taskidx]: for group in self.entries[taskidx][step]: entry = self.entries[taskidx][step][group] curr_entry = curr.setdefault(taskidx,{}).setdefault(step,{}).setdefault(group,{}) curr_entry["L"] = entry["L"][self.foldid] curr_entry["Z"] = entry["Z"][self.foldid] curr_entry["Y"] = entry["Y"][self.foldid] curr_entry["I"] = entry["I"][self.foldid] return curr ############################### ''' pass curr = self.results.setdefault(targetname,{}).setdefault(self.foldid,{}).setdefault(step,{}) submodel = self._get_submodel(cost, i) status = self._calc_status(step, submodel, float(tloss[i]), tZ[:,i*Ydim:(i+1)*Ydim], tY[:,i*Ydim:(i+1)*Ydim], tI, float(vloss[i]) if vloss is not None else None, vZ[:,i*Ydim:(i+1)*Ydim] if vloss is not None else None, vY[:,i*Ydim:(i+1)*Ydim] if vloss is not None else None, vI) submodel = None sm.sync() gc.collect() # Compare it to the best we've found so far, if any #curr = self.results.setdefault(targetname,{}).setdefault(self.foldid,{}).setdefault(step,{}) #if curr: # perfkey = "va" if vloss is not None else "tr" # if curr ''' ''' def _calc_status(self, step, model, tloss, tZ, tY, tI, vloss, vZ, vY, vI, **kwargs): if tI is not None: p = np.argsort(tI.ravel()) tZ = tZ[p,:] tY = tY[p,:] tI = tI[p,:] if vI is not None: p = np.argsort(vI.ravel()) vZ = vZ[p,:] vY = vY[p,:] vI = vI[p,:] # Build a short string describing the current state txt = "" if step is not None: txt += "%06d:" % step if tloss is not None: txt += "\t tloss=%.8f" % tloss if vloss is not None: txt += "\t vloss=%.8f" % vloss for key,val in kwargs.iteritems(): txt += "\t%s=%s\t " % tloss for i in range(tY.shape[1]): tZi = tZ[:,i:i+1] tYi = tY[:,i:i+1] tMi = ~np.isnan(tYi) tpearson = scipy.stats.pearsonr(tZi[tMi],tYi[tMi]) tspearman = scipy.stats.spearmanr(tZi[tMi],tYi[tMi]) tauc = bootstrap_auc(tZi[tMi],tYi[tMi]) txt += "\t tp%02d=%.3f (%g)" % (i,tpearson[0],tpearson[1]) txt += "\t ts%02d=%.3f (%g)" % (i,tspearman[0],tspearman[1]) txt += "\t ta%02d=%.3f (%g)" % (i,tauc[0],tauc[1]) if vY is not None: vZi = vZ[:,i:i+1] vYi = vY[:,i:i+1] vMi = ~np.isnan(vYi) vpearson = scipy.stats.pearsonr(vZi[vMi],vYi[vMi]) vspearman = scipy.stats.spearmanr(vZi[vMi],vYi[vMi]) vauc = bootstrap_auc(vZi[vMi],vYi[vMi]) txt += "\t vp%02d=%.3f (%g)" % (i,vpearson[0],vpearson[1]) txt += "\t vs%02d=%.3f (%g)" % (i,vspearman[0],vspearman[1]) txt += "\t va%02d=%.3f (%g)" % (i,vauc[0],vauc[1]) # If such state was provided, append it to our file. if txt != "": mode = "w" if self.entries == [] else "a" with open(self.filename,mode) as f: f.write(txt+"\n") images = self.extract_filters(model) if "store_featuremaps" in globals.flags else None entry = {} if step is not None: entry['step'] = step if tloss is not None: entry['tloss'] = tloss if tloss is not None: entry['tauc'] = tauc if tZ is not None: entry['tZ'] = tZ if tY is not None: entry['tY'] = tY if tI is not None: entry['tI'] = tI if vloss is not None: entry['vloss'] = vloss if vloss is not None: entry['vauc'] = vauc if vZ is not None: entry['vZ'] = vZ if vY is not None: entry['vY'] = vY if vI is not None: entry['vI'] = vI if images is not None: entry['images'] = images entry.update(kwargs) self.entries.append(entry) ''' ''' @staticmethod def merge_reports(logfile_pattern, task_ids, sample_ids, reports): merged = reports[0].__class__(logfile_pattern, task_ids, sample_ids) for i in range(len(sample_ids)): kwargs = {} for key in ("tZ","tY","tI","vZ","vY","vI"): if key in reports[0].subreports[0].entries[-1]: kwargs[key] = np.vstack([r.subreports[i].entries[-1][key] for r in reports]) else: kwargs[key] = None merged.subreports[i].update(step=None, model=None, tloss=None, vloss=None, **kwargs) return merged @staticmethod def shutdown(): import _tkinter as tk tk.quit() def update(self, step, cost, tdata, vdata): tloss,tZ,tY,tI = _calc_performance_stats(cost,tdata) vloss,vZ,vY,vI = _calc_performance_stats(cost,vdata) if vdata is not None else (None,None,None,None) assert tY.shape[1] % tloss.size == 0 Ydim = tY.shape[1] // tloss.size for i in range(len(self.sample_ids)): model_i = copy.deepcopy(cost.model) sm.sync() model_i.slice_inst(i) sm.sync() # Slice the trainable weights self.subreports[i].update(step, model_i, float(tloss[i]), tZ[:,i*Ydim:(i+1)*Ydim], tY[:,i*Ydim:(i+1)*Ydim], tI, float(vloss[i]) if vloss is not None else None, vZ[:,i*Ydim:(i+1)*Ydim] if vloss is not None else None, vY[:,i*Ydim:(i+1)*Ydim] if vloss is not None else None, vI) model_i = None sm.sync() gc.collect() tauc = None vauc = None if Ydim == 1: tauc = np.zeros(len(self.sample_ids)) if vloss is not None: vauc = np.zeros(len(self.sample_ids)) for i in range(len(self.sample_ids)): tauc[i] = calc_auc(tZ[:,i].ravel(), tY[:,i].ravel()) if vloss is not None: vauc[i] = calc_auc(vZ[:,i].ravel(), vY[:,i].ravel()) return tloss,vloss,tauc,vauc def dump(self, **kwargs): for subrep in self.subreports: subrep.dump(**kwargs) '''
DeepBind-master
code/libs/deepity/deepity/report.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # import os import copy import logging import tempfile import cPickle as pickle import numpy as np import numpy.random as npr import smat as sm from .util import tic,toc from os.path import join,basename,splitext,exists def _default_augmented(data): return data class datasource(object): """ A datasource provides sliced views into a dataset. For example, it might be used like >>> chunk = my_datasource[first:last] >>> chunk.Y array([[...]]) # array of training targets A subclass may store the data itself in host memory, in device memory, synthesized, or even paged from disk. If the subclass items contain attribute "Y", it is assumed to be be training targets, stored as an N x (M*numtargets) numpy array where M is the dimensionality """ def __init__(self, input_attrs, output_attrs, extra_attrs=None): self._input_attrs = input_attrs self._output_attrs = output_attrs self._extra_attrs = extra_attrs self._data_attrs = input_attrs + output_attrs self._all_attrs = input_attrs + output_attrs if extra_attrs: self._all_attrs = self._all_attrs + extra_attrs self.__dict__.update({ name : None for name in self._data_attrs }) if not hasattr(self,"targetnames"): self.targetnames = ["Target"] self.augmented = _default_augmented def input_attrs(self): return self._input_attrs def output_attrs(self): return self._output_attrs def data_attrs(self): return self._data_attrs def input_data(self): return { key : getattr(self,key) for key in self._input_attrs } def output_data(self): return { key : getattr(self,key) for key in self._output_attrs } def data(self): return { key : getattr(self,key) for key in self._data_attrs } def attrdim(self,attrname): raise NotImplementedError("Subclass should implement attrdim().") def open(self): # Subclass should treat this function as a request to 'open' # the database and get it ready for use. raise NotImplementedError("Subclass should implement open().") def __len__(self): # Subclass should return the number of individual training examples. raise NotImplementedError("Subclass should implement __len__.") def __getitem__(self, indices): # Subclass should return a datasource instance that contains one attribute for each input. # If the object has an attribute "Y", then that will be used as targets during # any training task. raise NotImplementedError("Subclass should implement __getitem__.") def dump_preprocessors(self, outdir, cols=None): return def shuffle(self): raise NotImplementedError("Subclass did not implement shuffle.") def asbatches(self, batchsize=256): # Subclass should return a new object, where that object's __getitem__[i] # returns minibatch #i, rather than an individual item. # Needed for use with batch-based trainers, like SGD. # If use_smat is True, then the resulting batches should be # converted to an smat.sarray intance, rather than numpy.ndarrays. raise NotImplementedError("Subclass did not implement asbatches.") def astargets(self, targetnames): # For multi-task learning, this raise NotImplementedError("Subclass did not implement astargets.") def split(self, index=0, nsplit=1): # Returns two datasources, A and B, split in a way # that is useful for k-fold cross validation (k = nsplit+1). # Suppose we had 10 samples: # 0,1,2,3,4,5,6,7,8,9 # then split() produces # A = 0,1,2,3,4 # B = 5,6,7,8,9 # whereas split(1) produces the reverse # A = 5,6,7,8,9 # B = 0,1,2,3,4 # and, similarly, split(1,3) produces an approximate # 3-way split # A = 0,1,2,6,7,8,9 # B = 3,4,5 # Split A is always the larger of the two splits. assert index <= nsplit if nsplit > 0: size = len(self) at = [int(x) for x in np.linspace(0, size, nsplit+1+1)] rindex = nsplit-index sliceB = slice(at[rindex],at[rindex+1]) sliceA1 = slice(at[0],at[rindex]) sliceA2 = slice(at[rindex+1],at[-1]) #print sliceB, sliceA1, sliceA2 #splitsize = size // (nsplit+1) #sliceA1 = slice(0,(nsplit-index)*splitsize) #sliceA2 = slice((nsplit-index+1)*splitsize,size) #sliceB = slice(sliceA1.stop,sliceA2.start) return self._split(sliceA1,sliceA2,sliceB) return self,None def _split(self, sliceA1, sliceA2, sliceB): # Subclass should implement the rest of split() raise NotImplementedError("Subclass did not implement split.") ###################################################################### class resident_datasource(datasource): """ A datasource that can be stored completely in host memory. That means it is straight-forward to support arbitrary slicing, or loading/saving, of the dataset. """ def __init__(self, input_attrs, output_attrs, extra_attrs=None, join=None): super(resident_datasource,self).__init__(input_attrs, output_attrs, extra_attrs) self.join = join def attrdim(self,attrname): attr = getattr(self,attrname) if isinstance(attr,np.ndarray): dim = attr.shape[1] if attr.ndim > 1 else 1 elif isinstance(attr,list): dim = 1 else: raise NotImplementedError("Cannot determine dimension of datasource attribute %s" %attrname) if attrname in self._output_attrs: assert dim % self.ntask() == 0 dim /= self.ntask() return dim def __len__(self): return len(self.X) def __getitem__(self, i): newsrc = copy.copy(self) for name in newsrc._all_attrs: oldattr = getattr(newsrc, name) if isinstance(oldattr, np.ndarray): newval = oldattr[i,:] setattr(newsrc, name, newval) # Replace newsrc.X with newsrc.X[i] elif isinstance(oldattr, list): if isinstance(i,slice): newval = oldattr[i] else: newval = [oldattr[x] for x in i] setattr(newsrc, name, newval) return newsrc def shuffle(self, perm=None): if perm is None: perm = npr.permutation(len(self)) for name in self._all_attrs: attr = getattr(self, name) if isinstance(attr,np.ndarray): attr[:] = attr[perm] # Permute the rows elif isinstance(attr,list): setattr(self, name, [attr[i] for i in perm]) else: raise NotImplementedError("Unrecognized attribute type %s for attribute %s" % (type(attr), name)) def _split(self, sliceA1, sliceA2, sliceB): # For A, we must vertically stack the A1 and A2 portions of each attribute A = copy.copy(self) for name in A._all_attrs: oldattr = getattr(A,name) if isinstance(oldattr,np.ndarray): newval = np.vstack((oldattr[sliceA1,:],oldattr[sliceA2,:])) setattr(A,name,newval) # Replace A.X with vstack(A.X[A1],A.X[A2]) elif isinstance(oldattr,list): newval = oldattr[sliceA1] + oldattr[sliceA2] setattr(A,name,newval) # Replace A.X with A.X[A1]+A.X[A2] else: raise NotImplementedError("Unrecognized attribute type %s for attribute %s" % (type(oldattr), name)) # For B, we can just directly return contiguous sliceB B = self[sliceB] return A,B def astargets(self, targetnames): # Returns a *shallow* copy of the datasource, where the original targets # are now swapped out for some new, derived targets. This is used # during hyperparameter search, when there are several models being # trained in parallel, each on an arbitrary column slice of the original # matrix of targets Y. # Create a shallow copy, and replace the OUTPUT attribute with our new arrangement of columns # First, compute the number of targets we currently have, and the number of columns for each target newsrc = copy.copy(self) ntarget = len(self.targetnames) if ntarget == 0: return newsrc assert self.Y.shape[1] % ntarget == 0, "Number of target columns was not divisible by number of targets!" targetsize = self.Y.shape[1] // ntarget # Then, compute a list of column indices that will replicate/slice the columns of the current targets targetidx = [self.targetnames.index(name) for name in targetnames] cols = np.repeat(targetidx, targetsize)*targetsize # If targetidx=[0,1,3,4] and targetsize=3 this gives [0,0,0,3,3,3,9,9,9,12,12,12] cols += np.tile(np.arange(targetsize),len(targetnames)) # ... which then gets turned into [0,1,2,3,4,5,9,10,11,12,13,14] # Create a shallow copy where the newsrc.targetnames = targetnames if hasattr(newsrc,"targets"): newsrc.targets = self.targets[:,cols].copy() if hasattr(newsrc,"Ymask"): newsrc.Ymask = self.Ymask[:,cols].copy() newsrc.Y = self.Y[:,cols].copy() return newsrc def convert_to_sarray(self): # Upload the data to a GPU device for name in self._data_attrs: oldattr = getattr(self,name) setattr(self,name,sm.asarray(oldattr)) def asbatches(self, batchsize=64, reshuffle=False): # By default, create a bunch of tiny resident_datasource instances, # and upload each to the GPU as we go. n = len(self) assert n > 0 nbatch = (n + batchsize - 1) // batchsize batches = [] for i in range(nbatch): idx = np.arange(i*batchsize,min(n,(i+1)*batchsize)) batch = self[idx] batch.convert_to_sarray() batches.append(batch) return shuffled_repeat_iter(batches, reshuffle) def close(self): #for attr in self._all_attrs: # delattr(self,attr) return # Return a wrapper around our list of batches. # The wrapper will keep serving batches forever, # cycling through the list, and shuffling the order # each time it starts a new pass. class shuffled_repeat_iter(object): """ Repeated traversal over a list of items, where the order is re-shuffled for each pass through the items. """ def __init__(self, items, reshuffle): self._items = items self._reshuffle = reshuffle self._order = np.arange(len(self._items)) self._index = len(items) def __len__(self): return len(self._items) def __getitem__(self,i): return self._items[i] def __iter__(self): return self._items.__iter__() def shuffle(self): np.random.shuffle(self._order) def curr(self): if self._index == len(self._items): if self._reshuffle: np.random.shuffle(self._order) self._index = 0 return self._items[self._order[self._index]] def next(self): item = self.curr() self._index += 1 return item ############################################## def make_predictions(model,datasrc): if isinstance(datasrc,datasource): datasrc = datasrc.asbatches(128) results = {} for batch in datasrc: args = batch.input_data() result = model.eval(**args) for key,val in result.iteritems(): if not key in results: results[key] = [] results[key].append(result[key].asnumpy()) for key,val in results.iteritems(): results[key] = np.vstack(results[key]) return results def count_errors(model,datasrc): # If model.ninst > datasrc.ntask, then that means multiple models # were trained on the original data, so we need to replicate the task. # For each task, we generate model.ninst/data.ntask copies if isinstance(datasrc,datasource): datasrc = datasrc.asbatches(128) Z = make_predictions(model,datasrc)["Z"] Y = np.vstack([sm.asnumpy(batch.Y) for batch in datasrc]) error_counts = [] for i in range(model.ninst): s = slice(i*Z.shape[1]//model.ninst,(i+1)*Z.shape[1]//model.ninst) count = np.sum(np.argmax(Z[:,s],axis=1) != np.argmax(Y[:,s],axis=1)) error_counts.append(count) error_counts = np.asarray(error_counts) return error_counts
DeepBind-master
code/libs/deepity/deepity/data.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # # DO NOT IMPORT THIS MODULE # It is meant to be spawned by report.py as a separate process, # in order to avoid problems using matplotlib from within child # processes of the multiprocessing module # (crashing on exit; instability in subsequent child processes) import os import os.path import sys import copy import glob import re import numpy as np import argparse import cPickle import tape2logo sys.path.append("libs/smat/py") sys.path.append("libs/deepity") sys.path.append("libs/kangaroo") import deepity import kangaroo from PIL import Image from PIL import ImageDraw from PIL import ImageFont import time import matplotlib matplotlib.rcParams.update({'font.size': 9, 'font.family': 'sans serif', 'text.usetex' : False, 'figure.max_num_figures' : 100}) if (not os.environ.has_key("DISPLAY")) and (not os.environ.has_key("HOMEDRIVE")): matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter from matplotlib import colors as colors from matplotlib import cm from matplotlib.figure import Figure gridimg_pal_RedBlue = matplotlib.colors.LinearSegmentedColormap('RedBlue', { 'red': ((0.00, 0.0, 0.0), (0.50, 1.0, 1.0), (1.00, 1.0, 1.0)), 'green': ((0.00, 0.0, 0.0), (0.50, 1.0, 1.0), (1.00, 0.0, 0.0)), 'blue': ((0.00, 1.0, 1.0), (0.50, 1.0, 1.0), (1.00, 0.0, 0.0)), },gamma =1.0)(np.arange(256)) gridimg_pal = np.asarray(gridimg_pal_RedBlue[:,:3]*255, dtype=np.uint8) gridimg_pal_Red = matplotlib.colors.LinearSegmentedColormap('Red', { 'red': ((0.00, 1.0, 1.0), (1.00, 1.0, 1.0)), 'green': ((0.00, 1.0, 1.0), (1.00, 0.0, 0.0)), 'blue': ((0.00, 1.0, 1.0), (1.00, 0.0, 0.0)), },gamma =1.0)(np.arange(256)) gridimg_pal_positive = np.asarray(gridimg_pal_Red[:,:3]*255, dtype=np.uint8) _image_grid_font = ImageFont.truetype(os.path.abspath(os.path.dirname(__file__))+"/arial.ttf", 9) #_image_grid_font = ImageFont.load_default() import scipy import scipy.misc import scipy.stats import warnings #warnings.simplefilter('error', UserWarning) def calc_auc(z,y, want_curve = False): assert len(z) == len(y) ymin = y.min() ymax = y.max() lo = (0.02-0) / (1.0 - 0.0) * (ymax-ymin) + ymin hi = (0.10-0) / (1.0 - 0.0) * (ymax-ymin) + ymin mlo = y<=lo mhi = y>=hi y[mlo] = 0 y[mhi] = 1 y[np.logical_and(mlo,mhi)] = np.nan m = ~np.isnan(y) y = y[m] z = z[m] order = np.argsort(z,axis=0)[::-1].ravel() # Sort by decreasing order of prediction strength z = z[order] y = y[order] npos = np.count_nonzero(y) # Total number of positives. nneg = len(y)-npos # Total number of negatives. if nneg == 0 or npos == 0: return (1,None) if want_curve else 1 n = len(y) fprate = np.zeros((n+1,1)) tprate = np.zeros((n+1,1)) ntpos,nfpos = 0.,0. for i,yi in enumerate(y): if yi: ntpos += 1 else: nfpos += 1 tprate[i+1] = ntpos/npos fprate[i+1] = nfpos/nneg auc = np.trapz(tprate,fprate,axis=0) if want_curve: curve = np.hstack([fprate,tprate]) return auc,curve return auc def makepath(dir): """ Makes a complete path if it does not exist already. Does not remove any existing files. Fixes periodic failure of os.makedirs on Windows. """ if os.path.exists(dir): return dir retries = 8 while retries >= 0: try: time.sleep(0.001) os.makedirs(dir) retries = -1 except Exception, e: if retries == 0: raise else: retries -= 1 return dir ##################################################################### class filter_images(object): def __init__(self,F,per_image_scale=False,symmetric_range=True): assert len(F.shape) == 3 # (size_y,size_x,num_filters) # Get information about shape and range of filter elements self.vmean = F.reshape((F.shape[0],-1)).mean(axis=1).reshape((-1,1,1)) self.vmin = F.reshape((F.shape[0],-1)).min(axis=1).reshape((-1,1,1)) self.vmax = F.reshape((F.shape[0],-1)).max(axis=1).reshape((-1,1,1)) if symmetric_range: self.vmax = np.maximum(abs(self.vmin),abs(self.vmax)) self.vmin = -self.vmax self.vranges = [(F[i,:,:].min(), F[i,:,:].max()) for i in range(F.shape[0])] # Convert filters to images self.raw = F I = F.copy() if per_image_scale: I -= self.vmin I *= 1./(self.vmax-self.vmin) else: I -= self.vmin.min() I *= 1./(self.vmax.max()-self.vmin.min()) I = np.maximum(0,I) I = np.minimum(1,I) I *= 255 I = np.uint8(I) self.images = I def __len__(self): return self.images.shape[0] def __getitem__(self,i): return self.images[i,:,:] def __iter__(self): return [self.images[i,:,:] for i in range(len(self))].__iter__() def zoom(self, factor): self.images = np.repeat(self.images,factor,1) self.images = np.repeat(self.images,factor,2) def zoom_smooth(self, factor): I = self.images Z = np.zeros((I.shape[0],I.shape[1]*factor,I.shape[2]*factor), dtype=I.dtype) for i in range(len(I)): img = Image.fromarray(I[i]) img = img.resize((int(img.size[0]*factor),int(img.size[1]*factor)), Image.ANTIALIAS) Z[i,:,:] = np.array(img) self.images = Z def L2RGB(I,cmap): I = scipy.misc.toimage(I, pal=cmap).convert("RGBA") return np.array(I) def addborder(I, color=0): I = np.vstack([color*np.ones_like(I[:1,:,:]), I, color*np.ones_like(I[:1,:,:])]) I = np.hstack([color*np.ones_like(I[:,:1,:]), I, color*np.ones_like(I[:,:1,:])]) return I def image_grid(fimgs, maxwd = 6000, maxht = 5000, cmap=None, fade=False, positive=False): I = fimgs.images max_vmax = fimgs.vmax.max() min_vmin = fimgs.vmin.min() if cmap is None: cmap = np.repeat(np.arange(256).reshape((-1,1)),3) n,fht,fwd = I.shape[:3] # n = number of features if fwd > maxwd or fht > maxht: print "image larger than maximum size allowed" return None is_logo = (len(I.shape) == 4) #if not is_logo: fwd += 2 # border fht += 2 # border idwd = 20 decwd = 12 txtwd = 48 wd = idwd+decwd+fwd+txtwd ht = fht maxrows = min(int(maxht-1)//(ht+1), n) # How many images can stack on top of each other? (-1 / +3 because of 1 pixel border and 1 pixel cell padding) maxcols = min(int(maxwd-1)//(wd+1), (n+maxrows-1)//maxrows) # Start from a blank white image G = np.ones(((ht+1)*maxrows-1,(wd+1)*maxcols-1,4),dtype=I.dtype) if G.dtype == np.uint8: G *= 255 # Copy each image into a spot in the grid for i in range(n): col = i // maxrows row = i % maxrows if col >= maxcols: break x0 = col*(wd+1) y0 = row*(ht+1) if is_logo: F = I[i,:,:,:].copy() else: F = L2RGB(I[i,:,:], cmap) F = addborder(F) rmin,rmax = fimgs.vranges[i] mid = ht//2 hi = float(max(0, rmax)) / abs(max_vmax) lo = float(max(0,-rmin)) / abs(min_vmin) if not positive else 0 #if positive: # F[1:-1,1:-1] = 255-F[1:-1,1:-1] if fade and hi <= 0.1 and lo <= 0.1: F = 192 + F//4 # Fade out anything that's extremely weak, so that user's attention is drawn to the other filters. hi = int((mid-1) * hi + 0.5) lo = int((mid-1) * lo + 0.5) img = np.hstack([255*np.ones((ht,idwd,4),np.uint8), F, 255*np.ones((ht,decwd+txtwd,4),np.uint8)]) # Draw a little vertical bar thingy to visually indicate magnitude of range # relative to other filters img[mid-hi:mid, idwd+fwd+3:idwd+fwd+decwd-3,:] = np.asarray([255,0,0,255]).reshape((1,1,4)) img[mid+1:mid+1+lo, idwd+fwd+3:idwd+fwd+decwd-3,:] = np.asarray([0,0,255,255]).reshape((1,1,4)) #img[mid,idwd+fwd+2:idwd+fwd+decwd-2,:] *= (1-max(float(rmax) / abs(max_vmax),float(-rmin) / abs(min_vmin)))**0.8 img = Image.fromarray(img) # convert to Image so that we can use ImageDraw draw = ImageDraw.Draw(img) draw.text((0,2),"%3d"%i,(200,200,200),font=_image_grid_font) if rmax != rmin and not positive: draw.text((idwd+decwd+F.shape[1]+0, 2),"%+.3f"%rmax,0,font=_image_grid_font) draw.text((idwd+decwd+F.shape[1]+2,13),"%+.3f"%rmin,0,font=_image_grid_font) else: draw.text((idwd+decwd+F.shape[1]+2, 2),"%+.3f"%rmax,0,font=_image_grid_font) img = np.array(img) # convert back to numpy G[y0:y0+ht,x0:x0+wd,:] = img return G def fimgs2logos(fimgs, finalheight, finalletterwidth): filters = fimgs.raw nfilter,_,fsize = filters.shape # n = number of filters logos = 255*np.ones((nfilter,finalheight,fsize*finalletterwidth,4), np.uint8) limgs = copy.deepcopy(fimgs) limgs.images = logos for k in range(nfilter): logos[k,:,:,:] = tape2logo.tape2logo(filters[k,:,:], finalheight, finalletterwidth, 5) return limgs def reverse_complement_weights(W): W = W[:,:,::-1] W = W[:,[3,2,1,0],:] return W dpi = 80.0 ######################################################## def unpack_model(pklfile, args): outdir = os.path.dirname(pklfile) with open(pklfile) as f: model = cPickle.load(f) weightnodes = {} def collect_filters(path,obj): if hasattr(obj,"getfilters"): F = obj.getfilters() if F is not None: weightnodes[path] = F model.visit(collect_filters) if len(weightnodes) == 0: return zoom = args.zoom for name,weights in weightnodes.iteritems(): name = "model"+name.replace("[","(").replace("]",")") is_conv = (".conv_" in name and weights.shape[-1] > 1) # convnet filters treated differently. # First, generate if is_conv: # Save colourized filters fimgs = filter_images(weights, per_image_scale=True) fimgs.zoom(max(1,12//fimgs.images.shape[1])) if args.pub: fimgs.zoom_smooth(12*zoom) #fimgs.zoom_smooth(0.5) else: fimgs.zoom_smooth(4*zoom) fimgs.zoom_smooth(0.5) #fimgs.zoom(max(1,24//fimgs.images.shape[1])) scipy.misc.imsave(outdir+"/"+name+".color.png",image_grid(fimgs, cmap=gridimg_pal, fade=True)) # Save black and white filters if args.greyscale: fimgs = filter_images(weights, per_image_scale=True) if args.pub: fimgs.zoom(max(1,48//fimgs.images.shape[1])) else: fimgs.zoom(max(1,24//fimgs.images.shape[1])) scipy.misc.imsave(outdir+"/"+name+".grey.png",image_grid(fimgs, fade=True)) logoheight, letterwd = 41, 6 weights -= (np.sort(weights, axis=1)[:,1:2,:] + np.sort(weights, axis=1)[:,2:3,:])/2 #weights -= np.sort(weights, axis=1)[:,1:2,:] # Subtract off the second-smallest value in each column #weights -= weights.min(axis=1).reshape((weights.shape[0],1,weights.shape[2])); logoheight = 24 logoheight = int(round(zoom*logoheight)) letterwd = int(round(zoom*letterwd)) fwdlogo = fimgs2logos(filter_images(weights, per_image_scale=True), logoheight, letterwd) #revlogo = fimgs2logos(filter_images(reverse_complement_weights(weights), per_image_scale=True), logoheight, letterwd) fwdlogo = image_grid(fwdlogo, fade=True) #revlogo = image_grid(revlogo, fade=True) fwdtitle = Image.fromarray(255*np.ones((20,fwdlogo.shape[1],3),np.uint8)); ImageDraw.Draw(fwdtitle).text((20,2),"actual",(0,0,0),font=_image_grid_font) #revtitle = Image.fromarray(255*np.ones((20,revlogo.shape[1],3),np.uint8)); ImageDraw.Draw(revtitle).text((20,2),"reverse complement",(0,0,0),font=_image_grid_font) scipy.misc.imsave(outdir+"/"+name+".logo.png", fwdlogo) #scipy.misc.imsave(outdir+"/"+name+".logo.png", np.hstack([np.vstack([np.array(fwdtitle), fwdlogo]), np.vstack([np.array(revtitle), revlogo])])) else: # Save colourized weight maps fimgs = filter_images(weights, per_image_scale=False) fimgs.zoom(max(1,12//fimgs.images.shape[1])) scipy.misc.imsave(outdir+"/"+name+".png",image_grid(fimgs, cmap=gridimg_pal)) def save_predict_plot(args, filename, targetname, y, z): fig = plt.figure(figsize=(300/dpi,300/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=False) ax = fig.add_axes([0.14,0.14,.74,.74]) ybar = fig.add_axes([0.89, 0.14, 0.11, 0.74]) keep = ~np.isnan(y) y = y[keep] z = z[keep] lo = min(y.min(),z.min()) hi = max(y.max(),z.max()) aximg = ax.hist2d(y,z,bins=200,range=[[lo-.05,hi+.05],[lo-.05,hi+.05]],cmap=cm.hot,cmin=1)[3] ybar.hist(z, bins=50, orientation='horizontal', histtype='bar', cumulative=False, color=[0.0,0.0,1.0], range=[lo-0.05, hi+0.05], edgecolor="none") ybar.set_ylim([lo-0.05, hi+0.05]) ybar.axis("off") ax.set_title(targetname) ax.set_xlabel("target") ax.set_ylabel("prediction") if args.pub: filename = filename.rsplit(".")[0]+".pdf" fig.savefig(filename,dpi=dpi) del fig plt.close() def save_auc_plot(args, filename, targetname, y, z): m = ~np.isnan(y) y = y[m] z = z[m] if not (np.all(y>=0) and np.all(y<=1)): return auc,curve = calc_auc(z, y, want_curve=True) if curve is None: return xval = curve[:,0] yval = curve[:,1] fig = plt.figure(figsize=(300/dpi,300/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=False) ax = fig.add_axes([0.18,0.1,.8,.8]) ax.plot(xval,yval,'-r') ax.set_title(targetname) ax.set_xlabel("false positive rate") ax.set_ylabel("true positive rate") if args.pub: filename = filename.rsplit(".")[0]+".pdf" fig.savefig(filename, dpi=dpi) del fig plt.close() def unpack(path, args): if path.endswith("model.pkl"): unpack_model(path, args) if path.endswith("predict.npz"): unpack_predict(path, args) def unpack_predict(npzfile, args): outdir = os.path.dirname(npzfile) groups = np.load(npzfile)['groups'][()] targetname = np.load(npzfile)['targetname'][()] # Dump the prediction/target scatterplots for groupname, group in groups.iteritems(): y = group["Y"][:,0] # Just take the first column, assume single-dimensional output z = group["Z"][:,0] save_predict_plot(args, outdir+"/predict.scatter-%s.png"%(groupname), targetname, y, z) save_auc_plot(args, outdir+"/predict.auc-%s.png"%(groupname), targetname, y, z) args = argparse.ArgumentParser(description="Unpack a \"model.pkl\" and \"predict.npz\" and visualize their contents (filters, AUC curves, etc)") args.add_argument("path", type=str, help="A report.npz file, or a directory to search.") args.add_argument("-p,","--pub", action="store_true", help="Output publication-quality figures.") args.add_argument("-g,","--greyscale", action="store_true", help="Output greyscale filters in addition to the red/blue color ones.") args.add_argument("-z","--zoom", type=float, default=1, help="Zoom factor relative to default size; for generating print-quality bitmaps.") args = args.parse_args() if not os.path.exists(args.path): quit("Cannot find file \"%s\"."%args.path) if os.path.isdir(args.path): for dirpath, dirnames, filenames in os.walk(args.path): for filename in filenames: unpack(os.path.join(dirpath, filename), args) else: unpack(args.path, args)
DeepBind-master
code/libs/deepity/deepity/dumpviz.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # from __future__ import absolute_import, division import time import os from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked class SQLiteLockFile(LockBase): "Demonstrate SQL-based locking." testdb = None def __init__(self, path, threaded=True): """ >>> lock = SQLiteLockFile('somefile') >>> lock = SQLiteLockFile('somefile', threaded=False) """ LockBase.__init__(self, path, threaded) self.lock_file = unicode(self.lock_file) self.unique_name = unicode(self.unique_name) if SQLiteLockFile.testdb is None: import tempfile _fd, testdb = tempfile.mkstemp() os.close(_fd) os.unlink(testdb) del _fd, tempfile SQLiteLockFile.testdb = testdb import sqlite3 self.connection = sqlite3.connect(SQLiteLockFile.testdb) c = self.connection.cursor() try: c.execute("create table locks" "(" " lock_file varchar(32)," " unique_name varchar(32)" ")") except sqlite3.OperationalError: pass else: self.connection.commit() import atexit atexit.register(os.unlink, SQLiteLockFile.testdb) def acquire(self, timeout=None): end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout if timeout is None: wait = 0.1 elif timeout <= 0: wait = 0 else: wait = timeout / 10 cursor = self.connection.cursor() while True: if not self.is_locked(): # Not locked. Try to lock it. cursor.execute("insert into locks" " (lock_file, unique_name)" " values" " (?, ?)", (self.lock_file, self.unique_name)) self.connection.commit() # Check to see if we are the only lock holder. cursor.execute("select * from locks" " where unique_name = ?", (self.unique_name,)) rows = cursor.fetchall() if len(rows) > 1: # Nope. Someone else got there. Remove our lock. cursor.execute("delete from locks" " where unique_name = ?", (self.unique_name,)) self.connection.commit() else: # Yup. We're done, so go home. return else: # Check to see if we are the only lock holder. cursor.execute("select * from locks" " where unique_name = ?", (self.unique_name,)) rows = cursor.fetchall() if len(rows) == 1: # We're the locker, so go home. return # Maybe we should wait a bit longer. if timeout is not None and time.time() > end_time: if timeout > 0: # No more waiting. raise LockTimeout else: # Someone else has the lock and we are impatient.. raise AlreadyLocked # Well, okay. We'll give it a bit longer. time.sleep(wait) def release(self): if not self.is_locked(): raise NotLocked if not self.i_am_locking(): raise NotMyLock((self._who_is_locking(), self.unique_name)) cursor = self.connection.cursor() cursor.execute("delete from locks" " where unique_name = ?", (self.unique_name,)) self.connection.commit() def _who_is_locking(self): cursor = self.connection.cursor() cursor.execute("select unique_name from locks" " where lock_file = ?", (self.lock_file,)) return cursor.fetchone()[0] def is_locked(self): cursor = self.connection.cursor() cursor.execute("select * from locks" " where lock_file = ?", (self.lock_file,)) rows = cursor.fetchall() return not not rows def i_am_locking(self): cursor = self.connection.cursor() cursor.execute("select * from locks" " where lock_file = ?" " and unique_name = ?", (self.lock_file, self.unique_name)) return not not cursor.fetchall() def break_lock(self): cursor = self.connection.cursor() cursor.execute("delete from locks" " where lock_file = ?", (self.lock_file,)) self.connection.commit()
DeepBind-master
code/libs/deepity/deepity/_lockfile/sqlitelockfile.py
# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Author's note: # This file was distributed as part of the Nature Biotechnology # supplementary software release for DeepBind. Users of DeepBind # are encouraged to instead use the latest source code and binaries # for scoring sequences at # http://tools.genes.toronto.edu/deepbind/ # """ lockfile.py - Platform-independent advisory file locks. Requires Python 2.5 unless you apply 2.4.diff Locking is done on a per-thread basis instead of a per-process basis. Usage: >>> lock = LockFile('somefile') >>> try: ... lock.acquire() ... except AlreadyLocked: ... print 'somefile', 'is locked already.' ... except LockFailed: ... print 'somefile', 'can\\'t be locked.' ... else: ... print 'got lock' got lock >>> print lock.is_locked() True >>> lock.release() >>> lock = LockFile('somefile') >>> print lock.is_locked() False >>> with lock: ... print lock.is_locked() True >>> print lock.is_locked() False >>> lock = LockFile('somefile') >>> # It is okay to lock twice from the same thread... >>> with lock: ... lock.acquire() ... >>> # Though no counter is kept, so you can't unlock multiple times... >>> print lock.is_locked() False Exceptions: Error - base class for other exceptions LockError - base class for all locking exceptions AlreadyLocked - Another thread or process already holds the lock LockFailed - Lock failed for some other reason UnlockError - base class for all unlocking exceptions AlreadyUnlocked - File was not locked. NotMyLock - File was locked but not by the current thread/process """ import sys import socket import os import threading import time import urllib import warnings # Work with PEP8 and non-PEP8 versions of threading module. if not hasattr(threading, "current_thread"): threading.current_thread = threading.currentThread if not hasattr(threading.Thread, "get_name"): threading.Thread.get_name = threading.Thread.getName __all__ = ['Error', 'LockError', 'LockTimeout', 'AlreadyLocked', 'LockFailed', 'UnlockError', 'NotLocked', 'NotMyLock', 'LinkLockFile', 'MkdirLockFile', 'SQLiteLockFile', 'LockBase'] class Error(Exception): """ Base class for other exceptions. >>> try: ... raise Error ... except Exception: ... pass """ pass class LockError(Error): """ Base class for error arising from attempts to acquire the lock. >>> try: ... raise LockError ... except Error: ... pass """ pass class LockTimeout(LockError): """Raised when lock creation fails within a user-defined period of time. >>> try: ... raise LockTimeout ... except LockError: ... pass """ pass class AlreadyLocked(LockError): """Some other thread/process is locking the file. >>> try: ... raise AlreadyLocked ... except LockError: ... pass """ pass class LockFailed(LockError): """Lock file creation failed for some other reason. >>> try: ... raise LockFailed ... except LockError: ... pass """ pass class UnlockError(Error): """ Base class for errors arising from attempts to release the lock. >>> try: ... raise UnlockError ... except Error: ... pass """ pass class NotLocked(UnlockError): """Raised when an attempt is made to unlock an unlocked file. >>> try: ... raise NotLocked ... except UnlockError: ... pass """ pass class NotMyLock(UnlockError): """Raised when an attempt is made to unlock a file someone else locked. >>> try: ... raise NotMyLock ... except UnlockError: ... pass """ pass class LockBase: """Base class for platform-specific lock classes.""" def __init__(self, path, threaded=True): """ >>> lock = LockBase('somefile') >>> lock = LockBase('somefile', threaded=False) """ self.path = path self.lock_file = os.path.abspath(path) + ".lock" self.hostname = socket.gethostname() self.pid = os.getpid() if threaded: t = threading.current_thread() # Thread objects in Python 2.4 and earlier do not have ident # attrs. Worm around that. ident = getattr(t, "ident", hash(t)) self.tname = "-%x" % (ident & 0xffffffff) else: self.tname = "" dirname = os.path.dirname(self.lock_file) self.unique_name = os.path.join(dirname, "%s%s.%s" % (self.hostname, self.tname, self.pid)) def acquire(self, timeout=None): """ Acquire the lock. * If timeout is omitted (or None), wait forever trying to lock the file. * If timeout > 0, try to acquire the lock for that many seconds. If the lock period expires and the file is still locked, raise LockTimeout. * If timeout <= 0, raise AlreadyLocked immediately if the file is already locked. """ raise NotImplemented("implement in subclass") def release(self): """ Release the lock. If the file is not locked, raise NotLocked. """ raise NotImplemented("implement in subclass") def is_locked(self): """ Tell whether or not the file is locked. """ raise NotImplemented("implement in subclass") def i_am_locking(self): """ Return True if this object is locking the file. """ raise NotImplemented("implement in subclass") def break_lock(self): """ Remove a lock. Useful if a locking thread failed to unlock. """ raise NotImplemented("implement in subclass") def __enter__(self): """ Context manager support. """ self.acquire() return self def __exit__(self, *_exc): """ Context manager support. """ self.release() def _fl_helper(cls, mod, *args, **kwds): warnings.warn("Import from %s module instead of lockfile package" % mod, DeprecationWarning, stacklevel=2) # This is a bit funky, but it's only for awhile. The way the unit tests # are constructed this function winds up as an unbound method, so it # actually takes three args, not two. We want to toss out self. if not isinstance(args[0], str): # We are testing, avoid the first arg args = args[1:] if len(args) == 1 and not kwds: kwds["threaded"] = True return cls(*args, **kwds) def LinkFileLock(*args, **kwds): """Factory function provided for backwards compatibility. Do not use in new code. Instead, import LinkLockFile from the lockfile.linklockfile module. """ import linklockfile return _fl_helper(linklockfile.LinkLockFile, "lockfile.linklockfile", *args, **kwds) def MkdirFileLock(*args, **kwds): """Factory function provided for backwards compatibility. Do not use in new code. Instead, import MkdirLockFile from the lockfile.mkdirlockfile module. """ import mkdirlockfile return _fl_helper(mkdirlockfile.MkdirLockFile, "lockfile.mkdirlockfile", *args, **kwds) def SQLiteFileLock(*args, **kwds): """Factory function provided for backwards compatibility. Do not use in new code. Instead, import SQLiteLockFile from the lockfile.mkdirlockfile module. """ import sqlitelockfile return _fl_helper(sqlitelockfile.SQLiteLockFile, "lockfile.sqlitelockfile", *args, **kwds) if hasattr(os, "link"): import linklockfile as _llf LockFile = _llf.LinkLockFile else: import mkdirlockfile as _mlf LockFile = _mlf.MkdirLockFile FileLock = LockFile
DeepBind-master
code/libs/deepity/deepity/_lockfile/__init__.py