小武与tfpyth的碰撞----torch.autograd.Function进阶版本

由于工作需要,目前需要融合两个模型,但是两个模型的框架完全不一样,一个是pytorch一个是keras。头疼。
目前有两个确认可行的方案。

方案一:将其中一者的模型转化为另一框架,然后进行融合。遇到的问题在于两个模型都有预训练模型,所以如果这样的转换,模型可以复现,但是训练的参数怎么办呢?难道又要重新训练吗?

方案二:将一种一者的输出结果保存为h5,因为两个模型只是作为特征提取,而本身并不参与新模型的反向传播。但是问题在于,数据多了h5也多,而且非常不方便新模型的参数调整。

但是就在做这个工作一个月后出现了tfpyth. 或许有希望吧。所以记录下tfpyth的代码学习,看看别人是如何进行转换的。

def test_pytorch_in_tensorflow_eager_mode():
    tf.enable_eager_execution()
    tfe = tf.contrib.eager

    def pytorch_expr(a, b):
        return 3 * a + 4 * b * b

    x = tfpyth.eager_tensorflow_from_torch(pytorch_expr)

    assert tf.math.equal(x(tf.convert_to_tensor(1.0), tf.convert_to_tensor(3.0)), 39.0)

    dx = tfe.gradients_function(x)
    assert all(tf.math.equal(dx(tf.convert_to_tensor(1.0), tf.convert_to_tensor(3.0)), [3.0, 24.0]))
    tf.disable_eager_execution()

x = tfpyth.eager_tensorflow_from_torch(pytorch_expr) ,输入的是是一个函数。

**def eager_tensorflow_from_torch(func):
    """
    Wraps a PyTorch function into a TensorFlow eager-mode function (ie can be executed within Tensorflow eager-mode).

    :param func: Function that takes PyTorch tensors and returns a PyTorch tensor.
    :return: Differentiable Tensorflow eager-mode function.
    """

    @tf.custom_gradient
    def compute(*inputs):
        th_inputs = [th.tensor(tf_input.numpy(), requires_grad=True) for tf_input in inputs]
        th_output = func(*th_inputs)
        #输入的是tensorflow下的tensor, 先转化为pytorch下的tensor
        #经过func也就是前面的pytorch_expr,然后输出的也是pytorch 的tensor。
        
    
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是基于`torch.autograd.Function`实现`torch.nn.Linear`功能的示例代码: ```python import torch from torch.autograd import Function class LinearFunction(Function): @staticmethod def forward(ctx, input, weight, bias=None): ctx.save_for_backward(input, weight, bias) output = input.mm(weight.t()) if bias is not None: output += bias.unsqueeze(0).expand_as(output) return output @staticmethod def backward(ctx, grad_output): input, weight, bias = ctx.saved_tensors grad_input = grad_weight = grad_bias = None if ctx.needs_input_grad[0]: grad_input = grad_output.mm(weight) if ctx.needs_input_grad[1]: grad_weight = grad_output.t().mm(input) if bias is not None and ctx.needs_input_grad[2]: grad_bias = grad_output.sum(0) return grad_input, grad_weight, grad_bias class LinearLayer(torch.nn.Module): def __init__(self, input_size, output_size): super(LinearLayer, self).__init__() self.input_size = input_size self.output_size = output_size self.weight = torch.nn.Parameter(torch.Tensor(output_size, input_size)) self.bias = torch.nn.Parameter(torch.Tensor(output_size)) self.reset_parameters() def reset_parameters(self): torch.nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) torch.nn.init.uniform_(self.bias, -bound, bound) def forward(self, input): return LinearFunction.apply(input, self.weight, self.bias) ``` 在这个示例中,我们首先定义了一个名为`LinearFunction`的自定义函数,该函数继承自`torch.autograd.Function`。在这个函数中,我们实现了linear层的前向传播和反向传播逻辑。 接下来,我们定义了`LinearLayer`类,该类继承自`torch.nn.Module`。在类的构造函数中,我们创建了权重和偏置项参数,并使用`reset_parameters`方法对它们进行初始化。 在`forward`方法中,我们调用了`LinearFunction`的`apply`方法来完成linear层的前向传播。通过这种方式,我们可以将`LinearFunction`作为一个可调用的函数使用,并且它具有自动求导的能力。 你可以创建一个`LinearLayer`的实例,并将输入数据传递给它进行前向传播。希望这个示例能够帮助你理解如何基于`torch.autograd.Function`实现linear层的功能!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值