diff --git a/devito/core/operator.py b/devito/core/operator.py index 2a84d381f7..1ebd3dcb34 100644 --- a/devito/core/operator.py +++ b/devito/core/operator.py @@ -202,10 +202,9 @@ class BasicOperator(Operator): See `examples/userapi/08_staggered_interp.ipynb` for a worked example. """ - HALF_ARITH = False + ARITHM_MODE = 'default' """ - Whether an Operator working in half precision carries out the arithmetic there - too, rounding its literals and its FD weights to half. Off by default. + Whether to use default arithmetic or FP16 arithmetic for half-precision fields. """ @classmethod @@ -237,13 +236,17 @@ def _normalize_sym_kwargs(cls, **kwargs): """ so = dict(kwargs.get('sym_options', {})) out = {'interp-mode': so.pop('interp-mode', cls.INTERP_MODE), - 'half-arith': so.pop('half-arith', cls.HALF_ARITH)} + 'arithm-mode': so.pop('arithm-mode', cls.ARITHM_MODE)} if so: raise InvalidOperator( f'Unrecognized symbolic options: [{", ".join(list(so))}]' ) + mode = out['arithm-mode'] + if not isinstance(mode, str) or mode not in ('default', 'fp16'): + raise InvalidOperator("`arithm-mode` must be 'default' or 'fp16'") + return out @classmethod diff --git a/devito/ir/cgen/printer.py b/devito/ir/cgen/printer.py index 94729b61e3..6dd5cc7a47 100644 --- a/devito/ir/cgen/printer.py +++ b/devito/ir/cgen/printer.py @@ -287,12 +287,9 @@ def _print_Mod(self, expr): return '%'.join(args) def _print_Mul(self, expr): + """Print reciprocal factors in one denominator, e.g. `a/((b*c)*d)`.""" args, neg = [], False - # SymPy's CodePrinter extracts negative coefficients with the standalone - # _keep_coeff helper, which can rebuild a plain SymPy Mul. Since this - # is not a method, UnevalMul cannot override it. Extract signs before - # delegating to preserve the product's class without patching SymPy or - # copying its multiplication printer. + # Extract signs without letting SymPy's `_keep_coeff` evaluate the product for a in expr.args: if a.is_Number and a.is_negative: a = -a @@ -302,15 +299,40 @@ def _print_Mul(self, expr): args.append(a) args = args or [S.One] - if len(args) > 1: - term = super()._print_Mul(expr.func(*args, evaluate=False)) - else: + product = expr.func(*args, evaluate=False) if len(args) > 1 else None + if product is None: term = self.parenthesize(args[0], precedence(expr)) + elif product in getattr(self, 'math_macros', ()): + # Let SymPy print named constants such as `M_PI_2` + term = super()._print_Mul(product) + else: + prec = precedence(product) + if self.order in ('old', 'none'): + args = sympy.Mul.make_args(product) + else: + args = product.as_ordered_factors() + + numerator, denominator = [], [] + for a in args: + if a.is_Pow and a.is_commutative and \ + a.exp.is_Rational and a.exp.is_negative: + base, exp = a.args + if exp != -1: + base = sympy.Pow(base, -exp, evaluate=False) + denominator.append(self.parenthesize(base, prec)) + else: + numerator.append(self.parenthesize(a, prec)) + + term = '*'.join(numerator) or self._print(S.One) + if len(denominator) == 1: + term += f'/{denominator[0]}' + elif denominator: + term += f"/({'*'.join(denominator)})" if neg: return term[1:] if term.startswith('-') else f'-{term}' - else: - return term + + return term def _print_fmath_func(self, name, expr): args = ",".join([self._print(i) for i in expr.args]) diff --git a/devito/ir/iet/efunc.py b/devito/ir/iet/efunc.py index c646038da6..3baaf7ca1c 100644 --- a/devito/ir/iet/efunc.py +++ b/devito/ir/iet/efunc.py @@ -136,12 +136,12 @@ def make_efunc(name, iet, region=None, retval='void', prefix='static', # Callable machinery -def make_callable(name, iet, retval='void', prefix='static'): +def make_callable(name, iet, retval='void', prefix='static', cls=Callable): """ - Utility function to create a Callable from an IET. + Create a Callable (or subclass `cls`) from an IET. """ parameters = derive_parameters(iet, ordering='canonical') - return Callable(name, iet, retval, parameters=parameters, prefix=prefix) + return cls(name, iet, retval, parameters=parameters, prefix=prefix) # EntryFunction machinery @@ -190,7 +190,7 @@ def __init__(self, name, body, parameters): class DeviceFunction(Callable): """ - A Callable executed asynchronously on a device. + A Callable executed on a device, including kernels and inline helpers. """ def __init__(self, name, body, retval='void', parameters=None, diff --git a/devito/ir/iet/visitors.py b/devito/ir/iet/visitors.py index d91cac0bcc..f2de6456da 100644 --- a/devito/ir/iet/visitors.py +++ b/devito/ir/iet/visitors.py @@ -12,6 +12,7 @@ from typing import Any, Generic, TypeVar import cgen as c +import numpy as np from sympy import IndexedBase from sympy.core.function import Application @@ -24,12 +25,12 @@ from devito.ir.support.space import Backward from devito.ir.support.utils import IMask from devito.symbolics import ( - FieldFromComposite, FieldFromPointer, ListInitializer, uxreplace + FieldFromComposite, FieldFromPointer, ListInitializer, sympy_dtype, uxreplace ) from devito.symbolics.extended_dtypes import NoDeclStruct from devito.tools import ( - GenericVisitor, as_tuple, c_restrict_void_p, filter_ordered, filter_sorted, flatten, - is_external_ctype, natural_sort_key + GenericVisitor, as_tuple, c_restrict_void_p, dtypes_vector_mapper, filter_ordered, + filter_sorted, flatten, is_external_ctype, natural_sort_key ) from devito.tools.cgen import make_struct from devito.types import ( @@ -262,8 +263,16 @@ def __init__(self, *args, printer=None, **kwargs): def ccode(self, expr, dtype=None, exact_prec=None): defaults = self.printer._default_settings dtype = defaults['dtype'] if dtype is None else dtype + if exact_prec is None: exact_prec = defaults['exact_prec'] + + base = dtypes_vector_mapper.get_base_dtype(dtype, dtype) + if exact_prec and base == np.float16: + # E.g., `half_out = 0.9998*half_in + float_in` needs FP32 + # literals despite its FP16 destination + dtype = sympy_dtype(expr, base=base) + return get_printer(self.printer, dtype, exact_prec).doprint(expr, None) @property diff --git a/devito/operator/operator.py b/devito/operator/operator.py index 70d700cba3..59d5eeb44d 100644 --- a/devito/operator/operator.py +++ b/devito/operator/operator.py @@ -827,6 +827,10 @@ def arguments(self, **kwargs): # Code generation and JIT compilation + def _signature_items(self): + # Retain literal precision and the complete toolchain ABI in JIT identity + return (str(self.ccode), repr(self._compiler.abi_id())) + @cached_property def _soname(self): """A unique name for the shared object resulting from JIT compilation.""" @@ -836,7 +840,7 @@ def _soname(self): def _printer(self): # A Target may offer a second printer e.g. for Operators # using half-precision arithmetic - if self._sym_options.get('half-arith'): + if self._sym_options.get('arithm-mode') == 'fp16': with suppress(AttributeError): return self._Target.HalfArithPrinter return self._Target.Printer diff --git a/devito/passes/clusters/cse.py b/devito/passes/clusters/cse.py index bdb26b7f1a..ca80f4336e 100644 --- a/devito/passes/clusters/cse.py +++ b/devito/passes/clusters/cse.py @@ -17,6 +17,8 @@ DefFunction, IndexedPointer, Reserved, estimate_cost, q_leaf, q_terminal, search ) from devito.symbolics.manipulation import _uxreplace +from devito.symbolics.unevaluation import Add as UnevalAdd +from devito.symbolics.unevaluation import Mul as UnevalMul from devito.tools import DAG, as_list, as_tuple, extract_dtype, frozendict from devito.types import Eq, Symbol, Temp @@ -463,9 +465,12 @@ def _(expr): return mapper +@_catch.register(UnevalAdd) +@_catch.register(UnevalMul) @_catch.register(Pow) @_catch.register(Function) def _(expr): + # Reuse frozen arithmetic only as complete subexpressions mapper = _catch(expr.args) mapper[Candidate(expr)].append(expr) diff --git a/devito/passes/clusters/factorization.py b/devito/passes/clusters/factorization.py index 3d157048c3..f0f68e03f7 100644 --- a/devito/passes/clusters/factorization.py +++ b/devito/passes/clusters/factorization.py @@ -6,6 +6,8 @@ from devito.symbolics import ( BasicWrapperMixin, estimate_cost, q_routine, retrieve_symbols, reuse_if_untouched ) +from devito.symbolics.unevaluation import Add as UnevalAdd +from devito.symbolics.unevaluation import Mul as UnevalMul from devito.tools import ReducerMap from devito.types.object import AbstractObject @@ -209,7 +211,7 @@ def _collect_nested(expr, strategy): elif expr.is_Pow: return expr, {'pows': expr} elif (expr.is_Symbol or expr.is_Indexed or not expr.args or - isinstance(expr, (BasicWrapperMixin, AbstractObject))): + isinstance(expr, (BasicWrapperMixin, AbstractObject, UnevalAdd, UnevalMul))): return expr, {} elif expr.is_Add: return strategies[strategy](expr, strategy), {} diff --git a/devito/passes/clusters/fusion.py b/devito/passes/clusters/fusion.py index cd00bf97bc..45e915f733 100644 --- a/devito/passes/clusters/fusion.py +++ b/devito/passes/clusters/fusion.py @@ -248,9 +248,14 @@ def _toposort(self, cgroups, prefix): # Are there any ClusterGroups that could potentially be topologically # reordered? If not, do not waste time - counter = Counter(self._key(cg).strict for cg in cgroups) - if len(counter.most_common()) == 1 or \ - not any(v > 1 for it, v in counter.most_common()): + keys = [self._key(cg) for cg in cgroups] + if len({k.full for k in keys}) == 1: + return ClusterGroup(cgroups, prefix) + + # Same strict keys can still hide different scheduling preferences. + # E.g., `r0, shared0, r1, shared1` may reorder to fuse `r0, r1`. + counter = Counter(k.strict for k in keys) + if not any(v > 1 for v in counter.values()): return ClusterGroup(cgroups, prefix) dag = self._build_dag(cgroups, prefix) diff --git a/devito/passes/clusters/unevaluate.py b/devito/passes/clusters/unevaluate.py index b895e1eafa..e1e355a091 100644 --- a/devito/passes/clusters/unevaluate.py +++ b/devito/passes/clusters/unevaluate.py @@ -5,7 +5,7 @@ @cluster_pass(mode='all') -def unevaluate(cluster): +def unevaluate(cluster, **kwargs): exprs = [_unevaluate(e) for e in cluster.exprs] return cluster.rebuild(exprs=exprs) diff --git a/devito/passes/iet/definitions.py b/devito/passes/iet/definitions.py index 02e7f4b599..9a5b99d362 100644 --- a/devito/passes/iet/definitions.py +++ b/devito/passes/iet/definitions.py @@ -201,7 +201,7 @@ def _alloc_host_array_on_high_bw_mem(self, site, obj, storage, *args): storage.update(obj, site, allocs=tuple(allocs), frees=free, efuncs=efuncs) - def _alloc_local_array_on_high_bw_mem(self, site, obj, storage, *args): + def _alloc_local_array_on_high_bw_mem(self, site, obj, storage, *args, **kwargs): """ Allocate a local Array in the host high bandwidth memory. """ @@ -471,7 +471,7 @@ def _inject_definitions(self, iet, storage): return processed, flatten(efuncs) @iet_pass - def place_definitions(self, iet, globs=None, **kwargs): + def place_definitions(self, iet, globs=None, alignments=None, **kwargs): """ Create a new IET where all symbols have been declared, allocated, and deallocated in one or more memory spaces. @@ -507,7 +507,9 @@ def place_definitions(self, iet, globs=None, **kwargs): if i.is_transient: self._alloc_bundle_struct_on_high_bw_mem(iet, i, storage) elif i._mem_local: - self._alloc_local_array_on_high_bw_mem(iet, i, storage) + self._alloc_local_array_on_high_bw_mem( + iet, i, storage, alignments=alignments + ) elif i._mem_mapped: self._alloc_mapped_array_on_high_bw_mem(iet, i, storage) elif i._mem_stack: @@ -518,7 +520,9 @@ def place_definitions(self, iet, globs=None, **kwargs): if i._mem_host: self._alloc_host_array_on_high_bw_mem(iet, i, storage) elif i._mem_local: - self._alloc_local_array_on_high_bw_mem(iet, i, storage) + self._alloc_local_array_on_high_bw_mem( + iet, i, storage, alignments=alignments + ) else: self._alloc_mapped_array_on_high_bw_mem(iet, i, storage) elif i._mem_stack: @@ -579,11 +583,22 @@ def place_casts(self, iet, **kwargs): return iet, {} + def derive_alignments(self, graph): + """ + Choose allocation padding from alignment requirements across `graph`. + + Backends may inspect all kernels and helpers before deciding how many + elements to insert before each field's logical allocation origin. + An empty mapper retains the backend's ordinary allocation behavior. + """ + return {} + def process(self, graph): """ Apply the `place_definitions` and `place_casts` passes. """ - self.place_definitions(graph, globs=set()) + alignments = self.derive_alignments(graph) + self.place_definitions(graph, globs=set(), alignments=alignments) self.place_casts(graph) @@ -596,7 +611,7 @@ def __init__(self, options=None, **kwargs): super().__init__(options=options, **kwargs) - def _alloc_local_array_on_high_bw_mem(self, site, obj, storage): + def _alloc_local_array_on_high_bw_mem(self, site, obj, storage, **kwargs): """ Allocate a local Array in the device high bandwidth memory. """ @@ -673,7 +688,7 @@ def _map_function_on_high_bw_mem(self, site, obj, storage, devicerm, storage.update(obj, site, maps=mmap, unmaps=unmap, efuncs=efuncs) @iet_pass - def place_transfers(self, iet, data_movs=None, ctx=None, **kwargs): + def place_transfers(self, iet, data_movs=None, alignments=None, **kwargs): """ Create a new IET with host-device data transfers. This requires mapping symbols to the suitable memory spaces. @@ -695,14 +710,14 @@ def place_transfers(self, iet, data_movs=None, ctx=None, **kwargs): self._map_array_on_high_bw_mem(iet, i, storage) else: self._map_function_on_high_bw_mem( - iet, i, storage, devicerm, ctx=ctx + iet, i, storage, devicerm, alignments=alignments ) for i in filter_sorted(reads - writes): if i.is_Array: self._map_array_on_high_bw_mem(iet, i, storage) else: self._map_function_on_high_bw_mem( - iet, i, storage, devicerm, read_only=True, ctx=ctx + iet, i, storage, devicerm, read_only=True, alignments=alignments ) iet, efuncs = self._inject_definitions(iet, storage) @@ -735,8 +750,9 @@ def process(self, graph): """ Apply the `place_transfers`, `place_definitions` and `place_casts` passes. """ - self.place_transfers(graph, data_movs=graph.data_movs) - self.place_definitions(graph, globs=set()) + alignments = self.derive_alignments(graph) + self.place_transfers(graph, data_movs=graph.data_movs, alignments=alignments) + self.place_definitions(graph, globs=set(), alignments=alignments) self.place_devptr(graph) self.place_bundling(graph, writes_input=graph.writes_input) self.place_casts(graph) diff --git a/devito/passes/iet/dtypes.py b/devito/passes/iet/dtypes.py index b2b3abcc37..7d596767a1 100644 --- a/devito/passes/iet/dtypes.py +++ b/devito/passes/iet/dtypes.py @@ -12,7 +12,7 @@ @iet_pass def _complex_includes(iet: Callable, langbb: type[LangBB], compiler: Compiler, - sregistry: SymbolRegistry) -> tuple[Callable, dict]: + sregistry: SymbolRegistry, **kwargs) -> tuple[Callable, dict]: """ Includes complex arithmetic headers for the given language, if needed. """ @@ -48,9 +48,9 @@ def lower_dtypes(graph: Callable, compiler: Compiler = None, sregistry: SymbolRegistry = None, **kwargs) -> tuple[Callable, dict]: """ - Lowers float16 scalar types to pointers since we can't directly pass their - value. Also includes headers for complex arithmetic if needed. + Lower dtype-specific parameters and arithmetic, and include required headers. """ for dtype_pass in dtype_passes: - dtype_pass(graph, langbb=langbb, compiler=compiler, sregistry=sregistry) + dtype_pass(graph, langbb=langbb, compiler=compiler, sregistry=sregistry, + **kwargs) diff --git a/devito/symbolics/extended_sympy.py b/devito/symbolics/extended_sympy.py index eeb290feee..7a51b6c43d 100644 --- a/devito/symbolics/extended_sympy.py +++ b/devito/symbolics/extended_sympy.py @@ -15,7 +15,8 @@ from devito.finite_differences.elementary import Max, Min from devito.tools import ( # noqa Bunch, Pickable, as_tuple, ctypes_to_cstr, ctypes_vector_mapper, double2, double3, - double4, dtype_to_ctype, float2, float3, float4, int2, int3, int4, is_integer + double4, dtype_to_ctype, extract_dtype, float2, float3, float4, int2, int3, int4, + is_integer ) from devito.types import Symbol from devito.types.basic import Basic @@ -493,6 +494,13 @@ def stars(self): def dtype(self): return self._dtype + @cached_property + def alignment(self): + """Byte alignment of a typed access, if the target's size is known.""" + with suppress(TypeError): + return np.dtype(self.dtype).itemsize + return None + @property def reinterpret(self): return self._reinterpret @@ -543,6 +551,10 @@ def __new__(cls, base, index, **kwargs): def base(self): return self._base + @property + def dtype(self): + return self.base.dtype + @property def index(self): return self._index @@ -660,6 +672,14 @@ def __new__(cls, value, step, **kwargs): return super().__new__(cls, value, step, **kwargs) + def _eval_is_integer(self): + if self.value.is_integer: + return True + # Opaque dtypes, e.g. CustomDtype('size_t'), are instances, not classes + with suppress(TypeError): + if issubclass(extract_dtype(self.value), np.integer): + return True + @property def value(self): return self.args[0] diff --git a/devito/symbolics/inspection.py b/devito/symbolics/inspection.py index 4903ef60a6..19a6c7894c 100644 --- a/devito/symbolics/inspection.py +++ b/devito/symbolics/inspection.py @@ -290,7 +290,7 @@ def has_integer_args(*args): if len(args) == 1: try: return np.issubdtype(args[0].dtype, np.integer) - except AttributeError: + except (AttributeError, TypeError): return is_integer(args[0]) res = True diff --git a/devito/symbolics/manipulation.py b/devito/symbolics/manipulation.py index 8744cde4f2..f5af42d0d5 100644 --- a/devito/symbolics/manipulation.py +++ b/devito/symbolics/manipulation.py @@ -20,7 +20,6 @@ from devito.symbolics.unevaluation import Add as UnevalAdd from devito.symbolics.unevaluation import Mul as UnevalMul from devito.symbolics.unevaluation import Pow as UnevalPow -from devito.symbolics.unevaluation import UnevaluableMixin from devito.symbolics.unevaluation import ceiling as UnevalCeil from devito.symbolics.unevaluation import floor as UnevalFloor from devito.tools import ( @@ -56,9 +55,9 @@ def uxreplace(expr, rule): be avoided at all costs (e.g., to prevent SymPy from unpicking Devito transformations, such as factorization). - Evaluated expressions retain canonical argument ordering. Lowered, - unevaluated arithmetic retains its operand order and grouping unless - substitution makes it completely numeric. + Ordinary sums and products retain canonical argument ordering. Unevaluated + Add/Mul instead preserve operand order and grouping, e.g. replacing `a` in + `c*(b*a)` retains `c*(b*z)`. Fully numeric replacements may be evaluated. By avoiding re-evaluations, this function is typically much quicker than SymPy's xreplace. @@ -85,43 +84,40 @@ def _uxreplace(expr, rule): def _uxreplace_default(expr, rule): + if not rule: + return expr, False + if expr in rule: - v = rule[expr] - if not isinstance(v, dict): - return v, True - args, eargs = split(expr.args, lambda i: i in v) - args = [v[i] for i in args if v[i] is not None] - changed = True - elif expr.__class__ in rule: - # Exact type -> type substitution - cls = rule[expr.__class__] - expr = cls(*expr.args) - args, eargs = [], expr.args + replacement = rule[expr] + if not isinstance(replacement, dict): + return replacement, True + + # Apply compound overrides to the immediate operands in place + args = [] + for a in expr.args: + if a not in replacement: + args.append(_uxreplace(a, rule)[0]) + elif replacement[a] is not None: + args.append(replacement[a]) changed = True else: - try: - args, eargs = [], expr.args - except AttributeError: - # E.g., unsympified `int` - args, eargs = [], [] - changed = False + changed = expr.__class__ in rule + if changed: + cls = rule[expr.__class__] + expr = cls(*expr.args) - if rule: - eargs, flag = _uxreplace_dispatch(eargs, rule) - args.extend(eargs) + args, flag = _uxreplace_dispatch(getattr(expr, 'args', ()), rule) changed |= flag - # If a Reconstructable object, we need to parse the kwargs as well - if _uxreplace_registry.dispatchable(expr): - v = {i: getattr(expr, i) for i in expr.__rkwargs__} - kwargs, flag = _uxreplace_dispatch(v, rule) - else: - kwargs, flag = {}, False + kwargs = {} + if _uxreplace_registry.dispatchable(expr): + # A Reconstructable can carry symbolic arguments in its kwargs + kwargs = {i: getattr(expr, i) for i in expr.__rkwargs__} + kwargs, flag = _uxreplace_dispatch(kwargs, rule) changed |= flag - if changed: - return _uxreplace_handle(expr, args, kwargs), True - + if changed: + return _uxreplace_handle(expr, list(args), kwargs), True return expr, False @@ -217,11 +213,10 @@ def _(expr, args, kwargs): return expr.func(*args, evaluate=evaluate) -# The SymPy bases precede UnevaluableMixin in these classes' dispatch MRO @_uxreplace_handle.register(UnevalAdd) @_uxreplace_handle.register(UnevalMul) def _(expr, args, kwargs): - # Lowered arithmetic must survive substitutions without reassociation + # Preserve grouping and rounding points, e.g. `c*(w*u)` if all(i.is_Number for i in args): return expr.func.__base__(*args) return expr.func(*args) @@ -355,7 +350,9 @@ def subs_if_composite(expr, subs): return reuse_if_untouched(expr, (subs_if_composite(e, subs) for e in expr)) elif type(expr) is list: return reuse_if_untouched(expr, [subs_if_composite(e, subs) for e in expr]) - elif all(isinstance(i, (Indexed, IndexDerivative)) for i in subs): + elif all(isinstance(i, (Indexed, IndexDerivative, UnevalAdd, UnevalMul)) + for i in subs): + # Frozen arithmetic only permits exact matches, never partial reassociation return uxreplace(expr, subs) else: processed = expr.subs(subs) @@ -406,8 +403,7 @@ def _eval_numbers(expr, args): """ numbers, others = split(args, lambda i: i.is_Number) if len(numbers) > 1: - cls = expr.func.__base__ if isinstance(expr, UnevaluableMixin) else expr.func - args[:] = [cls(*numbers)] + others + args[:] = [expr.func(*numbers)] + others def flatten_args(args, op, ignore=None): @@ -631,10 +627,18 @@ def evalrel(func=min, input=None, assumptions=None): def unevaluate(expr): """Protect lowered arithmetic from reevaluation during reconstruction.""" - if q_leaf(expr): + # Derivatives still need their own lowering, e.g. removing a unit weight + if q_leaf(expr) or isinstance(expr, IndexDerivative): return expr - args = [unevaluate(a) for a in expr.args] + # Freeze the scalar printer's order before replacing its operands + if expr.func is Add: + args = expr.as_ordered_terms() + elif expr.func is Mul: + args = expr.as_ordered_factors() + else: + args = expr.args + args = [unevaluate(a) for a in args] try: return uneval_mapper[expr.func](*args) diff --git a/devito/symbolics/unevaluation.py b/devito/symbolics/unevaluation.py index 7e348ec518..768040b5f6 100644 --- a/devito/symbolics/unevaluation.py +++ b/devito/symbolics/unevaluation.py @@ -11,6 +11,9 @@ def __new__(cls, *args, evaluate=None, **kwargs): class Add(sympy.Add, UnevaluableMixin): + + """An unevaluated sum whose terms retain their order after replacement.""" + __new__ = UnevaluableMixin.__new__ @@ -19,6 +22,9 @@ class Mod(sympy.Mod, UnevaluableMixin): class Mul(sympy.Mul, UnevaluableMixin): + + """An unevaluated product retaining factor order and grouping.""" + def __new__(cls, *args, evaluate=None, **kwargs): # A Mul will always be zero if any of its arguments are zero if any(sympify(arg).is_zero for arg in args): diff --git a/devito/tools/abc.py b/devito/tools/abc.py index 2e489ac3c0..366ac1a959 100644 --- a/devito/tools/abc.py +++ b/devito/tools/abc.py @@ -1,5 +1,7 @@ from hashlib import sha1 +from devito.tools.utils import as_tuple + __all__ = ['Pickable', 'Reconstructable', 'Signer', 'Singleton', 'Stamp', 'Tag'] @@ -170,6 +172,12 @@ class Pickable(Reconstructable): ``__reduce_ex__ = Pickable.__reduce_ex__`` depending on the MRO. """ + __rignored__ = () + """ + Instance attributes omitted from pickling, as a name or tuple of names. + E.g., `__rignored__ = '_C_ctype'` discards a process-local cached type. + """ + @property def _pickle_rargs(self): """ @@ -216,6 +224,15 @@ def _pickle_reconstructor(self): def __reduce_ex__(self, proto): ret = object.__reduce_ex__(self, proto) + + if self.__rignored__: + state = ret[2] if len(ret) > 2 else None + if state is None: + state = self.__dict__ + ignored = as_tuple(self.__rignored__) + state = {k: v for k, v in state.items() if k not in ignored} + ret = (*ret[:2], state, *ret[3:]) + reconstructor = self._pickle_reconstructor if reconstructor is None: return ret diff --git a/devito/types/array.py b/devito/types/array.py index 1988e2b0a8..c3e9026cff 100644 --- a/devito/types/array.py +++ b/devito/types/array.py @@ -700,7 +700,8 @@ def indices(self): @property def dtype(self): try: - return self.function.c0.dtype + dtype = self.function.c0.dtype + return dtypes_vector_mapper.get_base_dtype(dtype, dtype) except AttributeError: # Vector-component access over a scalar symbol, e.g. a float4 register. if self.function.is_Symbol: diff --git a/devito/types/basic.py b/devito/types/basic.py index fc8940f5e9..e1f63434f0 100644 --- a/devito/types/basic.py +++ b/devito/types/basic.py @@ -1788,6 +1788,9 @@ class IndexedBase(sympy.IndexedBase, Basic, Pickable): __rargs__ = ('label', 'shape') __rkwargs__ = ('function',) + # Recreate process-local ctypes classes from the Function's dtype + __rignored__ = '_C_ctype' + def __new__(cls, label, shape, function=None): # Make sure `label` is a devito.Symbol, not a sympy.Symbol if isinstance(label, str): diff --git a/devito/types/misc.py b/devito/types/misc.py index 61a2860148..38b9ea0fbf 100644 --- a/devito/types/misc.py +++ b/devito/types/misc.py @@ -1,4 +1,5 @@ -from ctypes import c_double, c_void_p +from ctypes import POINTER, c_double +from functools import cached_property import numpy as np import sympy @@ -9,7 +10,8 @@ # Moved in 1.13 from sympy.core.basic import ordering_of_classes -from devito.tools import CustomDtype, Pickable, as_tuple, frozendict +from devito.tools import CustomDtype, Pickable, as_tuple, dtype_to_ctype, frozendict +from devito.tools.dtypes_lowering import is_numpy_dtype from devito.types import Array, CompositeObject, Indexed, LocalObject, Symbol from devito.types.basic import IndexedData @@ -201,15 +203,41 @@ def _defines(self): class Pointer(LocalObject, sympy.Expr): - __rkwargs__ = LocalObject.__rkwargs__ + ('dtype',) + """ + A Pointer is defined by the pointee base type and its indirections. + + Unlike plain LocalObjects, Pointers can be used within arbitrary expressions. + Their dtype includes indirections so address arithmetic is typed as pointer + arithmetic. Pickling reconstructs it from `dtype_base` and `stars`. + + Examples + -------- + `Pointer('p', dtype_base=np.float32, stars='**')` declares `float **p`. + """ + + __rkwargs__ = LocalObject.__rkwargs__ + ('dtype_base', 'stars') - def __init__(self, *args, dtype=c_void_p, **kwargs): + def __init__(self, *args, dtype_base=None, stars='*', **kwargs): super().__init__(*args, **kwargs) - self._dtype = dtype + if not isinstance(stars, str) or any(i != '*' for i in stars): + raise ValueError('`stars` must be a string of zero or more `*` characters') + self.dtype_base = dtype_base + self.stars = stars - @property + def _hashable_content(self): + return super()._hashable_content() + (self.stars,) + + @cached_property def dtype(self): - return self._dtype + ctype = self.dtype_base + if is_numpy_dtype(ctype): + ctype = dtype_to_ctype(ctype) + if isinstance(ctype, CustomDtype): + # Keep the shared base type unchanged + return CustomDtype(ctype.name, ctype.template, ctype.modifier + self.stars) + for _ in self.stars: + ctype = POINTER(ctype) + return ctype class Indirection(Symbol): diff --git a/examples/performance/00_overview.ipynb b/examples/performance/00_overview.ipynb index 3345a1ac4e..ef8b53bd1f 100644 --- a/examples/performance/00_overview.ipynb +++ b/examples/performance/00_overview.ipynb @@ -208,7 +208,7 @@ " {\n", " for (int z = z_m; z <= z_M; z += 1)\n", " {\n", - " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y) + (-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", + " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y) + (8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", " }\n", " }\n", " }\n", @@ -283,7 +283,7 @@ " {\n", " for (int z = z_m; z <= z_M; z += 1)\n", " {\n", - " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y) + (-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", + " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y) + (8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", " }\n", " }\n", " }\n", @@ -341,7 +341,7 @@ " {\n", " for (int z = z_m; z <= z_M; z += 1)\n", " {\n", - " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y) + (-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", + " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y) + (8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", " }\n", " }\n", " }\n", @@ -431,7 +431,7 @@ " {\n", " for (int z = z0_blk1; z <= MIN(z_M, z0_blk1 + z0_blk1_size - 1); z += 1)\n", " {\n", - " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y) + (-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", + " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y) + (8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", " }\n", " }\n", " }\n", @@ -522,7 +522,7 @@ " {\n", " for (int z = z_m; z <= z_M; z += 1)\n", " {\n", - " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F*r1)*(8.33333333e-2F*r1*u[t0][x + 4][y + 1][z + 4] - 6.66666667e-1F*r1*u[t0][x + 4][y + 2][z + 4] + 6.66666667e-1F*r1*u[t0][x + 4][y + 4][z + 4] - 8.33333333e-2F*r1*u[t0][x + 4][y + 5][z + 4]) + (-8.33333333e-2F*r1)*(8.33333333e-2F*r1*u[t0][x + 4][y + 4][z + 4] - 6.66666667e-1F*r1*u[t0][x + 4][y + 5][z + 4] + 6.66666667e-1F*r1*u[t0][x + 4][y + 7][z + 4] - 8.33333333e-2F*r1*u[t0][x + 4][y + 8][z + 4]) + (8.33333333e-2F*r1)*(8.33333333e-2F*r1*u[t0][x + 4][y][z + 4] - 6.66666667e-1F*r1*u[t0][x + 4][y + 1][z + 4] + 6.66666667e-1F*r1*u[t0][x + 4][y + 3][z + 4] - 8.33333333e-2F*r1*u[t0][x + 4][y + 4][z + 4]) + (6.66666667e-1F*r1)*(8.33333333e-2F*r1*u[t0][x + 4][y + 3][z + 4] - 6.66666667e-1F*r1*u[t0][x + 4][y + 4][z + 4] + 6.66666667e-1F*r1*u[t0][x + 4][y + 6][z + 4] - 8.33333333e-2F*r1*u[t0][x + 4][y + 7][z + 4]))*r0[x][y][z];\n", + " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F*r1)*(8.33333333e-2F*r1*u[t0][x + 4][y][z + 4] - 6.66666667e-1F*r1*u[t0][x + 4][y + 1][z + 4] + 6.66666667e-1F*r1*u[t0][x + 4][y + 3][z + 4] - 8.33333333e-2F*r1*u[t0][x + 4][y + 4][z + 4]) + (6.66666667e-1F*r1)*(8.33333333e-2F*r1*u[t0][x + 4][y + 3][z + 4] - 6.66666667e-1F*r1*u[t0][x + 4][y + 4][z + 4] + 6.66666667e-1F*r1*u[t0][x + 4][y + 6][z + 4] - 8.33333333e-2F*r1*u[t0][x + 4][y + 7][z + 4]) + (-8.33333333e-2F*r1)*(8.33333333e-2F*r1*u[t0][x + 4][y + 4][z + 4] - 6.66666667e-1F*r1*u[t0][x + 4][y + 5][z + 4] + 6.66666667e-1F*r1*u[t0][x + 4][y + 7][z + 4] - 8.33333333e-2F*r1*u[t0][x + 4][y + 8][z + 4]) + (-6.66666667e-1F*r1)*(8.33333333e-2F*r1*u[t0][x + 4][y + 1][z + 4] - 6.66666667e-1F*r1*u[t0][x + 4][y + 2][z + 4] + 6.66666667e-1F*r1*u[t0][x + 4][y + 4][z + 4] - 8.33333333e-2F*r1*u[t0][x + 4][y + 5][z + 4]))*r0[x][y][z];\n", " }\n", " }\n", " }\n", @@ -567,9 +567,9 @@ " {\n", " for (int z = z_m; z <= z_M; z += 1)\n", " {\n", - "- u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y) + (-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", + "- u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y) + (8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", "+ float r0 = 1.0F/h_y;\n", - "+ u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 1][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 2][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 4][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 5][z + 4]) + (-8.33333333e-2F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 4][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 5][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 7][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 8][z + 4]) + (8.33333333e-2F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 1][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 3][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 4][z + 4]) + (6.66666667e-1F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 3][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 4][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 6][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 7][z + 4]))*sinf(f[x + 1][y + 1][z + 1]);\n", + "+ u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 1][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 3][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 4][z + 4]) + (6.66666667e-1F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 3][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 4][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 6][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 7][z + 4]) + (-8.33333333e-2F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 4][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 5][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 7][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 8][z + 4]) + (-6.66666667e-1F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 1][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 2][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 4][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 5][z + 4]))*sinf(f[x + 1][y + 1][z + 1]);\n", " }\n", " }\n", " }\n", @@ -604,7 +604,7 @@ " for (int z = z_m; z <= z_M; z += 1)\n", " {\n", " float r0 = 1.0F/h_y;\n", - "- u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 1][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 2][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 4][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 5][z + 4]) + (-8.33333333e-2F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 4][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 5][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 7][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 8][z + 4]) + (8.33333333e-2F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 1][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 3][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 4][z + 4]) + (6.66666667e-1F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 3][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 4][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 6][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 7][z + 4]))*sinf(f[x + 1][y + 1][z + 1]);\n", + "- u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 1][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 3][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 4][z + 4]) + (6.66666667e-1F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 3][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 4][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 6][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 7][z + 4]) + (-8.33333333e-2F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 4][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 5][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 7][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 8][z + 4]) + (-6.66666667e-1F*r0)*(8.33333333e-2F*r0*u[t0][x + 4][y + 1][z + 4] - 6.66666667e-1F*r0*u[t0][x + 4][y + 2][z + 4] + 6.66666667e-1F*r0*u[t0][x + 4][y + 4][z + 4] - 8.33333333e-2F*r0*u[t0][x + 4][y + 5][z + 4]))*sinf(f[x + 1][y + 1][z + 1]);\n", "+ u[t1][x + 4][y + 4][z + 4] = (r0*r0)*(f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*(6.94444444e-3F*(u[t0][x + 4][y][z + 4] + u[t0][x + 4][y + 8][z + 4]) + 4.44444444e-1F*(u[t0][x + 4][y + 2][z + 4] + u[t0][x + 4][y + 6][z + 4]) + 1.11111111e-1F*(-u[t0][x + 4][y + 1][z + 4] + u[t0][x + 4][y + 3][z + 4] + u[t0][x + 4][y + 5][z + 4] - u[t0][x + 4][y + 7][z + 4]) - 9.02777778e-1F*u[t0][x + 4][y + 4][z + 4])*sinf(f[x + 1][y + 1][z + 1]);\n", " }\n", " }\n", @@ -882,7 +882,7 @@ " {\n", " for (int z = z_m; z <= z_M; z += 1)\n", " {\n", - " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y) + (-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", + " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y) + (8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", " }\n", " }\n", " }\n", @@ -1020,7 +1020,7 @@ " {\n", " for (int z = z_m; z <= z_M; z += 1)\n", " {\n", - " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y) + (-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", + " u[t1][x + 4][y + 4][z + 4] = (f[x + 1][y + 1][z + 1]*f[x + 1][y + 1][z + 1])*((-6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 1][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 2][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 5][z + 4]/h_y) + (-8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 5][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 7][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 8][z + 4]/h_y) + (8.33333333e-2F/h_y)*(8.33333333e-2F*u[t0][x + 4][y][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 1][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 3][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 4][z + 4]/h_y) + (6.66666667e-1F/h_y)*(8.33333333e-2F*u[t0][x + 4][y + 3][z + 4]/h_y - 6.66666667e-1F*u[t0][x + 4][y + 4][z + 4]/h_y + 6.66666667e-1F*u[t0][x + 4][y + 6][z + 4]/h_y - 8.33333333e-2F*u[t0][x + 4][y + 7][z + 4]/h_y))*sinf(f[x + 1][y + 1][z + 1]);\n", " }\n", " }\n", " }\n", diff --git a/tests/test_dtypes.py b/tests/test_dtypes.py index ef0b6f41e8..d3f7fadc01 100644 --- a/tests/test_dtypes.py +++ b/tests/test_dtypes.py @@ -1,3 +1,4 @@ +import ctypes import pickle from pathlib import Path @@ -22,7 +23,7 @@ from devito.symbolics import DefFunction, sympy_dtype from devito.symbolics.extended_dtypes import ctypes_vector_mapper from devito.tools import dtype_to_cstr, dtypes_vector_mapper, extract_dtype, infer_dtype -from devito.types import ComponentAccess +from devito.types import Array, ComponentAccess, Pointer from devito.types.basic import Basic, Scalar, Symbol from devito.types.dense import TimeFunction from devito.types.sparse import SparseTimeFunction @@ -103,6 +104,23 @@ def test_vector_inference(): assert (f + ComponentAccess(v, 0)).dtype == np.float32 +@pytest.mark.parametrize('dtype', [np.float32, np.float64]) +def test_array_components(dtype): + grid = Grid(shape=(4,)) + x, = grid.dimensions + vector = dtypes_vector_mapper[dtype, 2] + array = Array(name='a', dimensions=x, dtype=vector) + assert ComponentAccess(array[x], 0).dtype == dtype + assert extract_dtype(ComponentAccess(array[x], 1)) == dtype + + +def test_pointer_stars(): + p = Pointer(name='p', dtype_base=ctypes.c_float) + q = Pointer(name='p', dtype_base=ctypes.c_float, stars='**') + + assert p != q + + @pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) @pytest.mark.parametrize('kwargs', _configs, ids=kw_id) def test_dtype_mapping(dtype: np.dtype[np.inexact], kwargs: dict[str, str], diff --git a/tests/test_iet.py b/tests/test_iet.py index 129ffc2fc1..620505e38f 100644 --- a/tests/test_iet.py +++ b/tests/test_iet.py @@ -725,7 +725,7 @@ def test_list_inline(): def test_dereference_base_plus_off(): - ptr = Pointer(name='p', dtype=np.float32) + ptr = Pointer(name='p', dtype_base=np.float32) off = Symbol(name='offs', dtype=np.int32) dim0 = CustomDimension(name='d0', symbolic_size=2) diff --git a/tests/test_operator.py b/tests/test_operator.py index b87a9c02d3..4e72acc9d6 100644 --- a/tests/test_operator.py +++ b/tests/test_operator.py @@ -22,7 +22,9 @@ TensorFunction, TensorTimeFunction, TimeFunction, VectorFunction, VectorTimeFunction, configuration, dimensions, div, error, exp, grad, sin, switchconfig ) +from devito.arch import compiler_registry from devito.arch.archinfo import Device +from devito.arch.compiler import GNUCompiler from devito.exceptions import InvalidOperator from devito.finite_differences.differentiable import diff2sympy from devito.ir.clusters import Cluster @@ -44,6 +46,17 @@ from devito.warnings import DevitoWarning +class AbiCompiler(GNUCompiler): + + """Give identically configured compilers distinct ABIs through their names.""" + + def abi_id(self): + return (super().abi_id(), self.name) + + +compiler_registry.update(dict.fromkeys(('abi-test-0', 'abi-test-1'), AbiCompiler)) + + def dimify(dimensions): assert isinstance(dimensions, str) return tuple(SpaceDimension(name=i) for i in dimensions.split()) @@ -149,6 +162,24 @@ def test_opt_options(self): Operator(Eq(u, u + 1), opt=('advanced', {'buf-async-degree': async_degree})) + for mode in (False, 'float16'): + with pytest.raises(InvalidOperator, match='arithm-mode.*default.*fp16'): + Operator(Eq(u, u + 1), sym_opt={'arithm-mode': mode}) + + @pytest.mark.parametrize('mode', ['default', 'fp16']) + def test_arithmetic_mode(self, mode): + grid = Grid(shape=(4, 4)) + + f = Function(name='f', grid=grid, dtype=np.float16) + + eq = Eq(f, f + 1) + + options = {'arithm-mode': mode} + op = Operator(eq, sym_opt=options) + + assert op._sym_options['arithm-mode'] == mode + assert options == {'arithm-mode': mode} + def test_compiler_uniqueness(self): grid = Grid(shape=(3, 3, 3)) @@ -201,6 +232,22 @@ def test_jit_compiler_flags(self, envvar, flags, monkeypatch): assert op0._soname != op1._soname assert op1._soname == op2._soname + @pytest.mark.parametrize('mode', ['default', 'fp16']) + def test_jit_compiler_abi(self, mode): + grid = Grid(shape=(4, 4)) + + f = Function(name='f', grid=grid) + + eq = Eq(f, f + 1) + + first, second = [Operator(eq, sym_opt={'arithm-mode': mode}, + platform='cpu64', language='C', compiler=name) + for name in ('abi-test-0', 'abi-test-1')] + + assert str(first.ccode) == str(second.ccode) + assert first._compiler._signature_items() == second._compiler._signature_items() + assert first._soname != second._soname + @pytest.mark.parametrize('name', ['r0', 'r1']) def test_generated_names_avoid_inputs(self, name): grid = Grid(shape=(8, 8), extent=(7., 7.)) @@ -2409,6 +2456,18 @@ def test_pseudo_time_dep(self): assert_structure(op, ['t,x,y', 't', 't,x,y'], 't,x,y,x,y') + def test_topofuse_weak_keys(self): + """Different shared-read preferences must not suppress topological sorting.""" + grid = Grid(shape=(4, 4)) + a, b, p, q = [Function(name=n, grid=grid, space_order=0) for n in 'abpq'] + shared = Array(name='shared', dimensions=grid.dimensions, scope='shared') + r0, r1 = [Symbol(name=n) for n in ('r0', 'r1')] + equations = [Eq(r0, 2*a), Eq(p, r0*shared), + Eq(r1, 3*b), Eq(q, r1*shared)] + op = Operator(equations, opt=('topofuse', {'openmp': False})) + writes = [e.expr.lhs for e in FindNodes(Expression).visit(op)] + assert writes == [r0, r1, p.indexify(), q.indexify()] + class TestInternals: diff --git a/tests/test_pickle.py b/tests/test_pickle.py index 10606f9abc..4436d67ec4 100644 --- a/tests/test_pickle.py +++ b/tests/test_pickle.py @@ -25,10 +25,11 @@ as_long, indexify, pow_to_mul ) from devito.symbolics.unevaluation import Mod -from devito.tools import EnrichedTuple +from devito.tools import CustomDtype, EnrichedTuple, Pickable, ctypes_to_cstr from devito.types import ( Array, ComponentAccess, CustomDimension, DefaultDimension, DeviceID, FIndexed, - Indirection, Lock, NPThreads, PointerArray, PThreadArray, Region, Scalar, SharedData + Indirection, Lock, NPThreads, Pointer, PointerArray, PThreadArray, Region, Scalar, + SharedData ) from devito.types import Symbol as dSymbol from devito.types import TempFunction, ThreadID, Timer @@ -75,6 +76,49 @@ def test_abstractsymbol(self, pickle): assert s0 == new_s0 assert s1 == new_s1 + @pytest.mark.parametrize('protocol', [0, pickle0.HIGHEST_PROTOCOL]) + def test_ignored_state(self, pickle, protocol): + obj = Pickable() + obj.__rignored__ = ('cache',) + obj.cache = lambda: None + obj.value = 3 + + restored = pickle.loads(pickle.dumps(obj, protocol=protocol)) + + assert restored.value == obj.value + assert 'cache' not in restored.__dict__ and 'cache' in obj.__dict__ + + def test_indexed_cached_ctype(self, pickle): + grid = Grid(shape=(4, 4)) + f = Function(name='f', grid=grid) + indexed = f.indexed + ctype = indexed._C_ctype + + restored = pickle.loads(pickle.dumps(indexed)) + assert restored.function.name == f.name + assert restored.function.dtype == f.dtype + assert restored._C_ctype == ctype + + @pytest.mark.parametrize('dtype_base,stars,expected', [ + (None, '*', 'void *'), + (np.float32, '*', 'float *'), + (np.float32, '**', 'float **'), + (np.float32, '***', 'float ***'), + (ctypes.c_float, '*', 'float *'), + ('cufftHandle', '', 'cufftHandle'), + (CustomDtype('float'), '*', 'float*'), + ]) + def test_typed_pointer(self, pickle, dtype_base, stars, expected): + p = Pointer(name='p', dtype_base=dtype_base, stars=stars, + liveness='eager', scope='shared') + assert p.dtype is p.dtype + + restored = pickle.loads(pickle.dumps(p)) + assert restored.name == p.name + assert restored.dtype_base == dtype_base and restored.stars == stars + assert ctypes_to_cstr(restored._C_ctype) == expected + assert restored.liveness == p.liveness and restored.scope == p.scope + def test_constant(self, pickle): c = Constant(name='c') assert c.data == 0. diff --git a/tests/test_symbolics.py b/tests/test_symbolics.py index b6b13eb0bd..976a15f3cb 100644 --- a/tests/test_symbolics.py +++ b/tests/test_symbolics.py @@ -21,16 +21,20 @@ from devito.passes.iet.languages.openacc import AccPrinter from devito.symbolics import ( # noqa INT, BaseCast, CallFromComposite, CallFromPointer, Cast, DefFunction, - FieldFromComposite, FieldFromPointer, IntDiv, ListInitializer, Namespace, - ReservedWord, RoundUp, Rvalue, SizeOf, VectorAccess, evalrel, pow_to_mul, q_negative, - q_positive, retrieve_derivatives, retrieve_functions, retrieve_indexed, - subs_if_composite, unevaluate, uxreplace, xreplace_indices + FieldFromComposite, FieldFromPointer, IndexedPointer, IntDiv, ListInitializer, + Namespace, ReservedWord, RoundUp, Rvalue, SizeOf, VectorAccess, cast, evalrel, + has_integer_args, pow_to_mul, q_negative, q_positive, retrieve_derivatives, + retrieve_functions, retrieve_indexed, subs_if_composite, unevaluate, uxreplace, + xreplace_indices ) from devito.symbolics.unevaluation import Add as UnevalAdd from devito.symbolics.unevaluation import Mul as UnevalMul -from devito.tools import CustomDtype, as_tuple, dtypes_vector_mapper, frozendict +from devito.tools import ( + CustomDtype, as_tuple, dtypes_vector_mapper, extract_dtype, frozendict +) from devito.types import ( - Array, Bundle, ComponentAccess, FIndexed, LocalObject, Object, StencilDimension + Array, Bundle, ComponentAccess, CustomDimension, FIndexed, LocalObject, Object, + StencilDimension ) from devito.types import Symbol as dSymbol from devito.types import Temp @@ -278,6 +282,15 @@ def test_bundle(): assert fg._rebuild().components == fg.components +def test_pointer_cast_dtype(): + dimension = CustomDimension(name='d', symbolic_size=4) + table = Array(name='table', dimensions=dimension, dtype=np.uint32) + dtype = dtypes_vector_mapper[np.float32, 2] + pointer = cast(dtype, '*')(table.indexed, reinterpret=True) + access = IndexedPointer(pointer, dimension) + assert access.dtype == extract_dtype(access) == dtype + + def test_call_from_pointer(): s = Symbol('s') @@ -353,6 +366,17 @@ def test_field_from_composite(): assert ffc1.free_symbols == {s} +@pytest.mark.parametrize('dtype, expected', [ + (np.int32, True), (c_uint64, True), (np.float32, False), + (CustomDtype('size_t'), False) +]) +def test_integer_args(dtype, expected): + s = dSymbol('s', dtype=dtype) + + assert has_integer_args(s) == expected + assert has_integer_args(s, 1) == expected + + def test_extended_sympy_arithmetic(): # NOTE: `s` gets turned into a devito.Symbol, whose dtype # defaults to np.int32 @@ -446,6 +470,17 @@ def test_lowered_sign_identity(): assert ccode(UnevalMul(-1, -1)) == '1' +def test_lowered_reciprocal_product(): + h, k = [dSymbol(i, dtype=np.float32) for i in ('h', 'k')] + + assert ccode(unevaluate(pow_to_mul(-2.0/h**2))) == '-2.0F/(h*h)' + assert ccode(unevaluate(pow_to_mul(-2.0/(h**2*k**2)))) == '-2.0F/((h*h)*(k*k))' + + +def test_product_math_macro(): + assert ccode(-sympy.pi/2) == '-M_PI_2' + + @pytest.mark.parametrize('cls, lowered', [ (sympy.Add, UnevalAdd), (sympy.Mul, UnevalMul) @@ -461,6 +496,16 @@ def test_freeze_grouping(cls, lowered): assert unevaluate(frozen) is frozen +def test_freeze_derivative(): + grid = Grid(shape=(8, 8)) + + f = Function(name='f', grid=grid, space_order=4) + + derivative = f.dx._evaluate(expand=False) + + assert unevaluate(derivative) is derivative + + def test_freeze_equal_instances(): a = Symbol.__xnew__(Symbol, 'equal_frozen_operand') b = Symbol.__xnew__(Symbol, 'equal_frozen_operand') @@ -481,7 +526,7 @@ def test_lowered_integer_offset(dtype, offset, expected): expr = size + offset lowered = unevaluate(expr) - assert lowered.args == expr.args + assert lowered.args == (size, offset) assert ccode(lowered) == 'bx_size' + expected # Renaming preserves the tree, while printing remains canonical @@ -663,6 +708,8 @@ def test_roundup(): with switchconfig(platform='bdw', language='openmp'): op = Operator(Eq(u, u + expr)) + assert expr.is_integer is True + assert (16*expr) % 16 == 0 assert ccode(expr) == 'ROUND_UP(a, 16)' assert '#define ROUND_UP(a,b)' in str(op) assert 'ROUND_UP(a, 16)' in str(op) @@ -1344,6 +1391,60 @@ def test_findexed_strides(self): assert rebuilt.strides == (b,) assert expr.strides == (a,) + @pytest.mark.parametrize('op, separator', [(UnevalAdd, ' + '), (UnevalMul, '*')]) + @pytest.mark.parametrize('dtype', [np.float16, np.float32]) + def test_uxreplace_order(self, op, separator, dtype): + a, b, c, z = [dSymbol(name=n, dtype=dtype) for n in 'abcz'] + expr = op(c, b, a) + assert expr.args == (c, b, a) + assert ccode(expr) == separator.join(('a', 'b', 'c')) + + rebuilt = uxreplace(expr, {a: z}) + + assert rebuilt.args == (c, b, z) + assert ccode(rebuilt) == separator.join(('b', 'c', 'z')) + assert uxreplace(rebuilt, {z: a, b: z, c: b}).args == (b, z, a) + assert uxreplace(expr, {z: a}) is expr + + @pytest.mark.parametrize('op, result', [(UnevalAdd, 5), (UnevalMul, 6)]) + def test_uxreplace_reconstruction(self, op, result): + a, b, c, z = [dSymbol(name=n) for n in 'abcz'] + nested = op(b, c) + expr = op(a, nested) + + assert uxreplace(expr, {a: z}).args == (z, nested) + assert uxreplace(op(a, b), {a: Number(2), b: Number(3)}) == result + + @pytest.mark.parametrize('op', [UnevalAdd, UnevalMul]) + def test_uxreplace_compound_order(self, op): + a, b, c, d, t, z = [dSymbol(name=n) for n in 'abcdtz'] + expr = op(a, b, c, d) + + rebuilt = uxreplace(expr, {expr: {c: t, d: None}, b: z}) + + assert rebuilt.args == (a, z, t) + + def test_unevaluated_factorization(self): + grid = Grid(shape=(8,)) + + a, b, c, z, out, ref = [Function(name=n, grid=grid, space_order=0) + for n in ('a', 'b', 'c', 'z', 'out', 'ref')] + + eq = uxreplace(Eq(out, UnevalAdd(UnevalMul(a, b), UnevalMul(a, c))), {a: z}) + eq0 = Eq(ref, z*b + z*c) + + reference = Operator(eq0, opt='noop') + candidate = Operator(eq, opt='advanced') + + z.data[:] = (np.arange(8) + 1)*.125 + b.data[:] = np.arange(8) + 1 + c.data[:] = -np.arange(8)*.03125 + + assert 'b[x]*z[x] + c[x]*z[x]' in str(candidate) + reference.apply() + candidate.apply() + assert np.allclose(out.data, ref.data) + def test_minmax(): grid = Grid(shape=(5, 5))