Skip to content

Instantly share code, notes, and snippets.

@fehiepsi
Last active October 25, 2018 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fehiepsi/3b44a01a9e09251b5360948f61ee94fc to your computer and use it in GitHub Desktop.
Save fehiepsi/3b44a01a9e09251b5360948f61ee94fc to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torch.autograd as autograd\n",
"import torch.distributions as dist\n",
"\n",
"torch.set_printoptions(precision=10)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"data = dist.Normal(0, 1).sample(torch.Size([100]))\n",
"\n",
"def fn(zu):\n",
" z = dist.biject_to(dist.constraints.positive)(zu)\n",
" return dist.Normal(0, z).log_prob(data).sum()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"zu = torch.tensor(1., requires_grad=True)\n",
"fn_jit = torch.jit.trace(fn, (zu,))"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor(-85.8022155762)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"fn(zu).backward()\n",
"zu.grad"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor(-85.8021774292)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"zu.grad.zero_()\n",
"fn_jit(zu).backward()\n",
"zu.grad"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor(-85.8022155762)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"autograd.grad(fn(zu), (zu,))[0]"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor(-85.8021774292)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"autograd.grad(fn_jit(zu), (zu,))[0]"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment