clip.py 4.7 KB
Newer Older
Y
Yu Yang 已提交
1 2
import functools
import layers
F
fengjiayi 已提交
3
from framework import Variable
F
fengjiayi 已提交
4
from . import core
Y
Yu Yang 已提交
5

F
fengjiayi 已提交
6 7 8
__all__ = [
    'GradientClipByValue', 'append_gradient_clip_ops', 'error_clip_callback'
]
Y
Yu Yang 已提交
9 10


F
fengjiayi 已提交
11
class BaseErrorClipAttr(object):
F
fengjiayi 已提交
12
    def append_clip_op(self, block, grad_name):
F
fengjiayi 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25
        raise NotImplementedError()


class ErrorClipByValue(BaseErrorClipAttr):
    def __init__(self, max, min=None):
        max = float(max)
        if min is None:
            min = -max
        else:
            min = float(min)
        self.max = max
        self.min = min

F
fengjiayi 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    def append_clip_op(self, block, grad_name):
        block.append_op(
            type="clip",
            inputs={"X": grad_name},
            outputs={"Out": grad_name},
            attrs={"min": self.min,
                   "max": self.max})


def error_clip_callback(block, context):
    # the context is a grad_to_var map
    grad_to_var = context
    op_desc = block.desc.op(block.desc.op_size() - 1)
    for grad_n in filter(lambda n: grad_to_var.has_key(n),
                         op_desc.output_arg_names()):
        fwd_var = block.var_recursive(grad_to_var[grad_n])
        error_clip = getattr(fwd_var, "error_clip", None)
        if error_clip is not None:
            error_clip.append_clip_op(block, grad_n)
F
fengjiayi 已提交
45 46


Y
Yu Yang 已提交
47
class BaseGradientClipAttr(object):
F
fengjiayi 已提交
48
    def process_context(self, context, param, grad):
Y
Yu Yang 已提交
49 50 51 52 53 54 55
        raise NotImplementedError()

    def create_operators(self, param, grad):
        raise NotImplementedError()


class NullGradientClipAttr(BaseGradientClipAttr):
F
fengjiayi 已提交
56
    def process_context(self, context, param, grad):
Y
Yu Yang 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
        pass

    def create_operators(self, param, grad):
        return param, grad


class GradientClipByValue(BaseGradientClipAttr):
    def __init__(self, max, min=None):
        max = float(max)
        if min is None:
            min = -max
        else:
            min = float(min)
        self.max = max
        self.min = min

F
fengjiayi 已提交
73
    def process_context(self, context, param, grad):
Y
Yu Yang 已提交
74 75 76 77 78 79 80
        pass

    def create_operators(self, param, grad):
        new_grad = layers.clip(x=grad, min=self.min, max=self.max)
        return param, new_grad


F
fengjiayi 已提交
81 82 83 84
class GradientClipByNorm(BaseGradientClipAttr):
    def __init__(self, clip_norm):
        self.clip_norm = clip_norm

F
fengjiayi 已提交
85
    def process_context(self, context, param, grad):
F
fengjiayi 已提交
86 87 88 89 90 91 92
        pass

    def create_operators(self, param, grad):
        new_grad = layers.clip_by_norm(x=grad, max_norm=self.clip_norm)
        return param, new_grad


F
fengjiayi 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
class GradientClipByGlobalNorm(BaseGradientClipAttr):
    global_norm_var = None
    clip_norm_var = None
    ratio_var = None

    @classmethod
    def init(cls, clip_norm):
        cls.global_norm_var = layers.fill_constant(
            shape=[1], dtype="float32", value=0.0)
        cls.clip_norm_var = layers.fill_constant(
            shape=[1], dtype="float32", value=clip_norm)

    def __init__(self):
        if not (isinstance(self.__class__.global_norm_var, Variable) and
                isinstance(self.__class__.clip_norm_var, Variable)):
            raise ValueError(
                "Class 'GradientClipByGlobalNorm' has not been properly initialized. Please call GradientClipByGlobalNorm.init() first."
            )

    def process_context(self, context, param, grad):
        local_norm_var = layers.reduce_sum(
            x=layers.pow(x=grad, factor=2), reduce_all=True)
        layers.sums(
            input=[local_norm_var, self.__class__.global_norm_var],
            out=[self.__class__.global_norm_var])

    def create_operators(self, param, grad):
        if self.__class__.ratio_var is None:
            self.__class__.global_norm_var = layers.sqrt(
                x=self.__class__.global_norm_var)
            self.__class__.ratio_var = layers.elementwise_div(
                x=self.__class__.clip_norm_var,
                y=layers.elementwise_max(
                    x=self.__class__.clip_norm_var,
                    y=self.__class__.global_norm_var))
        # 缺乏elementwise_max
        # 没法将ratio_var送给scale_op。
        # new_grad = layers.


Y
Yu Yang 已提交
133 134 135 136 137 138 139 140 141
def append_gradient_clip_ops(param_grad):
    context = dict()
    create_op_callbacks = []
    for p, g in param_grad:
        clip_attr = getattr(p, 'clip_attr', NullGradientClipAttr())
        if clip_attr is None:
            clip_attr = NullGradientClipAttr()
        if not isinstance(clip_attr, BaseGradientClipAttr):
            raise TypeError(
F
fengjiayi 已提交
142
                "clip attribute should be an instance of BaseGradientClipAttr")
Y
Yu Yang 已提交
143

F
fengjiayi 已提交
144
        clip_attr.process_context(context=context, param=p, grad=g)
Y
Yu Yang 已提交
145 146 147 148 149 150 151 152
        create_op_callbacks.append(
            functools.partial(
                clip_attr.create_operators, param=p, grad=g))

    return [each_callback() for each_callback in create_op_callbacks]


ClipByValue = GradientClipByValue