repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,179 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin) remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed to enable JAX cache on Neuron.
+import jax_neuronx # pylint: disable=unused-import
+import neuronxcc.nki.language as nl
+from jax import custom_vjp
+from neuronxcc.nki.kernels.attention import flash_attn_bwd, flash_fwd
+
+# pytype: enable=import-error
+
+Tensor = jax.Array
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+
+@partial(custom_vjp, nondiff_argnums=(4, 5, 6))
+def flash_attention(
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: Tensor,
+ causal: bool = False,
+ softmax_scale: float = 1.0,
+ dropout_rate: float = 0.0,
+):
+ """Wraps _mha_forward for custom vjp.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
+ bias: Optional logit biases of shape [1, 1, target_length, source_length].
+ softmax_scale: Optional scale to apply to softmax. Defaults to 1.
+ causal: Whether to apply causal mask.
+ dropout_rate: Dropout rate. Default to 0.0 (no dropout).
+
+ Returns:
+ The attention outputs of shape [batch_size, target_length, num_heads, per_head_dim].
+ """
+ out, _ = _mha_forward(query, key, value, bias, causal, softmax_scale, dropout_rate)
+ return out
+
+
+def _mha_forward(query, key, value, bias, causal, softmax_scale, dropout_rate):
+ """Computes attention outputs following FlashAttention.
+
+ See also `_mha_backward` for the backward pass.
+
+ Args:
+ query: Input query.
+ key: Input key.
+ value: Input value.
+ bias: Input bias.
+ causal: Input segment_ids.
+ softmax_scale: Softmax scale to use in the kernel.
+ dropout_rate: Dropout rate to use in the kernel.
+ """
+ # Get the batch size, sequence lengths, number of heads, and hidden dimension.
+ batch_size, _, num_heads, _ = query.shape
+
+ # Transpose the query, key, and value tensors.
+ q = query.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, q_seq_len].
+ k = key.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, kv_seq_len].
+ v = value.transpose(0, 2, 1, 3) # [batch_size, num_heads, kv_seq_len, d_model].
+
+ seed = jnp.array([1]) | why seed is hardcoded to [1]? |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,143 @@
+# Copyright © 2024 Amazon Inc.
+"""Tests for Flash attention on Neuron. Tested on trn1 & trn2."""
+
+import chex
+import jax
+import jax.numpy as jnp
+import pytest
+
+from axlearn.common.flash_attention.utils import mha_reference
+
+if jax.default_backend() != "neuron":
+ pytestmark = pytest.skip(
+ reason="Incompatible hardware, AWS Neuron only test.", allow_module_level=True
+ )
+
+
+@pytest.mark.parametrize(
+ "batch_size,seq_len,num_heads,per_head_dim",
+ [
+ (1, 2048, 1, 64),
+ (2, 2048, 2, 64),
+ (1, 2048, 1, 128),
+ (2, 2048, 2, 128),
+ (1, 2048, 8, 128),
+ (2, 2048, 8, 128),
+ ],
+)
+@pytest.mark.parametrize("causal", [True, False])
+@pytest.mark.parametrize("attention_bias_type", [None, "2d"])
+@pytest.mark.parametrize("input_dtype", [jnp.float16, jnp.bfloat16, jnp.float32])
+def test_fwd_against_ref(
+ batch_size: int,
+ seq_len: int,
+ num_heads: int,
+ per_head_dim: int,
+ causal: bool,
+ input_dtype: jnp.dtype,
+ attention_bias_type: bool, | attention_bias_type is str, not bool
```
attention_bias_type: str | None,
``` |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -275,6 +275,28 @@ def get_segment_ids(segment_ids: SegmentIdAttentionBias) -> Optional[Tensor]:
interpret=(backend == "cpu"),
)
+ elif backend == "neuron":
+ # pylint: disable=import-outside-toplevel
+ from axlearn.common.flash_attention.neuron_attention import (
+ flash_attention as neuron_flash_attention,
+ )
+
+ key = _repeat_kv_heads(query.shape[2], key)
+ value = _repeat_kv_heads(query.shape[2], value)
+
+ # other_biases inlcudes SegmentIdAttentionBias among other biases. | typo: inlcudes -> includes |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,179 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin) remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed to enable JAX cache on Neuron.
+import jax_neuronx # pylint: disable=unused-import
+import neuronxcc.nki.language as nl
+from jax import custom_vjp
+from neuronxcc.nki.kernels.attention import flash_attn_bwd, flash_fwd
+
+# pytype: enable=import-error
+
+Tensor = jax.Array
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+
+@partial(custom_vjp, nondiff_argnums=(4, 5, 6))
+def flash_attention(
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: Tensor,
+ causal: bool = False,
+ softmax_scale: float = 1.0,
+ dropout_rate: float = 0.0,
+):
+ """Wraps _mha_forward for custom vjp.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
+ bias: Optional logit biases of shape [1, 1, target_length, source_length].
+ softmax_scale: Optional scale to apply to softmax. Defaults to 1.
+ causal: Whether to apply causal mask. | Align docstring parameter order with actual function signature |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,179 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin) remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed to enable JAX cache on Neuron.
+import jax_neuronx # pylint: disable=unused-import
+import neuronxcc.nki.language as nl
+from jax import custom_vjp
+from neuronxcc.nki.kernels.attention import flash_attn_bwd, flash_fwd
+
+# pytype: enable=import-error
+
+Tensor = jax.Array
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+
+@partial(custom_vjp, nondiff_argnums=(4, 5, 6))
+def flash_attention(
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: Tensor,
+ causal: bool = False,
+ softmax_scale: float = 1.0,
+ dropout_rate: float = 0.0,
+):
+ """Wraps _mha_forward for custom vjp.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
+ bias: Optional logit biases of shape [1, 1, target_length, source_length].
+ softmax_scale: Optional scale to apply to softmax. Defaults to 1.
+ causal: Whether to apply causal mask.
+ dropout_rate: Dropout rate. Default to 0.0 (no dropout).
+
+ Returns:
+ The attention outputs of shape [batch_size, target_length, num_heads, per_head_dim].
+ """
+ out, _ = _mha_forward(query, key, value, bias, causal, softmax_scale, dropout_rate)
+ return out
+
+
+def _mha_forward(query, key, value, bias, causal, softmax_scale, dropout_rate):
+ """Computes attention outputs following FlashAttention.
+
+ See also `_mha_backward` for the backward pass.
+
+ Args:
+ query: Input query.
+ key: Input key.
+ value: Input value.
+ bias: Input bias.
+ causal: Input segment_ids.
+ softmax_scale: Softmax scale to use in the kernel.
+ dropout_rate: Dropout rate to use in the kernel.
+ """
+ # Get the batch size, sequence lengths, number of heads, and hidden dimension.
+ batch_size, _, num_heads, _ = query.shape
+
+ # Transpose the query, key, and value tensors.
+ q = query.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, q_seq_len].
+ k = key.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, kv_seq_len].
+ v = value.transpose(0, 2, 1, 3) # [batch_size, num_heads, kv_seq_len, d_model].
+
+ seed = jnp.array([1])
+
+ # Call the NKI kernel, duplicate the kernel if we cannot shard on num_heads.
+ if (num_heads % 2) == 0 and (num_heads // 2 > 0):
+ grid = batch_size, nl.nc(lnc) * (num_heads // lnc)
+ else:
+ grid = batch_size, num_heads
+
+ if bias is not None:
+ assert (
+ bias.ndim == 4
+ ), f"Neuron flash_attention is only expecting bias.ndim = 4 but got {bias.ndim}"
+ assert bias.shape[0] == 1 and bias.shape[1] == 1, (
+ f"Bias is only supported when batch and num_heads are both 1, "
+ f"batch is {bias.shape[0]} and num_heads is {bias.shape[1]}"
+ )
+ attn_output, lse = flash_fwd[grid](
+ q,
+ k,
+ v,
+ seed,
+ bias,
+ use_causal_mask=causal,
+ softmax_scale=softmax_scale,
+ mixed_precision=True,
+ dropout_p=dropout_rate,
+ )
+ else:
+ attn_output, lse = flash_fwd[grid](
+ q,
+ k,
+ v,
+ seed,
+ use_causal_mask=causal,
+ softmax_scale=softmax_scale,
+ mixed_precision=True,
+ dropout_p=dropout_rate,
+ )
+ # Transpose the output back to the original shape.
+ attn_output = attn_output.transpose(0, 2, 1, 3) # [batch_size, q_seq_len, num_heads, d_model].
+
+ return attn_output, (lse, attn_output, q, k, v, bias)
+
+
+def _mha_backward(causal, softmax_scale, dropout_rate, res, d_attn_output):
+ lse, o, q, k, v, bias = res
+ batch_size, num_heads, _, _ = q.shape
+
+ # Transpose the input tensors.
+ o = o.transpose(0, 2, 3, 1)
+ dy = d_attn_output.transpose(0, 2, 3, 1)
+
+ # Transpose v tensor.
+ v = jnp.transpose(v, axes=(0, 1, 3, 2))
+ seed = jnp.array([1])
+
+ # Call the NKI kernel, duplicate the kernel if we cannot shard on num_heads.
+ if (num_heads % 2) == 0 and (num_heads // 2 > 0):
+ grid = batch_size, nl.nc(lnc) * (num_heads // lnc)
+ else:
+ grid = batch_size, num_heads
+
+ if bias is not None:
+ assert (
+ bias.ndim == 4
+ ), f"Neuron flash_attention is only expecting bias.ndim = 4 but got {bias.ndim}"
+ assert bias.shape[0] == 1 and bias.shape[1] == 1, (
+ f"Bias is only supported when batch and num_heads are both 1, "
+ f"batch is {bias.shape[0]} and num_heads is {bias.shape[1]}"
+ )
+ d_query, d_key, d_value = flash_attn_bwd[grid](
+ q,
+ k,
+ v,
+ o,
+ dy,
+ lse,
+ seed,
+ bias,
+ use_causal_mask=causal,
+ mixed_precision=True,
+ dropout_p=dropout_rate,
+ softmax_scale=softmax_scale,
+ )
+ else:
+ d_query, d_key, d_value = flash_attn_bwd[grid](
+ q,
+ k,
+ v,
+ o,
+ dy,
+ lse,
+ seed,
+ use_causal_mask=causal,
+ mixed_precision=True,
+ dropout_p=dropout_rate,
+ softmax_scale=softmax_scale,
+ )
+
+ # Transpose the gradients back to the original shape.
+ d_query = d_query.transpose(0, 3, 1, 2)
+ d_key = d_key.transpose(0, 3, 1, 2)
+ d_value = d_value.transpose(0, 3, 1, 2) | can you add comment with expected dims for each transpose - similar to what you did in _mha_forward? |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,143 @@
+# Copyright © 2024 Amazon Inc.
+"""Tests for Flash attention on Neuron. Tested on trn1 & trn2."""
+
+import chex
+import jax
+import jax.numpy as jnp
+import pytest
+
+from axlearn.common.flash_attention.utils import mha_reference
+
+if jax.default_backend() != "neuron":
+ pytestmark = pytest.skip(
+ reason="Incompatible hardware, AWS Neuron only test.", allow_module_level=True
+ )
+
+
+@pytest.mark.parametrize(
+ "batch_size,seq_len,num_heads,per_head_dim",
+ [
+ (1, 2048, 1, 64),
+ (2, 2048, 2, 64),
+ (1, 2048, 1, 128),
+ (2, 2048, 2, 128),
+ (1, 2048, 8, 128),
+ (2, 2048, 8, 128),
+ ],
+)
+@pytest.mark.parametrize("causal", [True, False])
+@pytest.mark.parametrize("attention_bias_type", [None, "2d"])
+@pytest.mark.parametrize("input_dtype", [jnp.float16, jnp.bfloat16, jnp.float32])
+def test_fwd_against_ref(
+ batch_size: int,
+ seq_len: int,
+ num_heads: int,
+ per_head_dim: int,
+ causal: bool,
+ input_dtype: jnp.dtype,
+ attention_bias_type: bool,
+):
+ # On demand import only if test is needed.
+ # pylint: disable=import-outside-toplevel
+ from axlearn.common.flash_attention.neuron_attention import flash_attention
+
+ softmax_scale = 1.0 / (per_head_dim**0.5)
+ k1, k2, k3, k4 = jax.random.split(jax.random.PRNGKey(0), 4)
+ q = jax.random.normal(k1, (batch_size, seq_len, num_heads, per_head_dim), dtype=input_dtype)
+ k = jax.random.normal(k2, (batch_size, seq_len, num_heads, per_head_dim), dtype=input_dtype)
+ v = jax.random.normal(k3, (batch_size, seq_len, num_heads, per_head_dim), dtype=input_dtype)
+
+ if attention_bias_type == "2d":
+ bias = jax.random.normal(k4, (1, 1, seq_len, seq_len), dtype=input_dtype)
+ else:
+ bias = None
+
+ o = flash_attention(
+ q,
+ k,
+ v,
+ bias,
+ causal=causal,
+ softmax_scale=softmax_scale,
+ dropout_rate=0.0,
+ )
+ o_ref = mha_reference(
+ q,
+ k,
+ v,
+ bias,
+ causal=causal,
+ softmax_scale=softmax_scale,
+ dropout_rate=0.0,
+ )
+ if input_dtype == jnp.float16:
+ chex.assert_trees_all_close(o, o_ref, atol=0.07)
+ elif input_dtype == jnp.float32:
+ chex.assert_trees_all_close(o, o_ref, atol=0.03)
+
+
+@pytest.mark.parametrize(
+ "batch_size,num_heads,seq_len,per_head_dim",
+ [
+ (1, 1, 2048, 64),
+ (2, 2, 2048, 64),
+ (1, 1, 2048, 128),
+ (2, 2, 2048, 128),
+ (1, 8, 2048, 128),
+ (2, 8, 2048, 128),
+ ],
+)
+@pytest.mark.parametrize("causal", [True, False])
+@pytest.mark.parametrize("input_dtype", [jnp.bfloat16, jnp.float16, jnp.float32])
+@pytest.mark.parametrize("attention_bias_type", [None, "2d"])
+def test_bwd_against_ref(
+ batch_size: int,
+ num_heads: int,
+ seq_len: int,
+ per_head_dim: int,
+ causal: bool,
+ input_dtype: jnp.dtype,
+ attention_bias_type: bool,
+):
+ # On demand import only if test is needed.
+ # pylint: disable=import-outside-toplevel
+ from axlearn.common.flash_attention.neuron_attention import flash_attention
+
+ softmax_scale = 1.0 / (per_head_dim**0.5)
+ k1, k2, k3, k4 = jax.random.split(jax.random.PRNGKey(0), 4)
+ q = jax.random.normal(k1, (batch_size, seq_len, num_heads, per_head_dim), dtype=input_dtype)
+ k = jax.random.normal(k2, (batch_size, seq_len, num_heads, per_head_dim), dtype=input_dtype)
+ v = jax.random.normal(k3, (batch_size, seq_len, num_heads, per_head_dim), dtype=input_dtype)
+
+ if attention_bias_type == "2d":
+ bias = jax.random.normal(k4, (1, 1, seq_len, seq_len), dtype=input_dtype)
+ else:
+ bias = None
+ segment_ids = None
+
+ def fn(q, k, v, bias):
+ return flash_attention(
+ q,
+ k,
+ v,
+ bias,
+ causal=causal,
+ softmax_scale=softmax_scale,
+ dropout_rate=0.0,
+ ).sum()
+
+ def ref_fn(q, k, v, bias, segment_ids):
+ return mha_reference(
+ q,
+ k,
+ v,
+ bias,
+ segment_ids, | `segment_ids` is set to None which is default param value for it. It can be removed from `ref_fn` signature for consistency with fn/flash_attention above |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,143 @@
+# Copyright © 2024 Amazon Inc.
+"""Tests for Flash attention on Neuron. Tested on trn1 & trn2."""
+
+import chex
+import jax
+import jax.numpy as jnp
+import pytest
+
+from axlearn.common.flash_attention.utils import mha_reference
+
+if jax.default_backend() != "neuron":
+ pytestmark = pytest.skip(
+ reason="Incompatible hardware, AWS Neuron only test.", allow_module_level=True
+ )
+
+
+@pytest.mark.parametrize(
+ "batch_size,seq_len,num_heads,per_head_dim",
+ [
+ (1, 2048, 1, 64),
+ (2, 2048, 2, 64),
+ (1, 2048, 1, 128),
+ (2, 2048, 2, 128),
+ (1, 2048, 8, 128),
+ (2, 2048, 8, 128),
+ ],
+)
+@pytest.mark.parametrize("causal", [True, False])
+@pytest.mark.parametrize("attention_bias_type", [None, "2d"])
+@pytest.mark.parametrize("input_dtype", [jnp.float16, jnp.bfloat16, jnp.float32])
+def test_fwd_against_ref(
+ batch_size: int,
+ seq_len: int,
+ num_heads: int,
+ per_head_dim: int,
+ causal: bool,
+ input_dtype: jnp.dtype,
+ attention_bias_type: bool,
+):
+ # On demand import only if test is needed.
+ # pylint: disable=import-outside-toplevel
+ from axlearn.common.flash_attention.neuron_attention import flash_attention
+
+ softmax_scale = 1.0 / (per_head_dim**0.5)
+ k1, k2, k3, k4 = jax.random.split(jax.random.PRNGKey(0), 4)
+ q = jax.random.normal(k1, (batch_size, seq_len, num_heads, per_head_dim), dtype=input_dtype)
+ k = jax.random.normal(k2, (batch_size, seq_len, num_heads, per_head_dim), dtype=input_dtype)
+ v = jax.random.normal(k3, (batch_size, seq_len, num_heads, per_head_dim), dtype=input_dtype)
+
+ if attention_bias_type == "2d":
+ bias = jax.random.normal(k4, (1, 1, seq_len, seq_len), dtype=input_dtype)
+ else:
+ bias = None
+
+ o = flash_attention(
+ q,
+ k,
+ v,
+ bias,
+ causal=causal,
+ softmax_scale=softmax_scale,
+ dropout_rate=0.0,
+ )
+ o_ref = mha_reference(
+ q,
+ k,
+ v,
+ bias,
+ causal=causal,
+ softmax_scale=softmax_scale,
+ dropout_rate=0.0,
+ )
+ if input_dtype == jnp.float16:
+ chex.assert_trees_all_close(o, o_ref, atol=0.07)
+ elif input_dtype == jnp.float32:
+ chex.assert_trees_all_close(o, o_ref, atol=0.03)
+
+
+@pytest.mark.parametrize(
+ "batch_size,num_heads,seq_len,per_head_dim",
+ [
+ (1, 1, 2048, 64),
+ (2, 2, 2048, 64),
+ (1, 1, 2048, 128),
+ (2, 2, 2048, 128),
+ (1, 8, 2048, 128),
+ (2, 8, 2048, 128),
+ ],
+)
+@pytest.mark.parametrize("causal", [True, False])
+@pytest.mark.parametrize("input_dtype", [jnp.bfloat16, jnp.float16, jnp.float32])
+@pytest.mark.parametrize("attention_bias_type", [None, "2d"])
+def test_bwd_against_ref(
+ batch_size: int,
+ num_heads: int,
+ seq_len: int,
+ per_head_dim: int,
+ causal: bool,
+ input_dtype: jnp.dtype,
+ attention_bias_type: bool, | attention_bias_type is str, not bool |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed to enable JAX cache on Neuron.
+import jax_neuronx # pylint: disable=unused-import
+import neuronxcc.nki.language as nl
+from jax import custom_vjp
+from neuronxcc.nki.kernels.attention import flash_attn_bwd, flash_fwd
+
+# pytype: enable=import-error
+
+Tensor = jax.Array
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+
+@partial(custom_vjp, nondiff_argnums=(5, 6, 7))
+def flash_attention(
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: Optional[Tensor] = None,
+ prng_key: Optional[Tensor] = None,
+ causal: bool = False,
+ softmax_scale: float = 1.0,
+ dropout_rate: float = 0.0,
+):
+ """Wraps _mha_forward for custom vjp.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
+ bias: Optional logit biases of shape [1, 1, target_length, source_length].
+ prng_key: PRNG key used for dropout. Must be specified when dropout_rate > 0.0.
+ causal: Whether to apply causal mask.
+ softmax_scale: Optional scale to apply to softmax. Defaults to 1.
+ dropout_rate: Dropout rate. Default to 0.0 (no dropout).
+
+ Returns:
+ The attention outputs of shape [batch_size, target_length, num_heads, per_head_dim].
+ """
+ out, _ = _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate)
+ return out
+
+
+def _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate): | Missing types? |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed to enable JAX cache on Neuron.
+import jax_neuronx # pylint: disable=unused-import
+import neuronxcc.nki.language as nl
+from jax import custom_vjp
+from neuronxcc.nki.kernels.attention import flash_attn_bwd, flash_fwd
+
+# pytype: enable=import-error
+
+Tensor = jax.Array
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+
+@partial(custom_vjp, nondiff_argnums=(5, 6, 7))
+def flash_attention(
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: Optional[Tensor] = None,
+ prng_key: Optional[Tensor] = None,
+ causal: bool = False,
+ softmax_scale: float = 1.0,
+ dropout_rate: float = 0.0,
+):
+ """Wraps _mha_forward for custom vjp.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
+ bias: Optional logit biases of shape [1, 1, target_length, source_length].
+ prng_key: PRNG key used for dropout. Must be specified when dropout_rate > 0.0.
+ causal: Whether to apply causal mask.
+ softmax_scale: Optional scale to apply to softmax. Defaults to 1.
+ dropout_rate: Dropout rate. Default to 0.0 (no dropout).
+
+ Returns:
+ The attention outputs of shape [batch_size, target_length, num_heads, per_head_dim].
+ """
+ out, _ = _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate)
+ return out
+
+
+def _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate):
+ """Computes attention outputs following FlashAttention.
+
+ See also `_mha_backward` for the backward pass.
+
+ Args:
+ query: Input query.
+ key: Input key.
+ value: Input value.
+ bias: Input bias.
+ prng_key: PRNG key used for dropout. Must be specified when dropout_rate > 0.0.
+ causal: Input segment_ids. | Looks like a stale docstring? |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed to enable JAX cache on Neuron.
+import jax_neuronx # pylint: disable=unused-import
+import neuronxcc.nki.language as nl
+from jax import custom_vjp
+from neuronxcc.nki.kernels.attention import flash_attn_bwd, flash_fwd
+
+# pytype: enable=import-error
+
+Tensor = jax.Array
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+
+@partial(custom_vjp, nondiff_argnums=(5, 6, 7))
+def flash_attention(
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: Optional[Tensor] = None,
+ prng_key: Optional[Tensor] = None,
+ causal: bool = False,
+ softmax_scale: float = 1.0,
+ dropout_rate: float = 0.0,
+):
+ """Wraps _mha_forward for custom vjp.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
+ bias: Optional logit biases of shape [1, 1, target_length, source_length].
+ prng_key: PRNG key used for dropout. Must be specified when dropout_rate > 0.0.
+ causal: Whether to apply causal mask.
+ softmax_scale: Optional scale to apply to softmax. Defaults to 1.
+ dropout_rate: Dropout rate. Default to 0.0 (no dropout).
+
+ Returns:
+ The attention outputs of shape [batch_size, target_length, num_heads, per_head_dim].
+ """
+ out, _ = _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate)
+ return out
+
+
+def _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate):
+ """Computes attention outputs following FlashAttention.
+
+ See also `_mha_backward` for the backward pass.
+
+ Args:
+ query: Input query.
+ key: Input key.
+ value: Input value.
+ bias: Input bias.
+ prng_key: PRNG key used for dropout. Must be specified when dropout_rate > 0.0.
+ causal: Input segment_ids.
+ softmax_scale: Softmax scale to use in the kernel.
+ dropout_rate: Dropout rate to use in the kernel.
+ """
+ # Get the batch size, sequence lengths, number of heads, and hidden dimension.
+ batch_size, _, num_heads, _ = query.shape
+
+ # Transpose the query, key, and value tensors.
+ q = query.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, q_seq_len].
+ k = key.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, kv_seq_len].
+ v = value.transpose(0, 2, 1, 3) # [batch_size, num_heads, kv_seq_len, d_model].
+
+ if dropout_rate > 0:
+ assert dropout_rate < 1
+ assert prng_key is not None
+ else:
+ # Dummy unused key.
+ prng_key = jax.random.key(0)
+
+ # TODO(apoorvtintin): Pass rbg key to kernel directly when kernel is ready to accept it.
+ # Currenlty NKI kernel supports a single 32 bit key, temporarily override this till support
+ # for 128 bit keys is added. Till then dropout is not supported.
+ prng_key = jnp.array([1]) | Any reason not to raise if user specifies a prng_key? |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed to enable JAX cache on Neuron.
+import jax_neuronx # pylint: disable=unused-import
+import neuronxcc.nki.language as nl
+from jax import custom_vjp
+from neuronxcc.nki.kernels.attention import flash_attn_bwd, flash_fwd
+
+# pytype: enable=import-error
+
+Tensor = jax.Array
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+
+@partial(custom_vjp, nondiff_argnums=(5, 6, 7))
+def flash_attention(
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: Optional[Tensor] = None,
+ prng_key: Optional[Tensor] = None,
+ causal: bool = False,
+ softmax_scale: float = 1.0,
+ dropout_rate: float = 0.0,
+):
+ """Wraps _mha_forward for custom vjp.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
+ bias: Optional logit biases of shape [1, 1, target_length, source_length].
+ prng_key: PRNG key used for dropout. Must be specified when dropout_rate > 0.0.
+ causal: Whether to apply causal mask.
+ softmax_scale: Optional scale to apply to softmax. Defaults to 1.
+ dropout_rate: Dropout rate. Default to 0.0 (no dropout).
+
+ Returns:
+ The attention outputs of shape [batch_size, target_length, num_heads, per_head_dim].
+ """
+ out, _ = _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate)
+ return out
+
+
+def _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate):
+ """Computes attention outputs following FlashAttention.
+
+ See also `_mha_backward` for the backward pass.
+
+ Args:
+ query: Input query.
+ key: Input key.
+ value: Input value.
+ bias: Input bias.
+ prng_key: PRNG key used for dropout. Must be specified when dropout_rate > 0.0.
+ causal: Input segment_ids.
+ softmax_scale: Softmax scale to use in the kernel.
+ dropout_rate: Dropout rate to use in the kernel.
+ """
+ # Get the batch size, sequence lengths, number of heads, and hidden dimension.
+ batch_size, _, num_heads, _ = query.shape
+
+ # Transpose the query, key, and value tensors.
+ q = query.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, q_seq_len].
+ k = key.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, kv_seq_len].
+ v = value.transpose(0, 2, 1, 3) # [batch_size, num_heads, kv_seq_len, d_model].
+
+ if dropout_rate > 0:
+ assert dropout_rate < 1
+ assert prng_key is not None | Prefer to raise ValueError over assert. Assertion errors are for catching logic bugs. |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed to enable JAX cache on Neuron.
+import jax_neuronx # pylint: disable=unused-import
+import neuronxcc.nki.language as nl
+from jax import custom_vjp
+from neuronxcc.nki.kernels.attention import flash_attn_bwd, flash_fwd
+
+# pytype: enable=import-error
+
+Tensor = jax.Array
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+
+@partial(custom_vjp, nondiff_argnums=(5, 6, 7))
+def flash_attention(
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: Optional[Tensor] = None,
+ prng_key: Optional[Tensor] = None,
+ causal: bool = False,
+ softmax_scale: float = 1.0,
+ dropout_rate: float = 0.0,
+):
+ """Wraps _mha_forward for custom vjp.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
+ bias: Optional logit biases of shape [1, 1, target_length, source_length].
+ prng_key: PRNG key used for dropout. Must be specified when dropout_rate > 0.0.
+ causal: Whether to apply causal mask.
+ softmax_scale: Optional scale to apply to softmax. Defaults to 1.
+ dropout_rate: Dropout rate. Default to 0.0 (no dropout).
+
+ Returns:
+ The attention outputs of shape [batch_size, target_length, num_heads, per_head_dim].
+ """
+ out, _ = _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate)
+ return out
+
+
+def _mha_forward(query, key, value, bias, prng_key, causal, softmax_scale, dropout_rate):
+ """Computes attention outputs following FlashAttention.
+
+ See also `_mha_backward` for the backward pass.
+
+ Args:
+ query: Input query.
+ key: Input key.
+ value: Input value.
+ bias: Input bias.
+ prng_key: PRNG key used for dropout. Must be specified when dropout_rate > 0.0.
+ causal: Input segment_ids.
+ softmax_scale: Softmax scale to use in the kernel.
+ dropout_rate: Dropout rate to use in the kernel.
+ """
+ # Get the batch size, sequence lengths, number of heads, and hidden dimension.
+ batch_size, _, num_heads, _ = query.shape
+
+ # Transpose the query, key, and value tensors.
+ q = query.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, q_seq_len].
+ k = key.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, kv_seq_len].
+ v = value.transpose(0, 2, 1, 3) # [batch_size, num_heads, kv_seq_len, d_model].
+
+ if dropout_rate > 0:
+ assert dropout_rate < 1
+ assert prng_key is not None
+ else:
+ # Dummy unused key.
+ prng_key = jax.random.key(0)
+
+ # TODO(apoorvtintin): Pass rbg key to kernel directly when kernel is ready to accept it.
+ # Currenlty NKI kernel supports a single 32 bit key, temporarily override this till support
+ # for 128 bit keys is added. Till then dropout is not supported.
+ prng_key = jnp.array([1])
+
+ # Call the NKI kernel, duplicate the kernel if we cannot shard on num_heads.
+ if num_heads > 0 and num_heads % lnc == 0:
+ grid = batch_size, nl.nc(lnc) * (num_heads // lnc)
+ else:
+ grid = batch_size, num_heads
+
+ if bias is not None:
+ assert (
+ bias.ndim == 4
+ ), f"Neuron flash_attention is only expecting bias.ndim = 4 but got {bias.ndim}"
+ assert bias.shape[0] == 1 and bias.shape[1] == 1, (
+ f"Bias is only supported when batch and num_heads are both 1, "
+ f"batch is {bias.shape[0]} and num_heads is {bias.shape[1]}"
+ ) | Likewise for these. |
axlearn | github_2023 | python | 988 | apple | apghml | @@ -1452,7 +1452,6 @@ def _check_masking(self, tree: Nested[Any], rule: str):
rule: The rule from `cfg.masking_rules` to check agains.
"""
cfg = self.config
- tree: dict | `Nested[Any]` is actually equivalent to `Any` from a type checking perspective since `Nested[XYZ]` allows for a bare `XYZ` not contained in any dict. So they are not equivalent. |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -146,6 +147,67 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Required[Dict[str, ConfigBase]] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ cfg = self.config
+ self._model_cfg_modifications = cfg.model_cfg_modifications
+
+ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
+ """Overwrite the model config of the specified modules.
+
+ Args:
+ cfg: The trainer config to be modified.
+
+ Raises:
+ ValueError: The target module is not found.
+
+ Returns:
+ The modified trainer config.
+ """
+
+ for module_name, model_cfg in self._model_cfg_modifications.items():
+ # No modification if None
+ if not model_cfg:
+ continue
+ # Here we assume x.y.z format.
+ # One example would be model.decoder.transformer.layer.
+ target_modules = module_name.split(".") | Can you try to extract a common util function named something like
`def replace_module_recursive(target_modules:str, config_key: str, target_config)` and make it applied to both here and RematSpecModifier |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -65,6 +67,26 @@ def test_remat_policy_override(self):
_ = cfg_modifier(cfg)
+class ModelConfigModifierTest(test_utils.TestCase):
+ def test_model_config_override(self):
+ cfg = SpmdTrainer.default_config().set(model=causal_lm.Model.default_config())
+ self.assertRegex(str(cfg.model.decoder), ".*StackedTransformerLayer")
+
+ cfg_modifier = (
+ ModelConfigModifier.default_config()
+ .set(
+ model_cfg_modifications={
+ "model.decoder.transformer": RepeatedTransformerLayer.default_config(),
+ }
+ )
+ .instantiate()
+ )
+
+ cfg = cfg_modifier(cfg)
+ # The default StackedTransformerLayer should have changed to RepeatedTransformerLayer
+ self.assertRegex(str(cfg.model.decoder), ".*RepeatedTransformerLayer") | Can we do exact match here for the config, something like following:
```suggestion
self.assertTrue(cfg.model.decoder is RepeatedTransformerLayer.default_config())
``` |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -65,6 +67,26 @@ def test_remat_policy_override(self):
_ = cfg_modifier(cfg)
+class ModelConfigModifierTest(test_utils.TestCase):
+ def test_model_config_override(self):
+ cfg = SpmdTrainer.default_config().set(model=causal_lm.Model.default_config())
+ self.assertRegex(str(cfg.model.decoder), ".*StackedTransformerLayer")
+
+ cfg_modifier = (
+ ModelConfigModifier.default_config()
+ .set(
+ model_cfg_modifications={
+ "model.decoder.transformer": RepeatedTransformerLayer.default_config(),
+ }
+ )
+ .instantiate()
+ )
+
+ cfg = cfg_modifier(cfg)
+ # The default StackedTransformerLayer should have changed to RepeatedTransformerLayer | Add a test to catch mismatch exception as well? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -17,7 +18,42 @@
from axlearn.common.gradient_accumulation import with_minibatch_steps
from axlearn.common.metrics import MetricAccumulator
from axlearn.common.trainer import SpmdTrainer
-from axlearn.common.utils import HybridMeshShape, MeshShape
+from axlearn.common.utils import HybridMeshShape, MeshShape, PartitionSpec
+
+
+def find_target_module(
+ module_name: str, cfg: SpmdTrainer.Config
+) -> tuple[ConfigModifier.Config, ConfigModifier.Config, ConfigModifier.Config]:
+ """Recursively search for the target module matching module_name in provided cfg | End comments with .
```suggestion
"""Recursively search for the target module matching module_name in provided cfg.
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -17,7 +18,42 @@
from axlearn.common.gradient_accumulation import with_minibatch_steps
from axlearn.common.metrics import MetricAccumulator
from axlearn.common.trainer import SpmdTrainer
-from axlearn.common.utils import HybridMeshShape, MeshShape
+from axlearn.common.utils import HybridMeshShape, MeshShape, PartitionSpec
+
+
+def find_target_module(
+ module_name: str, cfg: SpmdTrainer.Config
+) -> tuple[ConfigModifier.Config, ConfigModifier.Config, ConfigModifier.Config]: | Do not return tuples. Return a struct or namedtuple:
https://github.com/apple/axlearn/blob/main/docs/ml_api_style.md#avoid-returning-a-tuple-of-values
|
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -17,7 +18,42 @@
from axlearn.common.gradient_accumulation import with_minibatch_steps
from axlearn.common.metrics import MetricAccumulator
from axlearn.common.trainer import SpmdTrainer
-from axlearn.common.utils import HybridMeshShape, MeshShape
+from axlearn.common.utils import HybridMeshShape, MeshShape, PartitionSpec
+
+
+def find_target_module( | Does this need to be a public method? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +175,100 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Required[Dict[str, ConfigBase]] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ cfg = self.config
+ self._model_cfg_modifications = cfg.model_cfg_modifications
+
+ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
+ """Overwrite the model config of the specified modules.
+
+ Args:
+ cfg: The trainer config to be modified.
+
+ Raises:
+ ValueError: The target module is not found.
+
+ Returns:
+ The modified trainer config.
+ """
+
+ for module_name, model_cfg in self._model_cfg_modifications.items():
+ # No modification if None
+ if not model_cfg:
+ continue | Do we need to support this? Users can always omit the entry. |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +175,100 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Required[Dict[str, ConfigBase]] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ cfg = self.config
+ self._model_cfg_modifications = cfg.model_cfg_modifications
+
+ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
+ """Overwrite the model config of the specified modules.
+
+ Args:
+ cfg: The trainer config to be modified.
+
+ Raises:
+ ValueError: The target module is not found.
+
+ Returns:
+ The modified trainer config.
+ """
+
+ for module_name, model_cfg in self._model_cfg_modifications.items():
+ # No modification if None
+ if not model_cfg:
+ continue
+
+ found_module, parent_module, key_in_parent = find_target_module(module_name, cfg)
+
+ # Copy configurations from the config being replaced on a best effort basis | Wait, this behavior is not explained in the class comments. So we are not replacing but merging the configs? Maybe we should support a merge function instead? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Required[Dict[str, ConfigBase]] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ cfg = self.config
+ self._model_cfg_modifications = cfg.model_cfg_modifications | Nit: Do we need this vs. accessing it via `self.config.model_cfg_modifications`? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Required[Dict[str, ConfigBase]] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ cfg = self.config
+ self._model_cfg_modifications = cfg.model_cfg_modifications
+
+ def _merge_configs(self, target_cfg: ConfigBase, found_module: ConfigBase) -> ConfigBase:
+ """Merge configurations from the config being replaced on a best effort basis.
+ Args:
+ target_cfg: configuration that will replace found_module.
+ found_module: existing configuration whose class will be replaced
+ but it's confguration will be merged with target_cfg.
+
+ Returns:
+ The modified config.
+
+ """ | Please follow Google style guide strictly in terms of linebreaks. |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Required[Dict[str, ConfigBase]] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ cfg = self.config
+ self._model_cfg_modifications = cfg.model_cfg_modifications
+
+ def _merge_configs(self, target_cfg: ConfigBase, found_module: ConfigBase) -> ConfigBase:
+ """Merge configurations from the config being replaced on a best effort basis.
+ Args:
+ target_cfg: configuration that will replace found_module.
+ found_module: existing configuration whose class will be replaced
+ but it's confguration will be merged with target_cfg.
+
+ Returns:
+ The modified config.
+
+ """
+ for key in target_cfg.keys():
+ if key == "klass":
+ continue
+ elif hasattr(found_module.module, key) and hasattr(target_cfg, key):
+ setattr(target_cfg, key, getattr(found_module.module, key))
+ return target_cfg
+
+ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
+ """Overwrite the model config of the specified modules.
+
+ Args:
+ cfg: The trainer config to be modified.
+
+ Raises:
+ ValueError: The target module is not found.
+
+ Returns:
+ The modified trainer config.
+ """
+
+ for module_name, model_cfg in self._model_cfg_modifications.items():
+ found_module = _find_target_module(module_name, cfg)
+
+ model_cfg = self._merge_configs(model_cfg, found_module) | `_merge_configs` actually mutates `model_cfg` IIUC. Is it safe to invoke `__call__` multiple times? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Required[Dict[str, ConfigBase]] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ cfg = self.config
+ self._model_cfg_modifications = cfg.model_cfg_modifications
+
+ def _merge_configs(self, target_cfg: ConfigBase, found_module: ConfigBase) -> ConfigBase:
+ """Merge configurations from the config being replaced on a best effort basis. | This comment is vague about how merging actually works. Looks like the rule is:
* Use target_cfg.klass
* Use the field value from found_module if the field exists in both configs (and is not "klass")
* Otherwise keep the value from target_cfg |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Required[Dict[str, ConfigBase]] = REQUIRED | How about:
```suggestion
model_cfg_modifications: Dict[str, Callable[[ConfigBase], ConfigBase]] = {}
```
?
That is, the values are config transformer functions. |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Required[Dict[str, ConfigBase]] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ cfg = self.config
+ self._model_cfg_modifications = cfg.model_cfg_modifications
+
+ def _merge_configs(self, target_cfg: ConfigBase, found_module: ConfigBase) -> ConfigBase:
+ """Merge configurations from the config being replaced on a best effort basis.
+ Args:
+ target_cfg: configuration that will replace found_module.
+ found_module: existing configuration whose class will be replaced
+ but it's confguration will be merged with target_cfg.
+
+ Returns:
+ The modified config.
+
+ """
+ for key in target_cfg.keys():
+ if key == "klass":
+ continue
+ elif hasattr(found_module.module, key) and hasattr(target_cfg, key):
+ setattr(target_cfg, key, getattr(found_module.module, key))
+ return target_cfg
+
+ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
+ """Overwrite the model config of the specified modules.
+
+ Args:
+ cfg: The trainer config to be modified.
+
+ Raises:
+ ValueError: The target module is not found.
+
+ Returns:
+ The modified trainer config.
+ """
+
+ for module_name, model_cfg in self._model_cfg_modifications.items():
+ found_module = _find_target_module(module_name, cfg) | In utils.py we have `get_recursively` and `set_recursively` for `Nested[...]`. I wonder if it will be useful to add corresponding methods to ConfigBase. Then we can do something like:
```suggestion
for cfg_path, cfg_modification in self._model_cfg_modifications.items():
child_cfg = cfg.get_recursively(cfg_path)
child_cfg = cfg_modification(child_cfg, path=cfg_path)
cfg.set_recursively(cfg_path, value=child_cfg)
``` |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -146,6 +186,113 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ model_cfg_modifications: Dict[str, Callable[[ConfigBase], ConfigBase]] = {} | There is a chain modifier already, should this be something simpler, saying taking two arguments,
1. target_module
2. modified_config
If you rely on chain, you don't really need a dict here. |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -17,7 +18,53 @@
from axlearn.common.gradient_accumulation import with_minibatch_steps
from axlearn.common.metrics import MetricAccumulator
from axlearn.common.trainer import SpmdTrainer
-from axlearn.common.utils import HybridMeshShape, MeshShape
+from axlearn.common.utils import HybridMeshShape, MeshShape, PartitionSpec
+
+
+class _FoundModule(NamedTuple):
+ """Module found in recursive search of matching module."""
+
+ # The module found
+ module: ConfigModifier.Config
+ # The parent of the module found
+ parent_module: ConfigModifier.Config
+ # Key of the found module in parent
+ key_in_parent: ConfigModifier.Config
+
+
+def _find_target_module(module_name: str, cfg: SpmdTrainer.Config) -> _FoundModule:
+ """Recursively search for the target module matching module_name in provided cfg.
+
+ Args:
+ module_name: Name of the target module
+ cfg: The trainer config to be searched for module_name
+
+ Raises:
+ ValueError: The module_name is not found.
+
+ Returns:
+ A Tuple(curr_module, key_in_parent, parent_module)
+ curr_module: Module found
+ parent_module: The parent module
+ key_in_parent: Key in parent for the found module
+ """
+
+ # Here we assume x.y.z format.
+ # One example would be model.decoder.transformer.layer.
+ target_modules = module_name.split(".")
+ curr_module = cfg
+ key_in_parent = None
+ parent_module = None
+
+ for target_module in target_modules: | nit, maybe name `target_module` to `target_module_key` since it is more approriate?
|
axlearn | github_2023 | python | 916 | apple | markblee | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key string.
+ key: str
+
+ def recursive_traverse(self, key_path: Sequence[str]) -> tuple[Any, str]:
+ """Recursively traverse the config to find the target key. | Please see other comment re `get_recursively`; also, I wonder whether we actually need recursion here (seems like a loop would be simpler). |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -146,6 +137,110 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier): | Which part of this class is specific to model? It seems to take generic modifications? |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -146,6 +137,110 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path | Outdated? |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -146,6 +137,110 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ target_config: Required[str] = REQUIRED
+ modification: Required[Configurable.Config] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ self._target_config = self.config.target_config
+ self._modification = self.config.modification
+
+ def _merge_configs(
+ self, target_cfg: Configurable.Config, found_module: Configurable.Config
+ ) -> Configurable.Config:
+ """Merge configurations from the config being replaced on a best effort basis.
+
+ Merge Rules:
+ - Klass is not changed, use target cfg | ```suggestion
- Klass is not changed, use target cfg.
```
Please end all sentences with punctuations. |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -146,6 +137,110 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.
+
+ Attributes:
+ model_cfg_modifications: A mapping from module path
+ (e.g. `model.decoder.transformer.layer`) to a Config.
+ """
+
+ target_config: Required[str] = REQUIRED
+ modification: Required[Configurable.Config] = REQUIRED
+
+ def __init__(self, cfg: Config):
+ super().__init__(cfg)
+ self._target_config = self.config.target_config
+ self._modification = self.config.modification
+
+ def _merge_configs(
+ self, target_cfg: Configurable.Config, found_module: Configurable.Config
+ ) -> Configurable.Config:
+ """Merge configurations from the config being replaced on a best effort basis.
+
+ Merge Rules:
+ - Klass is not changed, use target cfg
+ - If field exists in both then use from class being replaced
+ - Otherwise keep the value from target_cfg
+
+ Args:
+ target_cfg: configuration that will replace found_module.
+ found_module: existing configuration whose class will be replaced | ```suggestion
target_cfg: Configuration that will replace found_module.
found_module: Existing configuration whose class will be replaced
``` |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -151,6 +155,60 @@ def get_trainer_kwargs(
rope_theta = ROPE_THETA[version]
+ # TRN2 specific model config modifications
+ trn2_model_modifications = [
+ # Neuron compiler has a module to detect repeating blocks and reuse them during compilation.
+ # So compile time does not grow with the number of layers.
+ ModelConfigModifier.default_config().set(
+ target_config="model.decoder.transformer",
+ modification=StackedTransformerLayer.default_config(),
+ )
+ ]
+ if version != Version.V1:
+ trn2_model_modifications.append(
+ ModelConfigModifier.default_config().set(
+ target_config="model.decoder.transformer.layer.self_attention.attention." | A downside of representing these deeply nested configs as string paths is that they are brittle, and can quickly become outdated.
Have we considered using `cfg.visit` to achieve some of these modifications (e.g., https://github.com/apple/axlearn/blob/1c22688c1dc480777c43a1b8c8dd866dccda70e0/axlearn/common/layers.py#L266)?
(A bit late to review, so apologies if this discussion has already taken place.) |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key string.
+ key: str
+
+ def recursive_traverse(self, key_path: Sequence[str]) -> tuple[Any, str]: | Does this need to be a public method? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key string.
+ key: str
+
+ def recursive_traverse(self, key_path: Sequence[str]) -> tuple[Any, str]:
+ """Recursively traverse the config to find the target key.
+
+ Args:
+ key_path: A sequence of keys for indexing.
+
+ Raises:
+ ValueError: A key in key_path is not found.
+
+ Returns:
+ A tuple containing the parent object and the target key.
+ """
+ target_key = key_path[0]
+ if target_key not in self:
+ raise ValueError(f"{target_key} is not found in {self}.")
+
+ if len(key_path) == 1:
+ # Completed traversal
+ return self.TraverseResult(parent=self, key=key_path[0])
+
+ # Continue searching recursively
+ value = getattr(self, target_key)
+ return value.recursive_traverse(key_path[1:])
+
+ def get_recursively(self, key_path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ key_path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in key_path is not found.
+
+ Returns:
+ value at the key_path.
+ """
+ traverse_result = self.recursive_traverse(key_path)
+ return getattr(traverse_result.parent, traverse_result.key)
+
+ def set_recursively(self, key_path: Sequence[str], new_value: Any): | Please name consistently with https://github.com/apple/axlearn/blob/a854738ae728989ba2add761ee5ad64e9a41fea6/axlearn/common/utils.py#L907-L910.
```suggestion
def set_recursively(self, path: Sequence[str], *, value: Any):
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key string.
+ key: str
+
+ def recursive_traverse(self, key_path: Sequence[str]) -> tuple[Any, str]:
+ """Recursively traverse the config to find the target key.
+
+ Args:
+ key_path: A sequence of keys for indexing.
+
+ Raises:
+ ValueError: A key in key_path is not found.
+
+ Returns:
+ A tuple containing the parent object and the target key.
+ """
+ target_key = key_path[0]
+ if target_key not in self:
+ raise ValueError(f"{target_key} is not found in {self}.")
+
+ if len(key_path) == 1:
+ # Completed traversal
+ return self.TraverseResult(parent=self, key=key_path[0])
+
+ # Continue searching recursively
+ value = getattr(self, target_key)
+ return value.recursive_traverse(key_path[1:])
+
+ def get_recursively(self, key_path: Sequence[str]) -> Any: | ```suggestion
def get_recursively(self, path: Sequence[str]) -> Any:
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key string.
+ key: str
+
+ def recursive_traverse(self, key_path: Sequence[str]) -> tuple[Any, str]:
+ """Recursively traverse the config to find the target key.
+
+ Args:
+ key_path: A sequence of keys for indexing.
+
+ Raises:
+ ValueError: A key in key_path is not found.
+
+ Returns:
+ A tuple containing the parent object and the target key.
+ """
+ target_key = key_path[0]
+ if target_key not in self:
+ raise ValueError(f"{target_key} is not found in {self}.")
+
+ if len(key_path) == 1:
+ # Completed traversal
+ return self.TraverseResult(parent=self, key=key_path[0])
+
+ # Continue searching recursively
+ value = getattr(self, target_key)
+ return value.recursive_traverse(key_path[1:])
+
+ def get_recursively(self, key_path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ key_path: A sequence of keys for indexing to get the target value. | Can path be empty? Maybe it can return `self` if path is empty? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key string.
+ key: str
+
+ def recursive_traverse(self, key_path: Sequence[str]) -> tuple[Any, str]:
+ """Recursively traverse the config to find the target key.
+
+ Args:
+ key_path: A sequence of keys for indexing.
+
+ Raises:
+ ValueError: A key in key_path is not found.
+
+ Returns:
+ A tuple containing the parent object and the target key.
+ """
+ target_key = key_path[0]
+ if target_key not in self:
+ raise ValueError(f"{target_key} is not found in {self}.")
+
+ if len(key_path) == 1:
+ # Completed traversal
+ return self.TraverseResult(parent=self, key=key_path[0])
+
+ # Continue searching recursively
+ value = getattr(self, target_key)
+ return value.recursive_traverse(key_path[1:])
+
+ def get_recursively(self, key_path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ key_path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in key_path is not found.
+
+ Returns:
+ value at the key_path.
+ """
+ traverse_result = self.recursive_traverse(key_path)
+ return getattr(traverse_result.parent, traverse_result.key)
+
+ def set_recursively(self, key_path: Sequence[str], new_value: Any):
+ """Recursively find the target key in the config and set its value.
+
+ Args:
+ key_path: A sequence of keys for indexing to set the target value. | Can path be empty? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key string.
+ key: str
+
+ def recursive_traverse(self, key_path: Sequence[str]) -> tuple[Any, str]:
+ """Recursively traverse the config to find the target key.
+
+ Args:
+ key_path: A sequence of keys for indexing.
+
+ Raises:
+ ValueError: A key in key_path is not found.
+
+ Returns:
+ A tuple containing the parent object and the target key.
+ """
+ target_key = key_path[0]
+ if target_key not in self:
+ raise ValueError(f"{target_key} is not found in {self}.")
+
+ if len(key_path) == 1:
+ # Completed traversal
+ return self.TraverseResult(parent=self, key=key_path[0])
+
+ # Continue searching recursively
+ value = getattr(self, target_key)
+ return value.recursive_traverse(key_path[1:])
+
+ def get_recursively(self, key_path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ key_path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in key_path is not found.
+
+ Returns:
+ value at the key_path.
+ """
+ traverse_result = self.recursive_traverse(key_path)
+ return getattr(traverse_result.parent, traverse_result.key)
+
+ def set_recursively(self, key_path: Sequence[str], new_value: Any):
+ """Recursively find the target key in the config and set its value.
+
+ Args:
+ key_path: A sequence of keys for indexing to set the target value.
+ new_value: New value to replace the target value.
+
+ Raises:
+ ValueError: A key in key_path is not found.
+ """
+ traverse_result = self.recursive_traverse(key_path) | Can we do something like:
```suggestion
if not path:
raise ValueError(...)
parent = self.get_recursively(path[:-1])
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty
+
+ Returns:
+ value at the path.
+ """
+ if not path:
+ raise ValueError("Path is empty.")
+ | ```suggestion
if not path:
return self
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty
+
+ Returns:
+ value at the path.
+ """
+ if not path:
+ raise ValueError("Path is empty.")
+
+ if path[0] not in self:
+ raise ValueError(f"{path[0]} is not found in {self}.")
+
+ child = getattr(self, path[0])
+
+ if len(path) == 1:
+ return child
+
+ return child.get_recursively(path[1:]) | Nit: Can we avoid recursion with a loop? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty
+
+ Returns:
+ value at the path.
+ """
+ if not path:
+ raise ValueError("Path is empty.")
+
+ if path[0] not in self:
+ raise ValueError(f"{path[0]} is not found in {self}.")
+
+ child = getattr(self, path[0])
+
+ if len(path) == 1:
+ return child
+
+ return child.get_recursively(path[1:])
+
+ def set_recursively(self, path: Sequence[str], *, value: Any):
+ """Recursively find the target key in the config and set its value.
+
+ Args:
+ path: A sequence of keys for indexing to set the target value.
+ new_value: New value to replace the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty
+ """
+ if not path:
+ raise ValueError("Path is empty.")
+
+ if path[0] not in self:
+ raise ValueError(f"{path[0]} is not found in {self}.")
+
+ child = getattr(self, path[0])
+
+ if len(path) == 1:
+ return setattr(self, path[0], value) | ```suggestion
if len(path) == 1:
return setattr(self, path[0], value)
child = getattr(self, path[0])
`````` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty
+
+ Returns:
+ value at the path.
+ """
+ if not path:
+ raise ValueError("Path is empty.")
+
+ if path[0] not in self:
+ raise ValueError(f"{path[0]} is not found in {self}.")
+
+ child = getattr(self, path[0])
+
+ if len(path) == 1:
+ return child
+
+ return child.get_recursively(path[1:])
+
+ def set_recursively(self, path: Sequence[str], *, value: Any):
+ """Recursively find the target key in the config and set its value.
+
+ Args:
+ path: A sequence of keys for indexing to set the target value.
+ new_value: New value to replace the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty
+ """
+ if not path:
+ raise ValueError("Path is empty.")
+
+ if path[0] not in self:
+ raise ValueError(f"{path[0]} is not found in {self}.")
+
+ child = getattr(self, path[0])
+
+ if len(path) == 1:
+ return setattr(self, path[0], value)
+
+ return child.set_recursively(path[1:], value=value) | Avoid recursion? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty
+
+ Returns:
+ value at the path.
+ """
+ if not path:
+ raise ValueError("Path is empty.")
+
+ if path[0] not in self:
+ raise ValueError(f"{path[0]} is not found in {self}.")
+
+ child = getattr(self, path[0])
+
+ if len(path) == 1:
+ return child
+
+ return child.get_recursively(path[1:])
+
+ def set_recursively(self, path: Sequence[str], *, value: Any):
+ """Recursively find the target key in the config and set its value.
+
+ Args:
+ path: A sequence of keys for indexing to set the target value.
+ new_value: New value to replace the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty
+ """
+ if not path:
+ raise ValueError("Path is empty.")
+
+ if path[0] not in self:
+ raise ValueError(f"{path[0]} is not found in {self}.") | Do we need this check? getattr and setattr will raise anyways. |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -434,7 +552,7 @@ def get_trainer_kwargs(
),
learner_kwargs=dict(peak_lr=1.5e-4, weight_decay=0.1),
max_sequence_length=max_sequence_length,
- train_batch_size=train_batch_size,
+ train_batch_size=8, | Is this change intended? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,58 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty.
+ AttributeError: If key in path is not found.
+
+ Returns:
+ value at the path or self if path is empty.
+ """
+ current = self
+ index = 0
+
+ while path and index < len(path):
+ key = path[index]
+
+ # TODO(markblee): maybe use cfg.visit instead of getattr
+ current = getattr(current, key)
+ index += 1
+
+ if index == len(path):
+ return current | ```suggestion
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,58 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty.
+ AttributeError: If key in path is not found.
+
+ Returns:
+ value at the path or self if path is empty.
+ """
+ current = self
+ index = 0
+
+ while path and index < len(path):
+ key = path[index]
+
+ # TODO(markblee): maybe use cfg.visit instead of getattr
+ current = getattr(current, key)
+ index += 1
+
+ if index == len(path):
+ return current
+
+ return current
+
+ def set_recursively(self, path: Sequence[str], *, value: Any):
+ """Recursively find the target key in the config and set its value.
+
+ Args:
+ path: A sequence of keys for indexing to set the target value.
+ new_value: New value to replace the target value.
+
+ Raises:
+ ValueError: A key in path is not found or path is empty.
+ AttributeError: If key in path is not found.
+ """
+
+ if not path:
+ raise ValueError("Path is empty.")
+
+ current = self
+ for i, key in enumerate(path):
+ if i == len(path) - 1:
+ setattr(current, key, value)
+ return
+ else:
+ # TODO(markblee): maybe use cfg.visit instead of getattr
+ current = getattr(current, key) | ```suggestion
parent = self.get_recursively(path[:-1])
setattr(current, path[-1], value)
``` |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -151,6 +155,72 @@ def get_trainer_kwargs(
rope_theta = ROPE_THETA[version]
+ # TRN2 specific model config modifications | Can we move all the modifications in a helper function?
saying
def _generate_trainium2_custom_configs():
...
return trn2_model_modifications, trn2_partition_spec_modifications |
axlearn | github_2023 | python | 916 | apple | hanzhi713 | @@ -151,6 +155,72 @@ def get_trainer_kwargs(
rope_theta = ROPE_THETA[version]
+ # TRN2 specific model config modifications
+ trn2_model_modifications = [
+ # Neuron compiler has a module to detect repeating blocks and reuse them during compilation.
+ # So compile time does not grow with the number of layers.
+ ModuleConfigModifier.default_config().set(
+ target_config="model.decoder.transformer",
+ modification=StackedTransformerLayer.default_config(),
+ )
+ ]
+ # Grouped QKV is only used in fuji-v3 except in fuji-v2 if model is 70B
+ if version == Version.V3 or (model_size == "70B" and version != Version.V1):
+ trn2_model_modifications.append(
+ ModuleConfigModifier.default_config().set(
+ target_config="model.decoder.transformer.layer.self_attention.attention."
+ "input_linear.input_linear",
+ modification=GroupedQKVLinear.default_config(),
+ )
+ )
+
+ trn2_partition_spec_modifications = [
+ PartitionSpecModifier.default_config().set(
+ partition_specs={
+ # Vocab parallel embeddings sharding from Megatron LM.
+ "model.decoder.emb.token_emb": {
+ "param_partition_spec": (
+ "model",
+ ("expert", "fsdp", "seq"),
+ ),
+ "input_partition_spec": ("fsdp", None),
+ "output_partition_spec": ("fsdp", None, None),
+ "embedding_partition_spec": ("model", None),
+ },
+ # Sequence parallel shardings for norms.
+ "model.decoder.transformer.layer.self_attention.norm": {
+ "input_partition_spec": ("fsdp", "model", None), | Why is there no "data"? Is it because trn2 don't support data and fsdp at the same time? |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -394,6 +394,49 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the target value.
+
+ Raises:
+ AttributeError: If key in path is not found.
+
+ Returns:
+ value at the path or self if path is empty.
+ """
+ current = self
+ index = 0
+
+ while path and index < len(path):
+ key = path[index]
+
+ # TODO(markblee): maybe use cfg.visit instead of getattr
+ current = getattr(current, key)
+ index += 1
+
+ if index == len(path):
+ break | Hm, did I miss something or can we just do:
```suggestion
for part in path:
current = getattr(current, part)
```
(In any case, I can make some changes in a follow-up.) |
axlearn | github_2023 | python | 948 | apple | markblee | @@ -516,6 +514,7 @@ def select_fields(fields: Sequence[str]) -> DatasetToDatasetFn:
def remove_fields(fields: Sequence[str]) -> DatasetToDatasetFn:
"""Filter the dataset to remove the fields specified."""
+ from seqio import map_over_dataset # pylint: disable=import-outside-toplevel | (Please see my internal comment.) |
axlearn | github_2023 | python | 978 | apple | ruomingp | @@ -1524,3 +1525,29 @@ def forward(self, x: Tensor) -> Tensor:
self.add_state_update("value", new_moving_average)
self.add_state_update("count", 1 + self.parameters["count"])
return new_moving_average
+
+
+class BaseLossMetrics(BaseLayer): | layers.py doesn't seem the right file for this class. Can we keep it in metrics.py or create a new file? |
axlearn | github_2023 | python | 329 | apple | apivovarov | @@ -141,64 +146,80 @@ def cross_entropy(
targets = _one_hot_with_label_smoothing(
target_labels, num_classes, label_smoothing=label_smoothing
)
- pre_mask_loss, pre_mask_cross_entropy_loss, pre_mask_z_loss = _stable_cross_entropy(
+ per_target_loss, per_target_cross_entropy_loss, per_target_z_loss = _stable_cross_entropy(
logits, targets, z_loss_scale
)
- if mask is None:
- mask = jnp.logical_and(0 <= target_labels, target_labels < num_classes)
- mask = mask.astype(pre_mask_loss.dtype)
- num_unmasked = jnp.maximum(mask.sum(), 1)
- cross_entropy_loss = (pre_mask_cross_entropy_loss * mask).sum() / num_unmasked
- z_loss = (pre_mask_z_loss * mask).sum() / num_unmasked
- loss = (pre_mask_loss * mask).sum() / num_unmasked
+ if mask is not None:
+ if live_targets is None:
+ live_targets = mask
+ else:
+ raise ValueError("mask and live_targets must not be specified together")
+ if live_targets is None:
+ live_targets = jnp.logical_and(0 <= target_labels, target_labels < num_classes)
+ live_targets = live_targets.astype(per_target_loss.dtype)
+ denominator = jnp.maximum(live_targets.sum(), 1)
+ cross_entropy_loss = (per_target_cross_entropy_loss * live_targets).sum() / denominator
+ z_loss = (per_target_z_loss * live_targets).sum() / denominator
+ loss = (per_target_loss * live_targets).sum() / denominator
predicted_labels = jnp.argmax(logits, axis=-1)
- accuracy = (jnp.equal(predicted_labels, target_labels) * mask).sum() / num_unmasked
+ accuracy = (jnp.equal(predicted_labels, target_labels) * live_targets).sum() / denominator | Hi Ruoming, should we use this accuracy inside CrossEntropyLossMetrics::forward() instead of recalculating it in CrossEntropyLossMetrics::forward() ?
see: https://github.com/apple/axlearn/blob/main/axlearn/common/causal_lm.py#L108C1-L117C10
we can use loss_dict["accuracy"] instead of recalculating accuracy in causal_lm.py::CrossEntropyLossMetrics
@ruomingp @markblee |
axlearn | github_2023 | python | 934 | apple | apivovarov | @@ -32,16 +32,242 @@
from axlearn.common.layers import LayerNorm
from axlearn.common.logit_modifiers import LogitsToLogitsFn
from axlearn.common.loss import cross_entropy
-from axlearn.common.metrics import WeightedScalar
-from axlearn.common.module import Module, NestedTensor, Tensor, child_context
+from axlearn.common.metrics import BaseLossMetrics, WeightedScalar
+from axlearn.common.module import Module, NestedTensor, Tensor, child_context, new_output_collection
from axlearn.common.param_init import PARAM_REGEXP_WEIGHT, DefaultInitializer, WeightInitializer
-from axlearn.common.utils import flatten_items, with_sharding_constraint
+from axlearn.common.utils import (
+ Nested,
+ flatten_items,
+ validate_contains_paths,
+ with_sharding_constraint,
+)
def layer_norm_config(eps=1e-5):
return LayerNorm.default_config().set(eps=eps)
+class CrossEntropyLossMetrics(BaseLossMetrics):
+ """Computes cross entropy loss and related training summaries."""
+
+ @config_class
+ class Config(BaseLossMetrics.Config):
+ """Configures CrossEntropyLossMetrics.
+
+ Attributes:
+ z_loss_scale: An auxiliary z-loss scale. If not None and >0, encourages the softmax
+ normalizer to be well behaved.
+ """
+
+ z_loss_scale: Optional[float] = None
+
+ def forward(
+ self, input_batch: Nested[Tensor], *, predict_outputs: Nested[Tensor]
+ ) -> tuple[Tensor, Nested[Tensor]]:
+ """Computes cross entropy loss.
+
+ Args:
+ input_batch: A dict containing at minimum:
+ target_labels: An int Tensor of shape [...]. Negative targets do not contribute to
+ the loss calculation.
+ predict_outputs: A dict containing at minimum:
+ logits: A float Tensor of shape [..., num_classes].
+
+ Returns:
+ A tuple (loss, metrics):
+ loss: A scalar float Tensor corresponding to cross entropy loss, including auxiliary
+ z-loss if `cfg.z_loss_scale` is provided.
+ metrics: A dict containing:
+ cross_entropy: Same as loss.
+ per_token_loss: A float Tensor of same shape as `target_labels`. Ignored targets
+ will be masked, i.e., have per-token loss of 0.
+ live_targets: A bool Tensor of same shape as `target_labels`. False indicates
+ ignored targets.
+ num_targets: A scalar int Tensor corresponding to number of live targets.
+ """
+ validate_contains_paths(input_batch, paths=["target_labels"])
+ validate_contains_paths(predict_outputs, paths=["logits"])
+
+ cfg: CrossEntropyLossMetrics.Config = self.config
+
+ target_labels: Tensor = input_batch["target_labels"]
+ target_num_bytes: Optional[Tensor] = input_batch.get("target_num_bytes")
+ logits = predict_outputs["logits"]
+
+ live_targets = target_labels >= 0
+ num_targets = live_targets.sum()
+ accuracy = (
+ jnp.equal(jnp.argmax(logits, axis=-1), target_labels) * live_targets
+ ).sum() / jnp.maximum(1, num_targets)
+
+ loss, loss_dict = cross_entropy( | Hi Mark, do we need a separate accuracy calculation here (above cross_entropy) if the loss_dict from cross_entropy already contains an accuracy entry? @markblee |
axlearn | github_2023 | python | 972 | apple | dongyin92 | @@ -837,25 +837,41 @@ def extend_step(
q_proj, k_proj, v_proj = self.forward(query, **kv_kwargs, query_positions=query_positions)
updated_state = dict(time_step=time_step + num_query_steps)
if kv_state is None:
- # Update the cache via dynamic slice. [B, S, N, H].
+ # Update the cache via one-hot broadcast and addition.
cached_key = cached_states["key"]
cached_value = cached_states["value"]
- # Ensure that we accumulate using the original dtype.
- k_proj = k_proj.astype(cached_key.dtype)
- v_proj = v_proj.astype(cached_value.dtype)
-
- # TODO(dhwang2): jax.lax.dynamic_update_slice_in_dim is generally faster than advanced
- # indexing, but an unusual slowdown was observed, with RLHF sampling taking up to
- # 3 hours per run. Investigate and fix it.
- # Note: All X_idx are small, so generating them on-demand is not costly.
- b, _, n, h = cached_key.shape
- b_idx = jnp.arange(b)[:, None, None, None]
- t_idx = (jnp.arange(k_proj.shape[1])[None] + time_step[:, None])[:, :, None, None]
- n_idx = jnp.arange(n)[None, None, :, None]
- h_idx = jnp.arange(h)[None, None, None, :]
- k_proj = cached_key.at[b_idx, t_idx, n_idx, h_idx].set(k_proj)
- v_proj = cached_value.at[b_idx, t_idx, n_idx, h_idx].set(v_proj)
+ target_len = cached_key.shape[1] | From the doc string of this function, it says `cached_states` contains "key" and "value" of shape [batch, num_heads, per_head_dim, target_length]. Then why does `target_len = cached_key.shape[1]`? |
axlearn | github_2023 | python | 972 | apple | markblee | @@ -837,25 +837,41 @@ def extend_step(
q_proj, k_proj, v_proj = self.forward(query, **kv_kwargs, query_positions=query_positions)
updated_state = dict(time_step=time_step + num_query_steps)
if kv_state is None:
- # Update the cache via dynamic slice. [B, S, N, H].
+ # Update the cache via one-hot broadcast and addition.
cached_key = cached_states["key"]
cached_value = cached_states["value"]
- # Ensure that we accumulate using the original dtype.
- k_proj = k_proj.astype(cached_key.dtype)
- v_proj = v_proj.astype(cached_value.dtype)
-
- # TODO(dhwang2): jax.lax.dynamic_update_slice_in_dim is generally faster than advanced
- # indexing, but an unusual slowdown was observed, with RLHF sampling taking up to
- # 3 hours per run. Investigate and fix it.
- # Note: All X_idx are small, so generating them on-demand is not costly.
- b, _, n, h = cached_key.shape
- b_idx = jnp.arange(b)[:, None, None, None]
- t_idx = (jnp.arange(k_proj.shape[1])[None] + time_step[:, None])[:, :, None, None]
- n_idx = jnp.arange(n)[None, None, :, None]
- h_idx = jnp.arange(h)[None, None, None, :]
- k_proj = cached_key.at[b_idx, t_idx, n_idx, h_idx].set(k_proj)
- v_proj = cached_value.at[b_idx, t_idx, n_idx, h_idx].set(v_proj)
+ target_len = cached_key.shape[1]
+
+ # Create one-hot encodings for each position in the step range
+ # time_step is [B], need to create [B, step] indices
+ base_indices = time_step[:, None] + jnp.arange(num_query_steps) # [B, step]
+ oh_indices = jax.nn.one_hot(
+ base_indices, target_len, dtype=k_proj.dtype
+ ) # [B, step, T]
+
+ # Reshape to [B, step, T, 1, 1] to broadcast across N and H dimensions
+ oh_indices = oh_indices[:, :, :, None, None]
+ negated_oh_indices = (1 - oh_indices).astype(cached_key.dtype)
+ negated_oh_indices = jnp.prod(negated_oh_indices, axis=1) # [B, T, 1, 1]
+
+ # Reshape projections to align with one-hot encoding
+ # from [B, step, N, H] to [B, step, 1, N, H]
+ k_proj = k_proj[:, :, None, :, :]
+ v_proj = v_proj[:, :, None, :, :]
+
+ # Perform the update
+ # First multiply with one-hot encodings: [B, step, T, N, H]
+ k_proj = (k_proj * oh_indices).astype(cached_key.dtype)
+ v_proj = (v_proj * oh_indices).astype(cached_value.dtype)
+
+ # Sum across step dimension to get final projection values: [B, T, N, H]
+ k_proj = jnp.sum(k_proj, axis=1)
+ v_proj = jnp.sum(v_proj, axis=1)
+
+ # Combine with cached values
+ k_proj = (cached_key * negated_oh_indices) + k_proj
+ v_proj = (cached_value * negated_oh_indices) + v_proj | I wonder if we can simplify a bit:
```suggestion
source_len = cached_key.shape[1]
# Create a dispatch matrix of shape [B, T=step, S].
oh_indices = jax.nn.one_hot(
time_step[:, None] + jnp.arange(num_query_steps), source_len, dtype=k_proj.dtype
)
# Create a mask of shape [B, S, 1, 1].
negated_oh_indices = (1 - oh_indices.sum(axis=1))[..., None, None]
k_proj = jnp.einsum("bt...,bts->bs...", k_proj, oh_indices)
v_proj = jnp.einsum("bt...,bts->bs...", v_proj, oh_indices)
k_proj = cached_key * negated_oh_indices + k_proj
v_proj = cached_value * negated_oh_indices + v_proj
``` |
axlearn | github_2023 | python | 972 | apple | ds-hwang | @@ -837,25 +837,22 @@ def extend_step(
q_proj, k_proj, v_proj = self.forward(query, **kv_kwargs, query_positions=query_positions)
updated_state = dict(time_step=time_step + num_query_steps)
if kv_state is None:
- # Update the cache via dynamic slice. [B, S, N, H].
+ # Update the cache via one-hot broadcast and addition.
cached_key = cached_states["key"]
cached_value = cached_states["value"]
- # Ensure that we accumulate using the original dtype.
- k_proj = k_proj.astype(cached_key.dtype)
- v_proj = v_proj.astype(cached_value.dtype)
-
- # TODO(dhwang2): jax.lax.dynamic_update_slice_in_dim is generally faster than advanced
- # indexing, but an unusual slowdown was observed, with RLHF sampling taking up to
- # 3 hours per run. Investigate and fix it.
- # Note: All X_idx are small, so generating them on-demand is not costly.
- b, _, n, h = cached_key.shape
- b_idx = jnp.arange(b)[:, None, None, None]
- t_idx = (jnp.arange(k_proj.shape[1])[None] + time_step[:, None])[:, :, None, None]
- n_idx = jnp.arange(n)[None, None, :, None]
- h_idx = jnp.arange(h)[None, None, None, :]
- k_proj = cached_key.at[b_idx, t_idx, n_idx, h_idx].set(k_proj)
- v_proj = cached_value.at[b_idx, t_idx, n_idx, h_idx].set(v_proj)
+ source_len = cached_key.shape[1] | Could you add comment why we don't use dynamic_update_slice for future code reader? |
axlearn | github_2023 | python | 884 | apple | ruomingp | @@ -607,6 +610,7 @@ def host_to_global_device_array(
host_arrays: Nested[Union[np.ndarray, Tensor]],
*,
partition: DataPartitionType = DataPartitionType.FULL, | I think @markblee plans to remove the `DataPartitionType` enum and rely on https://jax.readthedocs.io/en/latest/_autosummary/jax.make_array_from_process_local_data.html to support flexible partition specs. |
axlearn | github_2023 | python | 884 | apple | kelvin-zou | @@ -423,6 +423,7 @@ def get_trainer_kwargs(
raise NotImplementedError(f"Unknown model size {model_size}.")
model_kwargs = trainer_kwargs.pop("model_kwargs")
model_kwargs.setdefault("vocab_size", vocab_size)
+ trainer_kwargs["input_partition_type"] = None if backend != "neuron" else DataPartitionType.BATCH | Please go with a configmodifier instead of hardcode in the code, otherwise it becomes hard for people to debug
|
axlearn | github_2023 | python | 884 | apple | kelvin-zou | @@ -188,11 +194,11 @@ def _pjit(self, fn: Callable) -> Callable:
in_shardings=(
self._model_param_partition_specs, # model_params.
None, # replicated_inputs (e.g., prng_key).
- utils.input_partition_spec(), # per_example_inputs.
+ utils.data_partition_type_to_spec(partition=self.config.input_partition_type, batch_axis_names=self.config.batch_axis_names), # per_example_inputs.
),
out_shardings=dict(
replicated=None,
- per_example=utils.input_partition_spec(),
+ per_example=utils.data_partition_type_to_spec( partition=self.config.input_partition_type, batch_axis_names=self.config.batch_axis_names), | Did you run through pylint? this line seems quite long. |
axlearn | github_2023 | python | 884 | apple | kelvin-zou | @@ -591,14 +591,17 @@ class DataPartitionType(Enum):
FULL = "full"
# Data are fully replicated across all devices.
REPLICATED = "replicated"
+ # Data are partitioned across batch axis only.
+ BATCH = "batch"
-
-def data_partition_type_to_spec(partition: DataPartitionType) -> PartitionSpec:
+def data_partition_type_to_spec(partition: DataPartitionType, * , batch_axis_names: Union[str, Sequence[str]] = ("data", "fsdp")) -> PartitionSpec:
"""Returns a PartitionSpec for the given partition type."""
if partition == DataPartitionType.FULL:
return input_partition_spec()
elif partition == DataPartitionType.REPLICATED:
return None
+ elif partition == DataPartitionType.BATCH:
+ return PartitionSpec(batch_axis_names) | Instead of directly assigning PartitionSpec, maybe extend `input_partition_spec ` with an argument batch_axis_names, with default None? |
axlearn | github_2023 | python | 884 | apple | kelvin-zou | @@ -37,16 +36,15 @@ def is_supported(
)
)
- | Are you using a different pylint style? Those lines should not be removed. |
axlearn | github_2023 | python | 884 | apple | markblee | @@ -1701,6 +1702,31 @@ def test_length(self):
class HostToGlobalArrayTest(TestCase):
"""Tests host_to_global_device_array."""
+ @pytest.mark.neuron
+ def test_partition_batch(self): | Are we able to pass the `test_every_other_process` only relying on `make_array_from_process_local_data`? If not, then it seems that input dispatch may still be needed. |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -4,18 +4,21 @@
from absl import app, flags
-from axlearn.common import launch, launch_trainer, measurement
+from axlearn.common import launch, launch_trainer, measurement, monitoring
from axlearn.common.config import config_for_function
def main(_):
measurement.initialize(flags.FLAGS)
+ monitoring.initialize(flags.FLAGS) | Do we need a separate module for this, or can we consolidate into the `measurement` interface? |
axlearn | github_2023 | python | 783 | apple | yiping-ma | @@ -800,13 +805,15 @@ def restore_checkpoint(self, restore_step: Optional[int] = None) -> Optional[int
step,
restore_input_iter,
)
+ self._maybe_record_event(measurement.Event.END_DATA_LOADING) | If this line got skipped due to self.checkpointer.restore() failure, the data loading end time will be missing for this event, is it expected? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +55,48 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_DATA_LOADING:
+ self._recorder.record_data_loading_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_DATA_LOADING:
+ self._recorder.record_data_loading_end_time(*args, **kwargs)
else:
logging.log_first_n(
logging.WARNING,
"Ignoring unknown event %s",
1,
event,
)
+
+ def start_monitoring(self, *args, **kwargs):
+ # Instantiate ml-goodput-measurement's GoodputMonitor
+ # to asynchronously calculate goodput and badput at
+ # the upload_interval and upload to the specified
+ # tensorboard directory. | Convert this into a docstring for the method? BTW, we use 100 line length. |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +55,48 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_DATA_LOADING:
+ self._recorder.record_data_loading_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_DATA_LOADING:
+ self._recorder.record_data_loading_end_time(*args, **kwargs)
else:
logging.log_first_n(
logging.WARNING,
"Ignoring unknown event %s",
1,
event,
)
+
+ def start_monitoring(self, *args, **kwargs):
+ # Instantiate ml-goodput-measurement's GoodputMonitor
+ # to asynchronously calculate goodput and badput at
+ # the upload_interval and upload to the specified
+ # tensorboard directory.
+ if self._monitor is None:
+ cfg: GoodputRecorder.Config = self.config
+ self._monitor = goodput_monitoring.GoodputMonitor(
+ job_name=cfg.name,
+ logger_name=f"goodput_logger_{cfg.name}",
+ tensorboard_dir=cfg.upload_dir,
+ upload_interval=int(cfg.upload_interval),
+ monitoring_enabled=(jax.process_index() == 0),
+ include_badput_breakdown=True,
+ )
+
+ if self._monitor:
+ self._monitor.start_goodput_uploader(*args, **kwargs)
+ logging.info("Started Goodput upload to Tensorboard in the background!")
+ else:
+ logging.log_first_n(
+ logging.WARNING,
+ "Goodput upload could not be started. Please check GoodputMonitor logs.",
+ 1,
+ ) | When do we expect reach this case? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -34,13 +36,46 @@ def test_from_flags(self, spec):
# Recorder is not instantiated until first event.
self.assertIsNone(recorder._recorder)
- def test_record(self):
+ def test_record_and_monitor(self):
fv = flags.FlagValues()
measurement.define_flags(flag_values=fv)
- fv.set_default("recorder_spec", ["name=test-name"])
+ fv.set_default(
+ "recorder_spec",
+ ["name=test-name", "upload_dir=/test/path/to/upload", "upload_interval=15"],
+ )
fv.mark_as_parsed()
recorder = GoodputRecorder.from_flags(fv)
recorder._recorder = mock.MagicMock()
recorder.record(measurement.Event.START_JOB)
self.assertTrue(recorder._recorder.record_job_start_time.called)
+
+ def test_start_monitoring(self):
+ fv = flags.FlagValues()
+ measurement.define_flags(flag_values=fv)
+ fv.set_default(
+ "recorder_spec",
+ ["name=test-name", "upload_dir=/test/path/to/upload", "upload_interval=15"],
+ )
+ fv.mark_as_parsed()
+
+ recorder = GoodputRecorder.from_flags(fv)
+ recorder._monitor = None # Ensure _monitor is initially None | ```suggestion
self.assertIsNone(recorder._monitor) # Ensure _monitor is initially None
``` |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -22,7 +23,11 @@ def from_flags(cls, fv: flags.FlagValues) -> "GoodputRecorder":
"""Converts flags to a recorder.
`fv.recorder_spec` will be interpreted as a list of `key=value` pairs; config names
- corresponding to keys will be set to the corresponding values.
+ corresponding to keys will be set to the corresponding values. A GoodputRecorder can
+ additionally take in following Tensorboard configs in the recorder_spec:
+ - upload_dir: The directory to write Tensorboard data to.
+ - upload_interval: The time interval in seconds at which to query and upload data | Should we move the configs to this class for now? I.e., on L19:
```
@config_class
class Config(measurement.Recorder.Config):
"""Configures GoodputRecorder."""
upload_dir: Required[str] = REQUIRED
upload_interval: Required[str] = REQUIRED
``` |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -13,6 +13,7 @@ def main(_):
launch.setup()
trainer_config = launch_trainer.get_trainer_config()
trainer_config.set(recorder=config_for_function(lambda: measurement.global_recorder))
+ measurement.start_monitoring() | I suppose we must do this after `launch.setup` due to `jax.process_index`? If so, maybe we should add a comment to the goodput `start_monitoring` docstring that it assumes jax distributed init. |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +65,50 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_DATA_LOADING:
+ self._recorder.record_data_loading_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_DATA_LOADING:
+ self._recorder.record_data_loading_end_time(*args, **kwargs)
else:
logging.log_first_n(
logging.WARNING,
"Ignoring unknown event %s",
1,
event,
)
+
+ def start_monitoring(self, *args, **kwargs):
+ """
+ Instantiate ml-goodput-measurement's GoodputMonitor to asynchronously calculate | We actually follow the Google style docstrings 🙂
```suggestion
"""Instantiates ml-goodput-measurement's GoodputMonitor to asynchronously calculate
``` |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -324,6 +325,7 @@ def __init__(
model=self.model,
model_param_partition_specs=model_param_partition_specs,
)
+ self._maybe_record_event(measurement.Event.END_ACCELERATOR_INIT) | Can you clarify what accelerator init is supposed to capture? E.g., would `utils_spmd` where we call jax distributed init be more appropriate? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -847,6 +850,7 @@ def _prepare_training(self, prng_key: Tensor) -> bool:
with fs.open(os.path.join(cfg.dir, "model_analysis.txt"), "w") as f:
f.write(model_analysis)
+ self._maybe_record_event(measurement.Event.END_TRAINING_PREPARATION) | What's usually considered part of "training preparation"? Should we count the jit compilation below as a potentially substantial part of it? What about the checkpoint restoration above? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -883,6 +887,7 @@ def restore_checkpoint(self, restore_step: Optional[int] = None) -> Optional[int
restore_input_iter = cfg.save_input_iterator
try:
# Try to restore with `input_iter`.
+ self._maybe_record_event(measurement.Event.START_DATA_LOADING) | Hm, is data loading be in relation to the input loading or the checkpoint or both? Here it seems only capturing the checkpoint restoration? |
axlearn | github_2023 | python | 783 | apple | ruomingp | @@ -49,10 +65,51 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_DATA_LOADING:
+ self._recorder.record_data_loading_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_DATA_LOADING:
+ self._recorder.record_data_loading_end_time(*args, **kwargs)
else:
logging.log_first_n(
logging.WARNING,
"Ignoring unknown event %s",
1,
event,
)
+
+ def start_monitoring(self, *args, **kwargs):
+ """Starts Monitoring of Goodput.
+
+ Instantiate ml-goodput-measurement's GoodputMonitor to asynchronously calculate
+ Goodput and Badput at the upload_interval and upload to the specified TensorBoard
+ directory.
+ Note: This function requires initialization of distributed JAX before it is called.
+ """
+ if self._monitor is None:
+ cfg: GoodputRecorder.Config = self.config
+ self._monitor = goodput_monitoring.GoodputMonitor(
+ job_name=cfg.name,
+ logger_name=f"goodput_logger_{cfg.name}",
+ tensorboard_dir=cfg.upload_dir,
+ upload_interval=int(cfg.upload_interval),
+ monitoring_enabled=(jax.process_index() == 0),
+ include_badput_breakdown=True,
+ )
+
+ if self._monitor:
+ self._monitor.start_goodput_uploader(*args, **kwargs)
+ logging.info("Started Goodput upload to Tensorboard in the background!")
+ else:
+ logging.log_first_n(
+ logging.WARNING,
+ "Goodput upload could not be started. Please check GoodputMonitor logs.",
+ 1,
+ ) | ```suggestion
)
if not self._monitor:
# This could happen if there are internal errors (such as access errors) from GCP services such as Cloud Logging or Cloud Storage.
logging.log_first_n(
logging.WARNING,
"Goodput upload could not be started. Please check GoodputMonitor logs.",
1,
)
self._monitor.start_goodput_uploader(*args, **kwargs)
logging.info("Started Goodput upload to Tensorboard in the background!")
``` |
axlearn | github_2023 | python | 783 | apple | ruomingp | @@ -47,6 +59,10 @@ def record(self, event: Event, *args, **kwargs):
"""Records an event with the given name."""
raise NotImplementedError(type(self))
+ def start_monitoring(self, **kwargs):
+ """Starts computing and uploading metrics at some configured interval in the background."""
+ raise NotImplementedError(type(self)) | To avoid breaking other subclasses of `Recorder`.
```suggestion
pass
``` |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +65,50 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_DATA_LOADING:
+ self._recorder.record_data_loading_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_DATA_LOADING:
+ self._recorder.record_data_loading_end_time(*args, **kwargs)
else:
logging.log_first_n(
logging.WARNING,
"Ignoring unknown event %s",
1,
event,
)
+
+ def start_monitoring(self, *args, **kwargs):
+ """Starts Monitoring of Goodput.
+
+ Instantiate ml-goodput-measurement's GoodputMonitor to asynchronously calculate
+ Goodput and Badput at the upload_interval and upload to the specified TensorBoard
+ directory.
+ Note: This function requires initialization of distributed JAX before it is called.
+ """
+ if self._monitor is None:
+ cfg: GoodputRecorder.Config = self.config
+ self._monitor = goodput_monitoring.GoodputMonitor(
+ job_name=cfg.name,
+ logger_name=f"goodput_logger_{cfg.name}",
+ tensorboard_dir=cfg.upload_dir,
+ upload_interval=int(cfg.upload_interval),
+ monitoring_enabled=(jax.process_index() == 0),
+ include_badput_breakdown=True,
+ )
+ if not self._monitor:
+ # This could happen if there are internal errors (such as access errors) from GCP services such as Cloud Logging or Cloud Storage.
+ logging.log_first_n(
+ logging.WARNING,
+ "Goodput upload could not be started. Please check GoodputMonitor logs.",
+ 1,
+ )
+ self._monitor.start_goodput_uploader(*args, **kwargs)
+ logging.info("Started Goodput upload to Tensorboard in the background!") | ```suggestion
if self._monitor:
self._monitor.start_goodput_uploader(*args, **kwargs)
logging.info("Started Goodput upload to Tensorboard in the background!")
else:
# This could happen if there are internal errors (such as access errors) from GCP services such as Cloud Logging or Cloud Storage.
logging.log_first_n(
logging.WARNING,
"Goodput upload could not be started. Please check GoodputMonitor logs.",
1,
)
```
So that we check that `self._monitor` is valid before invoking `start_goodput_uploader`.
BTW, it's still unclear to me how `self._monitor` can be None after we construct the instance of `GoodputMonitor`. Are we missing a try/catch somewhere? Does the `__init__` method of `GoodputMonitor` raise an exception (that seems a bit unexpected)? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -34,13 +36,46 @@ def test_from_flags(self, spec):
# Recorder is not instantiated until first event.
self.assertIsNone(recorder._recorder)
- def test_record(self):
+ def test_record_and_monitor(self):
fv = flags.FlagValues()
measurement.define_flags(flag_values=fv)
- fv.set_default("recorder_spec", ["name=test-name"])
+ fv.set_default(
+ "recorder_spec",
+ ["name=test-name", "upload_dir=/test/path/to/upload", "upload_interval=15"],
+ )
fv.mark_as_parsed()
recorder = GoodputRecorder.from_flags(fv)
recorder._recorder = mock.MagicMock()
recorder.record(measurement.Event.START_JOB)
self.assertTrue(recorder._recorder.record_job_start_time.called)
+
+ def test_start_monitoring(self): | Does this test the failure scenario? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -47,6 +59,10 @@ def record(self, event: Event, *args, **kwargs):
"""Records an event with the given name."""
raise NotImplementedError(type(self))
+ def start_monitoring(self, **kwargs):
+ """Starts computing and uploading metrics at some configured interval in the background."""
+ pass | Let's `raise NotImplementedError(type(self))` and let subclasses decide whether to implement -- it should be fairly straightforward for a subclass to decide to not monitor, but we want the decision to be explicit. |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +65,50 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_TRAINING_PREPARATION:
+ self._recorder.record_training_preparation_end_time(*args, **kwargs)
+ elif event == measurement.Event.START_DATA_LOADING:
+ self._recorder.record_data_loading_start_time(*args, **kwargs)
+ elif event == measurement.Event.END_DATA_LOADING:
+ self._recorder.record_data_loading_end_time(*args, **kwargs)
else:
logging.log_first_n(
logging.WARNING,
"Ignoring unknown event %s",
1,
event,
)
+
+ def start_monitoring(self, *args, **kwargs):
+ """Starts Monitoring of Goodput.
+
+ Instantiate ml-goodput-measurement's GoodputMonitor to asynchronously calculate
+ Goodput and Badput at the upload_interval and upload to the specified TensorBoard
+ directory.
+ Note: This function requires initialization of distributed JAX before it is called.
+ """
+ if self._monitor is None:
+ cfg: GoodputRecorder.Config = self.config
+ self._monitor = goodput_monitoring.GoodputMonitor(
+ job_name=cfg.name,
+ logger_name=f"goodput_logger_{cfg.name}",
+ tensorboard_dir=cfg.upload_dir,
+ upload_interval=int(cfg.upload_interval),
+ monitoring_enabled=(jax.process_index() == 0),
+ include_badput_breakdown=True,
+ )
+ if not self._monitor:
+ # This could happen if there are internal errors (such as access errors) from GCP services such as Cloud Logging or Cloud Storage. | BTW, I just triggered the CI, sorry for not doing so early. (I suspect lines like this will fail pylint for being too long.) |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +65,47 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELERATOR_INIT:
+ self._recorder.record_tpu_init_start_time(*args, **kwargs) | OOI, is there anything here specific to TPUs or can we use the same API for GPUs on GCP? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -120,3 +136,16 @@ def record_event(event: Event):
logging.log_first_n(logging.INFO, "No recorder configured, ignoring events.", 1)
else:
global_recorder.record(event)
+
+
+def start_monitoring():
+ """Begins monitoring events as per global monitor functionality."""
+ if global_recorder is None:
+ logging.log_first_n( | nit -- since `start_monitoring` is only called once, we don't need `log_first_n`. (Not having it may help catch when it's called multiple times.) |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -66,8 +65,7 @@ def __call__(
# Specification of an optimizer state array.
OptStateSpec = TensorSpec
-NestedOptStateSpec = Union[OptStateSpec, dict, Sequence]
-TransformPartitionSpecFn = Callable[[NestedParameterSpec], NestedOptStateSpec]
+TransformPartitionSpecFn = Callable[[Nested[ParameterSpec]], Nested[OptStateSpec]] | Thanks for the clean-up. Is this change related to the PR? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2008,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ offload_src: Optional[MemoryKind] = "device",
+ offload_dst: Optional[MemoryKind] = "pinned_host",
+) -> PartitionedGradientTransformation:
+ """Offload the state of the wrapped optimizer to `offload_dst`.
+
+ Args:
+ optimizer: The optimizer to offload.
+ offload_src: Offload-from memory kind. Default to "device".
+ offload_dst: Offload-to memory kind. Default to "pinned_host".
+
+ Returns:
+ A optimizer whose state is on `offload_dst` and does the same computation as `optimizer`.
+
+ Raises:
+ ValueError: when the `update` function of the returned optimizer is called outside of jit
+ context.
+
+ This function returns a new `PartitionedGradientTransformation` that
+ 1. Puts all states of the wrapped optimizer on `offload_dst` through the partition function
+ during state initialization in the trainer.
+ 2. Copies the states to `offload_src` before `optimizer.update` is called.
+ 3. Copies the updated states to `offload_dst` after `optimizer.update` is called.
+
+ The .update function of the returned `PartitionedGradientTransformation` must be called within
+ a jit function.
+
+ Example usage:
+ ```python
+ your_opt = adamw_optimizer(...)
+ offloaded_opt = offload_optimizer(your_opt)
+ ```
+
+ Only wrap the optimizer that you actually want to offload with this function to avoid
+ unneseccary overhead. This is usually the optimizer that occupies the most HBM. For example,
+ when you have chained optimizers:
+ ```python
+ # Recommended
+ chain([
+ some_preprocessing(...),
+ clip_by_global_norm(...),
+ offload_optimizer(adamw_decoupled_optimizer(...)),
+ ])
+ # Not recommended
+ offload_optimizer(chain([
+ some_preprocessing(...),
+ clip_by_global_norm(...),
+ adamw_decoupled_optimizer(...),
+ ]))
+ ```
+
+ When using `skip_and_clip_by_global_norm` with this offload optimizer, you must wrap the entire
+ `skip_and_clip_by_global_norm` inside. Do not wrap the inner of `skip_and_clip_by_global_norm`
+ or you will get errors. Correct example:
+ ```
+ offloaded_opt = offload_optimizer(skip_and_clip_by_global_norm(inner=adamw_optimizer(...)))
+ ```
+ The reason is that `skip_and_clip_by_global_norm` conditionally chooses the previous optimizer
+ state and the updated new optimizer state using `jnp.where`, which doesn't support tensors on
+ `pinned_host` memory space.
+ """
+ optimizer = maybe_instantiate(optimizer)
+ if offload_src is None or offload_dst is None:
+ raise ValueError(
+ "offload_src and offload_dst cannot be None when using optimizer offloading."
+ )
+
+ logging.info("Optimizer offloading enabled.") | Also log `offload_src` and `offload_dst`? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2008,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ offload_src: Optional[MemoryKind] = "device",
+ offload_dst: Optional[MemoryKind] = "pinned_host", | Do we need Optional since they cannot be None?
```suggestion
offload_src: MemoryKind = "device",
offload_dst: MemoryKind = "pinned_host",
``` |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2008,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ offload_src: Optional[MemoryKind] = "device",
+ offload_dst: Optional[MemoryKind] = "pinned_host",
+) -> PartitionedGradientTransformation:
+ """Offload the state of the wrapped optimizer to `offload_dst`.
+
+ Args:
+ optimizer: The optimizer to offload.
+ offload_src: Offload-from memory kind. Default to "device".
+ offload_dst: Offload-to memory kind. Default to "pinned_host".
+
+ Returns:
+ A optimizer whose state is on `offload_dst` and does the same computation as `optimizer`.
+
+ Raises:
+ ValueError: when the `update` function of the returned optimizer is called outside of jit
+ context.
+
+ This function returns a new `PartitionedGradientTransformation` that
+ 1. Puts all states of the wrapped optimizer on `offload_dst` through the partition function
+ during state initialization in the trainer.
+ 2. Copies the states to `offload_src` before `optimizer.update` is called.
+ 3. Copies the updated states to `offload_dst` after `optimizer.update` is called.
+
+ The .update function of the returned `PartitionedGradientTransformation` must be called within
+ a jit function.
+
+ Example usage:
+ ```python
+ your_opt = adamw_optimizer(...)
+ offloaded_opt = offload_optimizer(your_opt)
+ ```
+
+ Only wrap the optimizer that you actually want to offload with this function to avoid
+ unneseccary overhead. This is usually the optimizer that occupies the most HBM. For example,
+ when you have chained optimizers: | Where does the overhead come from? Is it from the states of `clip_by_global_norm` being offloaded? If so, could we use regular expressions to specify which states to offload? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2008,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ offload_src: Optional[MemoryKind] = "device",
+ offload_dst: Optional[MemoryKind] = "pinned_host",
+) -> PartitionedGradientTransformation:
+ """Offload the state of the wrapped optimizer to `offload_dst`.
+
+ Args:
+ optimizer: The optimizer to offload.
+ offload_src: Offload-from memory kind. Default to "device".
+ offload_dst: Offload-to memory kind. Default to "pinned_host".
+
+ Returns:
+ A optimizer whose state is on `offload_dst` and does the same computation as `optimizer`.
+
+ Raises:
+ ValueError: when the `update` function of the returned optimizer is called outside of jit
+ context.
+
+ This function returns a new `PartitionedGradientTransformation` that
+ 1. Puts all states of the wrapped optimizer on `offload_dst` through the partition function
+ during state initialization in the trainer.
+ 2. Copies the states to `offload_src` before `optimizer.update` is called.
+ 3. Copies the updated states to `offload_dst` after `optimizer.update` is called.
+
+ The .update function of the returned `PartitionedGradientTransformation` must be called within
+ a jit function.
+
+ Example usage:
+ ```python
+ your_opt = adamw_optimizer(...)
+ offloaded_opt = offload_optimizer(your_opt)
+ ```
+
+ Only wrap the optimizer that you actually want to offload with this function to avoid
+ unneseccary overhead. This is usually the optimizer that occupies the most HBM. For example,
+ when you have chained optimizers:
+ ```python
+ # Recommended
+ chain([
+ some_preprocessing(...),
+ clip_by_global_norm(...),
+ offload_optimizer(adamw_decoupled_optimizer(...)),
+ ])
+ # Not recommended
+ offload_optimizer(chain([
+ some_preprocessing(...),
+ clip_by_global_norm(...),
+ adamw_decoupled_optimizer(...),
+ ]))
+ ```
+
+ When using `skip_and_clip_by_global_norm` with this offload optimizer, you must wrap the entire
+ `skip_and_clip_by_global_norm` inside. Do not wrap the inner of `skip_and_clip_by_global_norm`
+ or you will get errors. Correct example:
+ ```
+ offloaded_opt = offload_optimizer(skip_and_clip_by_global_norm(inner=adamw_optimizer(...)))
+ ```
+ The reason is that `skip_and_clip_by_global_norm` conditionally chooses the previous optimizer
+ state and the updated new optimizer state using `jnp.where`, which doesn't support tensors on
+ `pinned_host` memory space.
+ """
+ optimizer = maybe_instantiate(optimizer)
+ if offload_src is None or offload_dst is None:
+ raise ValueError(
+ "offload_src and offload_dst cannot be None when using optimizer offloading."
+ )
+
+ logging.info("Optimizer offloading enabled.")
+
+ def init_fn(params: NestedOptParam):
+ return optimizer.init(params)
+
+ def update_fn(updates: optax.Updates, state: optax.OptState, params: NestedOptParam):
+ # TransferToMemoryKind let us change the memory kind of tensors without specifying the full
+ # sharding (i.e. jax.sharding.NamedSharding). Although there's no documentation about it,
+ # it's specified in the API signature. Reference:
+ # https://github.com/jax-ml/jax/blob/21f8885a9e104b8828c9a8b721eed0c68b622691/jax/_src/api.py#L2220
+ state = jax.device_put(state, TransferToMemoryKind(offload_src))
+ updates, state = optimizer.update(updates, state, params)
+ state = jax.device_put(state, TransferToMemoryKind(offload_dst), donate=True) | Do we need explicit `device_put` calls here? Is it enough to specify the partition spec with the right memory_kind? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2015,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ pattern: Union[str, re.Pattern] = ".*",
+ offload_src: MemoryKind = "device",
+ offload_dst: MemoryKind = "pinned_host",
+) -> PartitionedGradientTransformation:
+ """Offload the state of the wrapped optimizer that matches `pattern` to `offload_dst`.
+
+ Args:
+ optimizer: The optimizer to offload.
+ pattern: Regex pattern used to match the path of optimizer states. Matched states will be
+ offloaded. Default to regex that matches all states. | ```suggestion
pattern: Regex pattern used to match the path of optimizer states. Fully matched states will be
offloaded. Default to regex that matches all states.
``` |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2015,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ pattern: Union[str, re.Pattern] = ".*",
+ offload_src: MemoryKind = "device",
+ offload_dst: MemoryKind = "pinned_host",
+) -> PartitionedGradientTransformation:
+ """Offload the state of the wrapped optimizer that matches `pattern` to `offload_dst`.
+
+ Args:
+ optimizer: The optimizer to offload.
+ pattern: Regex pattern used to match the path of optimizer states. Matched states will be
+ offloaded. Default to regex that matches all states.
+ offload_src: Offload-from memory kind. Default to "device".
+ offload_dst: Offload-to memory kind. Default to "pinned_host".
+
+ Returns:
+ A optimizer whose state is on `offload_dst` and does the same computation as `optimizer`.
+
+ Raises:
+ ValueError: when the `update` function of the returned optimizer is called outside of jit
+ context.
+
+ This function returns a new `PartitionedGradientTransformation` that
+ 1. Puts matched states of the wrapped optimizer on `offload_dst` through the partition function
+ during state initialization in the trainer.
+ 2. Copies the matched states to `offload_src` before `optimizer.update` is called.
+ 3. Copies the matched updated states to `offload_dst` after `optimizer.update` is called.
+
+ The regex pattern is matched against the full path of each optimizer state. An example full
+ path is optimizer/1/0/mu/decoder/transformer/repeat/layer/feed_forward/linear1_0. If the | Hmmm, we should really use `named_chain` to avoid `/1` and `/0` in paths. |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2015,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ pattern: Union[str, re.Pattern] = ".*",
+ offload_src: MemoryKind = "device",
+ offload_dst: MemoryKind = "pinned_host",
+) -> PartitionedGradientTransformation:
+ """Offload the state of the wrapped optimizer that matches `pattern` to `offload_dst`.
+
+ Args:
+ optimizer: The optimizer to offload.
+ pattern: Regex pattern used to match the path of optimizer states. Matched states will be
+ offloaded. Default to regex that matches all states.
+ offload_src: Offload-from memory kind. Default to "device".
+ offload_dst: Offload-to memory kind. Default to "pinned_host".
+
+ Returns:
+ A optimizer whose state is on `offload_dst` and does the same computation as `optimizer`.
+
+ Raises:
+ ValueError: when the `update` function of the returned optimizer is called outside of jit
+ context.
+
+ This function returns a new `PartitionedGradientTransformation` that
+ 1. Puts matched states of the wrapped optimizer on `offload_dst` through the partition function
+ during state initialization in the trainer.
+ 2. Copies the matched states to `offload_src` before `optimizer.update` is called.
+ 3. Copies the matched updated states to `offload_dst` after `optimizer.update` is called.
+
+ The regex pattern is matched against the full path of each optimizer state. An example full
+ path is optimizer/1/0/mu/decoder/transformer/repeat/layer/feed_forward/linear1_0. If the
+ pattern should not depend on model structure, you can use ".*mu.*" to offload all `mu`. | ```suggestion
pattern should not depend on model structure, you can use ".*/mu/.*" to offload all `mu`.
``` |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -139,19 +140,40 @@ def update_fn(
return PartitionedGradientTransformation(init=init_fn, update=update_fn, partition=partition_fn)
-def copy_partition(param_specs: NestedParameterSpec) -> NestedPartitionSpec:
+def copy_partition(
+ param_specs: Nested[ParameterSpec],
+ *,
+ pattern: Union[None, str, re.Pattern] = None,
+ memory_kind: Optional[MemoryKind] = None,
+) -> Nested[OptStateSpec]: | Instead of coupling creation of `OptStateSpec` and setting of `memory_kind`, how about having a separate function for setting memory kind?
```
def set_memory_kind(opt_state_spec: Nested[OptStateSpec], *, pattern, memory_kind):
```
This allows `set_memory_kind` to be called multiple times, maybe for different memory kind. WDYT? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2015,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ pattern: Union[str, re.Pattern] = ".*",
+ offload_src: MemoryKind = "device",
+ offload_dst: MemoryKind = "pinned_host",
+) -> PartitionedGradientTransformation:
+ """Offload the state of the wrapped optimizer that matches `pattern` to `offload_dst`.
+
+ Args:
+ optimizer: The optimizer to offload.
+ pattern: Regex pattern used to match the path of optimizer states. Matched states will be
+ offloaded. Default to regex that matches all states.
+ offload_src: Offload-from memory kind. Default to "device".
+ offload_dst: Offload-to memory kind. Default to "pinned_host".
+
+ Returns:
+ A optimizer whose state is on `offload_dst` and does the same computation as `optimizer`.
+
+ Raises:
+ ValueError: when the `update` function of the returned optimizer is called outside of jit
+ context.
+
+ This function returns a new `PartitionedGradientTransformation` that
+ 1. Puts matched states of the wrapped optimizer on `offload_dst` through the partition function
+ during state initialization in the trainer.
+ 2. Copies the matched states to `offload_src` before `optimizer.update` is called.
+ 3. Copies the matched updated states to `offload_dst` after `optimizer.update` is called.
+
+ The regex pattern is matched against the full path of each optimizer state. An example full
+ path is optimizer/1/0/mu/decoder/transformer/repeat/layer/feed_forward/linear1_0. If the
+ pattern should not depend on model structure, you can use ".*mu.*" to offload all `mu`.
+
+ The .update function of the returned `PartitionedGradientTransformation` must be called within
+ a jit function.
+
+ Example usage:
+ ```python
+ your_opt = adamw_optimizer(...)
+ offloaded_opt = offload_optimizer(your_opt)
+ ```
+
+ When using `skip_and_clip_by_global_norm` with this offload optimizer, you must wrap the entire
+ `skip_and_clip_by_global_norm` inside. Do not wrap the inner of `skip_and_clip_by_global_norm`
+ or you will get errors. Correct example:
+ ```
+ offloaded_opt = offload_optimizer(skip_and_clip_by_global_norm(inner=adamw_optimizer(...)))
+ ```
+ The reason is that `skip_and_clip_by_global_norm` conditionally chooses the previous optimizer
+ state and the updated new optimizer state using `jnp.where`, which doesn't support tensors on
+ `pinned_host` memory space.
+ """
+ optimizer = maybe_instantiate(optimizer)
+ if offload_src is None or offload_dst is None:
+ raise ValueError(
+ "offload_src and offload_dst cannot be None when using optimizer offloading."
+ )
+
+ logging.info("Optimizer offloading from %s to %s enabled.", offload_src, offload_dst)
+
+ def init_fn(params: NestedOptParam):
+ return optimizer.init(params)
+
+ def _move_fn(state: optax.OptState, dst: MemoryKind) -> optax.OptState:
+ # TransferToMemoryKind let us change the memory kind of tensors without specifying the full
+ # sharding (i.e. jax.sharding.NamedSharding). Although there's no documentation about it,
+ # it's specified in the API signature. Reference:
+ # https://github.com/jax-ml/jax/blob/21f8885a9e104b8828c9a8b721eed0c68b622691/jax/_src/api.py#L2220
+ return jax.tree.map(
+ lambda path, tensor: jax.device_put(tensor, TransferToMemoryKind(dst))
+ if re.fullmatch(pattern, path)
+ else tensor,
+ tree_paths(state),
+ state,
+ )
+
+ def update_fn(updates: optax.Updates, state: optax.OptState, params: NestedOptParam):
+ state = _move_fn(state, offload_src)
+ updates, state = optimizer.update(updates, state, params)
+ state = _move_fn(state, offload_dst) | I wonder whether the explicit `device_put` calls mean that we need to move all optimizer states into device before optimizer computation, leading to high device memory usage.
In theory, optimizer computation can be streaming---the optimizer states of variables can be updated separately so we can stream them into and out of device memory as needed. How do we achieve this?
An alternative is to use `with_sharding_constraint` calls instead of `device_put` calls, where the partition specs given to the `with_sharding_constraint` calls will put the arrays in the device memory. WDYT? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -139,19 +140,40 @@ def update_fn(
return PartitionedGradientTransformation(init=init_fn, update=update_fn, partition=partition_fn)
-def copy_partition(param_specs: NestedParameterSpec) -> NestedPartitionSpec:
+def copy_partition(
+ specs: Nested[OptStateSpec],
+ *,
+ pattern: Union[None, str, re.Pattern] = None,
+ memory_kind: Optional[MemoryKind] = None,
+) -> Nested[OptStateSpec]:
+ """Copies OptStateSpec and optionally assigns with a different memory kind.
+
+ Args:
+ specs: Nested[OptStateSpec] to copy from.
+ pattern: Regex to match the full path of each spec. Matched specs will have their memory
+ kind replaced with `memory_kind`.
+ memory_kind: New memory kind. Default to None.
+ Returns: | ```suggestion
Returns:
``` |
axlearn | github_2023 | python | 956 | apple | ruomingp | @@ -636,6 +637,7 @@ def get_trainer_config_fn(
keep_every_n_steps: int = 50_000,
save_every_n_steps: Optional[int] = None,
init_state_builder: Optional[state_builder.Builder.Config] = None,
+ logical_feed_indices: Optional[Sequence[int]] = None, | Do we need this? I think InputDispatcher can figure it out automatically. |
axlearn | github_2023 | python | 926 | apple | markblee | @@ -1216,18 +1216,37 @@ class Config(BaseLayer.Config):
dim: Required[int] = REQUIRED # The dimensionality of the positional embedding.
theta: float = 10000.0 # The scale of base frequency.
- def forward(self, positions: Tensor) -> Tensor:
+ def default_query_positions(self, max_seq_len: int) -> Tensor: | ```suggestion
def _default_query_positions(self, max_seq_len: int) -> Tensor:
```
Users should pass `max_seq_len` rather than calling this method publicly. |
axlearn | github_2023 | python | 926 | apple | markblee | @@ -1216,18 +1216,37 @@ class Config(BaseLayer.Config):
dim: Required[int] = REQUIRED # The dimensionality of the positional embedding.
theta: float = 10000.0 # The scale of base frequency.
- def forward(self, positions: Tensor) -> Tensor:
+ def default_query_positions(self, max_seq_len: int) -> Tensor:
+ """Compute default `positions` value to be inputed into forward when `positions` is
+ not provided to the corresponding QKVLinear class such as `RoFormerQKVLinear`
+ """
+ return jnp.arange(max_seq_len)[None] # [batch_size=1, max_seq_len].
+
+ def forward(
+ self, positions: Optional[Tensor] = None, max_seq_len: Optional[int] = None
+ ) -> Tensor:
"""
TODO(bwzhang): 1. verify the performance under float32.
Args:
positions: A tensor representing the token position IDs.
The shape is [batch_size, seq_len].
+ max_seq_len: Max length of sequence, required if positions is not provided | ```suggestion
max_seq_len: Max length of sequence, required if positions is not provided.
``` |
axlearn | github_2023 | python | 926 | apple | ruomingp | @@ -1216,18 +1216,37 @@ class Config(BaseLayer.Config):
dim: Required[int] = REQUIRED # The dimensionality of the positional embedding.
theta: float = 10000.0 # The scale of base frequency.
- def forward(self, positions: Tensor) -> Tensor:
+ def default_query_positions(self, max_seq_len: int) -> Tensor:
+ """Compute default `positions` value to be inputed into forward when `positions` is
+ not provided to the corresponding QKVLinear class such as `RoFormerQKVLinear`
+ """
+ return jnp.arange(max_seq_len)[None] # [batch_size=1, max_seq_len].
+
+ def forward(
+ self, positions: Optional[Tensor] = None, max_seq_len: Optional[int] = None | Do we need to support both args? It seems simpler and more readable to take `positions` only and let the caller call `jnp.arange` if necessary. |
axlearn | github_2023 | python | 926 | apple | ruomingp | @@ -1216,18 +1216,37 @@ class Config(BaseLayer.Config):
dim: Required[int] = REQUIRED # The dimensionality of the positional embedding.
theta: float = 10000.0 # The scale of base frequency.
- def forward(self, positions: Tensor) -> Tensor:
+ def default_query_positions(self, max_seq_len: int) -> Tensor:
+ """Compute default `positions` value to be inputed into forward when `positions` is
+ not provided to the corresponding QKVLinear class such as `RoFormerQKVLinear`
+ """
+ return jnp.arange(max_seq_len)[None] # [batch_size=1, max_seq_len].
+
+ def forward(
+ self, positions: Optional[Tensor] = None, max_seq_len: Optional[int] = None
+ ) -> Tensor:
"""
TODO(bwzhang): 1. verify the performance under float32.
Args:
positions: A tensor representing the token position IDs.
The shape is [batch_size, seq_len].
+ max_seq_len: Max length of sequence, required if positions is not provided.
Returns:
Rotary Positional Embedding. Shape is [seq_len, dim].
+
+ Raises:
+ ValueError: If positions is None and max_seq_len is None.
"""
cfg = self.config
+ if positions is None:
+ if max_seq_len is None: | what happens if both `positions` and `max_seq_len` are provided? should we check that they are consistent? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.