Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joshlk/fdd485cca7afb2b1cfceb512fb1c0b0f to your computer and use it in GitHub Desktop.
Save joshlk/fdd485cca7afb2b1cfceb512fb1c0b0f to your computer and use it in GitHub Desktop.
Demonstration in PyTorch how convolutions can implemented using matrix multiplication
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "81e7ca94",
"metadata": {},
"outputs": [],
"source": [
"from torch import ops, nn\n",
"import torch"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "48f4402a",
"metadata": {},
"outputs": [],
"source": [
"torch.manual_seed(42)\n",
"n, k, m = 2, 3, 7\n",
"x = torch.rand((n, k))\n",
"w = torch.rand((k, m))"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "82f1f786",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[0.8491, 1.5473, 1.3366, 1.2461, 1.3900, 0.8708, 1.4785],\n",
" [0.6298, 1.3159, 1.2486, 0.9732, 1.1839, 0.8354, 1.2946]])"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"torch.matmul(x, w)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "5f14b47b",
"metadata": {},
"outputs": [],
"source": [
"conv2d = torch.nn.Conv2d(in_channels=k, out_channels=m, kernel_size=1, stride=1, bias=False)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "58acf800",
"metadata": {},
"outputs": [],
"source": [
"conv2d.weight.data = w.T.reshape(m, k, 1, 1)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "66b90a65",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[0.8491, 1.5473, 1.3366, 1.2461, 1.3900, 0.8708, 1.4785],\n",
" [0.6298, 1.3159, 1.2486, 0.9732, 1.1839, 0.8354, 1.2946]],\n",
" grad_fn=<PermuteBackward0>)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"conv2d(x.T.reshape(1, k, n, 1)).squeeze().T"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c737d72a",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment