sharding.py 14.8 KB
Newer Older
1
# Copyright (c) 2022-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
#
# See LICENSE for license information.
4
5
6
7
8
9
10
"""Sharding utilities for Transformer Engine in JAX.

This module provides utilities for managing tensor sharding in distributed training,
including support for various parallelism strategies like data parallelism (DP),
tensor parallelism (TP), pipeline parallelism (PP), and full-sharded data
parallelism (FSDP). It includes functions for sharding constraints, mesh management,
and collective operations.
11
12
13
"""
from contextlib import contextmanager
from dataclasses import dataclass
14
from typing import Callable, Optional
15
import warnings
Phuong Nguyen's avatar
Phuong Nguyen committed
16

17
18
import jax
import jax.numpy as jnp
19
20
from jax.interpreters import pxla
from jax.sharding import PartitionSpec, get_abstract_mesh
21
import numpy as np
22
23
24

_PXLA_THREAD_RESOURCES = pxla.thread_resources

25
# Axis Names
26
27
28
BATCH_AXES = "nvte_batch"
SEQLEN_AXES = "nvte_seqlen"
SEQLEN_TP_AXES = "nvte_seqlen_tp"
29
SEQLEN_CP_AXES = "nvte_seqlen_cp"
30
31
32
33
34
35
36
37
HEAD_AXES = "nvte_head"
HIDDEN_AXES = "nvte_hidden"
HIDDEN_TP_AXES = "nvte_hidden_tp"
JOINED_AXES = "nvte_joined"
W_NO_SHARD_AXES = "nvte_w_no_shard"
W_FSDP_AXES = "nvte_w_fsdp"
W_TP_AXES = "nvte_w_tp"
W_JOINED_AXES = "nvte_w_joined"
38

39

40
def _get_mesh_info(resource: str, mesh: jax.sharding.Mesh):
41
    assert resource in mesh.axis_names, f"{resource} is not in the axis_names of Mesh {mesh}."
42
43
44
    return mesh.shape[resource], resource


45
def _validate_mesh_resource_configuration(mesh_resource):
46
    """Validate that the mesh resource configuration is consistent and conflict-free."""
47
48
49
50
51
52
53
54
55
56
57
58
59
60
    is_dp_enabled = (
        mesh_resource.dp_resource is not None and get_mesh_axis_size(mesh_resource.dp_resource) > 1
    )
    is_tp_enabled = (
        mesh_resource.tp_resource is not None and get_mesh_axis_size(mesh_resource.tp_resource) > 1
    )
    is_tpsp_enabled = (
        mesh_resource.tpsp_resource is not None
        and get_mesh_axis_size(mesh_resource.tpsp_resource) > 1
    )
    is_fsdp_enabled = (
        mesh_resource.fsdp_resource is not None
        and get_mesh_axis_size(mesh_resource.fsdp_resource) > 1
    )
61

62
63
    assert not (is_dp_enabled and is_fsdp_enabled), (
        "Data parallelism and full-sharded data parallelism cannot be enabled at the same time."
64
65
        f" Got dp_resource={mesh_resource.dp_resource} and"
        f" fsdp_resource={mesh_resource.fsdp_resource}"
66
67
68
    )
    assert not (is_tp_enabled and is_tpsp_enabled), (
        "Tensor parallelism and tensor sequence parallelism cannot be enabled at the same time."
69
70
        f" Got tp_resource={mesh_resource.tp_resource} and"
        f" tpsp_resource={mesh_resource.tpsp_resource}"
71
    )
72
73


74
75
76
77
def get_sharding_map_logic_axis_to_mesh_axis():
    """
    Generate a dict to map logical axes to mesh axes.
    """
78
79
80
81
82
83
84
85
86
87
    mesh = _PXLA_THREAD_RESOURCES.env.physical_mesh
    if mesh is None or mesh.empty:
        # If no mesh is defined, return an empty dict and do not require a MeshResource context to be present
        return {}

    abstract_mesh = get_abstract_mesh()
    if sorted(abstract_mesh.manual_axes) == sorted(mesh.axis_names):
        # If all mesh axes are manual axes, return an empty dict and do not require a MeshResource context to be present
        return {}

88
89
90
91
    gsr = global_mesh_resource()

    is_tpsp_enabled = gsr.tpsp_resource is not None and get_mesh_axis_size(gsr.tpsp_resource) > 1
    is_fsdp_enabled = gsr.fsdp_resource is not None and get_mesh_axis_size(gsr.fsdp_resource) > 1
92
93

    te_logical_axis_to_mesh_axis = {
94
        BATCH_AXES: gsr.fsdp_resource if is_fsdp_enabled else gsr.dp_resource,
95
        SEQLEN_AXES: None,
96
        SEQLEN_TP_AXES: gsr.tpsp_resource,
97
        SEQLEN_CP_AXES: gsr.cp_resource,
98
        HEAD_AXES: gsr.tpsp_resource if is_tpsp_enabled else gsr.tp_resource,
99
        HIDDEN_AXES: None,
100
        HIDDEN_TP_AXES: gsr.tpsp_resource if is_tpsp_enabled else gsr.tp_resource,
101
102
103
        JOINED_AXES: None,
        W_NO_SHARD_AXES: None,
        W_FSDP_AXES: gsr.fsdp_resource,
104
        W_TP_AXES: gsr.tpsp_resource if is_tpsp_enabled else gsr.tp_resource,
105
106
107
108
109
        W_JOINED_AXES: None,
    }
    return te_logical_axis_to_mesh_axis


110
def _generate_pspec(logical_axis_names):
111
    """
112
113
114
115
116
117
118
    Convert TransformerEngine logical axes (e.g. BATCH_AXES) to a JAX PartitionSpec.
    Note, this method does not support Flax logical axes.

    Args:
        logical_axis_names: TransformerEngine logical axes to convert to a JAX PartitionSpec.
    Returns:
        A JAX PartitionSpec with the mesh axes corresponding to the given TransformerEngine logical axis names
119
    """
120
121
122
    rules = get_sharding_map_logic_axis_to_mesh_axis()

    mesh_axis_names = [rules.get(name) for name in logical_axis_names]
123
124
125
126
127
128
    pspec = jax.sharding.PartitionSpec(*mesh_axis_names)
    return pspec


def with_sharding_constraint(x: jnp.array, pspec: PartitionSpec):
    """
129
130
131
132
    A wrapper function to jax.lax.with_sharding_constraint
        1. Does nothing if mesh is empty.
        2. If all mesh axes are manual axes, replaces pspec with all Nones.
        3. Otherwise, strips only the manual axes.
133
134
135
136
137
138
139
    """
    if pspec is None:
        return x

    mesh = _PXLA_THREAD_RESOURCES.env.physical_mesh
    if mesh.empty:
        return x
140
141
142
143

    # We want to exclude the axes that already used by shard_map and shard_map
    # only sets those in the abstract_mesh, not the physical one
    manual_axis_names = get_abstract_mesh().manual_axes
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

    # Multiple mesh axes can be mapped to a single shape axis, so we need to unpack and process tuples here too
    def filter_manual_axes(name_or_tuple):
        if isinstance(name_or_tuple, tuple):
            out = tuple(n for n in name_or_tuple if n not in manual_axis_names)
            if len(out) == 0:
                return None
            return out
        if name_or_tuple in manual_axis_names:
            return None
        return name_or_tuple

    cleaned_axis_names = tuple(filter_manual_axes(name_or_tuple) for name_or_tuple in pspec)

    if cleaned_axis_names == (None,) * len(cleaned_axis_names):
        return x
160
161
162

    cleaned_pspec = PartitionSpec(*cleaned_axis_names)
    return jax.lax.with_sharding_constraint(x, cleaned_pspec)
163
164


165
166
167
def with_sharding_constraint_by_logical_axes(
    x: jnp.array, logical_axis_names: Optional[tuple | list]
):
168
    """
169
170
171
    A wrapper function to flax.linen.with_logical_constraint.

    DEPRECATED USE CASE: If no Flax logical axis rules are available, this function falls back to jax.lax.with_sharding_constraint using a hardcoded logical axis rule table from TE rules, such as BATCH_AXES. This functionality will be removed in the future.
172
173
174
175
176
177
178
179
180
181
182

    If logical_axis_names = None, this means no sharding constraint is applied.

    If logical_axis_names = (None, None, ...), this means a sharding constraint is applied and the tensor is replicated across all devices.

    Args:
        x: Input tensor to apply sharding constraint
        logical_axis_names: Logical axis names to apply sharding constraint
    Returns:
        Tensor with sharding constraint applied, or the original tensor if no logical axes are provided.

183
    """
184
    if not logical_axis_names:
185
186
        return x

187
188
189
190
191
192
193
    try:
        # Check if Flax logical axis rules are available, if so use them
        import flax

        flax_rules = flax.linen.get_logical_axis_rules()
        if len(flax_rules) > 0:
            return flax.linen.with_logical_constraint(
194
                x, logical_axis_names, fallback=flax.linen.spmd.RulesFallback.AXIS_IS_UNSHARDED
195
196
197
198
199
200
201
202
203
204
205
206
207
208
            )
    except ImportError:
        pass

    warnings.warn(
        "TransformerEngine logical axes, such as BATCH_AXES, SEQLEN_AXES, etc. are deprecated and"
        " will be removed in a future version. Please use Flax logical axes with a"
        " flax.linen.logical_axis_rules context and optionally use"
        " transformer_engine.jax.flax.extend_logical_axis_rules to add BATCH_AXES, etc. to your"
        " rules.",
        DeprecationWarning,
    )

    # If no logical axis rules are available from Flax, fallback to TE's hardcoded logical axis rule table
209
    assert len(x.shape) == len(logical_axis_names)
210
    pspec = _generate_pspec(logical_axis_names)
211
212
213
    return with_sharding_constraint(x, pspec)


214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def get_all_mesh_axes():
    """
    Get all name of mesh axes
    """
    mesh = _PXLA_THREAD_RESOURCES.env.physical_mesh
    return mesh.axis_names


def get_padded_spec(spec, ndim):
    """
    Get padded spec for partitioning from arguments' information
    """
    if spec is None:
        return (None,) * ndim
    assert len(spec) <= ndim
    return spec + (None,) * (ndim - len(spec))


232
233
234
def lax_paral_op(
    x: jnp.array, ops: Callable, mesh_resource: str, mesh: jax.sharding.Mesh, **kwargs
):
235
236
237
238
    """
    A wrapper function to invoke lax.p* operations, like psum.
    """
    if mesh_resource is not None:
239
        _, resource = _get_mesh_info(mesh_resource, mesh)
240
        return ops(x, resource, **kwargs)
241
242
243
244
245
246
247
248
249
250
    return x


def num_of_devices():
    """
    Get total number of detected devices
    """
    return len(jax.devices())


251
252
253
254
255
256
257
258
259
260
261
262
263
def get_num_devices_in_mesh(mesh=None):
    """
    Get the number of devices in the given mesh.
    If the mesh is None, it would be replaced
    by the global mesh.
    """
    if mesh is None:
        mesh = _PXLA_THREAD_RESOURCES.env.physical_mesh
    if mesh.empty:
        return 1
    return np.prod(list(mesh.shape.values()))


264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def get_mesh_axis_size(axis, mesh=None):
    """
    Get the axis size of the given mesh.
    If the mesh is None, it would be replaced
    by the global mesh.
    """
    if mesh is None:
        mesh = _PXLA_THREAD_RESOURCES.env.physical_mesh

    if axis is None:
        return 1

    assert axis in mesh.shape, f"{axis} is not a axis of the given mesh {mesh.shape}"
    return mesh.shape[axis]


def get_mesh_axis_rank(axis: str, mesh=None):
    """
    Gets the local axis rank of the `axis` of the array.
    If the mesh is None the rank is 0.
    """
    if mesh is None:
        return 0
    _, axis_name = _get_mesh_info(axis, mesh)
    return jax.lax.axis_index(axis_name)


291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def get_mesh_axis_rank_host(axis, mesh) -> int:
    """
    Same as get_mesh_axis_rank(), but return a host value instead of a
    traced device value.
    """
    if axis not in mesh.axis_names:
        raise ValueError(f"Axis {axis} not found in mesh axis names: {mesh.axis_names}")

    axis_index = mesh.axis_names.index(axis)

    # Convert mesh.devices (ndarray of Device objects) to flat list
    devices = mesh.devices
    local_device = jax.devices()[jax.process_index()]  # Pick one device on this host

    # Find index of local_device in mesh.devices
    coords = np.argwhere(devices == local_device)
    if coords.size == 0:
        raise ValueError(f"Local device {local_device} not found in mesh.devices.")
    coords = tuple(coords[0])  # Coordinates in the mesh array

    # Get the mesh rank along the specified axis
    rank = coords[axis_index]
    return int(rank)


316
@dataclass
317
class MeshResource:
318
319
320
321
322
323
324
325
    """A data container for managing mesh resources in distributed training.

    This class defines the mapping between logical axes and physical mesh axes
    for different types of parallelism in distributed training.

    Attributes:
        dp_resource: Axis name for data parallelism (batch sharding), default is None
        tp_resource: Axis name for tensor parallelism (hidden dimension sharding), default is None
326
        tpsp_resource: Axis name for tensor sequence parallelism (hidden and sequence sharding), default is None
327
328
329
        fsdp_resource: Axis name for full-sharded data parallelism, default is None
        pp_resource: Axis name for pipeline parallelism (layer sharding), default is None
        cp_resource: Axis name for context parallelism (sequence sharding), default is None
330
    """
331

332
333
    dp_resource: str = None
    tp_resource: str = None
334
    tpsp_resource: str = None
335
    fsdp_resource: str = None
336
    pp_resource: str = None
337
    cp_resource: str = None
338
339


340
_GLOBAL_MESH_RESOURCE = None
341
342
343


@contextmanager
344
def global_shard_guard(resource: MeshResource):
345
346
347
348
349
350
351
    """Context manager for setting global sharding configuration.

    This context manager allows temporarily setting the global mesh resource
    configuration for sharding operations.

    Args:
        resource: MeshResource instance defining the sharding configuration
352
    """
353
    global _GLOBAL_MESH_RESOURCE
354
    old_resources = _GLOBAL_MESH_RESOURCE
355
    try:
356
        _GLOBAL_MESH_RESOURCE = resource
357
358
        yield
    finally:
359
        _GLOBAL_MESH_RESOURCE = old_resources
360

361

362
def global_mesh_resource() -> MeshResource:
363
364
365
366
    """Get the current global mesh resource configuration.

    Returns:
        The current MeshResource instance
367
    """
368
369
370
371
372
    assert _GLOBAL_MESH_RESOURCE is not None, (
        "Global mesh resource is not set. Please set the MeshResource via a global_shard_guard"
        " context. If you are not using multiple GPUs, you can use an empty MeshResource by"
        " wrapping your program in 'with global_shard_guard(MeshResource()):'"
    )
373
    _validate_mesh_resource_configuration(_GLOBAL_MESH_RESOURCE)
374
    return _GLOBAL_MESH_RESOURCE
375

376

377
def all_reduce_sum_along_dp_fsdp(x: jnp.array, mesh: jax.sharding.Mesh):
378
379
380
381
382
383
384
385
    """Perform all-reduce sum operation along data parallelism and FSDP axes.

    Args:
        x: Input tensor to reduce
        mesh: JAX mesh for distributed computation

    Returns:
        Reduced tensor
386
    """
387
388
    x = lax_paral_op(x, jax.lax.psum, global_mesh_resource().dp_resource, mesh)
    return lax_paral_op(x, jax.lax.psum, global_mesh_resource().fsdp_resource, mesh)
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403


def all_reduce_sum_along_dp_fsdp_tpsp(x: jnp.array, mesh: jax.sharding.Mesh):
    """Perform all-reduce sum operation along data parallelism and sequence parallelism axes.

    Args:
        x: Input tensor to reduce
        mesh: JAX mesh for distributed computation

    Returns:
        Reduced tensor
    """
    x = lax_paral_op(x, jax.lax.psum, global_mesh_resource().tpsp_resource, mesh)
    x = lax_paral_op(x, jax.lax.psum, global_mesh_resource().dp_resource, mesh)
    return lax_paral_op(x, jax.lax.psum, global_mesh_resource().fsdp_resource, mesh)
404
405


406
def all_reduce_max_along_all_axes_except_PP(x: jnp.array, mesh: jax.sharding.Mesh):
407
408
409
410
411
412
413
414
    """Perform all-reduce max operation along all axes except pipeline parallelism.

    Args:
        x: Input tensor to reduce
        mesh: JAX mesh for distributed computation

    Returns:
        Reduced tensor
415
416
417
418
    """
    all_axes = get_all_mesh_axes()
    for axis in all_axes:
        if axis != global_mesh_resource().pp_resource:
419
            x = lax_paral_op(x, jax.lax.pmax, axis, mesh)
420
    return x
Phuong Nguyen's avatar
Phuong Nguyen committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438


def tpsp_axis_size():
    """
    Get the size of the tensor parallelism axis.
    Return 1 if no TP axis is set.
    """
    return get_mesh_axis_size(global_mesh_resource().tpsp_resource)


def dp_or_fsdp_axis_size():
    """
    Get the size of the data parallelism or FSDP axis.
    Return 1 if no DP/FSDP axis is set.
    """
    dp_size = get_mesh_axis_size(global_mesh_resource().dp_resource)
    fsdp_size = get_mesh_axis_size(global_mesh_resource().fsdp_resource)
    return dp_size if dp_size > 1 else fsdp_size