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
699
apple
markblee
@@ -0,0 +1,334 @@ +# Copyright © 2024 Apple Inc. +"""Utilities for the detailed tool use metrics.""" + +import re +import string +from enum import Enum +from typing import Union + +from typing_extensions import TypeAlias + +Value = Union[str, int, bool, float] +ValueOrListOf: TypeAlias = Union[Value, list[Value]] + +_STOP_WORDS = { + "a", + "about", + "above", + "after", + "again", + "against", + "ain", + "all", + "am", + "an", + "and", + "any", + "are", + "aren", + "aren't", + "as", + "at", + "be", + "because", + "been", + "before", + "being", + "below", + "between", + "both", + "but", + "by", + "can", + "couldn", + "couldn't", + "d", + "did", + "didn", + "didn't", + "do", + "does", + "doesn", + "doesn't", + "doing", + "don", + "don't", + "down", + "during", + "each", + "few", + "for", + "from", + "further", + "had", + "hadn", + "hadn't", + "has", + "hasn", + "hasn't", + "have", + "haven", + "haven't", + "having", + "he", + "her", + "here", + "hers", + "herself", + "him", + "himself", + "his", + "how", + "i", + "if", + "in", + "into", + "is", + "isn", + "isn't", + "it", + "it's", + "its", + "itself", + "just", + "ll", + "m", + "ma", + "me", + "mightn", + "mightn't", + "more", + "most", + "mustn", + "mustn't", + "my", + "myself", + "needn", + "needn't", + "no", + "nor", + "not", + "now", + "o", + "of", + "off", + "on", + "once", + "only", + "or", + "other", + "our", + "ours", + "ourselves", + "out", + "over", + "own", + "re", + "s", + "same", + "shan", + "shan't", + "she", + "she's", + "should", + "should've", + "shouldn", + "shouldn't", + "so", + "some", + "such", + "t", + "than", + "that", + "that'll", + "the", + "their", + "theirs", + "them", + "themselves", + "then", + "there", + "these", + "they", + "this", + "those", + "through", + "to", + "too", + "under", + "until", + "up", + "ve", + "very", + "was", + "wasn", + "wasn't", + "we", + "were", + "weren", + "weren't", + "what", + "when", + "where", + "which", + "while", + "who", + "whom", + "why", + "will", + "with", + "won", + "won't", + "wouldn", + "wouldn't", + "y", + "you", + "you'd", + "you'll", + "you're", + "you've", + "your", + "yours", + "yourself", + "yourselves", +} + + +class ArgumentMatchType(Enum): + STRICT = 1 + LENIENT = 2 + LENIENT_BAG_OF_WORD = 3 + + +def _string_lenient_transform(str_value: str) -> str: + """Performs a lenient string transformation.""" + normalized_str_value = str_value.lower() + normalized_str_value = normalized_str_value.translate(str.maketrans("", "", string.punctuation)) + words = normalized_str_value.split() + start_index = next( + (i for i in range(len(words)) if words[i] not in _STOP_WORDS), + len(words) - 1 if len(words) > 0 and words[-1] not in _STOP_WORDS else len(words), + )
nit -- a basic for loop seems more readable here? ```suggestion start_index = len(words) for i, word in enumerate(words): if word not in _STOP_WORDS: start_index = i break ```
axlearn
github_2023
python
699
apple
markblee
@@ -0,0 +1,334 @@ +# Copyright © 2024 Apple Inc. +"""Utilities for the detailed tool use metrics.""" + +import re +import string +from enum import Enum +from typing import Union + +from typing_extensions import TypeAlias + +Value = Union[str, int, bool, float] +ValueOrListOf: TypeAlias = Union[Value, list[Value]] + +_STOP_WORDS = { + "a", + "about", + "above", + "after", + "again", + "against", + "ain", + "all", + "am", + "an", + "and", + "any", + "are", + "aren", + "aren't", + "as", + "at", + "be", + "because", + "been", + "before", + "being", + "below", + "between", + "both", + "but", + "by", + "can", + "couldn", + "couldn't", + "d", + "did", + "didn", + "didn't", + "do", + "does", + "doesn", + "doesn't", + "doing", + "don", + "don't", + "down", + "during", + "each", + "few", + "for", + "from", + "further", + "had", + "hadn", + "hadn't", + "has", + "hasn", + "hasn't", + "have", + "haven", + "haven't", + "having", + "he", + "her", + "here", + "hers", + "herself", + "him", + "himself", + "his", + "how", + "i", + "if", + "in", + "into", + "is", + "isn", + "isn't", + "it", + "it's", + "its", + "itself", + "just", + "ll", + "m", + "ma", + "me", + "mightn", + "mightn't", + "more", + "most", + "mustn", + "mustn't", + "my", + "myself", + "needn", + "needn't", + "no", + "nor", + "not", + "now", + "o", + "of", + "off", + "on", + "once", + "only", + "or", + "other", + "our", + "ours", + "ourselves", + "out", + "over", + "own", + "re", + "s", + "same", + "shan", + "shan't", + "she", + "she's", + "should", + "should've", + "shouldn", + "shouldn't", + "so", + "some", + "such", + "t", + "than", + "that", + "that'll", + "the", + "their", + "theirs", + "them", + "themselves", + "then", + "there", + "these", + "they", + "this", + "those", + "through", + "to", + "too", + "under", + "until", + "up", + "ve", + "very", + "was", + "wasn", + "wasn't", + "we", + "were", + "weren", + "weren't", + "what", + "when", + "where", + "which", + "while", + "who", + "whom", + "why", + "will", + "with", + "won", + "won't", + "wouldn", + "wouldn't", + "y", + "you", + "you'd", + "you'll", + "you're", + "you've", + "your", + "yours", + "yourself", + "yourselves", +} + + +class ArgumentMatchType(Enum): + STRICT = 1 + LENIENT = 2 + LENIENT_BAG_OF_WORD = 3 + + +def _string_lenient_transform(str_value: str) -> str: + """Performs a lenient string transformation.""" + normalized_str_value = str_value.lower() + normalized_str_value = normalized_str_value.translate(str.maketrans("", "", string.punctuation)) + words = normalized_str_value.split() + start_index = next( + (i for i in range(len(words)) if words[i] not in _STOP_WORDS), + len(words) - 1 if len(words) > 0 and words[-1] not in _STOP_WORDS else len(words), + ) + end_index = next(
Same here.
axlearn
github_2023
python
699
apple
markblee
@@ -0,0 +1,334 @@ +# Copyright © 2024 Apple Inc. +"""Utilities for the detailed tool use metrics.""" + +import re +import string +from enum import Enum +from typing import Union + +from typing_extensions import TypeAlias + +Value = Union[str, int, bool, float] +ValueOrListOf: TypeAlias = Union[Value, list[Value]] + +_STOP_WORDS = { + "a", + "about", + "above", + "after", + "again", + "against", + "ain", + "all", + "am", + "an", + "and", + "any", + "are", + "aren", + "aren't", + "as", + "at", + "be", + "because", + "been", + "before", + "being", + "below", + "between", + "both", + "but", + "by", + "can", + "couldn", + "couldn't", + "d", + "did", + "didn", + "didn't", + "do", + "does", + "doesn", + "doesn't", + "doing", + "don", + "don't", + "down", + "during", + "each", + "few", + "for", + "from", + "further", + "had", + "hadn", + "hadn't", + "has", + "hasn", + "hasn't", + "have", + "haven", + "haven't", + "having", + "he", + "her", + "here", + "hers", + "herself", + "him", + "himself", + "his", + "how", + "i", + "if", + "in", + "into", + "is", + "isn", + "isn't", + "it", + "it's", + "its", + "itself", + "just", + "ll", + "m", + "ma", + "me", + "mightn", + "mightn't", + "more", + "most", + "mustn", + "mustn't", + "my", + "myself", + "needn", + "needn't", + "no", + "nor", + "not", + "now", + "o", + "of", + "off", + "on", + "once", + "only", + "or", + "other", + "our", + "ours", + "ourselves", + "out", + "over", + "own", + "re", + "s", + "same", + "shan", + "shan't", + "she", + "she's", + "should", + "should've", + "shouldn", + "shouldn't", + "so", + "some", + "such", + "t", + "than", + "that", + "that'll", + "the", + "their", + "theirs", + "them", + "themselves", + "then", + "there", + "these", + "they", + "this", + "those", + "through", + "to", + "too", + "under", + "until", + "up", + "ve", + "very", + "was", + "wasn", + "wasn't", + "we", + "were", + "weren", + "weren't", + "what", + "when", + "where", + "which", + "while", + "who", + "whom", + "why", + "will", + "with", + "won", + "won't", + "wouldn", + "wouldn't", + "y", + "you", + "you'd", + "you'll", + "you're", + "you've", + "your", + "yours", + "yourself", + "yourselves", +} + + +class ArgumentMatchType(Enum): + STRICT = 1 + LENIENT = 2 + LENIENT_BAG_OF_WORD = 3 + + +def _string_lenient_transform(str_value: str) -> str: + """Performs a lenient string transformation.""" + normalized_str_value = str_value.lower() + normalized_str_value = normalized_str_value.translate(str.maketrans("", "", string.punctuation)) + words = normalized_str_value.split() + start_index = next( + (i for i in range(len(words)) if words[i] not in _STOP_WORDS), + len(words) - 1 if len(words) > 0 and words[-1] not in _STOP_WORDS else len(words), + ) + end_index = next( + ( + i + 1 + for i in reversed(range(start_index + 1, len(words))) + if words[i] not in _STOP_WORDS + ), + start_index + 1, + ) + + words = words[start_index:end_index] + normalized_str_value = " ".join(words) + return normalized_str_value + + +def _word_set(input_str: str) -> set[str]: + """Returns a set of words splitting by whitespace, newline and tab, + and skipping empty strings from the set.""" + return {s for s in re.split(r"\s+", input_str) if s} + + +def _match_strings_bag_of_words(*, pred_str: str, target_str: str, threshold: float = 1.0) -> bool: + """Match strings using a bag of words approach. + + Args: + pred_str: The predicted argument string. + target_str: The target argument string. + threshold: Thresold to be compared with the ratio (# unique common words) / (# unique + pred_str words). The predicted string is considered to match the target if the ratio + is higher or equal to this threshold. + + Returns: + True if recall is higher or equal to threshold; otherwise return False. + """ + if pred_str == target_str: + return True + + if threshold <= 0: + raise ValueError( + f"Bag of words string matching threshold must be above 0, but is {threshold}." + ) + pred_word_set = _word_set(pred_str) + target_word_set = _word_set(target_str) + + if len(pred_word_set) == 0 and len(target_word_set) == 0: + return True + if len(target_word_set) == 0: + return False + + common_words = target_word_set.intersection(pred_word_set) + ratio = len(common_words) / len(target_word_set) + return ratio >= threshold + + +def _is_arg_value_equal( + *, + pred_arg: ValueOrListOf, + target_arg: ValueOrListOf, + match_type: ArgumentMatchType, +) -> bool: + """Checks if the predicted and target arguments are equal under different checks.""" + if match_type == ArgumentMatchType.STRICT: + return pred_arg == target_arg + + if ( + isinstance(pred_arg, list) + and isinstance(target_arg, list) + and len(pred_arg) == len(target_arg) + ): + return all( + _is_arg_value_equal( + pred_arg=el_pred, + target_arg=el_target, + match_type=match_type, + ) + for el_pred, el_target in zip(pred_arg, target_arg) + ) + # Only handling string payloads for lenient evaluation
```suggestion # Only handling string payloads for lenient evaluation. ``` (A gentle reminder to apply review comments throughout the PR.)
axlearn
github_2023
python
705
apple
markblee
@@ -666,3 +673,96 @@ def _mha_backward( flash_attention.defvjp(_mha_forward, _mha_backward) + + +def check_local_compute_capability(cc):
Does this need to be a public fn? Also annotate types/returns/docstring etc?
axlearn
github_2023
python
705
apple
markblee
@@ -666,3 +673,96 @@ def _mha_backward( flash_attention.defvjp(_mha_forward, _mha_backward) + + +def check_local_compute_capability(cc): + if cuda_versions is None: + raise RuntimeError("cuDNN is not detected.") + for i in range(jax.local_device_count()): + compute_cap = cuda_versions.cuda_compute_capability(i) + if compute_cap not in cc: + raise RuntimeError("Require compute capability in " + str(cc)) + + +# Interface to cuDNN's dot product attention. +# TODO(kelvin-zou): Verify dropout rate functions. +# TODO(kelvin-zou): Add support for segment IDs. +def cudnn_dot_product_attention( + query: Tensor, + key: Tensor, + value: Tensor, + bias: Optional[Tensor] = None, + mask: Optional[Tensor] = None, + causal: bool = False, + *, + softmax_scale: float = 1.0, + seed: int = 42, + dropout_rate: float = 0.0, + qkv_layout: str = "BTNH", +): + """Computes dot-product attention given query (Q), key (K), and value (V). + + Reference implementation: + https://github.com/google/jax/blob/f4158ace933482844c145a6b919bf5dc86e084ba/jax/_src/cudnn/fused_attention_stablehlo.py#L927. + https://github.com/openxla/xla/blob/536ba0b7d74f6637a7a772471a99ecf4f578aef2/xla/service/gpu/cublas_cudnn.cc#L77. + + We override the Jax fused multihead attention(fMHA) interface in axlearn + due to following reasons: + 1. Original Jax implementation has a bug to support multi-node training (fixed in jax 0.4.32). + 2. We may want to leverage more lower level CuDNN capabilities from xla and expose to users. + + 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 [batch_size, num_heads, target_length, source_length]. + mask: Optional logit mask of shape [batch_size, num_heads, target_length, source_length]. + softmax_scale: Optional scale to apply to softmax. Defaults to 1/sqrt(per_head_dim).
Is this accurate?
axlearn
github_2023
python
705
apple
markblee
@@ -666,3 +673,96 @@ def _mha_backward( flash_attention.defvjp(_mha_forward, _mha_backward) + + +def check_local_compute_capability(cc): + if cuda_versions is None: + raise RuntimeError("cuDNN is not detected.") + for i in range(jax.local_device_count()): + compute_cap = cuda_versions.cuda_compute_capability(i) + if compute_cap not in cc: + raise RuntimeError("Require compute capability in " + str(cc)) + + +# Interface to cuDNN's dot product attention. +# TODO(kelvin-zou): Verify dropout rate functions. +# TODO(kelvin-zou): Add support for segment IDs. +def cudnn_dot_product_attention( + query: Tensor, + key: Tensor, + value: Tensor, + bias: Optional[Tensor] = None, + mask: Optional[Tensor] = None, + causal: bool = False, + *, + softmax_scale: float = 1.0, + seed: int = 42, + dropout_rate: float = 0.0, + qkv_layout: str = "BTNH", +): + """Computes dot-product attention given query (Q), key (K), and value (V). + + Reference implementation: + https://github.com/google/jax/blob/f4158ace933482844c145a6b919bf5dc86e084ba/jax/_src/cudnn/fused_attention_stablehlo.py#L927. + https://github.com/openxla/xla/blob/536ba0b7d74f6637a7a772471a99ecf4f578aef2/xla/service/gpu/cublas_cudnn.cc#L77. + + We override the Jax fused multihead attention(fMHA) interface in axlearn + due to following reasons: + 1. Original Jax implementation has a bug to support multi-node training (fixed in jax 0.4.32). + 2. We may want to leverage more lower level CuDNN capabilities from xla and expose to users. + + 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 [batch_size, num_heads, target_length, source_length]. + mask: Optional logit mask of shape [batch_size, num_heads, target_length, source_length]. + softmax_scale: Optional scale to apply to softmax. Defaults to 1/sqrt(per_head_dim). + seed: Random seed for dropout. + dropout_rate: Dropout rate. + qkv_layout: Layout string, with supported formats being BTNH, BNTH, BSNH, + BNSH. Now it only supports BTNH. + + Returns: + Output of the same shape as the query. + + Raises: + NotImplementedError: If qkv_layout is not supported. + """ + + if qkv_layout != "BTNH": + raise NotImplementedError(f"Unsupported qkv_layout: {qkv_layout}") + # check if cuDNN is installed.
```suggestion # Check if cuDNN is installed. ``` and below
axlearn
github_2023
python
705
apple
markblee
@@ -174,56 +176,59 @@ def ref_fn(q, k, v, bias): chex.assert_trees_all_close(jax_grads, jax_ref_grads, atol=0.05) -# We also include a test for Triton with Pallas, to cross validate the triton -# compatibility with our own implementation. +# We test the cudnn_dot_product_attention against the reference flash_attention. +# Due to its algorithmic equivalence, the outputs should be close in both fp16 and bfloat16. @pytest.mark.parametrize( "batch_size,num_heads,seq_len,per_head_dim", [ - (2, 2, 384, 64), + (1, 2, 2048, 128), + (2, 2, 2048, 128), + (1, 4, 4096, 128), + (2, 8, 4096, 128), ], ) @pytest.mark.parametrize("causal", [True, False]) -@pytest.mark.parametrize("bias_type", ["none", "vector"]) +@pytest.mark.parametrize("dtype", [jnp.bfloat16, jnp.float16]) @pytest.mark.skipif(jax.devices()[0].platform != "gpu", reason="Test only runs on GPU.") -def test_mha_against_pallas_ref( +def test_cudnn_against_triton_ref( batch_size: int, num_heads: int, seq_len: int, per_head_dim: int, causal: bool, - bias_type: str, + dtype: jnp.dtype, ): q = jax.random.normal( - jax.random.PRNGKey(0), (batch_size, seq_len, num_heads, per_head_dim), dtype=jnp.float16 + jax.random.PRNGKey(0), (batch_size, seq_len, num_heads, per_head_dim), dtype=dtype ) k = jax.random.normal( - jax.random.PRNGKey(1), (batch_size, seq_len, num_heads, per_head_dim), dtype=jnp.float16 + jax.random.PRNGKey(1), (batch_size, seq_len, num_heads, per_head_dim), dtype=dtype ) v = jax.random.normal( - jax.random.PRNGKey(2), (batch_size, seq_len, num_heads, per_head_dim), dtype=jnp.float16 + jax.random.PRNGKey(2), (batch_size, seq_len, num_heads, per_head_dim), dtype=dtype ) # Make sure that it is running on GPU. assert str(q.devices()) == "{cuda(id=0)}" sm_scale = q.shape[-1] ** -0.5 - if bias_type == "vector": - segment_left = jnp.ones((batch_size, seq_len // 2), dtype=jnp.int32) - segment_right = jnp.zeros((batch_size, seq_len // 2), dtype=jnp.int32) - segment_ids = jnp.concatenate([segment_left, segment_right], axis=-1) - else: - segment_ids = None + # Compare outputs. - jax_out = mha_reference(q, k, v, bias=segment_ids, causal=causal, softmax_scale=sm_scale) - jax_ref_out = pallas_mha(q, k, v, segment_ids=segment_ids, causal=causal, sm_scale=sm_scale) - chex.assert_trees_all_close(jax_out, jax_ref_out, atol=0.005, rtol=1e-5) + jax_out = cudnn_dot_product_attention(q, k, v, bias=None, causal=causal, softmax_scale=sm_scale) + jax_ref_out = flash_attention(q, k, v, bias=None, causal=causal, softmax_scale=sm_scale) + # We relax the atol to support both fp16 and bf16 in the unit test. + chex.assert_trees_all_close(jax_out, jax_ref_out, atol=0.02, rtol=1e-5)
Can we retain the original atol for the float16 case?
axlearn
github_2023
python
705
apple
markblee
@@ -174,56 +176,65 @@ def ref_fn(q, k, v, bias): chex.assert_trees_all_close(jax_grads, jax_ref_grads, atol=0.05) -# We also include a test for Triton with Pallas, to cross validate the triton -# compatibility with our own implementation. +# We test the cudnn_dot_product_attention against the reference flash_attention. +# Due to its algorithmic equivalence, the outputs should be close in both fp16 and bfloat16. @pytest.mark.parametrize( "batch_size,num_heads,seq_len,per_head_dim", [ - (2, 2, 384, 64), + (1, 2, 2048, 128), + (2, 2, 2048, 128), + (1, 4, 4096, 128), + (2, 8, 4096, 128), ], ) @pytest.mark.parametrize("causal", [True, False]) -@pytest.mark.parametrize("bias_type", ["none", "vector"]) +@pytest.mark.parametrize("dtype", [jnp.bfloat16, jnp.float16]) @pytest.mark.skipif(jax.devices()[0].platform != "gpu", reason="Test only runs on GPU.") -def test_mha_against_pallas_ref( +def test_cudnn_against_triton_ref( batch_size: int, num_heads: int, seq_len: int, per_head_dim: int, causal: bool, - bias_type: str, + dtype: jnp.dtype, ): q = jax.random.normal( - jax.random.PRNGKey(0), (batch_size, seq_len, num_heads, per_head_dim), dtype=jnp.float16 + jax.random.PRNGKey(0), (batch_size, seq_len, num_heads, per_head_dim), dtype=dtype ) k = jax.random.normal( - jax.random.PRNGKey(1), (batch_size, seq_len, num_heads, per_head_dim), dtype=jnp.float16 + jax.random.PRNGKey(1), (batch_size, seq_len, num_heads, per_head_dim), dtype=dtype ) v = jax.random.normal( - jax.random.PRNGKey(2), (batch_size, seq_len, num_heads, per_head_dim), dtype=jnp.float16 + jax.random.PRNGKey(2), (batch_size, seq_len, num_heads, per_head_dim), dtype=dtype ) # Make sure that it is running on GPU. assert str(q.devices()) == "{cuda(id=0)}" sm_scale = q.shape[-1] ** -0.5 - if bias_type == "vector": - segment_left = jnp.ones((batch_size, seq_len // 2), dtype=jnp.int32) - segment_right = jnp.zeros((batch_size, seq_len // 2), dtype=jnp.int32) - segment_ids = jnp.concatenate([segment_left, segment_right], axis=-1) - else: - segment_ids = None + # Compare outputs. - jax_out = mha_reference(q, k, v, bias=segment_ids, causal=causal, softmax_scale=sm_scale) - jax_ref_out = pallas_mha(q, k, v, segment_ids=segment_ids, causal=causal, sm_scale=sm_scale) - chex.assert_trees_all_close(jax_out, jax_ref_out, atol=0.005, rtol=1e-5) + jax_out = cudnn_dot_product_attention(q, k, v, bias=None, causal=causal, softmax_scale=sm_scale) + jax_ref_out = flash_attention(q, k, v, bias=None, causal=causal, softmax_scale=sm_scale) + if dtype == jnp.bfloat16: + # We relax the atol to support bf16 in the unit test. + chex.assert_trees_all_close(jax_out, jax_ref_out, atol=0.02, rtol=1e-5) + elif dtype == jnp.float16: + chex.assert_trees_all_close(jax_out, jax_ref_out, atol=0.005, rtol=1e-5)
We should probably add an `else: raise` or similar. If someone parameterizes a different dtype, we don't want to inadvertently skip the check.
axlearn
github_2023
python
705
apple
markblee
@@ -174,56 +176,65 @@ def ref_fn(q, k, v, bias): chex.assert_trees_all_close(jax_grads, jax_ref_grads, atol=0.05) -# We also include a test for Triton with Pallas, to cross validate the triton -# compatibility with our own implementation. +# We test the cudnn_dot_product_attention against the reference flash_attention. +# Due to its algorithmic equivalence, the outputs should be close in both fp16 and bfloat16. @pytest.mark.parametrize( "batch_size,num_heads,seq_len,per_head_dim", [ - (2, 2, 384, 64), + (1, 2, 2048, 128), + (2, 2, 2048, 128), + (1, 4, 4096, 128), + (2, 8, 4096, 128), ], ) @pytest.mark.parametrize("causal", [True, False]) -@pytest.mark.parametrize("bias_type", ["none", "vector"]) +@pytest.mark.parametrize("dtype", [jnp.bfloat16, jnp.float16]) @pytest.mark.skipif(jax.devices()[0].platform != "gpu", reason="Test only runs on GPU.") -def test_mha_against_pallas_ref( +def test_cudnn_against_triton_ref( batch_size: int, num_heads: int, seq_len: int, per_head_dim: int, causal: bool, - bias_type: str, + dtype: jnp.dtype, ): q = jax.random.normal( - jax.random.PRNGKey(0), (batch_size, seq_len, num_heads, per_head_dim), dtype=jnp.float16 + jax.random.PRNGKey(0), (batch_size, seq_len, num_heads, per_head_dim), dtype=dtype ) k = jax.random.normal( - jax.random.PRNGKey(1), (batch_size, seq_len, num_heads, per_head_dim), dtype=jnp.float16 + jax.random.PRNGKey(1), (batch_size, seq_len, num_heads, per_head_dim), dtype=dtype ) v = jax.random.normal( - jax.random.PRNGKey(2), (batch_size, seq_len, num_heads, per_head_dim), dtype=jnp.float16 + jax.random.PRNGKey(2), (batch_size, seq_len, num_heads, per_head_dim), dtype=dtype ) # Make sure that it is running on GPU. assert str(q.devices()) == "{cuda(id=0)}" sm_scale = q.shape[-1] ** -0.5 - if bias_type == "vector": - segment_left = jnp.ones((batch_size, seq_len // 2), dtype=jnp.int32) - segment_right = jnp.zeros((batch_size, seq_len // 2), dtype=jnp.int32) - segment_ids = jnp.concatenate([segment_left, segment_right], axis=-1) - else: - segment_ids = None + # Compare outputs. - jax_out = mha_reference(q, k, v, bias=segment_ids, causal=causal, softmax_scale=sm_scale) - jax_ref_out = pallas_mha(q, k, v, segment_ids=segment_ids, causal=causal, sm_scale=sm_scale) - chex.assert_trees_all_close(jax_out, jax_ref_out, atol=0.005, rtol=1e-5) + jax_out = cudnn_dot_product_attention(q, k, v, bias=None, causal=causal, softmax_scale=sm_scale) + jax_ref_out = flash_attention(q, k, v, bias=None, causal=causal, softmax_scale=sm_scale) + if dtype == jnp.bfloat16: + # We relax the atol to support bf16 in the unit test. + chex.assert_trees_all_close(jax_out, jax_ref_out, atol=0.02, rtol=1e-5) + elif dtype == jnp.float16: + chex.assert_trees_all_close(jax_out, jax_ref_out, atol=0.005, rtol=1e-5) def fn(q, k, v): - return mha_reference(q, k, v, bias=segment_ids, causal=causal, softmax_scale=sm_scale).sum() + return cudnn_dot_product_attention( + q, k, v, bias=None, causal=causal, softmax_scale=sm_scale + ).sum() def ref_fn(q, k, v): - return pallas_mha(q, k, v, segment_ids=segment_ids, causal=causal, sm_scale=sm_scale).sum() + return flash_attention(q, k, v, bias=None, causal=causal, softmax_scale=sm_scale).sum() # Compare gradients. jax_grads = jax.grad(fn, argnums=(0, 1, 2))(q, k, v) jax_ref_grads = jax.grad(ref_fn, argnums=(0, 1, 2))(q, k, v) - chex.assert_trees_all_close(jax_grads, jax_ref_grads, atol=0.05, rtol=1e-5) + # The diff between grads are expected to be larger than the forward pass. + if dtype == jnp.bfloat16: + # We relax the rtol to support bf16 in the unit test. + chex.assert_trees_all_close(jax_grads, jax_ref_grads, atol=0.05, rtol=1e-2) + elif dtype == jnp.float16: + chex.assert_trees_all_close(jax_grads, jax_ref_grads, atol=0.05, rtol=1e-5)
Same here.
axlearn
github_2023
python
701
apple
markblee
@@ -211,12 +212,21 @@ def __init__( utils.validate_float_dtype(cfg.train_dtype) # Create the device mesh. - self._step_log( - "Devices: global=%s local=%s %s", - jax.device_count(), - jax.local_device_count(), - [device.platform for device in jax.local_devices()], - ) + if devices is None: + self._step_log(
nit -- you could also just assign `devices,local_devices` and log after the conditional.
axlearn
github_2023
python
701
apple
markblee
@@ -49,7 +52,7 @@ def _compile_and_dump_programs( compile_topology: Optional[str], compile_topology_num_slices: int = 1, ): - with set_data_dir("FAKE"): + with set_data_dir(FLAGS.data_dir):
nit -- We could also read from env rather than taking a new flag.
axlearn
github_2023
python
696
apple
markblee
@@ -1059,19 +1059,25 @@ def _maybe_stop_or_start_tracing( def select_mesh_config(trainer_config: SpmdTrainer.Config, *, mesh_selector: str): - """Selects a mesh rule (if one matches `mesh_selector` to override mesh config. + """Selects a mesh rule (if one matches mesh_selector to override mesh config. - If any of `trainer_config.mesh_rules` matches `mesh_selector`, modifies - `trainer_config.mesh_shape` according to the rule. + If any of trainer_config.mesh_rules matches mesh_selector, modifies
Can we retain the backticks for code formatting?
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,151 @@ +"""Defines trainer config modifiers, which will be used in model definitions."""
Missing copyright.
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,151 @@ +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Optional[int] = None + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified.
```suggestion cfg: The trainer config to be modified. ``` The types are already specified in the signature.
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,151 @@ +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Optional[int] = None + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Returns: + SpmdTrainer.Config: the modified trainer config.
```suggestion The modified trainer config. ```
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,151 @@ +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Optional[int] = None
Do we need to support `None`? The caller can just avoid applying the modifier if they don't want to enable it.
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,151 @@ +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Optional[int] = None + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Returns: + SpmdTrainer.Config: the modified trainer config. + """ + if self._grad_acc_steps is None: + return cfg + + cfg.learner.forward_fn_transformation = config.config_for_function( + with_minibatch_steps + ).set( + steps=self._grad_acc_steps, + metric_accumulator=self._metric_accumulator, + ) + return cfg + + +class RematPolicies(ConfigModifier):
A suggestion on naming: ```suggestion class RematSpecModifier(ConfigModifier): ``` It may be more consistent/discoverable to name them as `XModifier`.
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg: the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.learner.forward_fn_transformation = config.config_for_function( + with_minibatch_steps + ).set( + steps=self._grad_acc_steps, + metric_accumulator=self._metric_accumulator, + ) + return cfg + + +class RematSpecModifier(ConfigModifier): + """Update the remat policies for specified modules.""" + + @config_class + class Config(ConfigModifier.Config): + remat_policies: Optional[Dict[str, RematSpec]] = None
Could we apply the same comment re. None here? Also, should we spell out how users should configure these, e.g. with a config docstring: ``` @config_class class Config(ConfigModifier.Config): """Configures RematSpecModifier. Attributes: remat_policies: A mapping from module path (e.g. `model.decoder.transformer.layer`) to remat spec. """ ```
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg: the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.learner.forward_fn_transformation = config.config_for_function( + with_minibatch_steps + ).set( + steps=self._grad_acc_steps, + metric_accumulator=self._metric_accumulator, + ) + return cfg + + +class RematSpecModifier(ConfigModifier): + """Update the remat policies for specified modules.""" + + @config_class + class Config(ConfigModifier.Config): + remat_policies: Optional[Dict[str, RematSpec]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._remat_policies = cfg.remat_policies + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Update the remat policy for the specified modules. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified.
Likewise with the comments on typing/casing? ```suggestion cfg: The trainer config to be modified. ```
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier):
```suggestion class GradientAccumulationModifier(ConfigModifier): ```
axlearn
github_2023
python
696
apple
markblee
@@ -102,6 +105,26 @@ def sharding(self) -> jax.sharding.Sharding: NestedTensorSpec = Optional[Union[TensorSpec, dict[str, Any]]] +def offload_dots_saveble(offload_src, offload_dst):
Missing types/returns? ```suggestion def offload_dots_saveable(offload_src, offload_dst): ```
axlearn
github_2023
python
696
apple
markblee
@@ -102,6 +105,26 @@ def sharding(self) -> jax.sharding.Sharding: NestedTensorSpec = Optional[Union[TensorSpec, dict[str, Any]]] +def offload_dots_saveble(offload_src, offload_dst): + """Extract and combine the policy from save_and_offload_only_these_names and dots_saveable. + https://github.com/google/jax/blob/e3110c18f8bce83901cff42458d4204df9e3abeb/jax/_src/ad_checkpoint.py#L151 + This would remove the need to match the names for activation tensors. + Args:
```suggestion """Extract and combine the policy from save_and_offload_only_these_names and dots_saveable. https://github.com/google/jax/blob/e3110c18f8bce83901cff42458d4204df9e3abeb/jax/_src/ad_checkpoint.py#L151 This would remove the need to match the names for activation tensors. Args: ```
axlearn
github_2023
python
696
apple
markblee
@@ -102,6 +105,26 @@ def sharding(self) -> jax.sharding.Sharding: NestedTensorSpec = Optional[Union[TensorSpec, dict[str, Any]]] +def offload_dots_saveble(offload_src, offload_dst): + """Extract and combine the policy from save_and_offload_only_these_names and dots_saveable. + https://github.com/google/jax/blob/e3110c18f8bce83901cff42458d4204df9e3abeb/jax/_src/ad_checkpoint.py#L151 + This would remove the need to match the names for activation tensors. + Args: + offload_src (str): the source device for offloading. + offload_dst (str): the target device for offloading.
```suggestion offload_src: The source device for offloading. offload_dst: The target device for offloading. ```
axlearn
github_2023
python
696
apple
markblee
@@ -102,6 +105,26 @@ def sharding(self) -> jax.sharding.Sharding: NestedTensorSpec = Optional[Union[TensorSpec, dict[str, Any]]] +def offload_dots_saveble(offload_src, offload_dst): + """Extract and combine the policy from save_and_offload_only_these_names and dots_saveable. + https://github.com/google/jax/blob/e3110c18f8bce83901cff42458d4204df9e3abeb/jax/_src/ad_checkpoint.py#L151 + This would remove the need to match the names for activation tensors. + Args: + offload_src (str): the source device for offloading. + offload_dst (str): the target device for offloading. + """ + + def policy(prim, *_): + if prim is lax_internal.dot_general_p: + return pe.Offloadable(src=offload_src, dst=offload_dst) + return pe.Recompute + + return policy + + +extended_checkpoint_policies = types.SimpleNamespace(offload_dots_saveble=offload_dots_saveble)
Do we need this?
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg: the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.learner.forward_fn_transformation = config.config_for_function( + with_minibatch_steps + ).set( + steps=self._grad_acc_steps, + metric_accumulator=self._metric_accumulator, + ) + return cfg + + +class RematSpecModifier(ConfigModifier): + """Update the remat policies for specified modules.""" + + @config_class + class Config(ConfigModifier.Config): + remat_policies: Optional[Dict[str, RematSpec]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._remat_policies = cfg.remat_policies + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Update the remat policy for the specified modules. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Raises: + ValueError: the target module is not found. + ValueError: the remat_spec attribute is not found. + + Returns: + The modified trainer config. + """ + if self._remat_policies is None: + return cfg +
```suggestion ```
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg: the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.learner.forward_fn_transformation = config.config_for_function( + with_minibatch_steps + ).set( + steps=self._grad_acc_steps, + metric_accumulator=self._metric_accumulator, + ) + return cfg + + +class RematSpecModifier(ConfigModifier): + """Update the remat policies for specified modules.""" + + @config_class + class Config(ConfigModifier.Config): + remat_policies: Optional[Dict[str, RematSpec]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._remat_policies = cfg.remat_policies + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Update the remat policy for the specified modules. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Raises: + ValueError: the target module is not found. + ValueError: the remat_spec attribute is not found. + + Returns: + The modified trainer config. + """ + if self._remat_policies is None: + return cfg + + for module_name, remat_spec in self._remat_policies.items(): + # Here we assume x.y.z format. + # One example would be model.decoder.transformer.layer. + target_modules = module_name.split(".") + curr_module = cfg + for target_module in target_modules: + if not hasattr(curr_module, target_module): + raise ValueError(f"{target_module} is not found in {curr_module}.") + curr_module = getattr(curr_module, target_module) + # Here we assume all modules have remat_spec attribute. + if not hasattr(curr_module, "remat_spec"): + raise ValueError(f"{curr_module} does not have remat_spec attribute") + curr_module.remat_spec = remat_spec + return cfg + + +class MeshShapeModifier(ConfigModifier): + """Update the mesh_shape for the trainer config.""" + + @config_class + class Config(ConfigModifier.Config): + mesh_shape: Optional[Union[MeshShape, HybridMeshShape]] = None
Same comment as above.
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg: the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.learner.forward_fn_transformation = config.config_for_function( + with_minibatch_steps + ).set( + steps=self._grad_acc_steps, + metric_accumulator=self._metric_accumulator, + ) + return cfg + + +class RematSpecModifier(ConfigModifier): + """Update the remat policies for specified modules.""" + + @config_class + class Config(ConfigModifier.Config): + remat_policies: Optional[Dict[str, RematSpec]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._remat_policies = cfg.remat_policies + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Update the remat policy for the specified modules. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Raises: + ValueError: the target module is not found. + ValueError: the remat_spec attribute is not found. + + Returns: + The modified trainer config. + """ + if self._remat_policies is None: + return cfg + + for module_name, remat_spec in self._remat_policies.items(): + # Here we assume x.y.z format. + # One example would be model.decoder.transformer.layer. + target_modules = module_name.split(".") + curr_module = cfg + for target_module in target_modules: + if not hasattr(curr_module, target_module): + raise ValueError(f"{target_module} is not found in {curr_module}.") + curr_module = getattr(curr_module, target_module) + # Here we assume all modules have remat_spec attribute. + if not hasattr(curr_module, "remat_spec"): + raise ValueError(f"{curr_module} does not have remat_spec attribute") + curr_module.remat_spec = remat_spec + return cfg + + +class MeshShapeModifier(ConfigModifier): + """Update the mesh_shape for the trainer config.""" + + @config_class + class Config(ConfigModifier.Config): + mesh_shape: Optional[Union[MeshShape, HybridMeshShape]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._mesh_shape = cfg.mesh_shape + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the mesh shape. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified.
Same comment as above.
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg: the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.learner.forward_fn_transformation = config.config_for_function( + with_minibatch_steps + ).set( + steps=self._grad_acc_steps, + metric_accumulator=self._metric_accumulator, + ) + return cfg + + +class RematSpecModifier(ConfigModifier): + """Update the remat policies for specified modules.""" + + @config_class + class Config(ConfigModifier.Config): + remat_policies: Optional[Dict[str, RematSpec]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._remat_policies = cfg.remat_policies + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Update the remat policy for the specified modules. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Raises: + ValueError: the target module is not found. + ValueError: the remat_spec attribute is not found. + + Returns: + The modified trainer config. + """ + if self._remat_policies is None: + return cfg + + for module_name, remat_spec in self._remat_policies.items(): + # Here we assume x.y.z format. + # One example would be model.decoder.transformer.layer. + target_modules = module_name.split(".") + curr_module = cfg + for target_module in target_modules: + if not hasattr(curr_module, target_module): + raise ValueError(f"{target_module} is not found in {curr_module}.") + curr_module = getattr(curr_module, target_module) + # Here we assume all modules have remat_spec attribute. + if not hasattr(curr_module, "remat_spec"): + raise ValueError(f"{curr_module} does not have remat_spec attribute") + curr_module.remat_spec = remat_spec + return cfg + + +class MeshShapeModifier(ConfigModifier): + """Update the mesh_shape for the trainer config.""" + + @config_class + class Config(ConfigModifier.Config): + mesh_shape: Optional[Union[MeshShape, HybridMeshShape]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._mesh_shape = cfg.mesh_shape + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the mesh shape. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.mesh_shape = self._mesh_shape + return cfg + + +class ChainConfigModifier(ConfigModifier): + """Chain multiple config modifiers together.""" + + @config_class + class Config(ConfigModifier.Config): + config_modifiers: Required[List[ConfigOr[ConfigModifier]]] = REQUIRED + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._config_modifiers = [ + cfg_modifier.instantiate() for cfg_modifier in cfg.config_modifiers + ] + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Chain multiple config modifiers together. + The config modifiers will be applied in the order they are provided. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified.
Also here.
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg: the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.learner.forward_fn_transformation = config.config_for_function( + with_minibatch_steps + ).set( + steps=self._grad_acc_steps, + metric_accumulator=self._metric_accumulator, + ) + return cfg + + +class RematSpecModifier(ConfigModifier): + """Update the remat policies for specified modules.""" + + @config_class + class Config(ConfigModifier.Config): + remat_policies: Optional[Dict[str, RematSpec]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._remat_policies = cfg.remat_policies + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Update the remat policy for the specified modules. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Raises: + ValueError: the target module is not found. + ValueError: the remat_spec attribute is not found. + + Returns: + The modified trainer config. + """ + if self._remat_policies is None: + return cfg + + for module_name, remat_spec in self._remat_policies.items(): + # Here we assume x.y.z format. + # One example would be model.decoder.transformer.layer. + target_modules = module_name.split(".") + curr_module = cfg + for target_module in target_modules: + if not hasattr(curr_module, target_module): + raise ValueError(f"{target_module} is not found in {curr_module}.") + curr_module = getattr(curr_module, target_module) + # Here we assume all modules have remat_spec attribute. + if not hasattr(curr_module, "remat_spec"): + raise ValueError(f"{curr_module} does not have remat_spec attribute") + curr_module.remat_spec = remat_spec + return cfg + + +class MeshShapeModifier(ConfigModifier): + """Update the mesh_shape for the trainer config.""" + + @config_class + class Config(ConfigModifier.Config): + mesh_shape: Optional[Union[MeshShape, HybridMeshShape]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._mesh_shape = cfg.mesh_shape + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the mesh shape. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.mesh_shape = self._mesh_shape + return cfg + + +class ChainConfigModifier(ConfigModifier): + """Chain multiple config modifiers together.""" + + @config_class + class Config(ConfigModifier.Config): + config_modifiers: Required[List[ConfigOr[ConfigModifier]]] = REQUIRED + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._config_modifiers = [ + cfg_modifier.instantiate() for cfg_modifier in cfg.config_modifiers
Since we specify the config modifier as `ConfigOr[ConfigModifier]`, we should use ```suggestion maybe_instantiate(cfg_modifier) for cfg_modifier in cfg.config_modifiers ```
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg: the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.learner.forward_fn_transformation = config.config_for_function( + with_minibatch_steps + ).set( + steps=self._grad_acc_steps, + metric_accumulator=self._metric_accumulator, + ) + return cfg + + +class RematSpecModifier(ConfigModifier): + """Update the remat policies for specified modules.""" + + @config_class + class Config(ConfigModifier.Config): + remat_policies: Optional[Dict[str, RematSpec]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._remat_policies = cfg.remat_policies + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Update the remat policy for the specified modules. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Raises: + ValueError: the target module is not found. + ValueError: the remat_spec attribute is not found. + + Returns: + The modified trainer config. + """ + if self._remat_policies is None: + return cfg + + for module_name, remat_spec in self._remat_policies.items(): + # Here we assume x.y.z format. + # One example would be model.decoder.transformer.layer. + target_modules = module_name.split(".") + curr_module = cfg + for target_module in target_modules: + if not hasattr(curr_module, target_module): + raise ValueError(f"{target_module} is not found in {curr_module}.") + curr_module = getattr(curr_module, target_module) + # Here we assume all modules have remat_spec attribute. + if not hasattr(curr_module, "remat_spec"): + raise ValueError(f"{curr_module} does not have remat_spec attribute") + curr_module.remat_spec = remat_spec + return cfg + + +class MeshShapeModifier(ConfigModifier): + """Update the mesh_shape for the trainer config.""" + + @config_class + class Config(ConfigModifier.Config): + mesh_shape: Optional[Union[MeshShape, HybridMeshShape]] = None + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._mesh_shape = cfg.mesh_shape + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the mesh shape. + + Args: + cfg (SpmdTrainer.Config): the trainer config to be modified. + + Returns: + The modified trainer config. + """ + cfg.mesh_shape = self._mesh_shape + return cfg + + +class ChainConfigModifier(ConfigModifier): + """Chain multiple config modifiers together.""" + + @config_class + class Config(ConfigModifier.Config): + config_modifiers: Required[List[ConfigOr[ConfigModifier]]] = REQUIRED
```suggestion config_modifiers: Required[Sequence[ConfigOr[ConfigModifier]]] = REQUIRED ```
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config()
```suggestion metric_accumulator: MetricAccumulator.Config = MetricAccumulator.default_config() ```
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,150 @@ +# Copyright © 2023 Apple Inc. + +"""Defines trainer config modifiers, which will be used in model definitions.""" + +from typing import Dict, List, Optional, Union + +from axlearn.common import config +from axlearn.common.base_layer import RematSpec +from axlearn.common.config import REQUIRED, ConfigModifier, ConfigOr, Required, config_class +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 + + +class GradientAccumulation(ConfigModifier): + """Accumulate gradients for grad_acc_steps steps.""" + + @config_class + class Config(ConfigModifier.Config): + grad_acc_steps: Required[int] = REQUIRED + metric_accumulator: Required[MetricAccumulator.Config] = MetricAccumulator.default_config() + + def __init__(self, cfg: Config): + super().__init__(cfg) + cfg = self.config + self._grad_acc_steps = cfg.grad_acc_steps + self._metric_accumulator = cfg.metric_accumulator + + def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: + """Overwrite the forward_fn_transformation to accumulate gradients for grad_acc_steps steps. + + Note this would not affect the global batch size or the logical training steps. + The optimization step is applied each time after grad_acc_steps steps of + forward and backward passes on mini-batches. + + global_bs=mini_bs*grad_acc_steps + train_steps=mini_steps/grad_acc_steps + + Args: + cfg: the trainer config to be modified.
```suggestion cfg: The trainer config to be modified. ```
axlearn
github_2023
python
696
apple
markblee
@@ -102,6 +105,26 @@ def sharding(self) -> jax.sharding.Sharding: NestedTensorSpec = Optional[Union[TensorSpec, dict[str, Any]]] +def offload_dots_saveble(offload_src, offload_dst): + """Extract and combine the policy from save_and_offload_only_these_names and dots_saveable.
Is this accurate? Seems that `dots_saveable` includes `lax_convolution.conv_general_dilated_p`. Also clarify how it combines `save_and_offload_only_these_names `?
axlearn
github_2023
python
696
apple
markblee
@@ -0,0 +1,180 @@ +# Copyright © 2023 Apple Inc.
```suggestion # Copyright © 2024 Apple Inc. ``` (here and elsewhere)
axlearn
github_2023
python
693
apple
markblee
@@ -659,7 +659,7 @@ class Config(BaseLayer.Config): # Dimension of each attention head. per_head_dim: Required[int] = REQUIRED # Autoregressive cache dtype. Should match the step dtype. - # Needs to match the forward dtype for Repeated layers. If None, infer as config.dtype. + # Needs to match the forward dtype for Repeated layers. If None, infer as BaseLayer.dtype().
```suggestion # Needs to match the forward dtype for Repeated layers. If None, infer as `self.dtype()`. ```
axlearn
github_2023
python
695
apple
ruomingp
@@ -185,78 +134,169 @@ def test_training_lm_processor_single_example(self, text: str): # The inputs should be one-off the labels. self.assertNestedAllClose(target_labels[:-1], input_ids[1:]) + @parameterized.parameters( + dict( + packing_method=PackingMethodType.EOS_DELIM_MASK, + expected_batches=[ + { + "input_ids": [ + [1, 21820, 296, 2, 29], + [3155, 1, 21820, 8114, 2], + ], + "target_labels": [ + [21820, 296, 2, 29, 3155], + [1, 21820, 8114, 2, 29], + ], + "input_segment_ids": [ + [1, 1, 1, 1, 1], + [1, 2, 2, 2, 2], + ], + "input_positions": [ + [0, 1, 2, 3, 4], + [0, 0, 1, 2, 3], + ], + "target_num_bytes": [18, 17], + }, + { + "input_ids": [ + [29, 3155, 1, 21820, 296], + [2, 29, 3155, 0, 0], + ], + "target_labels": [ + [3155, 1, 21820, 296, 2], + [29, 3155, 1, 0, 0], + ], + "input_segment_ids": [ + [1, 1, 2, 2, 2], + [1, 1, 1, 0, 0], + ], + "input_positions": [ + [0, 1, 0, 1, 2], + [0, 1, 2, 0, 0], + ], + "target_num_bytes": [19, 3], + }, + ], + ), + dict( + packing_method=PackingMethodType.EOS_DELIM_NO_MASK, + expected_batches=[ + { + "input_ids": [ + [1, 21820, 296, 2, 29], + [3155, 1, 21820, 8114, 2], + ], + "target_labels": [ + [21820, 296, 2, 29, 3155], + [1, 21820, 8114, 2, 29], + ], + "target_num_bytes": [18, 17], + }, + { + "input_ids": [ + [29, 3155, 1, 21820, 296], + [2, 29, 3155, 0, 0], + ], + "target_labels": [ + [3155, 1, 21820, 296, 2], + [29, 3155, 1, 0, 0], + ], + "target_num_bytes": [19, 3], + }, + ], + ), + ) @pytest.mark.skipif( not os.path.exists(t5_sentence_piece_vocab_file), reason="Missing testdata." ) - def test_fake_text_lm_training_data(self): - expected_batches = [ - { - "input_ids": [ - [1, 21820, 296, 2, 29, 3155], - [29, 3155, 1, 21820, 1782, 2], - [1782, 2, 29, 3155, 1, 21820], - ], - "target_labels": [ - [21820, 296, 2, 29, 3155, 1], - [3155, 1, 21820, 1782, 2, 29], - [2, 29, 3155, 1, 21820, 1712], - ], - "target_num_bytes": [19, 18, 18], - }, - { - "input_ids": [ - [1, 21820, 296, 2, 29, 3155], - [29, 3155, 1, 21820, 296, 2], - [29, 3155, 1, 21820, 1712, 2], - ], - "target_labels": [ - [21820, 296, 2, 29, 3155, 1], - [3155, 1, 21820, 296, 2, 29], - [3155, 1, 21820, 1712, 2, 29], - ], - "target_num_bytes": [19, 20, 18], - }, + def test_fake_text_lm_training_data( + self, packing_method: PackingMethodType, expected_batches: list[dict[str, Any]] + ): + texts = [ + "hello world\n", + "hello moon\n", ] - self._test_fake_text_lm_training_data( - vocab_cfg=self.vocab_cfg, expected_batches=expected_batches + + # window_size > len(texts) to repeat the sentence. 18 tokens in total. + # [ 1, 21820, 296, 2, 29, 3155, 1, 21820, 8114, + # 2, 29, 3155, 1, 21820, 296, 2, 29, 3155] + window_size = 3 + + # Pad the concatenated sequence to 20 tokens. + # [ 1, 21820, 296, 2, 29, 3155, 1, 21820, 8114, 2 + # 29, 3155, 1, 21820, 296, 2, 29, 3155, 0, 0] + batch_size, max_len = 2, 5 + + # Always pad. + max_padding_fraction = 1.0
With this change, do we still test the truncation behavior?
axlearn
github_2023
python
695
apple
ruomingp
@@ -142,12 +163,45 @@ def process_batched(inputs: dict[str, Any]) -> dict[str, Any]: target_num_bytes = num_bytes( batched_target_labels, sp_vocab=vocab, newlines_replaced_with=replace_newlines_with ) - return dict( + + result = dict( input_ids=batched_input_ids, target_labels=batched_target_labels, target_num_bytes=target_num_bytes, ) + if packing_method == PackingMethodType.EOS_DELIM_MASK: + segment_starts = tf.cast(tf.equal(batched_input_ids, vocab.eos_id), tf.int32) + segment_ids = tf.cumsum(segment_starts, axis=1) + segment_ids = segment_ids - segment_ids[:, :1] + 1 + segment_ids = tf.where(tf.equal(batched_input_ids, vocab.pad_id), 0, segment_ids) + + assert segment_ids.shape[1] == max_len + + def cummax_on_last_axis(x): + """tf.scan implementation of cummax.""" + assert len(x.shape) == 2 + # transpose to [seq, batch] for tf.scan, which iterates on dimension 0. + x = tf.transpose(x) + x = tf.scan(tf.maximum, x, initializer=tf.reduce_min(x, axis=0))
Neat use of tf.scan!
axlearn
github_2023
python
656
apple
samos123
@@ -403,4 +401,24 @@ def make_grad_accum_config( make_grad_accum_config, make_single_host_config_func, 4 ) + if model_size == "70B": + + def make_config_with_act_offload(base_config_name: str) -> SpmdTrainer.Config: + """Make configs for the v5e/v6e tpu with low HBM.""" + # pytype: disable=annotation-type-mismatch + cfg: SpmdTrainer.Config = config_map[base_config_name]().clone() + # pytype: enable=annotation-type-mismatch + update_model_remat_config(
Would it call update_model_remat_config twice this way? The first time during initial config of base config and then 2nd time during make_config_with_act_offload
axlearn
github_2023
python
675
apple
ruomingp
@@ -1162,6 +1171,139 @@ def test_only_linear_weight(self): target_state.trainer_state.model["linear2"]["bias"], ) + def _create_fake_state_and_convert(self, scope_mapping: Dict[str, str]): + # Create fake source_state and target_state with nested layers. + source_cfg, source_state = _create_dummy_state( + jax.random.PRNGKey(0), + DummyNestedModel.default_config().set(path="linear", path2="linear2"), + ) + _, target_state = _create_dummy_state( + jax.random.PRNGKey(1), + DummyModel.default_config().set( + child=DummyNestedLayer.default_config().set(path="linear") + ), + ) + + converter = ( + ModelStateScopeConverter.default_config() + .set( + name="test", + source_trainer_config=source_cfg, + scope=scope_mapping, + ) + .instantiate(parent=None) + ) + converted_state = converter.source_to_target(source_state, target_state) + return source_state, converted_state + + @parameterized.parameters( + {"scope_mapping": {"linear": "model/linear", "child": "model"}}, + {"scope_mapping": {"linear/bias": "model/linear/bias", "child": "model"}}, + { + "scope_mapping": { + "linear/bias": "model/linear/bias", + "child/linear": "model/linear", + "child": "model", + } + }, + { + "scope_mapping": { + "linear/bias": "model/linear/bias", + "child": "model", + "child/linear": "model/linear", + } + }, + ) + def test_duplicate_source_scopes_leaf_first(self, scope_mapping): + # Map leaf first. + # Create fake source_state and target_state with nested layers and perform conversion. + source_state, converted_state = self._create_fake_state_and_convert(scope_mapping) + + self.assertNestedAllClose( + converted_state.trainer_state.model["linear"]["bias"], + source_state.trainer_state.model["model"]["linear"]["bias"], + ) + self.assertNestedAllClose( + converted_state.trainer_state.model["child"]["linear"]["bias"], + source_state.trainer_state.model["model"]["linear"]["bias"], + ) + # converted_state's "linear/bias" is donated. + self.assertTrue( + converted_state.trainer_state.model["linear"]["bias"] + is source_state.trainer_state.model["model"]["linear"]["bias"] + ) + # converted_state's "child" is a copy and has different memory. + self.assertTrue( + converted_state.trainer_state.model["child"]["linear"]["bias"] + is not source_state.trainer_state.model["model"]["linear"]["bias"] + ) + + @parameterized.parameters( + {"scope_mapping": {"child/linear": "model/linear", "linear": "model/linear"}}, + {"scope_mapping": {"child/linear": "model/linear", "linear/bias": "model/linear/bias"}}, + {"scope_mapping": {"child": "model", "linear/bias": "model/linear/bias"}}, + ) + def test_duplicate_source_scopes_leaf_last(self, scope_mapping): + # Map leaf at last. + + # Create fake source_state and target_state with nested layers and perform conversion. + source_state, converted_state = self._create_fake_state_and_convert(scope_mapping) + + self.assertNestedAllClose( + converted_state.trainer_state.model["linear"]["bias"], + source_state.trainer_state.model["model"]["linear"]["bias"], + ) + self.assertNestedAllClose( + converted_state.trainer_state.model["child"]["linear"], + source_state.trainer_state.model["model"]["linear"], + ) + # source_state's "model" is donated to coverted_state's "child". + self.assertTrue( + converted_state.trainer_state.model["child"]["linear"]["bias"] + is source_state.trainer_state.model["model"]["linear"]["bias"] + ) + self.assertTrue( + converted_state.trainer_state.model["child"]["linear"]["weight"] + is source_state.trainer_state.model["model"]["linear"]["weight"] + ) + # converted_state's "linear/bias" is a copy and has different memory. + self.assertTrue( + converted_state.trainer_state.model["linear"]["bias"] + is not source_state.trainer_state.model["model"]["linear"]["bias"] + ) + + def test_duplicate_source_scopes_edge_case(self): + # Create fake source_state and target_state with nested layers and perform conversion. + scope_mapping = {"linear": "model/linear", "child/linear": "model/linear2"} + source_state, converted_state = self._create_fake_state_and_convert(scope_mapping) + + self.assertNestedAllClose( + converted_state.trainer_state.model["linear"], + source_state.trainer_state.model["model"]["linear"], + ) + self.assertNestedAllClose( + converted_state.trainer_state.model["child"]["linear"], + source_state.trainer_state.model["model"]["linear2"], + ) + # converted_state's "linear" is donated. + self.assertTrue( + converted_state.trainer_state.model["linear"]["bias"] + is source_state.trainer_state.model["model"]["linear"]["bias"] + )
Nit: use assertIs(...)?
axlearn
github_2023
python
675
apple
markblee
@@ -791,10 +792,38 @@ def target_to_source(self, target: Builder.State) -> tuple[Builder.State, Any]: return source, aux def source_to_target(self, source: Builder.State, aux: Any) -> Builder.State: - """Load model state from source to target.""" + """Load model state from source to target. + + Note: If a Tensor from `source` is included by multiple source scopes, makes deep copy of + the Tensor so that the target Tensors do not refer to the same underlying Tensor. + """ restored_state = clone_tree(aux.trainer_state) + + copied_leaf_paths = set() + + def _copy_leaf(path: str, leaf: Tensor, source_scope: str, separator: str = "/") -> Tensor: + if path: + # If path is not empty, concatenate with source_scope. + path = f"{source_scope}{separator}{path}" + else: + # If path is empty, it means source_scope is leaf. + path = source_scope + if path in copied_leaf_paths: + return leaf.copy() + copied_leaf_paths.add(path) + return leaf + for target_scope, source_scope in self.scopes.items(): - source_model = utils.get_recursively(source.trainer_state.model, source_scope) + orig_source_model = utils.get_recursively(source.trainer_state.model, source_scope) + source_model = jax.tree_util.tree_map_with_path( + lambda path, leaf: _copy_leaf( + "/".join(_key_entry_to_str(k) for k in path),
Move this into `_copy_leaf` so we can use separator for the join?
axlearn
github_2023
python
675
apple
markblee
@@ -791,10 +793,41 @@ def target_to_source(self, target: Builder.State) -> tuple[Builder.State, Any]: return source, aux def source_to_target(self, source: Builder.State, aux: Any) -> Builder.State: - """Load model state from source to target.""" + """Load model state from source to target. + + Note: If a Tensor from `source` is included by multiple source scopes, makes deep copy of + the Tensor so that the target Tensors do not refer to the same underlying Tensor. + """ restored_state = clone_tree(aux.trainer_state) + + copied_leaf_paths = set() + + def _copy_leaf( + path: tuple[KeyEntry], leaf: Tensor, source_scope: str, separator: str = "/" + ) -> Tensor: + path = separator.join(_key_entry_to_str(k) for k in path) + if path: + # If path is not empty, concatenate with source_scope. + path = f"{source_scope}{separator}{path}" + else: + # If path is empty, it means source_scope is leaf. + path = source_scope + if path in copied_leaf_paths: + return leaf.copy() + copied_leaf_paths.add(path) + return leaf + for target_scope, source_scope in self.scopes.items(): - source_model = utils.get_recursively(source.trainer_state.model, source_scope) + orig_source_model = utils.get_recursively(source.trainer_state.model, source_scope) + source_model = jax.tree_util.tree_map_with_path( + lambda path, leaf: _copy_leaf( + path, + leaf, + source_scope=source_scope, # pylint: disable=cell-var-from-loop
```suggestion lambda path, leaf, src_scope=source_scope: _copy_leaf( path, leaf, source_scope=src_scope, ```
axlearn
github_2023
python
674
apple
markblee
@@ -61,8 +61,14 @@ def is_pending(self) -> bool: return self in {CloudBuildStatus.PENDING, CloudBuildStatus.QUEUED, CloudBuildStatus.WORKING} -def get_cloud_build_status(project_id: str, image_name: str) -> Optional[CloudBuildStatus]: - """Get the status of the latest build filter on the image_name. +def get_cloud_build_status( + *, project_id: str, image_name: str, tags: list[str] +) -> Optional[CloudBuildStatus]: + """Gets the status of the latest build by filtering on the build tags or image name.
```suggestion """Gets the status of the latest build by filtering on the build tags or image name. ```
axlearn
github_2023
python
659
apple
markblee
@@ -121,22 +122,47 @@ def filter_for_validation(structure): ) -# pylint: disable-next=redefined-builtin -def save_tf_savables(value_map: Dict[str, Any], *, dir: str): - """Saves TF savables from `value_map` into `dir`.""" +def _upload_dir(src_dir_handle: tempfile.TemporaryDirectory, *, dst_dir: str): + """Upload a directory (non-recursively) from a temporary dir to dst_dir. + + Temporary dir will be deleted after the upload is complete. + """ + src_dir = src_dir_handle.name + if not tf.io.gfile.exists(dst_dir):
nit -- `makedirs` should work even if it exists.
axlearn
github_2023
python
659
apple
markblee
@@ -272,6 +298,7 @@ def __init__(self, cfg: Config): self._manager = array_serialization.GlobalAsyncCheckpointManager( timeout_secs=cfg.timeout_secs ) + self._executor = futures.ThreadPoolExecutor()
Since we're no longer using a context manager, should we invoke `shutdown` explicitly?
axlearn
github_2023
python
651
apple
cpgaffney1
@@ -922,3 +971,216 @@ def validate_and_restore(*, step: int, ckpt_dir: str): restored_state = state return step, restored_state + + +class OrbaxCheckpointer(BaseCheckpointer): + """A checkpointer that uses orbax CheckpointManager. + + NOTE: While this class uses index files to do additional validation on checkpoint state, the + index file is not used for committing checkpoints (i.e., it is not reliable to check for the + presence of 'index' file). Instead, use `checkpoint_paths` to identify committed checkpoints. + """ + + # Disable lazy imports within the class, to avoid requiring orbax dependency globally. + # pylint: disable=import-outside-toplevel + + @config_class + class Config(BaseCheckpointer.Config): + """Configures OrbaxCheckpointer. + + Attributes: + keep_last_n: Keep this many past ckpts. + validation_type: Checkpoint validation during restore. + save_concurrent_gb: Max concurrent GB during save. Defaults to 96 (orbax default). + restore_concurrent_gb: Max concurrent GB during write. Defaults to 96 (orbax default). + """ + + keep_last_n: int = 1 + validation_type: CheckpointValidationType = CheckpointValidationType.EXACT + save_concurrent_gb: int = 96 + restore_concurrent_gb: int = 96 + + @classmethod + def checkpoint_paths(cls, base_dir: str) -> List[str]: + """See `BaseCheckpointer.checkpointer_paths`.""" + import orbax.checkpoint as ocp + + return [str(path) for path in ocp.utils.checkpoint_steps_paths(base_dir)] + + def __init__(self, cfg: Config, *, parent: Optional[Module]): + super().__init__(cfg, parent=parent) + import orbax.checkpoint as ocp + + cfg: OrbaxCheckpointer.Config = self.config + save_policy = cfg.save_policy.instantiate() + + # Orbax only provides (current_step, last_saved_step) as args to the save policy, so we use + # a closure to capture evaler summaries. While the policy can be applied outside of orbax to + # decide whether or not to invoke `save()` at a given step, some features like + # save-on-preemption assume that `save()` is invoked every step. + # + # The semaphore will be acquired when we save, and released when we invoke the policy. + self._eval_summaries_sem = threading.Semaphore() + self._eval_summaries = {} + + def save_fn_with_summaries(step: int, last_saved_step: Optional[int]) -> bool: + del last_saved_step + try: + verdict = save_policy(step=step, evaler_summaries=self._eval_summaries) + finally: + self._eval_summaries.clear() + self._eval_summaries_sem.release() + return verdict + + # Use handlers to save index and tf_ckpt, so that they can be gc'ed and saved along with the + # save policy. + index_handler, self._index_args = self._wrap_handler( + save_fn=lambda dir, args: write_index_file(ckpt_dir=dir, index=args.item), + restore_fn=lambda dir, _: read_index_file(dir), + ) + tf_ckpt_handler, self._tf_ckpt_args = self._wrap_handler( + save_fn=lambda dir, args: save_tf_savables(args.item, dir=dir), + restore_fn=lambda dir, args: restore_tf_savables(args.item, dir=dir), + ) + + self._manager = ocp.CheckpointManager( + directory=cfg.dir, + options=ocp.CheckpointManagerOptions( + create=True, + max_to_keep=cfg.keep_last_n, + enable_async_checkpointing=True, + step_prefix=_STEP_PREFIX, + step_format_fixed_length=_STEP_NUM_DIGITS, + should_save_fn=save_fn_with_summaries, + ), + item_handlers={ + "index": index_handler(), + "tf_ckpt_map": tf_ckpt_handler(), + "state": ocp.StandardCheckpointHandler(save_concurrent_gb=cfg.save_concurrent_gb), + }, + ) + + def _get_spec(self, *, step: int, state: NestedTensor) -> Nested[Any]: + spec = {"index": [("step", step)], "tf_ckpt_map": {}} + for path, value in utils.flatten_items(state): + if isinstance(value, (Tensor, TensorSpec)): + dtype = getattr(value.dtype, "dtype", value.dtype) + spec["index"].append( + (path, {"dtype": str(dtype), "shape": str(tuple(value.shape))}) + ) + elif isinstance(value, tf.data.Iterator): + spec["index"].append((path, str(type(value)))) + spec["tf_ckpt_map"][path] = value + else: + spec["index"].append((path, value)) + return spec + + # pylint: disable-next=redefined-builtin + def ckpt_dir(self, step: int, dir: Optional[str] = None) -> str: + """Obtains the checkpoint dir for the given step.""" + if dir is None: + dir = self._manager.directory + # pylint: disable-next=protected-access + return str(self._manager._get_save_directory(step, dir))
Use ``` name_format = ocp.path.step.standard_name_format( step_prefix=_STEP_PREFIX, step_format_fixed_length=_STEP_NUM_DIGITS, ) ocp.path.step.build_step_path(directory, name_format, step) ```
axlearn
github_2023
python
651
apple
cpgaffney1
@@ -922,3 +971,216 @@ def validate_and_restore(*, step: int, ckpt_dir: str): restored_state = state return step, restored_state + + +class OrbaxCheckpointer(BaseCheckpointer): + """A checkpointer that uses orbax CheckpointManager. + + NOTE: While this class uses index files to do additional validation on checkpoint state, the + index file is not used for committing checkpoints (i.e., it is not reliable to check for the + presence of 'index' file). Instead, use `checkpoint_paths` to identify committed checkpoints. + """ + + # Disable lazy imports within the class, to avoid requiring orbax dependency globally.
What is the concern with doing this? Orbax doesn't loop in that many additional dependencies.
axlearn
github_2023
python
651
apple
cpgaffney1
@@ -922,3 +971,216 @@ def validate_and_restore(*, step: int, ckpt_dir: str): restored_state = state return step, restored_state + + +class OrbaxCheckpointer(BaseCheckpointer): + """A checkpointer that uses orbax CheckpointManager. + + NOTE: While this class uses index files to do additional validation on checkpoint state, the + index file is not used for committing checkpoints (i.e., it is not reliable to check for the + presence of 'index' file). Instead, use `checkpoint_paths` to identify committed checkpoints. + """ + + # Disable lazy imports within the class, to avoid requiring orbax dependency globally. + # pylint: disable=import-outside-toplevel + + @config_class + class Config(BaseCheckpointer.Config): + """Configures OrbaxCheckpointer. + + Attributes: + keep_last_n: Keep this many past ckpts. + validation_type: Checkpoint validation during restore. + save_concurrent_gb: Max concurrent GB during save. Defaults to 96 (orbax default). + restore_concurrent_gb: Max concurrent GB during write. Defaults to 96 (orbax default). + """ + + keep_last_n: int = 1 + validation_type: CheckpointValidationType = CheckpointValidationType.EXACT + save_concurrent_gb: int = 96 + restore_concurrent_gb: int = 96 + + @classmethod + def checkpoint_paths(cls, base_dir: str) -> List[str]: + """See `BaseCheckpointer.checkpointer_paths`.""" + import orbax.checkpoint as ocp + + return [str(path) for path in ocp.utils.checkpoint_steps_paths(base_dir)] + + def __init__(self, cfg: Config, *, parent: Optional[Module]): + super().__init__(cfg, parent=parent) + import orbax.checkpoint as ocp + + cfg: OrbaxCheckpointer.Config = self.config + save_policy = cfg.save_policy.instantiate() + + # Orbax only provides (current_step, last_saved_step) as args to the save policy, so we use + # a closure to capture evaler summaries. While the policy can be applied outside of orbax to + # decide whether or not to invoke `save()` at a given step, some features like + # save-on-preemption assume that `save()` is invoked every step. + # + # The semaphore will be acquired when we save, and released when we invoke the policy. + self._eval_summaries_sem = threading.Semaphore() + self._eval_summaries = {} + + def save_fn_with_summaries(step: int, last_saved_step: Optional[int]) -> bool: + del last_saved_step + try: + verdict = save_policy(step=step, evaler_summaries=self._eval_summaries) + finally: + self._eval_summaries.clear() + self._eval_summaries_sem.release() + return verdict + + # Use handlers to save index and tf_ckpt, so that they can be gc'ed and saved along with the + # save policy. + index_handler, self._index_args = self._wrap_handler( + save_fn=lambda dir, args: write_index_file(ckpt_dir=dir, index=args.item), + restore_fn=lambda dir, _: read_index_file(dir), + ) + tf_ckpt_handler, self._tf_ckpt_args = self._wrap_handler( + save_fn=lambda dir, args: save_tf_savables(args.item, dir=dir), + restore_fn=lambda dir, args: restore_tf_savables(args.item, dir=dir), + ) + + self._manager = ocp.CheckpointManager( + directory=cfg.dir, + options=ocp.CheckpointManagerOptions( + create=True, + max_to_keep=cfg.keep_last_n, + enable_async_checkpointing=True, + step_prefix=_STEP_PREFIX, + step_format_fixed_length=_STEP_NUM_DIGITS, + should_save_fn=save_fn_with_summaries, + ), + item_handlers={ + "index": index_handler(), + "tf_ckpt_map": tf_ckpt_handler(), + "state": ocp.StandardCheckpointHandler(save_concurrent_gb=cfg.save_concurrent_gb), + }, + ) + + def _get_spec(self, *, step: int, state: NestedTensor) -> Nested[Any]: + spec = {"index": [("step", step)], "tf_ckpt_map": {}} + for path, value in utils.flatten_items(state): + if isinstance(value, (Tensor, TensorSpec)): + dtype = getattr(value.dtype, "dtype", value.dtype) + spec["index"].append( + (path, {"dtype": str(dtype), "shape": str(tuple(value.shape))}) + ) + elif isinstance(value, tf.data.Iterator): + spec["index"].append((path, str(type(value)))) + spec["tf_ckpt_map"][path] = value + else: + spec["index"].append((path, value)) + return spec + + # pylint: disable-next=redefined-builtin + def ckpt_dir(self, step: int, dir: Optional[str] = None) -> str: + """Obtains the checkpoint dir for the given step.""" + if dir is None: + dir = self._manager.directory + # pylint: disable-next=protected-access + return str(self._manager._get_save_directory(step, dir)) + + def save( + self, *, step: int, state: Nested[Tensor], evaler_summaries: Optional[Dict[str, Any]] = None + ): + """See `BaseCheckpointer.save` for details. + + Checkpoint saving is handled by `orbax` checkpoint manager. + """ + import orbax.checkpoint as ocp + + spec = self._get_spec(step=step, state=state) + self._eval_summaries_sem.acquire() # pylint: disable=consider-using-with + assert not self._eval_summaries + self._eval_summaries.update(evaler_summaries or {}) + self._manager.save( + step=step, + # The input iterator is saved as part of `save_tf_savables`. + args=ocp.args.Composite( + index=self._index_args(spec["index"]), + tf_ckpt_map=self._tf_ckpt_args(spec["tf_ckpt_map"]), + state=ocp.args.StandardSave( + utils.prune_tree( + state, should_prune=lambda _, v: isinstance(v, tf.data.Iterator) + ) + ), + ), + ) + + def restore( + self, + *, + step: Optional[int] = None, + state: Union[Nested[Tensor], Nested[TensorSpec]], + ) -> Tuple[Optional[int], Nested[Tensor]]: + """See `BaseCheckpointer.restore` for details.""" + import orbax.checkpoint as ocp + + cfg: OrbaxCheckpointer.Config = self.config + + spec = self._get_spec(step=step, state=state) + state_specs = jax.tree_util.tree_map( + lambda x: jax.ShapeDtypeStruct(shape=x.shape, dtype=x.dtype, sharding=x.sharding), + jax.tree_util.tree_map(lambda x: None if isinstance(x, tf.data.Iterator) else x, state), + ) + try: + composite_state = self._manager.restore( + step, + args=ocp.args.Composite( + tf_ckpt_map=self._tf_ckpt_args(spec["tf_ckpt_map"]), + state=ocp.args.StandardRestore(state_specs), + ), + ) + restored_state = composite_state["state"] + except Exception as e: # pylint: disable=broad-except + if step is not None: + raise ValueError(f"Failed to restore at step {step}.") from e + logging.info("Could not find any completed checkpoints under %s: %s", cfg.dir, e) + restored_state = state + + # If we successfully restored from step=None, use the latest step. + if step is None:
My preference would be for doing this check first and raising an error earlier if no steps are found, followed by the try/except. I think it's a bit more readable but up to you.
axlearn
github_2023
python
651
apple
jiya-zhang
@@ -922,3 +953,220 @@ def validate_and_restore(*, step: int, ckpt_dir: str): restored_state = state return step, restored_state + + +class OrbaxCheckpointer(BaseCheckpointer): + """A checkpointer that uses orbax CheckpointManager. + + NOTE: While this class uses index files to do additional validation on checkpoint state, the + index file is not used for committing checkpoints (i.e., it is not reliable to check for the + presence of 'index' file). Instead, use `checkpoint_paths` to identify committed checkpoints. + """ + + # Disable lazy imports within the class, to avoid requiring orbax dependency globally. + # pylint: disable=import-outside-toplevel + + @config_class + class Config(BaseCheckpointer.Config): + """Configures OrbaxCheckpointer. + + Attributes: + keep_last_n: Keep this many past ckpts. + validation_type: Checkpoint validation during restore. + save_concurrent_gb: Max concurrent GB during save. Defaults to 96 (orbax default). + restore_concurrent_gb: Max concurrent GB during write. Defaults to 96 (orbax default). + """ + + keep_last_n: int = 1 + validation_type: CheckpointValidationType = CheckpointValidationType.EXACT + save_concurrent_gb: int = 96 + restore_concurrent_gb: int = 96 + + @classmethod + def checkpoint_paths(cls, base_dir: str) -> List[str]:
Is this method ever called?
axlearn
github_2023
python
651
apple
jiya-zhang
@@ -922,3 +953,220 @@ def validate_and_restore(*, step: int, ckpt_dir: str): restored_state = state return step, restored_state + + +class OrbaxCheckpointer(BaseCheckpointer): + """A checkpointer that uses orbax CheckpointManager. + + NOTE: While this class uses index files to do additional validation on checkpoint state, the + index file is not used for committing checkpoints (i.e., it is not reliable to check for the + presence of 'index' file). Instead, use `checkpoint_paths` to identify committed checkpoints. + """ + + # Disable lazy imports within the class, to avoid requiring orbax dependency globally. + # pylint: disable=import-outside-toplevel + + @config_class + class Config(BaseCheckpointer.Config): + """Configures OrbaxCheckpointer. + + Attributes: + keep_last_n: Keep this many past ckpts. + validation_type: Checkpoint validation during restore. + save_concurrent_gb: Max concurrent GB during save. Defaults to 96 (orbax default). + restore_concurrent_gb: Max concurrent GB during write. Defaults to 96 (orbax default). + """ + + keep_last_n: int = 1 + validation_type: CheckpointValidationType = CheckpointValidationType.EXACT + save_concurrent_gb: int = 96 + restore_concurrent_gb: int = 96 + + @classmethod + def checkpoint_paths(cls, base_dir: str) -> List[str]: + """See `BaseCheckpointer.checkpointer_paths`.""" + import orbax.checkpoint as ocp + + return [str(path) for path in ocp.utils.checkpoint_steps_paths(base_dir)] + + def __init__(self, cfg: Config, *, parent: Optional[Module]): + super().__init__(cfg, parent=parent) + import orbax.checkpoint as ocp + + cfg: OrbaxCheckpointer.Config = self.config + save_policy = cfg.save_policy.instantiate() + + # Orbax only provides (current_step, last_saved_step) as args to the save policy, so we use + # a closure to capture evaler summaries. While the policy can be applied outside of orbax to + # decide whether or not to invoke `save()` at a given step, some features like + # save-on-preemption assume that `save()` is invoked every step. + # + # The semaphore will be acquired when we save, and released when we invoke the policy. + self._eval_summaries_sem = threading.Semaphore() + self._eval_summaries = {} + + def save_fn_with_summaries(step: int, last_saved_step: Optional[int]) -> bool: + del last_saved_step + try: + verdict = save_policy(step=step, evaler_summaries=self._eval_summaries) + finally: + self._eval_summaries.clear() + self._eval_summaries_sem.release() + return verdict + + # Use handlers to save index and tf_ckpt, so that they can be gc'ed and saved along with the + # save policy. + index_handler, self._index_args = self._wrap_handler( + save_fn=lambda dir, args: write_index_file(ckpt_dir=dir, index=args.item), + restore_fn=lambda dir, _: read_index_file(dir), + ) + tf_ckpt_handler, self._tf_ckpt_args = self._wrap_handler( + save_fn=lambda dir, args: save_tf_savables(args.item, dir=dir), + restore_fn=lambda dir, args: restore_tf_savables(args.item, dir=dir), + ) + + self._name_format = ocp.step.standard_name_format( + step_prefix=_STEP_PREFIX, + step_format_fixed_length=_STEP_NUM_DIGITS, + ) + self._manager = ocp.CheckpointManager( + directory=cfg.dir, + options=ocp.CheckpointManagerOptions( + create=True, + max_to_keep=cfg.keep_last_n, + enable_async_checkpointing=True, + step_name_format=self._name_format, + should_save_fn=save_fn_with_summaries, + ), + item_handlers={ + "index": index_handler(), + "tf_ckpt_map": tf_ckpt_handler(), + "state": ocp.StandardCheckpointHandler(save_concurrent_gb=cfg.save_concurrent_gb), + }, + ) + + def _get_spec(self, *, step: int, state: NestedTensor) -> Nested[Any]: + spec = {"index": [("step", step)], "tf_ckpt_map": {}} + for path, value in utils.flatten_items(state): + if isinstance(value, (Tensor, TensorSpec)): + dtype = getattr(value.dtype, "dtype", value.dtype) + spec["index"].append( + (path, {"dtype": str(dtype), "shape": str(tuple(value.shape))}) + ) + elif isinstance(value, tf.data.Iterator): + spec["index"].append((path, str(type(value)))) + spec["tf_ckpt_map"][path] = value + else: + spec["index"].append((path, value)) + return spec + + # pylint: disable-next=redefined-builtin + def ckpt_dir(self, step: int, dir: Optional[str] = None) -> str:
Is this method ever called?
axlearn
github_2023
python
651
apple
jiya-zhang
@@ -922,3 +953,220 @@ def validate_and_restore(*, step: int, ckpt_dir: str): restored_state = state return step, restored_state + + +class OrbaxCheckpointer(BaseCheckpointer): + """A checkpointer that uses orbax CheckpointManager. + + NOTE: While this class uses index files to do additional validation on checkpoint state, the + index file is not used for committing checkpoints (i.e., it is not reliable to check for the + presence of 'index' file). Instead, use `checkpoint_paths` to identify committed checkpoints. + """ + + # Disable lazy imports within the class, to avoid requiring orbax dependency globally. + # pylint: disable=import-outside-toplevel + + @config_class + class Config(BaseCheckpointer.Config): + """Configures OrbaxCheckpointer. + + Attributes: + keep_last_n: Keep this many past ckpts. + validation_type: Checkpoint validation during restore. + save_concurrent_gb: Max concurrent GB during save. Defaults to 96 (orbax default). + restore_concurrent_gb: Max concurrent GB during write. Defaults to 96 (orbax default). + """ + + keep_last_n: int = 1 + validation_type: CheckpointValidationType = CheckpointValidationType.EXACT + save_concurrent_gb: int = 96 + restore_concurrent_gb: int = 96 + + @classmethod + def checkpoint_paths(cls, base_dir: str) -> List[str]: + """See `BaseCheckpointer.checkpointer_paths`.""" + import orbax.checkpoint as ocp + + return [str(path) for path in ocp.utils.checkpoint_steps_paths(base_dir)] + + def __init__(self, cfg: Config, *, parent: Optional[Module]): + super().__init__(cfg, parent=parent) + import orbax.checkpoint as ocp + + cfg: OrbaxCheckpointer.Config = self.config + save_policy = cfg.save_policy.instantiate() + + # Orbax only provides (current_step, last_saved_step) as args to the save policy, so we use + # a closure to capture evaler summaries. While the policy can be applied outside of orbax to + # decide whether or not to invoke `save()` at a given step, some features like + # save-on-preemption assume that `save()` is invoked every step. + # + # The semaphore will be acquired when we save, and released when we invoke the policy. + self._eval_summaries_sem = threading.Semaphore() + self._eval_summaries = {} + + def save_fn_with_summaries(step: int, last_saved_step: Optional[int]) -> bool: + del last_saved_step + try: + verdict = save_policy(step=step, evaler_summaries=self._eval_summaries) + finally: + self._eval_summaries.clear() + self._eval_summaries_sem.release() + return verdict + + # Use handlers to save index and tf_ckpt, so that they can be gc'ed and saved along with the + # save policy. + index_handler, self._index_args = self._wrap_handler( + save_fn=lambda dir, args: write_index_file(ckpt_dir=dir, index=args.item), + restore_fn=lambda dir, _: read_index_file(dir), + ) + tf_ckpt_handler, self._tf_ckpt_args = self._wrap_handler( + save_fn=lambda dir, args: save_tf_savables(args.item, dir=dir), + restore_fn=lambda dir, args: restore_tf_savables(args.item, dir=dir), + ) + + self._name_format = ocp.step.standard_name_format( + step_prefix=_STEP_PREFIX, + step_format_fixed_length=_STEP_NUM_DIGITS, + ) + self._manager = ocp.CheckpointManager( + directory=cfg.dir, + options=ocp.CheckpointManagerOptions( + create=True, + max_to_keep=cfg.keep_last_n, + enable_async_checkpointing=True, + step_name_format=self._name_format, + should_save_fn=save_fn_with_summaries, + ), + item_handlers={ + "index": index_handler(), + "tf_ckpt_map": tf_ckpt_handler(), + "state": ocp.StandardCheckpointHandler(save_concurrent_gb=cfg.save_concurrent_gb), + }, + ) + + def _get_spec(self, *, step: int, state: NestedTensor) -> Nested[Any]: + spec = {"index": [("step", step)], "tf_ckpt_map": {}} + for path, value in utils.flatten_items(state): + if isinstance(value, (Tensor, TensorSpec)): + dtype = getattr(value.dtype, "dtype", value.dtype) + spec["index"].append( + (path, {"dtype": str(dtype), "shape": str(tuple(value.shape))}) + ) + elif isinstance(value, tf.data.Iterator): + spec["index"].append((path, str(type(value)))) + spec["tf_ckpt_map"][path] = value + else: + spec["index"].append((path, value)) + return spec + + # pylint: disable-next=redefined-builtin + def ckpt_dir(self, step: int, dir: Optional[str] = None) -> str: + """Obtains the checkpoint dir for the given step.""" + import orbax.checkpoint as ocp + + if dir is None: + dir = self._manager.directory + return str(ocp.step.build_step_path(dir, self._name_format, step)) + + def save( + self, *, step: int, state: Nested[Tensor], evaler_summaries: Optional[Dict[str, Any]] = None + ): + """See `BaseCheckpointer.save` for details. + + Checkpoint saving is handled by `orbax` checkpoint manager. + """ + import orbax.checkpoint as ocp + + spec = self._get_spec(step=step, state=state) + self._eval_summaries_sem.acquire() # pylint: disable=consider-using-with + assert not self._eval_summaries + self._eval_summaries.update(evaler_summaries or {}) + self._manager.save( + step=step, + # The input iterator is saved as part of `save_tf_savables`. + args=ocp.args.Composite( + index=self._index_args(spec["index"]), + tf_ckpt_map=self._tf_ckpt_args(spec["tf_ckpt_map"]),
What are `index` and `tf_ckpt_args`? Does orbax provide similar functionalities, eg. checking tree structure (which I assume is what the index file is for)?
axlearn
github_2023
python
662
apple
markblee
@@ -270,6 +270,7 @@ def sample_decode( Args: prefix: The prefix to use for prompting. Of shape [batch, max_prefix_length]. + The prefix for each example in the batch should begin with the [BOS] token.
nit -- not all vocabs have `[BOS]`, maybe ```suggestion The prefix for each example in the batch should begin with a prompt token (e.g., BOS). ``` ?
axlearn
github_2023
python
662
apple
markblee
@@ -679,6 +679,98 @@ def test_output_logits_modifier(self): decoder = decoder_cfg.instantiate(parent=None) chex.assert_trees_all_close(decoder(5 * jnp.ones(3)), dict(logits=17 * 5 * jnp.ones(3))) + def test_token_scores_match_between_decoded_and_prefix(self): + """Test that token scores match between sample_decode passes. + + This reuses the generated tokens from the first pass as the prefix for the second pass. + This test is intented to detect if the scores from prefill_states do not match up with
```suggestion This test is intended to detect if the scores from prefill_states do not match up with ```
axlearn
github_2023
python
652
apple
markblee
@@ -172,6 +177,9 @@ def binary_clf_curve( fps = jnp.where(y_pred_diff, fps, jnp.iinfo(jnp.int32).max) fps = jax.lax.cummin(fps, reverse=True) + # Masked entries at the end of thresholds are set to jnp.finfo(jnp.float32).max. + # Reset them to the rightmost unmasked threshold value. + thresholds = jnp.where(weight, thresholds, thresholds[jnp.argsort(weight)[-1]])
Thanks, as discussed offline maybe we should remove this to simplify, since the masked values should not be used anyway, and I'm not sure that `jnp.argsort(weight)[-1]` gives the rightmost unmasked value.
axlearn
github_2023
python
643
apple
ruomingp
@@ -3874,6 +3874,7 @@ def build_remat_spec( ], self_attention: bool = True, feed_forward: bool = False, + offload: bool = False,
Instead of a bool, should we allow the caller to customize `offload_dst` directly? ```suggestion offload_dst: Optional[Literal["pinned_host"]] = None, ``` This will make the API more extensible and closer to the JAX API.
axlearn
github_2023
python
643
apple
ruomingp
@@ -3891,6 +3904,7 @@ def build_remat_spec( stack_cfg: A transformer config. self_attention: Checkpoint self attention layer activations if true. feed_forward: Checkpoint feed-forward layer activations if true. + offload_dst: Destination of remat checkptoing offloading.
Add a link to the JAX documentation on `offset_dst` on the potential values?
axlearn
github_2023
python
643
apple
ruomingp
@@ -188,6 +188,7 @@ def get_trainer_kwargs( num_kv_heads=None if version == Version.V1 else 8, rope_theta=rope_theta, flash_attention=flash_attention, + remat_offload_dst="pinned_host",
Add a comment on the observed MFU and step time?
axlearn
github_2023
python
643
apple
markblee
@@ -3891,6 +3904,10 @@ def build_remat_spec( stack_cfg: A transformer config. self_attention: Checkpoint self attention layer activations if true. feed_forward: Checkpoint feed-forward layer activations if true. + offload_dst: Destination of remat checkptoing offloading. Relevant Maxtext example: + https://github.com/google/maxtext/blob/ebd39aa64d670fa13a313b6f776e01ad9e450321/MaxText/layers/models.py#L230. + +
```suggestion ```
axlearn
github_2023
python
556
apple
ruomingp
@@ -1306,6 +1306,7 @@ def forward( *, key: Optional[Tensor] = None, value: Optional[Tensor] = None, + kv_state: Optional[KVState] = None,
If `kv_state` is not None, how is it used? Should it be passed to `i_proj` below? Otherwise we should throw a NotImplementedError if kv_state is not None.
axlearn
github_2023
python
465
apple
apghml
@@ -94,8 +95,7 @@ def _prune_empty(in_tree: NestedTensor) -> NestedTensor: return prune_tree(in_tree, lambda _, v: isinstance(v, dict) and not v) -@dataclasses.dataclass -class ForwardOutputs: +class ForwardOutputs(NamedTuple):
What is the purpose of this change?
axlearn
github_2023
python
465
apple
apghml
@@ -444,6 +444,153 @@ def _mask_tree(tree: dict, *, keep: dict) -> dict: ) +class MetricsAccumulationOp(NamedTuple):
Axlearn already has metric accumulation classes that are used by evalers. Could those be reused here instead of defining new classes?
axlearn
github_2023
python
465
apple
apghml
@@ -9,7 +9,8 @@ import dataclasses import enum -from typing import Callable, Mapping, Optional, Protocol, Sequence, Tuple +import logging
We typically use absl logging instead of python logging.
axlearn
github_2023
python
465
apple
apghml
@@ -444,6 +444,153 @@ def _mask_tree(tree: dict, *, keep: dict) -> dict: ) +class MetricsAccumulationOp(NamedTuple): + microbatches: int + + def aggregrate(self, x, buffer): + raise NotImplementedError(self) + + def normalize(self, buffer): + raise NotImplementedError(self) + + +class ArithmeticMeanStrategy(MetricsAccumulationOp): + def aggregrate(self, x, buffer): + return buffer + x + + def normalize(self, buffer): + return buffer / self.microbatches + + +class GeometricMeanStrategy(MetricsAccumulationOp): + def aggregrate(self, x, buffer): + return buffer * x + + def normalize(self, buffer): + return buffer ** (-self.microbatches) + + +class AddStrategy(MetricsAccumulationOp): + def aggregrate(self, x, buffer): + return buffer + x + + def normalize(self, buffer): + return buffer + + +class AccumulatedLearner(Learner): + """Learner module that uses gradient accumulation""" + + @config_class + class Config(Learner.Config): + """Configures Learner.""" + + # The number of microbatches to accumulate per optimizer step. + microbatches: Required[int] = REQUIRED + # tuple of key-value pairs specifying custom aggregation and normalization + # for a specific metric + metrics_accumulation_key_ops: Sequence[Dict[str, Optional[MetricsAccumulationOp]]] = [] + gradient_dtype: Optional[jnp.dtype] = jnp.bfloat16
Does the existing learner class use this? If not, we should try to be consistent with its API.
axlearn
github_2023
python
465
apple
apghml
@@ -444,6 +444,153 @@ def _mask_tree(tree: dict, *, keep: dict) -> dict: ) +class MetricsAccumulationOp(NamedTuple): + microbatches: int + + def aggregrate(self, x, buffer): + raise NotImplementedError(self) + + def normalize(self, buffer): + raise NotImplementedError(self) + + +class ArithmeticMeanStrategy(MetricsAccumulationOp): + def aggregrate(self, x, buffer): + return buffer + x + + def normalize(self, buffer): + return buffer / self.microbatches + + +class GeometricMeanStrategy(MetricsAccumulationOp): + def aggregrate(self, x, buffer): + return buffer * x + + def normalize(self, buffer): + return buffer ** (-self.microbatches) + + +class AddStrategy(MetricsAccumulationOp): + def aggregrate(self, x, buffer): + return buffer + x + + def normalize(self, buffer): + return buffer + + +class AccumulatedLearner(Learner): + """Learner module that uses gradient accumulation""" + + @config_class + class Config(Learner.Config): + """Configures Learner.""" + + # The number of microbatches to accumulate per optimizer step. + microbatches: Required[int] = REQUIRED + # tuple of key-value pairs specifying custom aggregation and normalization + # for a specific metric + metrics_accumulation_key_ops: Sequence[Dict[str, Optional[MetricsAccumulationOp]]] = [] + gradient_dtype: Optional[jnp.dtype] = jnp.bfloat16 + + def forward_and_backward( + self, *, fn: ForwardFn, inputs: NestedTensor, opt_params: NestedOptParam + ) -> ForwardBackwardOutputs: + """Run forward and backward for multiple microbatches and accumulate gradients + and metrics into buffers. + + Args: + fn (ForwardFn): Model forward pass + inputs (NestedTensor): input microbatches with a leading microbatch axis + opt_params (NestedOptParam): params which don't need gradients + + Returns: + ForwardBackwardOutputs: pytree containing gradients and metrics + """
I wonder if instead of having a separate learner for microbatching, it would be more flexible to have a generic way of wrapping a ForwardFn so that it uses Jax.lax.map to run the microbatches. Beyond avoiding the need to add a new learner, it would also allow for other microbetching uses outside of learner, eg inference or in second order optimizers.
axlearn
github_2023
python
614
apple
markblee
@@ -0,0 +1,298 @@ +# Copyright © 2024 Apple Inc. +"""This module provides functions to decorate a ForwardFn to allow for a minibatched +version that enables gradient accumulation. +""" +import functools +from typing import Any, Callable, Optional, Tuple + +import jax +import numpy as np +from jax import numpy as jnp + +from axlearn.common import utils +from axlearn.common.config import ConfigOr, maybe_instantiate +from axlearn.common.metrics import MetricAccumulator +from axlearn.common.update_transformation import ForwardFn, ForwardOutputs +from axlearn.common.utils import Nested, Tensor, input_partition_spec, with_sharding_constraint + + +def _compute_minibatch_size(input_batch: Nested[Tensor], *, steps: int) -> int: + """Utility function to compute minibatch size from input batch. + + Args: + input_batch: A ForwardFn input_batch. + steps: Integer steps to divide inputs with. + + Returns: + An integer representing minibatch size. + + Raises: + ValueError if the input batch is not divisible by steps.
Sorry for missing this earlier, but we should document the other raise conditions too.
axlearn
github_2023
python
544
apple
markblee
@@ -299,6 +299,21 @@ def _start(self): if tier is not None: reserved = str(tier) == "0" logging.info("Found tier=%s in env. Using reserved=%s", tier, reserved) + + # Create labels for vm tier that can be used to group tpu metrics. + # In QRM, vm tier can be one of guaranteed, spot, or, bestEffort. + # bestEffort is implemented to create spot instance. Hence, + # guaranteeded -> reserved and bestEffort|spot -> spot + # BASTION_TIER env has presendence over the reserved_tpu + labels = {} + if reserved is None: + reserved_tier = gcp_settings("reserved_tpu", default=False, required=False) + else: + reserved_tier = reserved + if reserved_tier: + labels["vmtier"] = "reserved" + else: + labels["vmtier"] = "spot"
```suggestion if reserved is None: reserved = gcp_settings("reserved_tpu", default=False, required=False) labels = {"bastion_tier": "reserved" if reserved else "spot"} ``` Not sure if `vmtier` label is arbitrary?
axlearn
github_2023
python
544
apple
markblee
@@ -299,6 +299,15 @@ def _start(self): if tier is not None: reserved = str(tier) == "0" logging.info("Found tier=%s in env. Using reserved=%s", tier, reserved) + + # Create labels for vm tier that can be used to group tpu metrics. + # In QRM, vm tier can be one of guaranteed, spot, or, bestEffort. + # bestEffort is implemented to create spot instance. Hence, + # guaranteeded -> reserved and bestEffort|spot -> spot
```suggestion # The "reserved" label is used for guaranteed instances and "spot" for other instances (e.g. best-effort or spot instances). ```
axlearn
github_2023
python
544
apple
markblee
@@ -299,6 +299,15 @@ def _start(self): if tier is not None: reserved = str(tier) == "0" logging.info("Found tier=%s in env. Using reserved=%s", tier, reserved) + + # Create labels for vm tier that can be used to group tpu metrics. + # In QRM, vm tier can be one of guaranteed, spot, or, bestEffort. + # bestEffort is implemented to create spot instance. Hence, + # guaranteeded -> reserved and bestEffort|spot -> spot + # BASTION_TIER env has presendence over the reserved_tpu
```suggestion # BASTION_TIER env has presendence over the reserved_tpu. ```
axlearn
github_2023
python
592
apple
apghml
@@ -62,6 +62,11 @@ def generate_job_name() -> str: return f"{os.environ['USER'].replace('_', '')}-{uuid.uuid4().hex.lower()[:6]}" +def generate_job_id() -> str: + """Generate a unique job uuid.""" + return str(uuid.uuid4())
IIUC, uuid4 is a random uuid. Do we know if the randomness used is good? Would it make sense to instead use `secrets.token_urlsafe()`, which is cryptographically random?
axlearn
github_2023
others
470
apple
markblee
@@ -75,6 +75,10 @@ ENV RUN_PYTHON_SDK_IN_DEFAULT_ENVIRONMENT=1 RUN pip install .[gcp,dataflow] COPY . . +COPY --from=apache/beam_python3.9_sdk:2.52.0 /opt/apache/beam /opt/apache/beam +ENTRYPOINT ["/opt/apache/beam/boot"]
Do we plan to merge https://github.com/apple/axlearn/pull/384 eventually?
axlearn
github_2023
others
470
apple
markblee
@@ -75,6 +75,10 @@ ENV RUN_PYTHON_SDK_IN_DEFAULT_ENVIRONMENT=1 RUN pip install .[gcp,dataflow] COPY . . +COPY --from=apache/beam_python3.9_sdk:2.52.0 /opt/apache/beam /opt/apache/beam +ENTRYPOINT ["/opt/apache/beam/boot"] + +
nit -- spacing ```suggestion ```
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn.
```suggestion """An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. ``` Can we also make a separate directory like `axlearn/cloud/gcp/examples` with these scripts, to distinguish from libraries?
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx'
nit -- Usually, `trainer_dir` refers to the root of this dir. Maybe we can call it `checkpoint_dir`?
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore")
Comment on why we need this?
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference"""
```suggestion """Defines how to load a custom checkpoint and run inference.""" ```
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict
Missing types. Also comment on what `flag_dict` is supposed to represent? I suppose these are the locally-parsed flag values corresponding to trainer flags?
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict
Following the [google style guide](https://google.github.io/styleguide/pyguide.html#386-punctuation-spelling-and-grammar), comments should be full sentences with punctuations. (Please also fix elsewhere, thanks!)
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values)
```suggestion trainer_cfg = trainer_utils.get_trainer_config(flag_values=flag_values) ```
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values) + + # get InferenceRunner Config from Trainer Config and instantiate InferenceRunner + inference_runner_cfg = InferenceRunner.config_from_trainer(module_config) + inference_runner_cfg.init_state_builder.set(dir=flag_values.trainer_dir) + inference_runner = InferenceRunner(cfg=inference_runner_cfg, parent=None)
```suggestion inference_runner = inference_runner_cfg.instantiate(parent=None) ```
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values) + + # get InferenceRunner Config from Trainer Config and instantiate InferenceRunner + inference_runner_cfg = InferenceRunner.config_from_trainer(module_config) + inference_runner_cfg.init_state_builder.set(dir=flag_values.trainer_dir) + inference_runner = InferenceRunner(cfg=inference_runner_cfg, parent=None) + + # create Method Runner only once + method_runner = inference_runner.create_method_runner( + method="predict", prng_key=jax.random.PRNGKey(1) + ) + return method_runner
nit -- we don't need the extra `method_runner` variable.
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values) + + # get InferenceRunner Config from Trainer Config and instantiate InferenceRunner + inference_runner_cfg = InferenceRunner.config_from_trainer(module_config) + inference_runner_cfg.init_state_builder.set(dir=flag_values.trainer_dir) + inference_runner = InferenceRunner(cfg=inference_runner_cfg, parent=None) + + # create Method Runner only once + method_runner = inference_runner.create_method_runner( + method="predict", prng_key=jax.random.PRNGKey(1)
Should we have a way to configure the PRNGKey?
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values) + + # get InferenceRunner Config from Trainer Config and instantiate InferenceRunner + inference_runner_cfg = InferenceRunner.config_from_trainer(module_config) + inference_runner_cfg.init_state_builder.set(dir=flag_values.trainer_dir) + inference_runner = InferenceRunner(cfg=inference_runner_cfg, parent=None) + + # create Method Runner only once + method_runner = inference_runner.create_method_runner( + method="predict", prng_key=jax.random.PRNGKey(1) + ) + return method_runner + + def run_inference( + self, + batch: Sequence[NestedTensor], + model: MethodRunner, + inference_args: Optional[Dict[str, Any]] = None, + ):
Missing returns?
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values) + + # get InferenceRunner Config from Trainer Config and instantiate InferenceRunner + inference_runner_cfg = InferenceRunner.config_from_trainer(module_config) + inference_runner_cfg.init_state_builder.set(dir=flag_values.trainer_dir) + inference_runner = InferenceRunner(cfg=inference_runner_cfg, parent=None) + + # create Method Runner only once + method_runner = inference_runner.create_method_runner( + method="predict", prng_key=jax.random.PRNGKey(1) + ) + return method_runner + + def run_inference( + self, + batch: Sequence[NestedTensor], + model: MethodRunner, + inference_args: Optional[Dict[str, Any]] = None, + ): + """Runs inferences on a batch of NestedTensors. + NestedTensor: https://github.com/apple/axlearn/blob/main/axlearn/common/utils.py#L56 + + Args: + batch: A sequence of examples as NestedTensors. + model: An instance of a MethodRunner. + inference_args: Any additional arguments for an inference. + + Returns: + A list of type MethodRunner.Output.
```suggestion Args: batch: A sequence of examples as NestedTensors. model: An instance of a MethodRunner. inference_kwargs: Optional additional keyword arguments for inference. Returns: A list of method runner outputs. ``` In general, we do not need to spell out the types in the docstring, since they are already in the fn signature. Also, it seems that we do not make use of `inference_kwargs`, is that intended?
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values) + + # get InferenceRunner Config from Trainer Config and instantiate InferenceRunner + inference_runner_cfg = InferenceRunner.config_from_trainer(module_config) + inference_runner_cfg.init_state_builder.set(dir=flag_values.trainer_dir) + inference_runner = InferenceRunner(cfg=inference_runner_cfg, parent=None) + + # create Method Runner only once + method_runner = inference_runner.create_method_runner( + method="predict", prng_key=jax.random.PRNGKey(1) + ) + return method_runner + + def run_inference( + self, + batch: Sequence[NestedTensor], + model: MethodRunner, + inference_args: Optional[Dict[str, Any]] = None, + ): + """Runs inferences on a batch of NestedTensors. + NestedTensor: https://github.com/apple/axlearn/blob/main/axlearn/common/utils.py#L56 + + Args: + batch: A sequence of examples as NestedTensors. + model: An instance of a MethodRunner. + inference_args: Any additional arguments for an inference. + + Returns: + A list of type MethodRunner.Output. + """ + logging.info("Running Inference...") + output_list = [] + for el in batch: + output_list.append(model(el)) + + return output_list + + +class PostProcessFn(beam.DoFn): + def process(self, element): + logging.info(f"Inference finished. Output type: {type(element)}")
nit -- use fstring for logging.
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values) + + # get InferenceRunner Config from Trainer Config and instantiate InferenceRunner + inference_runner_cfg = InferenceRunner.config_from_trainer(module_config) + inference_runner_cfg.init_state_builder.set(dir=flag_values.trainer_dir) + inference_runner = InferenceRunner(cfg=inference_runner_cfg, parent=None) + + # create Method Runner only once + method_runner = inference_runner.create_method_runner( + method="predict", prng_key=jax.random.PRNGKey(1) + ) + return method_runner + + def run_inference( + self, + batch: Sequence[NestedTensor], + model: MethodRunner, + inference_args: Optional[Dict[str, Any]] = None, + ): + """Runs inferences on a batch of NestedTensors. + NestedTensor: https://github.com/apple/axlearn/blob/main/axlearn/common/utils.py#L56 + + Args: + batch: A sequence of examples as NestedTensors. + model: An instance of a MethodRunner. + inference_args: Any additional arguments for an inference. + + Returns: + A list of type MethodRunner.Output. + """ + logging.info("Running Inference...") + output_list = [] + for el in batch: + output_list.append(model(el)) + + return output_list + + +class PostProcessFn(beam.DoFn): + def process(self, element):
Missing types. Also, comment on what this `PostProcessFn` is supposed to do?
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values) + + # get InferenceRunner Config from Trainer Config and instantiate InferenceRunner + inference_runner_cfg = InferenceRunner.config_from_trainer(module_config) + inference_runner_cfg.init_state_builder.set(dir=flag_values.trainer_dir) + inference_runner = InferenceRunner(cfg=inference_runner_cfg, parent=None) + + # create Method Runner only once + method_runner = inference_runner.create_method_runner( + method="predict", prng_key=jax.random.PRNGKey(1) + ) + return method_runner + + def run_inference( + self, + batch: Sequence[NestedTensor], + model: MethodRunner, + inference_args: Optional[Dict[str, Any]] = None, + ): + """Runs inferences on a batch of NestedTensors. + NestedTensor: https://github.com/apple/axlearn/blob/main/axlearn/common/utils.py#L56 + + Args: + batch: A sequence of examples as NestedTensors. + model: An instance of a MethodRunner. + inference_args: Any additional arguments for an inference. + + Returns: + A list of type MethodRunner.Output. + """ + logging.info("Running Inference...") + output_list = [] + for el in batch: + output_list.append(model(el)) + + return output_list + + +class PostProcessFn(beam.DoFn): + def process(self, element): + logging.info(f"Inference finished. Output type: {type(element)}") + yield None + + +def get_examples() -> Sequence[NestedTensor]: + """Returns a list of fake input. You can edit this function to return your desired input. + Fake input: https://github.com/apple/axlearn/blob/main/axlearn/common/input_fake.py#L49 + + Returns: + A list of examples of type FakeLmInput. + Must be a Sequence since Beam expects a Sequence of examples. + A Sequence of NestedTensor, Tensor, or other types should all work. + """ + cfg = input_fake.FakeLmInput.default_config() + cfg.is_training = False + cfg.global_batch_size = 1 + cfg.total_num_batches = 3 + + fake_input = input_fake.FakeLmInput(cfg) + example_list = [] + for _ in range(cfg.total_num_batches): + example_list.append(fake_input.__next__())
nit -- iterate over `fake_input` directly and break (or use `take`) if needed.
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,205 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +import warnings +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + +warnings.filterwarnings("ignore") + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a model and run inference""" + + def __init__(self, flag_dict): + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner: + """Loads a pre-trained model in the desired type (MethodRunner in this case). + Reference: https://github.com/apple/axlearn/blob/main/axlearn/common/inference.py#L54 + + Returns: + An instance of MethodRunner. + """ + # construct absl FlagValues from dict + flag_values = self._flag_values_from_dict(self._flag_dict) + + module_config = trainer_utils.get_trainer_config(flag_values=flag_values) + + # get InferenceRunner Config from Trainer Config and instantiate InferenceRunner + inference_runner_cfg = InferenceRunner.config_from_trainer(module_config) + inference_runner_cfg.init_state_builder.set(dir=flag_values.trainer_dir) + inference_runner = InferenceRunner(cfg=inference_runner_cfg, parent=None) + + # create Method Runner only once + method_runner = inference_runner.create_method_runner( + method="predict", prng_key=jax.random.PRNGKey(1) + ) + return method_runner + + def run_inference( + self, + batch: Sequence[NestedTensor], + model: MethodRunner, + inference_args: Optional[Dict[str, Any]] = None, + ): + """Runs inferences on a batch of NestedTensors. + NestedTensor: https://github.com/apple/axlearn/blob/main/axlearn/common/utils.py#L56 + + Args: + batch: A sequence of examples as NestedTensors. + model: An instance of a MethodRunner. + inference_args: Any additional arguments for an inference. + + Returns: + A list of type MethodRunner.Output. + """ + logging.info("Running Inference...") + output_list = [] + for el in batch: + output_list.append(model(el)) + + return output_list + + +class PostProcessFn(beam.DoFn): + def process(self, element): + logging.info(f"Inference finished. Output type: {type(element)}") + yield None + + +def get_examples() -> Sequence[NestedTensor]: + """Returns a list of fake input. You can edit this function to return your desired input. + Fake input: https://github.com/apple/axlearn/blob/main/axlearn/common/input_fake.py#L49 + + Returns: + A list of examples of type FakeLmInput. + Must be a Sequence since Beam expects a Sequence of examples. + A Sequence of NestedTensor, Tensor, or other types should all work. + """ + cfg = input_fake.FakeLmInput.default_config() + cfg.is_training = False + cfg.global_batch_size = 1 + cfg.total_num_batches = 3 + + fake_input = input_fake.FakeLmInput(cfg) + example_list = [] + for _ in range(cfg.total_num_batches): + example_list.append(fake_input.__next__()) + + return example_list + + +def parse_flags(argv): + """Parse out arguments in addition to the defined absl flags + (can be found in axlearn/common/launch_trainer.py). + Addition arguments are returned to the 'main' function by 'app.run'. + """
Seems this is mainly intended for pipeline args? If so, clarify in docstring?
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,105 @@ +"""An Apache Beam example pipeline to run batch inference jobs with a HuggingFace model. +Reference: https://cloud.google.com/dataflow/docs/notebooks/ +run_inference_huggingface#runinference_with_a_pretrained_model_from_hugging_face_hub + +
```suggestion """An Apache Beam example pipeline to run batch inference jobs with a HuggingFace model. Reference: https://cloud.google.com/dataflow/docs/notebooks/ run_inference_huggingface#runinference_with_a_pretrained_model_from_hugging_face_hub ```
axlearn
github_2023
others
470
apple
markblee
@@ -33,6 +33,7 @@ dependencies = [ "tensorstore>=0.1.21", # used for supporting GDA checkpoints "toml", # for config management "typing-extensions==4.9.0", # needed for typing.Protocol. >4.9.0 runs into attribute error `__non_callable_proto_members__`. + "scipy==1.12.0",
I think this should go away with a rebase.
axlearn
github_2023
python
470
apple
markblee
@@ -0,0 +1,202 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn.
I think we require a copyright header on all files.
axlearn
github_2023
python
470
apple
yqwangustc
@@ -0,0 +1,202 @@ +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. + +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.examples.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.examples.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.examples.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +from typing import Any, Dict, Optional, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.input_fake as input_fake +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]):
Looks like this is a new thing. Do you have document pointer for this ModelHandler ?
axlearn
github_2023
others
470
apple
ruomingp
@@ -75,6 +75,9 @@ ENV RUN_PYTHON_SDK_IN_DEFAULT_ENVIRONMENT=1 RUN pip install .[gcp,dataflow] COPY . . +COPY --from=apache/beam_python3.9_sdk:2.52.0 /opt/apache/beam /opt/apache/beam +ENTRYPOINT ["/opt/apache/beam/boot"]
Comment on why we need this step?
axlearn
github_2023
python
470
apple
ruomingp
@@ -0,0 +1,205 @@ +# Copyright © 2024 Google LLC + +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. + +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.examples.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.examples.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job:
Is there a way to use TPU?
axlearn
github_2023
python
470
apple
ruomingp
@@ -0,0 +1,205 @@ +# Copyright © 2024 Google LLC + +"""An Apache Beam example pipeline to run batch inference jobs using a model trained with AXLearn. + +Command line options: +--module: the same module used for training +--config: the same config used for training +--trainer_dir: location of your checkpoints for inference + +To debug locally: +$ docker run -it --mount type=bind,src=$HOME/.config/gcloud,dst=/root/.config/gcloud \ + --entrypoint /bin/bash ${DOCKER_REPO}/${DOCKER_IMAGE}:{DOCKER_TAG} +> python3 -m axlearn.cloud.gcp.examples.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' + +To use axlearn CLI: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + -- "'python3 -m axlearn.cloud.gcp.examples.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +To use GPUs for your job: +$ axlearn gcp dataflow start \ + --bundler_spec=dockerfile=Dockerfile \ + --bundler_spec=repo=${DOCKER_REPO} \ + --bundler_spec=image=${DOCKER_IMAGE} \ + --bundler_spec=target=dataflow \ + --bundler_spec=allow_dirty=True \ + --dataflow_spec=runner=DataflowRunner \ + --dataflow_spec=dataflow_service_options=\ + "worker_accelerator=type:nvidia-l4;count:1;install-nvidia-driver" \ + -- "'python3 -m axlearn.cloud.gcp.examples.dataflow_inference_custom \ + --module=text.gpt.c4_trainer \ + --config=fuji-7B-single \ + --trainer_dir='gs://.../checkpoints/step_xxx' \ + '" + +""" + + +import copy +import logging +from typing import Any, Dict, Sequence + +import apache_beam as beam +import jax +from absl import app, flags +from absl.flags import argparse_flags +from apache_beam.ml.inference.base import ModelHandler, PredictionResult, RunInference +from apache_beam.options.pipeline_options import PipelineOptions + +import axlearn.common.launch_trainer as trainer_utils +from axlearn.common import input_fake +from axlearn.common.inference import InferenceRunner, MethodRunner +from axlearn.common.utils import NestedTensor + + +class CustomModelHandler(ModelHandler[Dict, PredictionResult, Any]): + """Defines how to load a custom checkpoint and run inference.""" + + # pylint: disable-next=super-init-not-called + def __init__(self, flag_dict: Dict): + # Store absl FLAGS in a flag dictionary to avoid pickling issues + self._flag_dict = flag_dict + + def _flag_values_from_dict(self, flag_values: Dict) -> flags.FlagValues: + # Avoid mutating global FLAGS. + fv = copy.deepcopy(flags.FLAGS) + for k, v in flag_values.items(): + try: + fv.set_default(k, v) + # pylint: disable-next=protected-access + except flags._exceptions.UnrecognizedFlagError: + # Ignore unrecognized flags from other modules + pass + fv.mark_as_parsed() + return fv + + def load_model(self) -> MethodRunner:
Is this method inheriting from the parent class?
axlearn
github_2023
python
224
apple
ruomingp
@@ -130,7 +129,6 @@ def __init__(self, cfg: _BaseLoraAdapter.Config, *, parent: Module): cfg.lora_up.set( input_dim=cfg.rank, output_dim=cfg.output_dim, - param_partition_spec=["model", None],
Is there a test for this change?
axlearn
github_2023
python
578
apple
markblee
@@ -188,6 +187,24 @@ def _aggregate_tool_role_messages(messages: List[Dict[str, Any]]) -> List[Dict[s return aggregated_messages +def _santize_request(request: Dict[str, Any]): + """Santizes request to follow Gemini request rules."""
```suggestion def _format_request(request: Dict[str, Any]): """Formats request to follow Gemini request rules.""" ``` Since it seems more like formatting than sanitization?
axlearn
github_2023
python
578
apple
markblee
@@ -69,20 +65,22 @@ async def async_generate( """ cfg: OpenAIClient.Config = self.config client: AsyncOpenAI = self._client - assert prompt is not None or messages is not None, ValidationError( + prompt = request.get("prompt", None) + messages = request.get("messages", None) + assert prompt is None or messages is None, ValidationError(
Is this correct? Previously we require one to be non-None, but now we check that one of them is None.
axlearn
github_2023
python
578
apple
markblee
@@ -188,6 +187,24 @@ def _aggregate_tool_role_messages(messages: List[Dict[str, Any]]) -> List[Dict[s return aggregated_messages +def _santize_request(request: Dict[str, Any]): + """Santizes request to follow Gemini request rules.""" + if "messages" in request: + new_messages = [] + for message in request["messages"]: + new_messages.append(_format_tool_message(message=message)) + request["messages"] = new_messages
nit -- could be simpler with list comprehensions.
axlearn
github_2023
python
300
apple
gyin94
@@ -125,26 +125,40 @@ class Foo: def similar_names(name: str, candidates: Iterable[str]) -> List[str]: - """Return a sorted list of candidates that are similar to name.""" - - def overlaps(name: str, key: str) -> float: - """The fraction of 3-char substrings in <name> that appear in key.""" - matches = 0 - trials = 0 - for i in range(len(name) - 2): - trials += 1 - if name[i : i + 3] in key: - matches += 1 - return float(matches) / max(trials, 1) - - # Compute overlaps for each candidate. - pairs = [(overlaps(name, key), key) for key in candidates] - # Filter out candidates below 0.5 overlap threshold. - pairs = [pair for pair in pairs if pair[0] > 0.5] - # Sort by highest overlap, breaking ties alphabetically. - pairs.sort(key=lambda pair: (-pair[0], pair[1])) - # Return just the keys. - return [key for _, key in pairs] + """Use Peter Novig's spell correcter at https://norvig.com/spell-correct.html""" + word_count = Counter([_ for _ in candidates]) + + def P(word, N=sum(word_count.values())):
consider a type hint and return type?
axlearn
github_2023
python
572
apple
patrick-toulme
@@ -305,80 +310,99 @@ def vmap_fn( policy=jax.checkpoint_policies.nothing_saveable, ) def scan_fn( - carry_output_t_1: NestedTensor, - scan_t: Tuple[NestedTensor, NestedTensor, NestedTensor], + carry_in: NestedTensor, + xs_t: Tuple[NestedTensor, NestedTensor], ): - """Processes timestep v_carry in the pipeline (in parallel across pipeline stages). + """Processes timestep `t` in the pipeline (in parallel across pipeline stages). Args: - carry_output_t_1: A NestedTensor where each Tensor has shape - [N=num_layers, ...], representing carry output of timestep {t-1}. - scan_t: A tuple of (prng_key_t, input_t, x_t), each is a NestedTensor where each - leaf tensor has shape [N, ...] or [1, ...]. + carry_in: A NestedTensor containing loop state carried across scan iterations. + xs_t: A tuple (prng_key_t, x_t). Each is a NestedTensor with leaves of shape + [N, ...] or [1, ...]. Returns: - carry_output_t, dict(carry=..., y=..., output_collection=...), where - - `carry_output_t` and `carry` represents the carry output of timestep t and has - the same structure and shape as `carry_carry_output_t_1`; - - `y` is a NestedTensor representing the layerwise output of fn with leaves of - shape [N, ...]. - - `output_collection` is an OutputCollection representing the auxiliary outputs - of fn with leaves of shape [N, ...]; + (carry_out, ys_t), where: + - `carry_out` will be used as `carry_in` in the next scan iteration, and thus + has the same structure and shape as `carry_in`. + - `ys_t` is dict(carry=..., y=..., output_collection=...) and will be stacked as + `ys` after scan is done. + Note that `carry` does not necessarily have the same structure as + `carry_out`, and represents the stage-wise carry output from `fn` with + leaves of shape [N, ...]. While only last-stage outputs are needed, we + retain [N, ...] for consistent sharding. + `y` is a `NestedTensor` representing the stage-wise output of `fn` with + leaves of shape [N, ...]. + `output_collection` is an `OutputCollection` representing the auxiliary + outputs of `fn` with leaves of shape [N, ...]. """ - def compute_carry_input( - v_input_t: Tensor, v_carry_output_t_1: Tensor, partition_spec: PartitionSpec - ): - """Computes the carry input for timestep v_carry. - - Args: - v_input_t: A Tensor of shape [1, ...], where - v_input_t of timestep t == microbatch[t] if t < M; otherwise padding. - v_carry_output_t_1: A Tensor of shape [N, ...], representing carry output of - timestep {t-1}. - partition_spec: PartitionSpec for carry values. - """ - # Layer 0 input will be v_input_t, that is, microbatch[t] if t < M. - # Layer 1..N-1 inputs will be v_carry_output_t_1[0..N-2], that is, the outputs - # of layer 0..N-2 from iteration t - 1. - v_carry_input_t = jnp.concatenate([v_input_t, v_carry_output_t_1[:-1]], axis=0) - return with_sharding_constraint( - v_carry_input_t, PartitionSpec(*(["pipeline"] + list(partition_spec[1:]))) - ) - - # Per-timestep inputs. - # Each leaf tensor in `prng_key_t` and `x_t` has shape [N, ...]. - prng_key_t, input_t, x_t = scan_t - carry_input_t = jax.tree_util.tree_map( - compute_carry_input, input_t, carry_output_t_1, carry_partition_spec + # Input state. + t = carry_in["t"] + carry_output_t_1 = carry_in["carry_output_t_1"] + per_stage_inputs = carry_in["per_stage_inputs"] + + # Per-timestep inputs. Each leaf tensor has shape [N, ...] or [1, ...]. + prng_key_t, x_t = xs_t + + # Compute vmap inputs. When t >= m, we feed dummy inputs to the pipeline until the + # pipeline is flushed. Note that at the end of all iterations we only extract the + # last-stage outputs from the stacked vmap outputs. + # Leaves are of shape [N, ...] representing per-stage inputs. + vmap_in = self._compute_carry_input(per_stage_inputs, carry_output_t_1, t=t) + + # Use stop_gradient for invalid (bubble) microbatch iterations. This jnp.where will + # be optimized away by XLA, but in the backward pass it will be masking with zeros. + state = jax.tree_util.tree_map( + lambda x: jnp.where(self._is_valid_stage(x, t=t), x, jax.lax.stop_gradient(x)), + layer_context.state, ) # Parallel processing along the N axis. - vmap_out = jax.vmap(vmap_fn)(layer_context.state, prng_key_t, carry_input_t, x_t) + vmap_out = jax.vmap(vmap_fn)(state, prng_key_t, vmap_in, x_t) self.vlog(3, "vmap_out.output_collection=%s", shapes(vmap_out["output_collection"])) - return vmap_out["carry"], vmap_out - carry_t0 = jax.tree_util.tree_map( - lambda x: jnp.tile(jnp.zeros_like(x[:1]), [n] + [1] * (x.ndim - 1)), carry + # Output state. + carry_out = dict( + t=t + 1, + carry_output_t_1=vmap_out["carry"], + per_stage_inputs=per_stage_inputs, + ) + # TODO(markblee): Consider slicing out just the last-stage outputs of vmap_out. + # Note that vmap outputs are typically sharded over stages and may incur extra + # communication per-iteration (e.g. from broadcasting last stage outputs). + return carry_out, vmap_out + + state_t0 = dict( + # Current loop iteration. + t=jnp.array(0, dtype=jnp.int32), + # [N, microbatch_size, ...]. + carry_output_t_1=jax.tree_util.tree_map( + lambda x: jnp.zeros((n,) + x.shape[1:]), carry
see this PR: https://github.com/markblee/axlearn/pull/1
axlearn
github_2023
python
573
apple
markblee
@@ -272,6 +264,85 @@ async def async_generate_from_requests( del item["async_index"] return responses + @classmethod + def define_flags(cls, fv: flags.FlagValues): + """Defines flags for generator.py.""" + common_kwargs = dict(flag_values=fv, allow_override=True) + # For client. + flags.DEFINE_string("model", None, "The model name.", **common_kwargs) + flags.DEFINE_string("client_name", "openai", "Open api client name.", **common_kwargs) + flags.DEFINE_integer("timeout", 120, "Seconds for timeout requests.", **common_kwargs) + # For generator. + flags.DEFINE_integer( + "concurrency", 8, "Number of concurrent clients for generations.", **common_kwargs + ) + flags.DEFINE_integer( + "max_non_rate_limit_retries", + 5, + "Max number of retries for a request due to non rate limit error.", + **common_kwargs, + ) + flags.DEFINE_integer( + "max_rate_limit_retries", + 25, + "Max number of retries for a request due to rate limit error.", + **common_kwargs, + ) + flags.DEFINE_integer( + "retry_sleep_in_seconds", + 4, + "Seconds for retry sleep time when hitting rate limit.", + **common_kwargs, + ) + flags.DEFINE_boolean( + "allow_non_rate_limit_error", + True, + "True to allow non rate limit error and store empty response.", + **common_kwargs, + ) + flags.DEFINE_string( + "decode_parameters", + None, + "A json string of decoding parameters." + "If None, max_tokens is 1024 and temperature is 0.0 for greedy decoding.", + **common_kwargs, + ) + # For file input. + flags.DEFINE_string( + "input_file", + None, + "Path to the input data file. Each line is a json string of OpenAI request style.", + **common_kwargs, + ) + flags.DEFINE_string( + "output_file", + None, + "Path to the output data file. Each line is a json string of OpenAI request style.", + **common_kwargs, + ) + flags.DEFINE_boolean(
Forgot to mention, but for these non-config flags (check_vllm_readiness, debug or repeat_requests_for_n) it may be worth defining them separately in `generator.py`. Feel free to address separately.