Skip to content

compiler: Misc tweaks to fully support FP16 storage/compute across all backends - #3109

Open
FabioLuporini wants to merge 20 commits into
mainfrom
fix/fp16-wdr-storage
Open

FabioLuporini wants to merge 20 commits into
mainfrom
fix/fp16-wdr-storage

Conversation

@FabioLuporini

Copy link
Copy Markdown
Contributor

No description provided.

@codecov

codecov Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.43860% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 84.04%. Comparing base (2681402) to head (07a2e2c).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
devito/symbolics/extended_sympy.py 57.14% 4 Missing and 2 partials ⚠️
devito/ir/cgen/printer.py 81.81% 2 Missing and 2 partials ⚠️
devito/ir/iet/visitors.py 50.00% 1 Missing and 1 partial ⚠️
devito/passes/iet/definitions.py 92.30% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3109      +/-   ##
==========================================
+ Coverage   83.96%   84.04%   +0.08%     
==========================================
  Files         261      261              
  Lines       60017    60238     +221     
  Branches     5065     5088      +23     
==========================================
+ Hits        50393    50629     +236     
+ Misses       8780     8762      -18     
- Partials      844      847       +3     
Flag Coverage Δ
pytest-gpu-aomp-amdgpuX 68.24% <66.47%> (-0.03%) ⬇️
pytest-gpu-gcc- 78.87% <95.43%> (+0.15%) ⬆️
pytest-gpu-icx- 78.80% <95.43%> (+36.55%) ⬆️
pytest-gpu-nvc-nvidiaX 69.05% <66.47%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@FabioLuporini
FabioLuporini force-pushed the fix/fp16-wdr-storage branch 3 times, most recently from 9645b9a to d500a13 Compare November 16, 2026 14:58
Comment thread devito/mpi/routines.py Outdated
f = alias or self.target.c0
neighborhood = f.grid.distributor.neighborhood
# Internal Arrays may retain a serialized, non-distributed Grid
neighborhood = args.grid.distributor.neighborhood

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This gets rehashed in #3108 . Also pretty sure this is undoing a functions on subdomains bug that got patched...

Comment thread devito/symbolics/extended_sympy.py Outdated
def _eval_is_integer(self):
dtype = extract_dtype(self.value)
if (self.value.is_integer or
isinstance(dtype, type) and issubclass(dtype, np.integer)):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why would dtype not be a type?

Comment thread devito/types/misc.py
return self._dtype
ctype = self.dtype_base
if isinstance(ctype, CustomDtype):
return CustomDtype(ctype.name, ctype.template, ctype.modifier + self.stars)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that this is returning a new CustomDtype, does this property need caching to avoid duplication?

Comment thread tests/test_operator.py Outdated
op = Operator(Eq(f, f + 1), sym_opt=options)

assert op._sym_options['arithm-mode'] == mode
assert 'half-arith' not in op._sym_options

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems a bit redundant to check the old name isn't in there?

Comment thread tests/test_operator.py Outdated
assert options == {'arithm-mode': mode}

@pytest.mark.parametrize('mode', [None, False, True, 1, 'float16', {}, []])
def test_invalid_arithmetic_mode(self, mode):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably an overkill test?

Comment thread tests/test_operator.py Outdated
assert op1._soname == op2._soname

@pytest.mark.parametrize('mode', ['default', 'fp16'])
def test_jit_compiler_abi(self, mode, monkeypatch):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try to avoid monkeypatching?

Comment thread devito/symbolics/manipulation.py Outdated
return expr.func(*args)


@_uxreplace_handle.register(OrderedAdd)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes no sense OrderedAdd is an Add why doesn't the dispatch already do that

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's exactly the point ; a plain Add, like also a sympy.Add, is subjected to reordering of the arguments based on the canonical ordering. Here we want to bypass that , so that if u have an Add a+b+c and then a substitution a->z so that u get z+b+c, then you remain with z+b+c, instead of b+c+z

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, maybe UnevaluatedAdd already did that? will look into this...

Comment thread devito/types/basic.py Outdated
def __getstate__(self):
state = dict(self.__dict__)
# Recreate process-local ctypes classes from the Function's dtype
state.pop('_C_ctype', None)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would be better if Pickable implementent something like _ignored_state so that don't need to add __getstate__ everywhere and just

_ignored_state = '_C_ctype`.

would extend to a bunch of place wehre we have stuff like that

Comment thread tests/test_iet.py Outdated

def test_dereference_base_plus_off():
ptr = Pointer(name='p', dtype=np.float32)
ptr = Pointer(name='p', dtype_base=c_float)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why would we used lowered ctypes instead of the numpy dtype and lower it like for everything else?

Comment thread devito/symbolics/unevaluation.py Outdated
__new__ = UnevaluableMixin.__new__


class OrderedAdd(Add):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I appreciate why we need yet another class. Making UnevaluatedAdd ordered would make things much simpler and i doubt it would create issues.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can look into this. I may simply have forgotten how UnevaluatedAdd behaved

Comment thread devito/types/misc.py
return self._dtype
ctype = self.dtype_base
if isinstance(ctype, CustomDtype):
return CustomDtype(ctype.name, ctype.template, ctype.modifier + self.stars)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does it need to create a new one insted of letting the printer handle the stars like for Cast

@FabioLuporini
FabioLuporini force-pushed the fix/fp16-wdr-storage branch 2 times, most recently from c6f3d1a to c8bf5ee Compare November 27, 2026 17:28
@review-notebook-app

Copy link
Copy Markdown

Review Notebooks

Notebooks changed:

Review visual diffs and comment on any notebook cell. All comments sync back to this PR.


Powered by ReviewNB

FabioLuporini and others added 12 commits December 1, 2026 15:23
Copilot now supplies saved Function replacements with matching ConditionalDimension factors, so the broad override filter is unnecessary.
Use arithm-mode throughout symbolic lowering and include generated source and compiler ABI in every Operator signature. Preserve scalar component and cast-pointer result types for ordinary packed accesses.

Validate focused CPU typing, JIT identity and serialization checks, plus the dependent PRO GPU arithmetic checks.
Store the picklable pointee type and indirection in standard reconstruction
metadata, deriving the full ctype on demand. Remove the custom ctypes pointer
reducer and cover pointer depth, equality, scope and serialization.
Resolve MPI neighbors from the execution Grid so reconstructed internal Arrays communicate between decoupler workers. Also wrap the overlong symbolic-test imports.
Return a conservative result for C-only types such as size_t instead of passing NumPy's TypeError through FP16 code generation. Cover numeric ctypes and opaque dtypes in scalar and mixed argument queries.

Validation: 9 targeted OSS symbolic tests, 12 CUDA regression and adjacent tests, isort, Flake8, and Ruff.
Select the RHS precision before creating an exact-precision printer and forward normalized Operator options to dtype-specific lowering passes.
Keep marked sums and products opaque to CSE and factorization, and
preserve their stored operand order when printing. Dedicated uxreplace
handlers retain the existing scalar reconstruction semantics.

Cover FP16/FP32 printing, substitutions and Operator factorization.
Codex and others added 8 commits December 1, 2026 15:23
Comment thread devito/ir/cgen/printer.py
Comment on lines +305 to +330
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)})"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a lot of extra complexity without any clear explanation of what it's doing

# E.g., unsympified `int`
args, eargs = [], []
changed = False
changed = expr.__class__ in rule

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grab the # Exact type -> type substitution comment from before

Comment thread devito/tools/abc.py
state = ret[2] if len(ret) > 2 else None
if state is None:
state = self.__dict__
ignored = as_tuple(self.__rignored__)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just set __rignored__ as a tuple consistently in the first place?

Comment thread tests/test_operator.py

class AbiCompiler(GNUCompiler):

"""Give identically configured compilers distinct ABIs through their names."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this needed for?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants