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
15 changes: 5 additions & 10 deletions brax/training/agents/ppo/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,16 +753,11 @@ def training_epoch_with_timing(
{},
)

devices = jax.local_devices()[:local_devices_to_use]
mesh = jax.sharding.Mesh(np.array(devices), ('_device_put_sharded',))
sharding = jax.NamedSharding(mesh, jax.P('_device_put_sharded'))

def _replicate(x):
if isinstance(x, jax.Array):
return jax.device_put(jnp.stack([x] * len(devices)), sharding)
return jax.device_put(np.stack([x] * len(devices)), sharding)

training_state = jax.tree_util.tree_map(_replicate, training_state)
training_state = pmap.bcast_local_devices(
training_state,
local_devices_to_use,
axis_name=_PMAP_AXIS_NAME,
)

eval_env = _maybe_wrap_env(
eval_env or environment,
Expand Down
8 changes: 5 additions & 3 deletions brax/training/pmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@
import numpy as np


def bcast_local_devices(value, local_devices_to_use=1):
def bcast_local_devices(
value, local_devices_to_use=1, axis_name='_device_put_sharded'
):
"""Broadcasts an object to all local devices."""
devices = jax.local_devices()[:local_devices_to_use]
mesh = jax.sharding.Mesh(np.array(devices), ('_device_put_sharded',))
sharding = jax.NamedSharding(mesh, jax.P('_device_put_sharded'))
mesh = jax.sharding.Mesh(np.array(devices), (axis_name,))
sharding = jax.NamedSharding(mesh, jax.P(axis_name))

def _replicate(x):
if isinstance(x, jax.Array):
Expand Down
35 changes: 35 additions & 0 deletions brax/training/pmap_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2026 The Brax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for pmap utilities."""

from absl.testing import absltest
from brax.training import pmap
import jax
import jax.numpy as jnp


class PmapTest(absltest.TestCase):

def testBcastLocalDevicesUsesRequestedAxisName(self):
value = pmap.bcast_local_devices(
jnp.arange(4), local_devices_to_use=1, axis_name='i'
)

self.assertEqual(value.sharding.mesh.axis_names, ('i',))
self.assertEqual(value.sharding.spec, jax.P('i'))


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