【问题标题】:Theano - how to override gradient for part of op graphTheano - 如何覆盖部分操作图的渐变
【发布时间】:2017-03-29 12:50:55
【问题描述】:

我手头有一个相当复杂的模型。该模型有多个具有线性结构的部分:

y = theano.tensor.dot(W,x) + b

我想构建一个优化器,它使用自定义规则来计算所有线性结构的梯度,同时保持其他操作不变。 为我的模型的所有线性部分覆盖渐变操作的最简单方法是什么?最好不需要编写新的操作。

【问题讨论】:

    标签: deep-learning theano


    【解决方案1】:

    所以,我花了一些时间为 Theano 开发 PR截至 2017 年 1 月 13 日未合并已经合并),它使用户能够部分覆盖 theano.OpFromGraph 实例的渐变.覆盖是使用符号图完成的,因此您仍然可以获得 theano 优化的全部好处。

    典型用例:

    • 数值安全考虑
    • 重新缩放/剪裁渐变
    • 像黎曼自然梯度这样的专业梯度程序

    制作一个具有压倒性渐变的操作:

    1. 制作所需的计算图
    2. 为 OpFromGraph 的梯度创建一个 OpFromGraph 实例(或 python 函数)
    3. 将 OfG 实例设为您的 Op,并设置 grad_overrides 参数
    4. 调用 OfG 实例来构建您的模型

    定义 OpFromGraph 就像编译一个 theano 函数,但有一些区别:

    • 不支持 updatesgivens(截至 2017 年 1 月)
    • 你得到一个符号 Op 而不是一个数值函数

    例子:

    '''
    This creates an atan2_safe Op with smoothed gradient at (0,0)
    '''
    import theano as th
    import theano.tensor as T
    
    # Turn this on if you want theano to build one large graph for your model instead of precompiling the small graph.
    USE_INLINE = False
    # In a real case you would set EPS to a much smaller value
    EPS = 0.01
    
    # define a graph for needed Op
    s_x, s_y = T.scalars('xy')
    s_darg = T.scalar(); # backpropagated gradient
    s_arg = T.arctan2(s_y, s_x)
    s_abs2 = T.sqr(s_x) + T.sqr(s_y) + EPS
    s_dx = -s_y / s_abs2
    s_dy = s_x / s_abs2
    
    # construct OfG with gradient overrides
    # NOTE: there are unused inputs in the gradient expression,
    #     however the input count must match, so we pass    
    #     on_unused_input='ignore'
    atan2_safe_grad = th.OpFromGraph([s_x, s_y, s_darg], [s_dx, s_dy], inline=USE_INLINE, on_unused_input='ignore')
    atan2_safe = th.OpFromGraph([s_x, s_y], [s_arg], inline=USE_INLINE, grad_overrides=atan2_safe_grad)
    
    # build graph using the new Op
    x, y = T.scalar(), T.scalar()
    arg = atan2_safe(x, y)
    dx, dy = T.grad(arg, [x, y])
    fn = th.function([x, y], [dx, dy])
    fn(1., 0.) # gives [-0.0, 0.99099]
    fn(0., 0.) # gives [0.0, 0.0], no more annoying nan!
    

    注意:theano.OpFromGraph 在很大程度上仍处于试验阶段,预计会有错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多