|
| 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) |
0 commit comments