Skip to content

Commit 850f3dd

Browse files
author
Mathias Louboutin
committed
compiler: Lower Devito stencils to native PyTorch autograd
1 parent abd7e65 commit 850f3dd

3 files changed

Lines changed: 223 additions & 12 deletions

File tree

‎devito/torch.py‎

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
"""PyTorch autograd for explicit spatial Devito stencils."""
2+
3+
import operator
4+
from functools import reduce
5+
6+
import sympy
7+
import torch
8+
import torch.nn.functional as F
9+
from torch.fx import Graph, GraphModule
10+
11+
from devito import Eq, Function, configuration
12+
from devito.finite_differences.differentiable import diff2sympy
13+
from devito.symbolics import indexify, retrieve_indexed
14+
from devito.tools import dtype_to_torch
15+
16+
__all__ = ['TorchStencil']
17+
18+
19+
_TORCH_FUNCTIONS = {
20+
sympy.Abs: torch.abs,
21+
sympy.cos: torch.cos,
22+
sympy.exp: torch.exp,
23+
sympy.log: torch.log,
24+
sympy.sin: torch.sin,
25+
sympy.tan: torch.tan,
26+
sympy.tanh: torch.tanh,
27+
}
28+
29+
30+
def _lower_expression(expr, graph, nodes):
31+
"""Translate scalar stencil arithmetic to elementwise tensor operations."""
32+
if expr in nodes:
33+
return nodes[expr]
34+
if expr.is_number and expr.is_real:
35+
return int(expr) if expr.is_Integer else float(expr)
36+
37+
if isinstance(expr, sympy.Add):
38+
operation = operator.add
39+
elif isinstance(expr, sympy.Mul):
40+
operation = operator.mul
41+
elif isinstance(expr, sympy.Pow):
42+
operation = operator.pow
43+
else:
44+
operation = _TORCH_FUNCTIONS.get(expr.func)
45+
if operation is None:
46+
raise ValueError(f'Unsupported stencil expression: {expr}')
47+
args = tuple(_lower_expression(arg, graph, nodes) for arg in expr.args)
48+
return graph.call_function(operation, args)
49+
50+
args = (_lower_expression(arg, graph, nodes) for arg in expr.args)
51+
return reduce(lambda a, b: graph.call_function(operation, (a, b)), args)
52+
53+
54+
class TorchStencil(torch.nn.Module):
55+
"""Evaluate a Devito spatial stencil with native PyTorch autograd.
56+
57+
Pass an expression and its input Functions in tensor argument order. The
58+
Functions must be unstaggered, live on the same grid, and share a float32
59+
or float64 dtype. Each CPU tensor supplies the corresponding Function's
60+
domain values. Ghost cells are fixed at zero.
61+
"""
62+
63+
def __init__(self, expression, *inputs):
64+
super().__init__()
65+
if not inputs or any(not isinstance(f, Function) or f.is_TimeFunction
66+
for f in inputs):
67+
raise TypeError('Expected spatial Devito Functions')
68+
if len({f.name for f in inputs}) != len(inputs):
69+
raise ValueError('Input Functions must have distinct names')
70+
first = inputs[0]
71+
grid = first.grid
72+
if grid is None or any(f.grid is not grid or f.dimensions != grid.dimensions
73+
or f.shape != grid.shape or not f.staggered.on_node
74+
or f.dtype != first.dtype for f in inputs):
75+
raise ValueError('Expected unstaggered Functions of one dtype on one grid')
76+
if first.dtype.__name__ not in ('float32', 'float64'):
77+
raise TypeError('Expected float32 or float64 Functions')
78+
if configuration['mpi']:
79+
raise NotImplementedError('TorchStencil requires serial grid storage')
80+
81+
self._shape = tuple(grid.shape)
82+
self._dtype = dtype_to_torch(first.dtype)
83+
self._input_count = len(inputs)
84+
85+
name = '_torch_stencil'
86+
while any(f.name == name for f in inputs):
87+
name += '_'
88+
output = Function(name=name, grid=grid, space_order=0, dtype=first.dtype)
89+
rhs = diff2sympy(indexify(Eq(output, expression).evaluate.rhs))
90+
accesses = tuple(dict.fromkeys(retrieve_indexed(rhs)))
91+
if {a.function for a in accesses} != set(inputs):
92+
raise ValueError('Supply each Function read by the stencil as an input')
93+
94+
accesses = sorted(accesses, key=lambda a: inputs.index(a.function))
95+
graph = Graph()
96+
nodes = {}
97+
offsets = [[] for _ in inputs]
98+
for i, access in enumerate(accesses):
99+
offset = tuple(
100+
j - d for j, d in zip(access.indices, grid.dimensions, strict=True)
101+
)
102+
if any(not j.is_Integer for j in offset):
103+
raise ValueError('Stencil reads must use fixed integer offsets')
104+
offset = tuple(int(j) for j in offset)
105+
if any(not -left <= j <= right for j, (left, right) in
106+
zip(offset, access.function._size_halo, strict=True)):
107+
raise ValueError('Stencil offsets exceed the input Function halo')
108+
offsets[inputs.index(access.function)].append(offset)
109+
nodes[access] = graph.placeholder(f'read_{i}')
110+
111+
self._padding = []
112+
self._slices = []
113+
for field_offsets in offsets:
114+
halo = tuple((max(0, -min(axis)), max(0, max(axis)))
115+
for axis in zip(*field_offsets, strict=True))
116+
self._padding.append(tuple(n for pair in reversed(halo) for n in pair))
117+
self._slices.append(tuple(
118+
tuple(slice(left+j, left+j+n) for (left, _), j, n in
119+
zip(halo, offset, self._shape, strict=True))
120+
for offset in field_offsets
121+
))
122+
123+
scalar = rhs.xreplace(grid.spacing_map)
124+
self._coordinates = []
125+
for axis, dim in enumerate(grid.dimensions):
126+
if dim in scalar.free_symbols:
127+
nodes[dim] = graph.placeholder(f'coordinate_{axis}')
128+
self._coordinates.append(axis)
129+
graph.output(_lower_expression(scalar, graph, nodes))
130+
self._evaluate = GraphModule({}, graph)
131+
132+
def forward(self, *inputs):
133+
if len(inputs) != self._input_count:
134+
raise ValueError('Pass one tensor for each stencil input Function')
135+
for tensor in inputs:
136+
if (not isinstance(tensor, torch.Tensor) or tensor.device.type != 'cpu'
137+
or tensor.dtype != self._dtype or tensor.shape != self._shape
138+
or tensor.layout != torch.strided):
139+
raise ValueError('Expected CPU tensors matching the grid and dtype')
140+
141+
reads = []
142+
for value, padding, slices in zip(inputs, self._padding, self._slices,
143+
strict=True):
144+
padded = F.pad(value, padding) if any(padding) else value
145+
reads.extend(padded[index] for index in slices)
146+
147+
for axis in self._coordinates:
148+
size = self._shape[axis]
149+
shape = [1] * len(self._shape)
150+
shape[axis] = size
151+
reads.append(torch.arange(size, dtype=self._dtype,
152+
device=inputs[0].device).reshape(shape))
153+
return self._evaluate(*reads)

‎docs/torch.md‎

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -132,18 +132,46 @@ CUDA-aware MPI is not assumed. OpenACC kernels continue to consume GPU tensor
132132
pointers directly, without staging. Install `.[mpi]` and an MPI runtime to use
133133
distributed execution.
134134

135-
Autograd tensors are not supported. PyTorch has no read-only views, so
136-
`data_ro_*` returns independent snapshots. Negative-stride tensor reads produce
137-
copies because PyTorch cannot represent negative-stride views; direct assignment
138-
through negative slices writes back to the original allocation. Combining
139-
negative strides with advanced tensor indexing is not currently supported.
140-
141-
For an explicit differentiable integration, see
142-
[the diffusion layer example](../examples/pytorch/devito_layer.py).
143-
That CPU-only `nn.Module`
144-
supplies a verified first-order input adjoint for a fixed linear diffusion
145-
operator. Its native kernels receive detached workspaces; the autograd bridge
146-
does not make arbitrary Operators or physical coefficients differentiable.
135+
Raw tensor overrides and TorchAllocator storage require detached tensors.
136+
PyTorch has no read-only views, so `data_ro_*` returns independent snapshots.
137+
Negative-stride tensor reads produce copies because PyTorch cannot represent
138+
negative-stride views. Direct assignment through negative slices writes back
139+
to the original allocation. Combining negative strides with advanced tensor
140+
indexing is currently unsupported.
141+
142+
## Symbolic stencil autograd
143+
144+
`devito.torch.TorchStencil` wraps an explicit spatial expression as a PyTorch
145+
module. Input tensors follow the order of the supplied Devito Functions. This
146+
example computes gradients for both the initial state and a spatially varying
147+
coefficient through two stencil steps.
148+
149+
```python
150+
import torch
151+
from devito import Function, Grid
152+
from devito.torch import TorchStencil
153+
154+
grid = Grid(shape=(32, 32), extent=(31., 31.))
155+
u = Function(name='u', grid=grid, space_order=2)
156+
alpha = Function(name='alpha', grid=grid, space_order=0)
157+
step = TorchStencil(u + alpha*u.laplace, u, alpha)
158+
159+
initial = torch.randn(32, 32, requires_grad=True)
160+
coefficient = torch.full((32, 32), 0.1, requires_grad=True)
161+
result = step(step(initial, coefficient), coefficient)
162+
result.square().mean().backward()
163+
```
164+
165+
Devito evaluates the symbolic finite differences when constructing the module.
166+
The module lowers the resulting stencil reads and arithmetic to PyTorch tensor
167+
operations. PyTorch records padding, slicing, and pointwise operations in its
168+
autograd graph and computes gradients through them.
169+
170+
This interface supports serial CPU float32 and float64 tensors on an unstaggered
171+
grid with a fixed zero halo. Express coefficients as numeric literals or tensor
172+
fields. Use repeated module calls for time stepping. The
173+
[fixed diffusion example](../examples/pytorch/devito_layer.py) demonstrates
174+
training a network around a time-loop Operator.
147175

148176
```sh
149177
OMP_NUM_THREADS=2 python -m pytest -q \

‎tests/torch/test_layer.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,33 @@ def test_invalid_input():
7878
layer(torch.zeros(8, 8))
7979
with pytest.raises(TypeError):
8080
layer(torch.zeros((1, 1, 8, 8), dtype=torch.int64))
81+
82+
83+
def test_symbolic_stencil_autograd():
84+
import numpy as np
85+
86+
from devito import Function, Grid
87+
from devito.torch import TorchStencil
88+
89+
grid = Grid(shape=(4, 5), extent=(6., 4.))
90+
state = Function(name='state', grid=grid, space_order=2, dtype=np.float64)
91+
weight = Function(name='weight', grid=grid, space_order=0, dtype=np.float64)
92+
layer = TorchStencil(state + weight*state.dx**2, state, weight)
93+
94+
value = torch.randn(5, 4, dtype=torch.float64).T.requires_grad_()
95+
coefficient = torch.randn_like(value, requires_grad=True)
96+
97+
def reference(x, w):
98+
shifted = torch.nn.functional.pad(x, (0, 0, 0, 1))[1:]
99+
return x + w*((shifted - x)/2)**2
100+
101+
result = layer(layer(value, coefficient), coefficient)
102+
expected = reference(reference(value, coefficient), coefficient)
103+
seed = torch.randn_like(result)
104+
actual_gradients = torch.autograd.grad(result, (value, coefficient), seed)
105+
expected_gradients = torch.autograd.grad(expected, (value, coefficient), seed)
106+
torch.testing.assert_close(result, expected)
107+
for actual, expected in zip(actual_gradients, expected_gradients, strict=True):
108+
torch.testing.assert_close(actual, expected)
109+
assert torch.autograd.gradcheck(layer, (value, coefficient), fast_mode=True)
110+
assert torch.autograd.gradgradcheck(layer, (value, coefficient), fast_mode=True)

0 commit comments

Comments
 (0)