Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions flax/core/lift.py
Original file line number Diff line number Diff line change
Expand Up @@ -1604,6 +1604,7 @@ def jit(
donate_argnums: int | Iterable[int] = (),
device=None,
backend: str | None = None,
inline: bool | jax.Inline = False,
) -> Callable[..., Any]:
"""Lifted version of ``jax.jit``.

Expand Down Expand Up @@ -1643,6 +1644,8 @@ def jit(
``jax.devices()[0]``.
backend: a string representing the XLA backend: ``'cpu'``, ``'gpu'``, or
``'tpu'``.
inline: Optional boolean or :class:`jax.Inline` value controlling inlining
of calls to the jitted function (for example ``jax.Inline.XLA_LATE``).

Returns:
A wrapped version of ``fn``, set up for just-in-time compilation.
Expand All @@ -1668,6 +1671,7 @@ def jit(
donate_argnums=donate_argnums,
device=device,
backend=backend,
inline=inline,
)
@functools.wraps(fn)
def jitted(fingerprint, variable_groups, rng_groups, *args, **kwargs):
Expand Down
22 changes: 13 additions & 9 deletions flax/linen/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -925,15 +925,16 @@ def vmap(


def jit(
target: Target,
variables: CollectionFilter = True,
rngs: PRNGSequenceFilter = True,
static_argnums: int | Iterable[int] = (),
static_argnames: str | Iterable[str] = (),
donate_argnums: int | Iterable[int] = (),
device=None,
backend: str | None = None,
methods=None,
target: Target,
variables: CollectionFilter = True,
rngs: PRNGSequenceFilter = True,
static_argnums: int | Iterable[int] = (),
static_argnames: str | Iterable[str] = (),
donate_argnums: int | Iterable[int] = (),
device=None,
backend: str | None = None,
methods=None,
inline: bool | jax.Inline = False,
) -> Target:
"""Lifted version of ``jax.jit``.

Expand Down Expand Up @@ -975,6 +976,8 @@ def jit(
backend: a string representing the XLA backend: ``'cpu'``, ``'gpu'``, or
``'tpu'``.
methods: If ``target`` is a ``Module``, the methods of ``Module`` to jit.
inline: Optional boolean or :class:`jax.Inline` value controlling inlining
of calls to the jitted function (for example ``jax.Inline.XLA_LATE``).

Returns:
A wrapped version of target, set up for just-in-time compilation.
Expand All @@ -991,6 +994,7 @@ def jit(
device=device,
backend=backend,
methods=methods,
inline=inline,
)


Expand Down
32 changes: 32 additions & 0 deletions tests/core/core_lift_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,38 @@ def f(scope, _module_hash, x):
self.assertEqual(compiles, 3) # applying again should not
self.assertEqual(state['intermediates']['x'].sum(), 3 * 2 * 2)

def test_jit_inline_xla_late(self):
compiles = 0

def f_impl(scope, unused_module_hash, x):
nonlocal compiles
compiles += 1
return nn.dense(scope, x, 2)

f = lift.jit(f_impl, inline=jax.Inline.XLA_LATE)
x = jnp.ones((3, 2))
_, params = init(f)(random.key(0), 1, x)
compiles = 0

def run_twice(p0, p1, y):
y = apply(f)(p0, 1, y)
return apply(f)(p1, 1, y)

lowered_text = jax.jit(run_twice).lower(params, params, x).as_text()
self.assertEqual(compiles, 1)
# Check that both calls share a single lowered callee definition.
private_funcs = [
line
for line in lowered_text.splitlines()
if 'func.func private ' in line
]
self.assertLen(private_funcs, 1)
# Check that both callsites carry the per-callsite `inlineable = "xla_late"`
# frontend attribute.
self.assertEqual(lowered_text.count('inlineable = "xla_late"'), 2)
expected = apply(f_impl)(params, 1, apply(f_impl)(params, 1, x))
np.testing.assert_allclose(run_twice(params, params, x), expected)

def test_vjp(self):
def g(scope, x, y):
p = scope.param('test', nn.initializers.constant(0.5), ())
Expand Down
58 changes: 58 additions & 0 deletions tests/linen/linen_transforms_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2791,6 +2791,64 @@ def __call__(self, inputs):
self.assertEqual(trace_counts[0], 2 if retracing_scan else 1)
self.assertEqual(trace_counts[1], 2 if retracing_scan else 1)

def test_jit_inline_xla_late(self):
trace_count = 0

class Block(nn.Module):
dim: int

@nn.compact
def __call__(self, x):
nonlocal trace_count
trace_count += 1
return nn.Dense(self.dim)(nn.relu(x)) + x

class MiniModel(nn.Module):
inline: bool | jax.Inline | None = None

def setup(self):
block_cls = (
Block
if self.inline is None
else nn.jit(Block, inline=self.inline)
)
self.layers = [block_cls(4, name=f'block_{i}') for i in range(3)]

def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x

x = jnp.ones((2, 4))
ref_model = MiniModel(inline=None)
late_model = MiniModel(inline=jax.Inline.XLA_LATE)
inlined_model = MiniModel(inline=True)
variables = ref_model.init(random.key(0), x)

trace_count = 0
lowered_late = jax.jit(late_model.apply).lower(variables, x).as_text()
self.assertEqual(trace_count, 1)
# Check that all 3 layers share a single lowered callee definition.
core_fn_funcs = [
line
for line in lowered_late.splitlines()
if 'func.func private @core_fn' in line
]
self.assertLen(core_fn_funcs, 1)
# Check that all 3 callsites invoke the shared callee and carry the
# per-callsite `inlineable = "xla_late"` frontend attribute.
self.assertEqual(lowered_late.count('call @core_fn('), 3)
self.assertEqual(lowered_late.count('inlineable = "xla_late"'), 3)

# With inline=True, JAX inlines the callee at lowering time.
lowered_inlined = jax.jit(inlined_model.apply).lower(variables, x).as_text()
self.assertNotIn('func.func private @core_fn', lowered_inlined)
self.assertNotIn('inlineable = "xla_late"', lowered_inlined)

expected = ref_model.apply(variables, x)
np.testing.assert_allclose(late_model.apply(variables, x), expected)
np.testing.assert_allclose(inlined_model.apply(variables, x), expected)


if __name__ == '__main__':
absltest.main()
Loading