# Calculate the gradient of pytorch model

**URL:** <https://discuss.pytorch.org/t/calculate-the-gradient-of-pytorch-model/185590>\
**Category:** Uncategorized\
**Created:** [August 2, 2023, 7:50pm UTC](https://discuss.pytorch.org/t/calculate-the-gradient-of-pytorch-model/185590 "2023-08-02T19:50:35Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mohamed\_Nabih](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mohamed_nabih/32/19887_2.png) [@Mohamed\_Nabih](https://discuss.pytorch.org/u/Mohamed_Nabih)\
**Post date:** [August 2, 2023, 7:50pm UTC](https://discuss.pytorch.org/t/calculate-the-gradient-of-pytorch-model/185590/1 "2023-08-02T19:50:35Z")

</div>

I have a model trained for four epochs and I saved this model after each epoch. Is there is a way to calculate the gradient as the difference between two models I mean between the saved model after the fourth epoch and the model saved after the third epoch.

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 3, 2023, 12:20am UTC](https://discuss.pytorch.org/t/calculate-the-gradient-of-pytorch-model/185590/2 "2023-08-03T00:20:46Z")

</div>

I’m unsure what exactly your use case is, but in case you want to calculate any difference between parameters you could directly iterate these as seen here:

```python
modelA = models.resnet18()
modelB = models.resnet18()

diffs = {}
for (name, paramA), (paramB) in zip(modelA.named_parameters(), modelB.parameters()):
    diffs[name] = (paramA - paramB).abs()

```

---

<div class="post-metadata">

**Author:** ![Mohamed\_Nabih](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mohamed_nabih/32/19887_2.png) [@Mohamed\_Nabih](https://discuss.pytorch.org/u/Mohamed_Nabih)\
**Post date:** [August 3, 2023, 12:44am UTC](https://discuss.pytorch.org/t/calculate-the-gradient-of-pytorch-model/185590/3 "2023-08-03T00:44:33Z")

</div>

@ptrblck Thanks for your reply, what I want to do it to calculate the gradient as the difference between the two model weights i.e.  
gradient = (W\_n ) - (W\_n-1), where n is the number of epochs.

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 3, 2023, 12:46am UTC](https://discuss.pytorch.org/t/calculate-the-gradient-of-pytorch-model/185590/4 "2023-08-03T00:46:36Z")

</div>

My code shows how to calculate the difference between the parameters of two different models. In your case both models would have been trained for some epochs while I just use randomly initialized models as an example.
