gpt4 book ai didi

python - Pytorch 中基于磁带的 autograd 是什么?

转载 作者:行者123 更新时间:2023-12-03 17:17:55 24 4
gpt4 key购买 nike

我明白 autograd用于暗示自动微分。但究竟是什么tape-based autogradPytorch以及为什么有这么多的讨论肯定或否定它。
例如:
this

In pytorch, there is no traditional sense of tape


this

We don’t really build gradient tapes per se. But graphs.


但不是 this

Autograd is now a core torch package for automatic differentiation. Ituses a tape based system for automatic differentiation.


如需进一步引用,请与 GradientTape 进行比较。在 Tensorflow .

最佳答案

有不同类型的自动微分,例如forward-mode , reverse-mode , hybrids ; ( more explanation )。 tape-based自动毕业在 Pytorch仅指的用途反向模式自动微分,source . 反向模式 auto diff 只是一种用于有效计算梯度的技术,它恰好被反向传播使用,source .

现在,在 PyTorch , Autograd 是自动微分的核心 Torch 包。它使用 tape-based系统 自动微分 .在正向阶段,autograd磁带会记住所有操作 它执行了,在向后阶段,它将 重播操作 .
同样在 TensorFlow ,要自动区分,还需要记住在前向传递过程中发生了什么操作以什么顺序发生。然后,在反向传递期间,TensorFlow 在 中遍历此操作列表。计算梯度的反向顺序 .现在,TensorFlow 提供了 tf.GradientTape 自动微分API;即计算关于某些输入的计算梯度,通常是 tf.Variables . TensorFlow 记录 tf.GradientTape 的上下文中执行的相关操作到 胶带 .然后 TensorFlow 使用该磁带计算 的梯度。记录 计算使用 reverse mode differentiation .
所以,从高层的角度来看,两者都在做同样的操作。但是,在自定义训练循环期间,forward loss的通过与计算在 TensorFlow 中更明确因为它使用 tf.GradientTape API 范围,而在 PyTorch这些操作是隐式的,但需要设置 required_grad标记到 False临时更新训练参数(权重和偏差)。为此,它使用 torch.no_grad API 明确。换句话说,TensorFlow 的 tf.GradientTape()类似于 PyTorch 的 loss.backward() .以下是上述语句的代码中的简单形式。

# TensorFlow 
[w, b] = tf_model.trainable_variables
for epoch in range(epochs):
with tf.GradientTape() as tape:
# forward passing and loss calculations
# within explicit tape scope
predictions = tf_model(x)
loss = squared_error(predictions, y)

# compute gradients (grad)
w_grad, b_grad = tape.gradient(loss, tf_model.trainable_variables)

# update training variables
w.assign(w - w_grad * learning_rate)
b.assign(b - b_grad * learning_rate)


# PyTorch
[w, b] = torch_model.parameters()
for epoch in range(epochs):
# forward pass and loss calculation
# implicit tape-based AD
y_pred = torch_model(inputs)
loss = squared_error(y_pred, labels)

# compute gradients (grad)
loss.backward()

# update training variables / parameters
with torch.no_grad():
w -= w.grad * learning_rate
b -= b.grad * learning_rate
w.grad.zero_()
b.grad.zero_()
仅供引用,在上面,可训练变量( wb )在两个框架中都是手动更新的,但我们通常使用优化器(例如 adam )来完成这项工作。
# TensorFlow 
# ....
# update training variables
optimizer.apply_gradients(zip([w_grad, b_grad], model.trainable_weights))

# PyTorch
# ....
# update training variables / parameters
optimizer.step()
optimizer.zero_grad()

关于python - Pytorch 中基于磁带的 autograd 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64856195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com