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 | others | 946 | apple | ruomingp | @@ -83,7 +83,9 @@ dev = [
gcp = [
"cloud-tpu-client", # for creating and managing TPUs.
"crcmod", # for file uploads.
- "kubernetes",
+ # kubernetes==32.0.0 will cause "kube_config.py:520] Object of type ConfigNode is not JSON serializable" error
+ # when loading kube config, hence failing kubernetes client authentication. | Is there a github issue to track the problem? |
axlearn | github_2023 | python | 922 | apple | ruomingp | @@ -152,6 +153,8 @@ def test_decode_against_ref(
kv_head_factor: int,
window_len: int,
):
+ if jax.default_backend() != "gpu" and seq_len > 1024: | Nit: can we check it against "cpu" directly instead of `!= "gpu"`? |
axlearn | github_2023 | python | 922 | apple | ruomingp | @@ -346,6 +357,9 @@ def test_cudnn_against_triton_ref(
causal: bool,
dtype: jnp.dtype,
):
+ if jax.default_backend() == "cpu": | Likewise, let's avoid assuming that the backend is either gpu or cpu in multiple places.
```suggestion
if jax.default_backend() != "gpu":
``` |
axlearn | github_2023 | python | 922 | apple | ruomingp | @@ -414,6 +444,8 @@ def test_cudnn_dropout_against_xla_dropout(
by setting V to the identity matrix. However, this only works when seq_len == per_head_dim,
i.e. when the shape of output is the same as the shape of the dropout mask.
"""
+ if jax.default_backend() == "cpu":
+ pytest.skip(reason="cudnn function needs GPU.") | And here and elsewhere. |
axlearn | github_2023 | python | 922 | apple | ruomingp | @@ -97,12 +92,11 @@ def test_to_splash_mask(self, mask, expected):
@parameterized.product(
batch_size=[4],
- seq_len=[1024, 32768],
+ seq_len=[1024], | Since the sliding window size is 1024, it will be useful to keep a test case for seq_len > 1024. We can enable the test only on TPU if it's too slow on CPU. We can also use a seq_len such as 2048 for cpu if it's fast enough. |
axlearn | github_2023 | python | 922 | apple | ruomingp | @@ -268,20 +269,18 @@ def get_segment_ids(segment_ids: SegmentIdAttentionBias) -> Optional[Tensor]:
value,
bias=explicit_bias.value(),
segment_ids=get_segment_ids(segment_ids),
- # The `from_sequence()` function guarantees that if there is only one
- # mask, it is returned without modification.
- # This allows the `causal` path in `_legacy_tpu_flash_attention()` to work.
- mask=mask if not isinstance(mask, ZeroAttentionBias) else None,
+ mask=mask,
softmax_scale=softmax_scale,
block_size=block_size,
+ interpret=(backend == "cpu"), | Given how often we do this across locations, I wonder if we can do the following:
- Make `interpret` default to None (instead of False);
- If it's None, assume interpret=True if the backend is "cpu";
WDYT? |
axlearn | github_2023 | python | 883 | apple | apivovarov | @@ -0,0 +1,129 @@
+from absl import logging
+from functools import partial
+import jax
+import jax.numpy as jnp
+import jax.numpy as jnp | dup |
axlearn | github_2023 | python | 883 | apple | kelvin-zou | @@ -0,0 +1,129 @@
+from absl import logging | Copyright? |
axlearn | github_2023 | python | 883 | apple | kelvin-zou | @@ -0,0 +1,124 @@
+from functools import partial
+import jax
+import jax.numpy as jnp
+from jax import custom_vjp
+
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+@partial(custom_vjp, nondiff_argnums=(4, 5))
+def flash_attention(query, key, value, bias, causal, softmax_scale):
+ out, _ = _mha_forward(query, key, value, bias, causal, softmax_scale)
+ return out
+
+
+def _mha_forward(query, key, value, bias, causal, softmax_scale): | Can we get a support for segment ID and dropout as well? Both are quite needed nowadays. |
axlearn | github_2023 | python | 883 | apple | kelvin-zou | @@ -159,6 +159,21 @@ def jit_attn(query, key, value, bias, segment_ids):
return jit_attn
+ elif backend == "neuron":
+ from axlearn.common.flash_attention.neuron_attention import ( | On demand import is kind of risky, we can live with it for functions inside neuron_attention.py, can we at least get it as a header import for files outside of neuron_attention.py? |
axlearn | github_2023 | python | 883 | apple | kelvin-zou | @@ -0,0 +1,124 @@
+from functools import partial
+import jax
+import jax.numpy as jnp
+from jax import custom_vjp
+
+lnc = 2 if jax.devices()[0].device_kind == "NC_v3d" else 1
+
+@partial(custom_vjp, nondiff_argnums=(4, 5))
+def flash_attention(query, key, value, bias, causal, softmax_scale):
+ out, _ = _mha_forward(query, key, value, bias, causal, softmax_scale)
+ return out
+
+
+def _mha_forward(query, key, value, bias, causal, softmax_scale):
+ # Get the batch size, sequence lengths, number of heads, and hidden dimension
+ batch_size, q_seq_len, num_heads, d_model = query.shape
+
+ # Transpose the query, key, and value tensors
+ q = query.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, q_seq_len]
+ k = key.transpose(0, 2, 3, 1) # [batch_size, num_heads, d_model, kv_seq_len]
+ v = value.transpose(0, 2, 1, 3) # [batch_size, num_heads, kv_seq_len, d_model]
+
+ import neuronxcc.nki.language as nl | Please add pylint here |
axlearn | github_2023 | python | 933 | apple | ruomingp | @@ -2,23 +2,121 @@
"""Base Input interface."""
-from typing import Iterable, Iterator, Optional, Sequence, Union
+import re
+from typing import Iterable, Iterator, NamedTuple, Optional, Protocol, Sequence, Union
import jax
+from absl import logging
+from jax._src.mesh import thread_resources
from jax.sharding import PartitionSpec
-from axlearn.common.config import config_class
+from axlearn.common.config import ConfigOr, config_class, maybe_instantiate
from axlearn.common.input_dispatch import InputDispatcher
from axlearn.common.module import Module
from axlearn.common.utils import (
Nested,
Tensor,
as_numpy_array,
dispatch_input_batch,
+ tree_paths,
with_sharding_constraint,
)
+class InputPartitionFn(Protocol):
+ """Partitions the input batch."""
+
+ def __call__(self, input_batch: Nested[Tensor]) -> Nested[Tensor]:
+ """Applies sharding constraints to `input_batch` and returns the modified batch.
+
+ Implementations should avoid making in-place updates to `input_batch`.
+ """
+
+
+class PathAndRank(NamedTuple):
+ """A tuple (path, rank) used for matching against inputs in a batch.
+
+ Attributes:
+ path: An optional path or path regex. None means match everything.
+ rank: An optional rank (ndim). None means match everything.
+ """
+
+ path: Optional[Union[str, re.Pattern]]
+ rank: Optional[int]
+
+
+def partition_by_path_rank(
+ path_rank_to_partition: dict[PathAndRank, PartitionSpec], | Nit: maybe we don't really need a dict:
```suggestion
path_rank_to_partition: Sequence[IntputFieldPartitionSpec],
```
it simplifies the data structure and `IntputFieldPartitionSpec` is more extensible than `PartitionSpec`. |
axlearn | github_2023 | python | 850 | apple | samos123 | @@ -67,7 +67,7 @@ class Version(enum.Enum):
VOCAB_SIZE = {
Version.V1: 32 * 1024,
Version.V2: 32 * 1024,
- Version.V3: 128256,
+ Version.V3: 128 * 1024, | llama 3 is supposed to be 128256. Are there any plans to stick to standard llama 3? |
axlearn | github_2023 | python | 850 | apple | markblee | @@ -301,6 +305,10 @@ def model_config(
lm_head=lm_head_cfg,
dropout_rate=dropout_rate,
)
+ if pad_token_id: | Since `pad_token_id=0` is a valid token:
```suggestion
if pad_token_id is not None:
``` |
axlearn | github_2023 | python | 850 | apple | markblee | @@ -301,6 +305,10 @@ def model_config(
lm_head=lm_head_cfg,
dropout_rate=dropout_rate,
)
+ if pad_token_id:
+ decoder_cfg.set(pad_token_id=pad_token_id)
+ if eos_token_id: | ```suggestion
if eos_token_id is not None:
``` |
axlearn | github_2023 | python | 850 | apple | markblee | @@ -41,22 +41,29 @@
"""
-from axlearn.common.config import InstantiableConfig, config_for_function
+from axlearn.common.config import InstantiableConfig, config_for_class, config_for_function
from axlearn.common.input_lm import lm_text_preprocessor
from axlearn.common.utils import get_data_dir
from axlearn.experiments.text.common import DataMixtureComponent, vocab
from axlearn.experiments.text.gpt import fuji, gspmd
from axlearn.experiments.text.gpt.common import mixture_train_input_source, tfds_input
+from axlearn.experiments.text.gpt.vocabulary_fuji_v3 import FujiV3Vocabulary
from axlearn.experiments.trainer_config_utils import TrainerConfigFn
-# Sentencepiece vocabs generated from c4/en:3.0.1.
-# See bpe_{32k,128k}.json for the sentencepiece settings.
-_SENTENCEPIECE_MODEL_NAME = {
- 32 * 1024: "bpe_32k_c4.model",
- # TikToken is not yet supported, so we are using sentencepiece for now.
- # Our new grain-based inputs can support TikToken in the future.
- 128256: "bpe_128k_c4.model",
-}
+
+def _vocab_cfg(size: int): | nit -
```suggestion
def _vocab_cfg(vocab_size: int):
``` |
axlearn | github_2023 | python | 850 | apple | markblee | @@ -41,22 +41,29 @@
"""
-from axlearn.common.config import InstantiableConfig, config_for_function
+from axlearn.common.config import InstantiableConfig, config_for_class, config_for_function
from axlearn.common.input_lm import lm_text_preprocessor
from axlearn.common.utils import get_data_dir
from axlearn.experiments.text.common import DataMixtureComponent, vocab
from axlearn.experiments.text.gpt import fuji, gspmd
from axlearn.experiments.text.gpt.common import mixture_train_input_source, tfds_input
+from axlearn.experiments.text.gpt.vocabulary_fuji_v3 import FujiV3Vocabulary
from axlearn.experiments.trainer_config_utils import TrainerConfigFn
-# Sentencepiece vocabs generated from c4/en:3.0.1.
-# See bpe_{32k,128k}.json for the sentencepiece settings.
-_SENTENCEPIECE_MODEL_NAME = {
- 32 * 1024: "bpe_32k_c4.model",
- # TikToken is not yet supported, so we are using sentencepiece for now.
- # Our new grain-based inputs can support TikToken in the future.
- 128256: "bpe_128k_c4.model",
-}
+
+def _vocab_cfg(size: int):
+ if size == 32 * 1024:
+ # Sentencepiece vocabs generated from c4/en:3.0.1.
+ # See bpe_{32k,128k}.json for the sentencepiece settings.
+ return config_for_function(vocab).set(sentencepiece_model_name="bpe_32k_c4.model")
+ if size == 128 * 1024:
+ return config_for_function(vocab).set(sentencepiece_model_name="bpe_128k_c4.model")
+ if size == 128256:
+ # TikToken.
+ return config_for_class(FujiV3Vocabulary).set(filename="Llama-3-tokenizer.json")
+ raise ValueError(f"size {size} tokenizer does not exist.") | ```suggestion
raise ValueError(f"Tokenizer with vocab size {size} does not exist.")
``` |
axlearn | github_2023 | python | 850 | apple | markblee | @@ -445,6 +446,8 @@ def model_config(
ffn_dim: Optional[Union[int, config.FunctionConfigBase]] = None,
flash_attention: bool = False,
stack_cfg: Optional[BaseStackedTransformerLayer.Config] = None,
+ pad_token_id: Optional[int] = None,
+ eos_token_id: Optional[int] = None, | Please update docstring accordingly. |
axlearn | github_2023 | python | 850 | apple | markblee | @@ -423,6 +421,9 @@ def get_trainer_kwargs(
raise NotImplementedError(f"Unknown model size {model_size}.")
model_kwargs = trainer_kwargs.pop("model_kwargs")
model_kwargs.setdefault("vocab_size", vocab_size)
+ if version == Version.V3 and vocab_size == 128256: # tiktoken tokenizer | Can we use a private const for the tiktoken size?
```
_TIKTOKEN_VOCAB_SIZE = 128256
``` |
axlearn | github_2023 | python | 850 | apple | markblee | @@ -515,21 +520,24 @@ def trainer_configs(
"""
arch = "fuji"
config_map = {}
- for version, model_size, flash_attention in itertools.product(
- Version, MODEL_SIZES, [True, False]
+ for version, model_size, flash_attention, tiktoken in itertools.product(
+ Version, MODEL_SIZES, [True, False], [True, False]
):
+ if model_size not in TOTAL_TOKENS[version]: # This combination does not exist.
+ continue
+ if version != Version.V3 and tiktoken: # Only V3 has TikToken option.
+ continue
+ suffix = "-flash" if flash_attention else ""
vocab_size = VOCAB_SIZE[version]
+ if tiktoken:
+ suffix += "-tiktoken"
+ vocab_size = 128256 | Use the const here? |
axlearn | github_2023 | python | 850 | apple | markblee | @@ -27,6 +27,65 @@
# Use cpu for the test.
jax.config.update("jax_platform_name", "cpu")
+config_dict_1b = { | Add a link to the json config as a reference? |
axlearn | github_2023 | python | 850 | apple | markblee | @@ -0,0 +1,200 @@
+# Copyright © 2024 Apple Inc.
+
+"""Fuji v3 vocabulary."""
+
+import os
+import tempfile
+from typing import Optional, Protocol, Sequence, Union
+
+import jax
+import numpy as np
+import tensorflow.compat.v2 as tf
+from tokenizers import Tokenizer
+
+import axlearn.common.file_system as fs
+from axlearn.common.utils import get_data_dir
+
+
+class InnerTokenizer(Protocol):
+ """Defines a protocol of InnerTokenizer which is used in Vocabulary.
+
+ This is a subset of sentencepiece_processor.SentencePieceProcessor API that are used in
+ Vocabulary.
+ """
+
+ def encode_as_pieces(self, pieces: str) -> list[str]:
+ """Encode text input to tokens."""
+ pass
+
+ def piece_to_id(self, piece: str) -> int:
+ """Encode a token to id."""
+ pass
+
+
+class Vocabulary(Protocol):
+ """Defines a protocol of Vocabulary.
+
+ This is a subset of seqio.Vocabulary APIs that are used in text_to_lm_training_input and
+ test_to_lm_eval_input.
+ """
+
+ @property
+ def pad_id(self) -> int:
+ pass
+
+ @property
+ def eos_id(self) -> Optional[int]:
+ pass
+
+ def encode_tf(self, s: tf.Tensor) -> tf.Tensor:
+ """Tokenizes string Scalar to an int32 Tensor, without adding EOS."""
+ pass
+
+ def _decode_tf(self, ids: tf.Tensor) -> tf.Tensor:
+ """Detokenizes int32 batched Tensor."""
+ pass
+
+ def encode(self, s: str) -> list[int]:
+ """Tokenizes string to an int sequence, without adding EOS."""
+ pass
+
+ def _decode(self, ids: Sequence[int]) -> str:
+ """Detokenizes int sequence to a string, through all EOS."""
+ pass
+
+ def decode(self, ids: Sequence[int]) -> str:
+ """Detokenizes int32 iterable to a string, up through first EOS."""
+ pass
+
+ @property
+ def tokenizer(self) -> InnerTokenizer:
+ pass
+
+
+class FujiInnerTokenizer:
+ """A wrapper for tokenizer.Tokenizer so that it follows InnerTokenizer Protocol."""
+
+ def __init__(self, tokenizer):
+ self._tokenizer = tokenizer
+
+ def encode_as_pieces(self, pieces: str) -> list[str]:
+ """Encode text input to tokens."""
+ return self._tokenizer.encode(pieces, add_special_tokens=False).tokens
+
+ def piece_to_id(self, piece: str) -> int:
+ """Encode a token to id."""
+ return self._tokenizer.token_to_id(piece)
+
+
+class FujiV3Vocabulary:
+ """A wrapper for tokenizers.Tokenizer so that it follows Vocabulary Protocol.
+
+ Although its name has fuji, but it can be extended to work for all tokenizers.Tokenizer.
+ """
+
+ def __init__(self, filename: str):
+ data_dir = get_data_dir()
+ data_dir = (
+ os.path.join(os.path.dirname(__file__), "..", "..", "..", "data")
+ if data_dir is None or data_dir == "FAKE"
+ else data_dir
+ )
+ filename = os.path.join(data_dir, "tokenizers", "hf", filename)
+ if filename.startswith("gs:") or filename.startswith("s3:"):
+ # Create a different file for each usage.
+ tmp = tempfile.mkdtemp() | Should we cleanup `tmp` after tokenizer has been initialized? |
axlearn | github_2023 | python | 931 | apple | markblee | @@ -30,6 +31,8 @@ def _make_autoregressive_inputs(
max_len: int,
input_key: str = "target_labels",
split_fn: Optional[ConfigOr[_SplitFn]] = None,
+ num_threads: int = 1, | This is a private method, how do users configure it? Should we pass through `text_to_lm_training_input`?
Also, would it be more general to `read_options` directly in case it eventually supports some form of autotune? |
axlearn | github_2023 | python | 927 | apple | ruomingp | @@ -200,6 +200,13 @@ class Config(Module.Config):
# The provided config should instantiate to a thunk that returns the context manager.
context_manager: Optional[ConfigOr[Callable[[], ContextManager]]] = None
+ # If True, assumes the train_step may need to be recompiled and go through the lowering
+ # and compilation process every train step and rely on compilation cache to prevent
+ # excessive recompilations. Note: this could introduce overhead to training due to
+ # pre-compilation checks (such as sharding check) that increases the step time for some
+ # models. Note that this cache is always disabled at steps when xsc is enabled.
+ disable_python_train_step_cache: Optional[bool] = None | Let's avoid negative boolean fields, as `enable_python_train_step_cache=True` is more readable than `disable_python_train_step_cache=False`.
```suggestion
enable_python_train_step_cache: Optional[bool] = None
``` |
axlearn | github_2023 | python | 927 | apple | ruomingp | @@ -994,7 +1009,8 @@ def _get_compiled_train_step_fn(
replicate_llo=device_kinds.pop() in ["TPU v5e", "TPU v6e"],
),
)
- return compiled_jit_train_step_fn
+ self._compiled_train_step = compiled_jit_train_step_fn
+ return self._compiled_train_step | Should we leave `self._compiled_train_step` unchanged when `with_xsc` is true?
```suggestion
return compiled_jit_train_step_fn
``` |
axlearn | github_2023 | python | 927 | apple | ruomingp | @@ -964,8 +973,6 @@ def _get_compiled_train_step_fn(
) -> Callable[[TrainerState, NestedTensor], tuple[TrainerState, NestedTensor]]:
"""Build a fully compiled train step function.
- Relies on the JAX pjit cache to avoid recompilation where possible. | Relies on the JAX pjit cache to avoid recompilation when with_xsc=True or enable_python_train_step_cache=False. |
axlearn | github_2023 | python | 927 | apple | apghml | @@ -200,6 +200,14 @@ class Config(Module.Config):
# The provided config should instantiate to a thunk that returns the context manager.
context_manager: Optional[ConfigOr[Callable[[], ContextManager]]] = None
+ # If False, assumes the train_step may need to be recompiled and go through the lowering
+ # and compilation process every train step and rely on compilation cache to prevent
+ # excessive recompilations. Note: this could introduce overhead to training due to
+ # pre-compilation checks (such as sharding check) that increases the step time for some
+ # models. Note that this cache is always disabled at steps when xsc is enabled.
+ # Defaults to None which is interpreted as True.
+ enable_python_train_step_cache: Optional[bool] = None | ```suggestion
cache_compiled_train_step: Optional[bool] = None
``` |
axlearn | github_2023 | python | 927 | apple | apghml | @@ -200,6 +200,14 @@ class Config(Module.Config):
# The provided config should instantiate to a thunk that returns the context manager.
context_manager: Optional[ConfigOr[Callable[[], ContextManager]]] = None
+ # If False, assumes the train_step may need to be recompiled and go through the lowering
+ # and compilation process every train step and rely on compilation cache to prevent
+ # excessive recompilations. Note: this could introduce overhead to training due to
+ # pre-compilation checks (such as sharding check) that increases the step time for some
+ # models. Note that this cache is always disabled at steps when xsc is enabled. | Can we make it error if xsc is enabled and the config below is set to True? (Instead of silently disabling?)
But still retain the automatic disabling when the config field below is set to None? |
axlearn | github_2023 | python | 927 | apple | ruomingp | @@ -271,8 +279,11 @@ def __init__(
"xsc_check_policy was set for non-TPU XLA backend. Running without XSC."
)
else:
+ if cfg.cache_python_train_step is True:
+ raise ValueError("cache_python_train_step cannot be True when xsc is enabled.") | Actually `cache_python_train_step` is still useful even with XSC, since the non-XSC steps will be cached and only the XSC step needs to be recompiled. The XSC step does not run often, so maybe this is OK? |
axlearn | github_2023 | python | 927 | apple | markblee | @@ -200,6 +200,14 @@ class Config(Module.Config):
# The provided config should instantiate to a thunk that returns the context manager.
context_manager: Optional[ConfigOr[Callable[[], ContextManager]]] = None
+ # If False, assumes the train_step may need to be recompiled and go through the lowering
+ # and compilation process every train step and rely on compilation cache to prevent
+ # excessive recompilations. Note: this could introduce overhead to training due to
+ # pre-compilation checks (such as sharding check) that increases the step time for some
+ # models. Note that this cache is always disabled at steps when xsc is enabled.
+ # Defaults to None which is interpreted as True.
+ cache_python_train_step: Optional[bool] = None | nit --
```suggestion
cache_compiled_train_step: Optional[bool] = None
``` |
axlearn | github_2023 | python | 898 | apple | apghml | @@ -1459,3 +1459,30 @@ def validate_contains_paths(x: Nested[Tensor], paths: Sequence[str]):
f"Input is expected to contain '{path}'; "
f"instead, it contains: '{jax.tree_structure(x)}'."
) from e
+
+
+def save_only_these_regex_patterns(*regex_patterns_to_save): | Add an annotation for the args and return type? |
axlearn | github_2023 | python | 898 | apple | apghml | @@ -1459,3 +1459,30 @@ def validate_contains_paths(x: Nested[Tensor], paths: Sequence[str]):
f"Input is expected to contain '{path}'; "
f"instead, it contains: '{jax.tree_structure(x)}'."
) from e
+
+
+def save_only_these_regex_patterns(*regex_patterns_to_save):
+ """Save only the values that match the regex pattern.
+
+ Args:
+ regexes_to_save: List of regex patterns to save
+
+ Returns:
+ Callable: Policy that matches regex | Nit: we include type information in the function signature, not the docstring. |
axlearn | github_2023 | python | 898 | apple | apghml | @@ -277,8 +269,7 @@ def model_config(
layer_cfg.self_attention.attention.input_linear = attention_qkv_linear
layer_cfg.self_attention.structure = atten_structure
layer_cfg.self_attention.attention.atten_logit_cap = atten_logit_cap
- if stack_cfg.klass is RepeatedTransformerLayer:
- update_model_remat_config(stack_cfg=stack_cfg, layer_cfg=layer_cfg)
+ update_model_remat_config(stack_cfg=stack_cfg, layer_cfg=layer_cfg) | Could you explain why we originally only did this for RepeatedTransformer and why it is okay to do it for everything now? |
axlearn | github_2023 | python | 898 | apple | ruomingp | @@ -1459,3 +1459,30 @@ def validate_contains_paths(x: Nested[Tensor], paths: Sequence[str]):
f"Input is expected to contain '{path}'; "
f"instead, it contains: '{jax.tree_structure(x)}'."
) from e
+
+
+def save_only_these_regex_patterns(*regex_patterns_to_save):
+ """Save only the values that match the regex pattern.
+
+ Args:
+ regexes_to_save: List of regex patterns to save | Comment on what these regex match? |
axlearn | github_2023 | python | 898 | apple | ruomingp | @@ -3934,6 +3935,33 @@ def forward(
_SavePattern = Union[str, re.Pattern, None]
+def save_only_these_regex_patterns(*regex_patterns_to_save): | How is this different from https://github.com/apple/axlearn/blob/92205bc8928adaef14b980f7e4dd4936ee953e2f/axlearn/common/attention.py#L3933-L3956? |
axlearn | github_2023 | python | 898 | apple | ruomingp | @@ -3934,6 +3935,33 @@ def forward(
_SavePattern = Union[str, re.Pattern, None]
+def save_only_these_regex_patterns(*regex_patterns_to_save):
+ """Save only the values that match the regex pattern.
+
+ Args:
+ regexes_to_save: List of regex patterns to save
+
+ Returns:
+ Callable: Policy that matches regex
+ """
+ regex_patterns_to_save = frozenset(regex_patterns_to_save)
+
+ def policy(*_, **params):
+ if "name" in params:
+ param_name = params["name"]
+ for regex_to_save in regex_patterns_to_save:
+ if re.search(regex_to_save, param_name): | Use re.fullmatch for consistency with other AXLearn code? |
axlearn | github_2023 | python | 898 | apple | ruomingp | @@ -417,6 +418,36 @@ def get_trainer_kwargs(
"gpu-(p5.48xlarge|p4de.24xlarge)-(512|1024)",
mesh_shape_from_axes(data=-1, fsdp=128),
),
+ (
+ "neuron-(trn2|trn2n).48xlarge-64",
+ ChainConfigModifier.default_config().set(
+ config_modifiers=[
+ MeshShapeModifier.default_config().set(
+ mesh_shape=mesh_shape_from_axes(fsdp=-1, model=4)
+ ),
+ RematSpecModifier.default_config().set(
+ remat_policies={
+ "model.decoder.transformer.layer": RematSpec(
+ prevent_cse=True,
+ policy=config_for_function(
+ _save_and_offload_only_these_names_regex
+ ).set(
+ # pylint: disable=anomalous-backslash-in-string
+ names_which_can_be_saved=r"(TransformerAttentionLayer\.residual_add" # pylint: disable=C0301
+ "|.*\.?(k|q|v)_proj"
+ "|.*\.?linear1_[01]"
+ "|TransformerFeedForwardLayer\.mlp_residual)", | Consider defining it as a constant so that it can be reused across configs? |
axlearn | github_2023 | python | 898 | apple | ruomingp | @@ -417,6 +418,36 @@ def get_trainer_kwargs(
"gpu-(p5.48xlarge|p4de.24xlarge)-(512|1024)",
mesh_shape_from_axes(data=-1, fsdp=128),
),
+ (
+ "neuron-(trn2|trn2n).48xlarge-64",
+ ChainConfigModifier.default_config().set(
+ config_modifiers=[
+ MeshShapeModifier.default_config().set(
+ mesh_shape=mesh_shape_from_axes(fsdp=-1, model=4)
+ ),
+ RematSpecModifier.default_config().set(
+ remat_policies={
+ "model.decoder.transformer.layer": RematSpec(
+ prevent_cse=True,
+ policy=config_for_function(
+ _save_and_offload_only_these_names_regex
+ ).set(
+ # pylint: disable=anomalous-backslash-in-string
+ names_which_can_be_saved=r"(TransformerAttentionLayer\.residual_add" # pylint: disable=C0301
+ "|.*\.?(k|q|v)_proj"
+ "|.*\.?linear1_[01]"
+ "|TransformerFeedForwardLayer\.mlp_residual)",
+ names_which_can_be_offloaded=None, | Does Neuron support offloading activations? |
axlearn | github_2023 | python | 898 | apple | ruomingp | @@ -417,6 +418,36 @@ def get_trainer_kwargs(
"gpu-(p5.48xlarge|p4de.24xlarge)-(512|1024)",
mesh_shape_from_axes(data=-1, fsdp=128),
),
+ (
+ "neuron-(trn2|trn2n).48xlarge-64",
+ ChainConfigModifier.default_config().set(
+ config_modifiers=[
+ MeshShapeModifier.default_config().set(
+ mesh_shape=mesh_shape_from_axes(fsdp=-1, model=4)
+ ),
+ RematSpecModifier.default_config().set(
+ remat_policies={
+ "model.decoder.transformer.layer": RematSpec(
+ prevent_cse=True,
+ policy=config_for_function(
+ _save_and_offload_only_these_names_regex
+ ).set(
+ # pylint: disable=anomalous-backslash-in-string | Do we need this? |
axlearn | github_2023 | python | 898 | apple | hanzhi713 | @@ -86,6 +87,14 @@ class Version(enum.Enum):
}
+# Regex patterns for matching remat names
+class RematRegex(enum.Enum):
+ QKV_PROJ = r".*\.?(k|q|v)_proj"
+ LINEAR1_X = r".*\.?linear1_[01]"
+ RESIDUAL_ADD = r"(TransformerAttentionLayer\.residual_add" | Mismatched parentheses? |
axlearn | github_2023 | python | 898 | apple | ruomingp | @@ -133,13 +133,13 @@ def _compute_metrics(
if brevity_penalty:
decode_kwargs["brevity_penalty"] = brevity_penalty
- cfg: WordErrorRateMetricCalculator.Config = (
- WordErrorRateMetricCalculator.default_config().set(
- vocab=config_for_class(seqio.SentencePieceVocabulary).set(
- sentencepiece_model_file=vocab_file,
- ),
- model_method_kwargs=decode_kwargs,
- )
+ cfg: (
+ WordErrorRateMetricCalculator.Config
+ ) = WordErrorRateMetricCalculator.default_config().set( | Is this change intended? |
axlearn | github_2023 | python | 898 | apple | ruomingp | @@ -86,6 +87,14 @@ class Version(enum.Enum):
}
+# Regex patterns for matching remat names
+class RematRegex(enum.Enum):
+ QKV_PROJ = r".*\.?(k|q|v)_proj"
+ LINEAR1_X = r".*\.?linear1_[01]"
+ RESIDUAL_ADD = r"TransformerAttentionLayer\.residual_add"
+ MLP_RESIDUAL = r"TransformerFeedForwardLayer\.mlp_residual" | How do we check whether these regex match the right activations?
Consider adding a test as in https://github.com/apple/axlearn/blob/a15a3bcbb976c14db157a8958df368a48c614c1f/axlearn/common/attention_test.py#L3831-L3876. |
axlearn | github_2023 | python | 898 | apple | kelvin-zou | @@ -2801,6 +2805,7 @@ def _linear2(x):
self._add_tensor_stats("inputs", inputs)
remat_pt2 = "linear2"
+ remat_pt3 = "feed_forward_output" | hmm, is this necessary? Seems quite wasteful to checkpoint an activation after a norm? I would recommend restraining from making change here. |
axlearn | github_2023 | python | 898 | apple | kelvin-zou | @@ -2508,23 +2508,27 @@ def attention_thunk(target: Tensor) -> tuple[Optional[NestedTensor], Tensor]:
atten_state, atten_output = attention_thunk(TensorSpec(target.shape, target.dtype))
return dict(attention=atten_state), atten_output
+ remat_pt1 = "attention_output" | Is this really needed? How much perf gain we get from saving `attention_output`? |
axlearn | github_2023 | python | 898 | apple | hanzhi713 | @@ -3875,6 +3875,72 @@ def f(x, layer_params):
5,
)
+ def test_build_remat_spec_neuron(self):
+ model_dim, num_heads = 6, 2
+ cfg: TransformerLayer.Config = TransformerLayer.default_config().set(input_dim=model_dim)
+ cfg.self_attention.attention.set(num_heads=num_heads, causal=True)
+ cfg.feed_forward.hidden_dim = model_dim * 4
+ cfg.vlog = 5
+
+ layer: BaseTransformerLayer = cfg.clone(name="layer").instantiate(parent=None)
+ layer_params = layer.initialize_parameters_recursively(prng_key=jax.random.PRNGKey(0))
+
+ batch_size, tgt_len = 2, 5
+ rng = np.random.default_rng(seed=123)
+ target = rng.random([batch_size, tgt_len, cfg.input_dim], dtype=np.float32)
+
+ def f(x, layer_params):
+ forward_outputs, _ = F(
+ layer,
+ inputs=dict(
+ data=x,
+ ),
+ state=layer_params,
+ is_training=True,
+ prng_key=jax.random.PRNGKey(0),
+ )
+ return forward_outputs
+
+ # Ignore type errors.
+ spec: Any = build_remat_spec(mock.MagicMock())
+
+ policy = (
+ config_for_function(_save_and_offload_only_these_names_regex)
+ .set(
+ names_which_can_be_saved="|".join(
+ [
+ RematRegexSavePatterns.QKV_PROJ.value,
+ RematRegexSavePatterns.LINEAR1_X.value,
+ RematRegexSavePatterns.ATTENTION_OUTPUT.value, | It looks like the names here doesn't match those listed in `RematRegexSavePatterns` |
axlearn | github_2023 | python | 898 | apple | hanzhi713 | @@ -417,6 +418,38 @@ def get_trainer_kwargs(
"gpu-(p5.48xlarge|p4de.24xlarge)-(512|1024)",
mesh_shape_from_axes(data=-1, fsdp=128),
),
+ (
+ "neuron-(trn2|trn2n).48xlarge-64",
+ ChainConfigModifier.default_config().set(
+ config_modifiers=[
+ MeshShapeModifier.default_config().set(
+ mesh_shape=mesh_shape_from_axes(fsdp=-1, model=4)
+ ),
+ RematSpecModifier.default_config().set(
+ remat_policies={
+ "model.decoder.transformer.layer": RematSpec(
+ prevent_cse=True,
+ policy=config_for_function(
+ _save_and_offload_only_these_names_regex
+ ).set(
+ names_which_can_be_saved="|".join(
+ [
+ RematRegexSavePatterns.QKV_PROJ.value,
+ RematRegexSavePatterns.LINEAR1_X.value,
+ RematRegexSavePatterns.RESIDUAL_ADD.value,
+ RematRegexSavePatterns.MLP_RESIDUAL.value, | Same here |
axlearn | github_2023 | python | 898 | apple | hanzhi713 | @@ -417,6 +418,36 @@ def get_trainer_kwargs(
"gpu-(p5.48xlarge|p4de.24xlarge)-(512|1024)",
mesh_shape_from_axes(data=-1, fsdp=128),
),
+ (
+ "neuron-(trn2|trn2n).48xlarge-64",
+ ChainConfigModifier.default_config().set(
+ config_modifiers=[
+ MeshShapeModifier.default_config().set(
+ mesh_shape=mesh_shape_from_axes(fsdp=-1, model=4)
+ ),
+ RematSpecModifier.default_config().set(
+ remat_policies={
+ "model.decoder.transformer.layer": RematSpec(
+ prevent_cse=True,
+ policy=config_for_function(
+ _save_and_offload_only_these_names_regex
+ ).set(
+ names_which_can_be_saved="|".join(
+ [
+ RematRegexSavePatterns.QKV_PROJ.value,
+ RematRegexSavePatterns.LINEAR1_X.value, | How is this different from `dots_saveable`? |
axlearn | github_2023 | python | 898 | apple | kelvin-zou | @@ -3956,15 +3956,19 @@ def policy(prim, *_, **params):
return policy
-SELF_ATTENTION_SAVE_PATTERN = ".*([qkvo]_proj|context)"
-FEED_FORWARD_SAVE_PATTERN = ".*linear[12]_.*"
+# Regex patterns for matching remat names
+class RematRegexSavePatterns(enum.Enum):
+ QKV_PROJ = r".*\.?(k|q|v)_proj"
+ LINEAR1_X = r".*\.?linear1_[01]"
+ SELF_ATTENTION = ".*([qkvo]_proj|context)"
+ FEED_FORWARD = ".*linear[12]_.*" | Hmm, can we make the regex more composable, e.g., seems like `QKV_PROJ` is a subset of `SELF_ATTENTION`, and `LINEAR1_X` is a subset of `FEED_FORWARD`. Otherwise, we may get into an exponential number of save patterns.
You can try to build something similar to the following.
```suggestion
class RematRegexSavePatterns(enum.Enum):
QKV_PROJ = r".*\.?(k|q|v)_proj"
O_PROJ=r".*o_proj"
CONTEXT=".*context"
SELF_ATTENTION = re.compile( '|'.join( [O_PROJ,QKV_PROJ, CONTEXT]) )
``` |
axlearn | github_2023 | python | 898 | apple | hanzhi713 | @@ -3956,15 +3956,22 @@ def policy(prim, *_, **params):
return policy
-SELF_ATTENTION_SAVE_PATTERN = ".*([qkvo]_proj|context)"
-FEED_FORWARD_SAVE_PATTERN = ".*linear[12]_.*"
+# Regex patterns for matching remat names
+class RematRegexSavePatterns(enum.Enum):
+ QKV_PROJ = r".*[kqv]_proj"
+ O_PROJ = r".*o_proj"
+ CONTEXT = r".*context"
+ LINEAR1_X = r".*linear1_[01]"
+ LINEAR2_X = r".*linear2_[01]"
+ SELF_ATTENTION = re.compile("|".join([QKV_PROJ, O_PROJ, CONTEXT])).pattern | ```suggestion
SELF_ATTENTION = ".*([qkvo]_proj|context)"
```
We prefer keeping this unchanged to avoid updating golden config. |
axlearn | github_2023 | python | 898 | apple | kelvin-zou | @@ -3901,6 +3901,70 @@ def f(x, layer_params):
5,
)
+ def test_build_remat_spec_neuron(self):
+ model_dim, num_heads = 6, 2
+ cfg: TransformerLayer.Config = TransformerLayer.default_config().set(input_dim=model_dim)
+ cfg.self_attention.attention.set(num_heads=num_heads, causal=True)
+ cfg.feed_forward.hidden_dim = model_dim * 4
+ cfg.vlog = 5
+
+ layer: BaseTransformerLayer = cfg.clone(name="layer").instantiate(parent=None)
+ layer_params = layer.initialize_parameters_recursively(prng_key=jax.random.PRNGKey(0))
+
+ batch_size, tgt_len = 2, 5
+ rng = np.random.default_rng(seed=123)
+ target = rng.random([batch_size, tgt_len, cfg.input_dim], dtype=np.float32)
+
+ def f(x, layer_params):
+ forward_outputs, _ = F(
+ layer,
+ inputs=dict(
+ data=x,
+ ),
+ state=layer_params,
+ is_training=True,
+ prng_key=jax.random.PRNGKey(0),
+ )
+ return forward_outputs
+
+ # Ignore type errors.
+ spec: Any = build_remat_spec(mock.MagicMock())
+
+ policy = (
+ config_for_function(_save_and_offload_only_these_names_regex) | Can you use the one in utils.py instead? |
axlearn | github_2023 | python | 898 | apple | kelvin-zou | @@ -19,14 +19,15 @@
from axlearn.common import causal_lm, config
from axlearn.common.attention import (
- SELF_ATTENTION_SAVE_PATTERN,
BaseStackedTransformerLayer,
FusedGroupedQKVLinear,
FusedQKVLinear,
GroupedQueryAttention,
MultiheadAttention,
+ RematRegexSavePatterns,
RepeatedTransformerLayer,
RoFormerQKVLinear,
+ _save_and_offload_only_these_names_regex, | `_*` functions should not be imported, use the one in utils.py instead please. |
axlearn | github_2023 | python | 898 | apple | kelvin-zou | @@ -58,14 +57,15 @@
PipelinedTransformerLayer,
QKVLinear,
QLinear,
+ RematRegexSavePatterns,
RepeatedTransformerLayer,
RoFormerQKVLinear,
StackedTransformerLayer,
TransformerAttentionLayer,
TransformerFeedForwardLayer,
TransformerLayer,
_next_power_of_two,
- _save_and_offload_only_these_names_regex,
+ save_and_offload_only_these_names_regex, | Remove this one as well? |
axlearn | github_2023 | python | 898 | apple | kelvin-zou | @@ -3901,6 +3902,70 @@ def f(x, layer_params):
5,
)
+ def test_build_remat_spec_neuron(self):
+ model_dim, num_heads = 6, 2
+ cfg: TransformerLayer.Config = TransformerLayer.default_config().set(input_dim=model_dim)
+ cfg.self_attention.attention.set(num_heads=num_heads, causal=True)
+ cfg.feed_forward.hidden_dim = model_dim * 4
+ cfg.vlog = 5
+
+ layer: BaseTransformerLayer = cfg.clone(name="layer").instantiate(parent=None)
+ layer_params = layer.initialize_parameters_recursively(prng_key=jax.random.PRNGKey(0))
+
+ batch_size, tgt_len = 2, 5
+ rng = np.random.default_rng(seed=123)
+ target = rng.random([batch_size, tgt_len, cfg.input_dim], dtype=np.float32)
+
+ def f(x, layer_params):
+ forward_outputs, _ = F(
+ layer,
+ inputs=dict(
+ data=x,
+ ),
+ state=layer_params,
+ is_training=True,
+ prng_key=jax.random.PRNGKey(0),
+ )
+ return forward_outputs
+
+ # Ignore type errors.
+ spec: Any = build_remat_spec(mock.MagicMock())
+
+ policy = (
+ config_for_function(save_and_offload_only_these_names_regex)
+ .set(
+ names_which_can_be_saved="|".join(
+ [
+ RematRegexSavePatterns.QKV_PROJ.value,
+ RematRegexSavePatterns.LINEAR1_X.value,
+ ]
+ ),
+ names_which_can_be_offloaded=None,
+ offload_src=None,
+ offload_dst=None,
+ )
+ .instantiate()
+ )
+
+ _, default_policy_backward = jax.linearize(
+ jax.remat(f, policy=policy, prevent_cse=spec.prevent_cse),
+ jnp.asarray(target),
+ layer_params,
+ )
+ _, full_remat_backward = jax.linearize(
+ jax.remat(f),
+ jnp.asarray(target),
+ layer_params,
+ )
+
+ # Eliminated the remat of qkv_proj and linear1_0 = 4 dots. This assumes
+ # FlashAttention is not enabled. | Does flash attention play any role here? They should have the same diff w or w/o flash? |
axlearn | github_2023 | others | 917 | apple | ruomingp | @@ -5,19 +5,13 @@ ARG BASE_IMAGE=python:3.10-slim
FROM ${BASE_IMAGE} AS base
-RUN apt-get update
-RUN apt-get install -y apt-transport-https ca-certificates gnupg curl gcc g++
+RUN apt-get update && apt-get install -y curl gnupg | Can you explain this change? Is it about running `apt-get update &&` before *every* `apt-get install`? Why isn't it enough to run `apt-get update` once in the beginning? |
axlearn | github_2023 | others | 917 | apple | markblee | @@ -5,19 +5,14 @@ ARG BASE_IMAGE=python:3.10-slim
FROM ${BASE_IMAGE} AS base
-RUN apt-get update
-RUN apt-get install -y apt-transport-https ca-certificates gnupg curl gcc g++
+# Install curl and gpupg first so that we can use them to install google-cloud-cli.
+RUN apt-get update && apt-get install -y curl gnupg
-# Install git.
-RUN apt-get install -y git
-
-# Install gcloud. https://cloud.google.com/sdk/docs/install
RUN echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list && \
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | gpg --dearmor -o /usr/share/keyrings/cloud.google.gpg && \
- apt-get update -y && apt-get install google-cloud-cli -y
-
-# Install screen and other utils for launch script.
-RUN apt-get install -y jq screen ca-certificates
+ apt-get update -y && \
+ apt-get install -y apt-transport-https ca-certificates gcc g++ \
+ git screen ca-certificates google-perftools google-cloud-cli | Was it intentional to install `google-perftools` for all targets rather than just the tpu/gpu ones? If the PR is intended to just fix the apt install, do we need this change? |
axlearn | github_2023 | python | 923 | apple | ruomingp | @@ -211,15 +227,18 @@ def forward(self, input: Tensor) -> Tensor:
"""Generate the parameters for modulation.
Args:
- input: A tensor with shape [batch_size, ..., dim].
+ input: A tensor with shape [batch_size, dim] or [batch_size, num_length, dim].
Returns:
A list of tensors with length num_outputs.
- Each tensor has shape [batch_size, ..., dim].
+ Each tensor has shape [batch_size, 1|num_length, dim].
"""
cfg = self.config
x = get_activation_fn(cfg.activation)(input)
output = self.linear(x)
+ assert output.ndim in (2, 3) | Raise a ValueError instead of `assert` (which should only be used to enforce internal logic errors and cannot be triggered by user error). |
axlearn | github_2023 | python | 920 | apple | markblee | @@ -59,6 +59,28 @@ class BaseAttentionBias:
# If None, do not cast the dtype.
dtype: Optional[jnp.dtype] = struct.field(kw_only=True, default=None, pytree_node=False)
+ @final
+ def eval_shape(self) -> tuple[int, int, int, int]:
+ """Return the shape of the bias tensor.
+
+ Note: this doesn't materialize the value. jax.eval_shape calls value(), but it only does so
+ using tracers.
+
+ Returns
+ shape: [batch or 1, num_heads or 1, target_len, source_len].
+
+ Raises:
+ ValueError: If the bias has no value.
+ """
+ if not self.has_value(): | I suppose multiple calls to jax.eval_shape are automatically cached? |
axlearn | github_2023 | python | 912 | apple | samos123 | @@ -98,13 +100,14 @@ def default_xla_options(
xla_tpu_use_enhanced_launch_barrier="true",
# Sparsecore offloading for all reduce.
# Uncomment below flags to enable it.
- # xla_sc_disable_megacore_partitioning="true",
- # xla_tpu_use_tc_device_shape_on_sc="true",
- # tpu_use_continuations="true",
- # xla_jf_crs_combiner_threshold_count=10,
- # xla_sc_enable_instruction_fusion="false",
- # xla_sc_disjoint_spmem="false",
- # xla_tpu_enable_sparse_core_collective_offload_all_reduce="true",
+ xla_sc_disable_megacore_partitioning="true",
+ xla_tpu_use_tc_device_shape_on_sc="true",
+ tpu_use_continuations="true",
+ xla_sc_enable_instruction_fusion="false",
+ xla_sc_disjoint_spmem="false",
+ xla_tpu_enable_sparse_core_collective_offload_all_reduce="true",
+ # TODO(kelvinzou): temporary workaround to avoid memory leak in megascale.
+ megascale_grpc_enable_xor_tracer="false", | current plan is to release a fix in jax 0.4.39 which is planned for Jan 15. The fix is in libtpu. |
axlearn | github_2023 | python | 566 | apple | ruomingp | @@ -1193,6 +1193,10 @@ def create_device_mesh(
logging.warning("Falling back to ICI-only mesh on GPU, performance may be reduced.")
return build_standard_mesh(mesh_shape, devices=devices)
+ # Neuron also only uses standard mesh
+ if device_platform == "neuron":
+ return build_standard_mesh(mesh_shape, devices=devices) | Could we change L1179 to
```
attr = "process_index" if device_platform == "gpu" else "slice_index"
```
Then `is_multi_granule_env = hasattr(devices[0], attr)` will be False for "neuron", which probably is more consistent since we want to consider it to be a single-granule mesh? |
axlearn | github_2023 | python | 566 | apple | ruomingp | @@ -167,6 +167,10 @@ def get_trainer_kwargs(
"gpu-(p5.48xlarge|p4de.24xlarge)-(256|512|1024)",
mesh_shape_from_axes(data=-1, fsdp=8),
),
+ (
+ "neuron-(trn1.32xlarge|trn1n.32xlarge)-(32|64|256|512|1024|2048)",
+ mesh_shape_from_axes(data=-1, model=TRN_MODEL_AXIS_SIZE), | How does `model=8` compare to `fsdp=8`? Usually we find fsdp to be more efficient. |
axlearn | github_2023 | python | 566 | apple | kelvin-zou | @@ -267,12 +269,17 @@ def model_config(
batch_axis_names=batch_axis_names,
seq_axis_names="seq",
)
+
+ device_platform = np.asarray(jax.devices())[0].platform
+ # neuron uses Zero 3
+ fsdp_axis_names = ("expert", "fsdp", "seq") if device_platform != 'neuron' else ("data", "expert", "fsdp", "seq") | Does trn support fsdp?
If so why is this change needed? if not (at least according to our discussion), should you set it to 1 here? |
axlearn | github_2023 | python | 566 | apple | markblee | @@ -83,6 +83,7 @@ class Version(enum.Enum):
},
}
+TRN_MODEL_AXIS_SIZE=8 | Do we need a public const for this? |
axlearn | github_2023 | python | 566 | apple | markblee | @@ -267,12 +269,17 @@ def model_config(
batch_axis_names=batch_axis_names,
seq_axis_names="seq",
)
+
+ device_platform = np.asarray(jax.devices())[0].platform
+ # neuron uses Zero 3 | nit -- Comments should be full sentences with punctuation. |
axlearn | github_2023 | python | 566 | apple | markblee | @@ -267,12 +269,17 @@ def model_config(
batch_axis_names=batch_axis_names,
seq_axis_names="seq",
)
+
+ device_platform = np.asarray(jax.devices())[0].platform | `jax.devices()` during config building may be an unexpected dependency on global state -- should we take a `platform` arg or similar? |
axlearn | github_2023 | python | 885 | apple | ruomingp | @@ -174,6 +176,12 @@ def get_trainer_kwargs(
train_batch_size=train_batch_size,
max_step=max_step,
mesh_shape=mesh_shape_from_axes(data=-1, fsdp=8),
+ mesh_rules=(
+ (
+ "neuron-(trn2|trn2n).48xlarge-64",
+ mesh_shape_from_axes(fsdp=-1, model=4), | Comment on why we set `model=4` for neuron? |
axlearn | github_2023 | python | 885 | apple | ruomingp | @@ -473,7 +504,9 @@ def model_config(
ffn_dim = scaled_hidden_dim(scale=8 / 3, round_up_to_multiples_of=256)
if num_kv_heads:
atten_cfg = GroupedQueryAttention.default_config()
- atten_input_linear = FusedGroupedQKVLinear.default_config().set(num_kv_heads=num_kv_heads)
+ backend = jax.default_backend() | The fuji config should not depend on `jax.default_backend()`, otherwise the golden configs will not reflect the actual config being used.
Instead, we can create separate configs for a backend that requires different settings. |
axlearn | github_2023 | python | 885 | apple | ruomingp | @@ -417,12 +443,17 @@ def get_trainer_kwargs(
"gpu-(p5.48xlarge|p4de.24xlarge)-(512|1024)",
mesh_shape_from_axes(data=-1, fsdp=128),
),
+ (
+ "neuron-(trn2|trn2n).48xlarge-64",
+ mesh_shape_from_axes(fsdp=-1, model=4),
+ ),
),
)
else:
raise NotImplementedError(f"Unknown model size {model_size}.")
model_kwargs = trainer_kwargs.pop("model_kwargs")
model_kwargs.setdefault("vocab_size", vocab_size)
+ model_kwargs.setdefault("stack_cfg", None if backend != "neuron" else StackedTransformerLayer.default_config()) | Will the use of `StackedTransformerLayer` (vs. `RepeatedTransformerLayer`) lead to large XLA programs and long compilation time? |
axlearn | github_2023 | others | 542 | apple | madrob | @@ -0,0 +1,61 @@
+name: Build and Test
+
+on:
+ push:
+ branches:
+ - main
+ pull_request:
+
+jobs:
+ pre-commit:
+ runs-on: ubuntu-latest
+ outputs:
+ matrix: ${{ steps.set-matrix.outputs.matrix }}
+
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.9"
+ cache: "pip"
+ - name: Install Dependencies
+ run: |
+ python -m pip install --upgrade pip
+ # TODO(markblee): Remove gcp,vertexai_tensorboard from CI. (needed by pytype)
+ pip install '.[dev,gcp,vertexai_tensorboard]'
+ - name: Run pre-commit
+ run: pre-commit run --all-files
+ - name: Run pytype
+ run: pytype -j auto .
+
+ set-matrix:
+ runs-on: ubuntu-latest
+ outputs:
+ matrix: ${{ steps.set-matrix.outputs.matrix }}
+ steps:
+ - uses: actions/checkout@v3
+ - name: define pytest testing matrix
+ id: set-matrix
+ run: |
+ echo "matrix=$(python3 .github/workflows/set_matrix.py)" >> $GITHUB_OUTPUT
+
+ build-and-test:
+ needs: set-matrix
+ runs-on: ubuntu-latest
+ strategy:
+ matrix: ${{ fromJson(needs.set-matrix.outputs.matrix) }}
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v1
+ - uses: docker/setup-buildx-action@v3 | Is this right that we set up twice? |
axlearn | github_2023 | others | 542 | apple | madrob | @@ -0,0 +1,61 @@
+name: Build and Test
+
+on:
+ push:
+ branches:
+ - main
+ pull_request:
+
+jobs:
+ pre-commit:
+ runs-on: ubuntu-latest
+ outputs:
+ matrix: ${{ steps.set-matrix.outputs.matrix }}
+
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.9"
+ cache: "pip"
+ - name: Install Dependencies
+ run: |
+ python -m pip install --upgrade pip
+ # TODO(markblee): Remove gcp,vertexai_tensorboard from CI. (needed by pytype)
+ pip install '.[dev,gcp,vertexai_tensorboard]'
+ - name: Run pre-commit
+ run: pre-commit run --all-files
+ - name: Run pytype
+ run: pytype -j auto .
+
+ set-matrix:
+ runs-on: ubuntu-latest
+ outputs:
+ matrix: ${{ steps.set-matrix.outputs.matrix }}
+ steps:
+ - uses: actions/checkout@v3
+ - name: define pytest testing matrix
+ id: set-matrix
+ run: |
+ echo "matrix=$(python3 .github/workflows/set_matrix.py)" >> $GITHUB_OUTPUT
+
+ build-and-test: | Is there a way to set the name here to something nicer than the list of files? I'm imagining `build-and-test (1/10)` and then first step can be to echo list of files to output for debugging later? |
axlearn | github_2023 | python | 909 | apple | ruomingp | @@ -781,6 +782,21 @@ class Embedding(BaseLayer):
Batched map for int in [0, <num_embeddings>) -> <dim> float vector.
"""
+ class Scale(enum.Enum):
+ """Defines the scale method on embedding activations.
+
+ Available types:
+ 1. **UNIT**: Scale the activation components to ~1.
+
+ The activation component should roughly have a magnitude of 1. Since the embedding tensor is
+ initialized with a scale of `1/√dim`, the activation is multiplied by `√dim` to
+ maintain the desired scale. e.g. Gemma [1]
+ [1]
+ https://github.com/google-deepmind/gemma/blob/0d6ae857591248422127ca14c027909546362e6a/gemma/modules.py#L80
+ """
+
+ UNIT = 1 | Nit: use str values to be more readable.
```suggestion
UNIT = "unit"
``` |
axlearn | github_2023 | python | 887 | apple | Ethanlm | @@ -55,11 +110,20 @@ def default_xla_options(
xla_tpu_data_parallel_opt_different_sized_ops="true",
# Group non-blocking DCN collectives into as few stages as possible.
xla_tpu_enable_sunk_dcn_allreduce_done_with_host_reduction="true",
+ # Change to 16GB. The default is 4GB which is too small for larger models. This
+ # cause the step time to be double. You should increase this
+ # further if you see "Allocator failed to allocate". A feature
+ # to dynamically allocate may come later: b/380514965
+ megascale_grpc_premap_memory_bytes=17179869184, | This will affect all jobs. Is it a desired change? Should we limit it to v6e only? |
axlearn | github_2023 | python | 887 | apple | Ethanlm | @@ -44,6 +44,61 @@ def default_xla_options(
xla_enable_async_all_gather="true", # Allow async all-gather.
xla_enable_async_collective_permute="true", # Allow async collective permute.
)
+ if version == "v6e":
+ options.update(
+ # Improved performance for v6e.
+ xla_tpu_scoped_vmem_limit_kib=98304,
+ xla_tpu_enable_async_collective_fusion="true",
+ xla_tpu_enable_async_collective_fusion_fuse_all_gather="true",
+ xla_tpu_enable_async_collective_fusion_multiple_steps="true",
+ xla_tpu_overlap_compute_collective_tc="true",
+ xla_enable_async_all_gather="true",
+ # Host offloading flags
+ xla_tpu_enable_all_experimental_scheduler_features="true",
+ # Flag to enable memory tracking scheduling. The default AUTO only enables
+ # it in some situations. Not needed if
+ # xla_tpu_enable_all_experimental_scheduler_features is set to true already.
+ xla_tpu_enable_scheduler_memory_pressure_tracking="true",
+ # Flag controlling the maximum number of overlapping host offloadings.
+ xla_tpu_host_transfer_overlap_limit=24,
+ # Flag to enable the aggressive removal of opt-barriers.
+ xla_tpu_aggressive_opt_barrier_removal="true",
+ # Flag to enable more aggressive scheduling for async ops, such as pushing
+ # the async start to the beginning of the loop body.
+ xla_lhs_prioritize_async_depth_over_stall="true",
+ # Flag to enable pipelining of cross-DCN all-gathers.
+ xla_tpu_enable_ag_backward_pipelining="true",
+ xla_should_allow_loop_variant_parameter_in_chain="true",
+ xla_should_add_loop_invariant_op_in_chain="true",
+ # Flag controlling the maximum number of overlapping cross-DCN send/recv.
+ xla_max_concurrent_host_send_recv=100,
+ # Flag controlling the HBM memory limit as a percentage of the total HBM size.
+ # Default value is 95. Can tune up or down to give more or less memory for the
+ # scheduler. The scheduler favors more on less memory usage when it's under
+ # memory pressure, instead of hiding latency by overlapping more computations
+ # and communications.
+ xla_tpu_scheduler_percent_shared_memory_limit=90,
+ # Flag controlling the number of times the scheduler is run if the scheduled
+ # peak memory usage exceeds the initial memory limit, by setting memory limit
+ # to 90% of the previous memory limit each time. Default value is 1. Sometimes
+ # when the scheduler thinks it goes out memory, it may not actually happen due
+ # to other factors controlled by other compiler passes, or the initial memory
+ # limit is already set too low. Cutting the memory limit to 90% of previous one
+ # though, may make the scheduler weighting too much on the memory usage instead
+ # of latency side.
+ xla_latency_hiding_scheduler_rerun=2,
+ xla_tpu_use_enhanced_launch_barrier="true",
+ # Sparsecore offloading for all reduce.
+ # Uncomment below flags to enable it.
+ # xla_sc_disable_megacore_partitioning="true",
+ # xla_tpu_use_tc_device_shape_on_sc="true",
+ # tpu_use_continuations="true",
+ # xla_jf_crs_combiner_threshold_count=10,
+ # xla_sc_enable_instruction_fusion="false",
+ # xla_sc_disjoint_spmem="false",
+ # xla_tpu_enable_sparse_core_collective_offload_all_reduce="true",
+ )
+ options["2a886c8_chip_config_name"] = "megachip_tccontrol" | I remember this is only required for sparsecore offloading. If so, should we disable it by default? |
axlearn | github_2023 | python | 887 | apple | Ethanlm | @@ -31,7 +31,7 @@ def default_xla_options(
if backend != "tpu":
raise NotImplementedError(backend)
version = infer_tpu_version(infer_tpu_type(instance_type))
- options = dict(
+ options: Dict[str, int | str | bool] = dict( | ```
File "/home/runner/work/axlearn/axlearn/axlearn/common/compiler_options.py", line 34, in default_xla_options: Invalid type annotation 'Dict[str, int | str | bool]' [invalid-annotation]
Missing parameter 'y' in call to function int.__or__
Expected: (self, y)
Actually passed: (self)
File "/home/runner/work/axlearn/axlearn/axlearn/common/compiler_options.py", line 48, in default_xla_options: Function dict.update was called with the wrong arguments [wrong-arg-types]
Expected: (self, megascale_grpc_premap_memory_bytes, xla_enable_async_all_gather: int, ...)
Actually passed: (self, megascale_grpc_premap_memory_bytes, xla_enable_async_all_gather: str, ...)
``` |
axlearn | github_2023 | python | 887 | apple | Ethanlm | @@ -44,6 +44,68 @@ def default_xla_options(
xla_enable_async_all_gather="true", # Allow async all-gather.
xla_enable_async_collective_permute="true", # Allow async collective permute.
)
+ if version == "v6e":
+ options.update(
+ # Change to 16GB. The default is 4GB which is too small for larger models. This
+ # cause the step time to be double. You should increase this
+ # further if you see "Allocator failed to allocate". A feature
+ # to dynamically allocate may come later: b/380514965
+ megascale_grpc_premap_memory_bytes=17179869184,
+ # Improved performance for v6e.
+ xla_tpu_scoped_vmem_limit_kib=98304,
+ xla_tpu_enable_async_collective_fusion=True,
+ xla_tpu_enable_async_collective_fusion_fuse_all_gather=True, | Needs These need to be "true" instead of `True`, otherwise it will be converted to 1 by `xla_flags_from_options ` and then fail
```
I1212 21:41:11.645763 132689403348992 launch.py:112] LIBTPU_INIT_ARGS='--xla_tpu_spmd_rng_bit_generator_unsafe=1 --xla_tpu_enable_latency_hiding_scheduler=true --xla_tpu_perform_spmd_cse_prevention=false --megascale_grpc_premap_memory_bytes=17179869184 --xla_tpu_scoped_vmem_limit_kib=98304 --xla_tpu_enable_async_collective_fusion=1 --xla_tpu_enable_async_collective_fusion_fuse_all_gather=1 --xla_tpu_enable_async_collective_fusion_multiple_steps=1 --xla_tpu_overlap_compute_collective_tc=1 --xla_enable_async_all_gather=1 --xla_tpu_enable_all_experimental_scheduler_features=1 --xla_tpu_enable_scheduler_memory_pressure_tracking=1 --xla_tpu_host_transfer_overlap_limit=24 --xla_tpu_aggressive_opt_barrier_removal=1 --xla_lhs_prioritize_async_depth_over_stall=1 --xla_tpu_enable_ag_backward_pipelining=1 --xla_should_allow_loop_variant_parameter_in_chain=1 --xla_should_add_loop_invariant_op_in_chain=1 --xla_max_concurrent_host_send_recv=100 --xla_tpu_scheduler_percent_shared_memory_limit=90 --xla_latency_hiding_scheduler_rerun=2 --xla_tpu_use_enhanced_launch_barrier=1'
2024-12-12 21:41:14.669321: I external/tsl/tsl/platform/default/grpc_credentials.cc:30] gRPC insecure client credentials are used.
I1212 21:41:14.670917 132689403348992 distributed.py:119] Connecting to JAX distributed service on ethanli-fuji-70b-v2-test1-job-0-0.ethanli-fuji-70b-v2-test1:8476
2024-12-12 21:41:14.999583: I external/xla/xla/pjrt/distributed/client.cc:135] Connected to distributed JAX controller
ERROR: Illegal value '1' specified for flag 'xla_tpu_enable_async_collective_fusion_fuse_all_gather'; expected one of true/enabled, false/disabled or auto
ERROR: Illegal value '1' specified for flag 'xla_enable_async_all_gather'; expected one of true/enabled, false/disabled or auto
ERROR: Illegal value '1' specified for flag 'xla_tpu_enable_scheduler_memory_pressure_tracking'; expected one of true/enabled, false/disabled or auto
ERROR: Illegal value '1' specified for flag 'xla_tpu_aggressive_opt_barrier_removal'; expected one of true/enabled, false/disabled or auto
ERROR: Illegal value '1' specified for flag 'xla_lhs_prioritize_async_depth_over_stall'; expected one of true/enabled, false/disabled or auto
ERROR: Illegal value '1' specified for flag 'xla_should_allow_loop_variant_parameter_in_chain'; expected one of true/enabled, false/disabled or auto
ERROR: Illegal value '1' specified for flag 'xla_should_add_loop_invariant_op_in_chain'; expected one of true/enabled, false/disabled or auto
``` |
axlearn | github_2023 | python | 887 | apple | kelvin-zou | @@ -44,6 +44,68 @@ def default_xla_options(
xla_enable_async_all_gather="true", # Allow async all-gather.
xla_enable_async_collective_permute="true", # Allow async collective permute.
)
+ if version == "v6e":
+ options.update(
+ # Change to 16GB. The default is 4GB which is too small for larger models. This
+ # cause the step time to be double. You should increase this
+ # further if you see "Allocator failed to allocate". A feature
+ # to dynamically allocate may come later: b/380514965
+ megascale_grpc_premap_memory_bytes=17179869184,
+ # Improved performance for v6e.
+ xla_tpu_scoped_vmem_limit_kib=98304,
+ xla_tpu_enable_async_collective_fusion=True,
+ xla_tpu_enable_async_collective_fusion_fuse_all_gather=True,
+ xla_tpu_enable_async_collective_fusion_multiple_steps=True,
+ xla_tpu_overlap_compute_collective_tc=True,
+ xla_enable_async_all_gather=True,
+ # Host offloading flags
+ xla_tpu_enable_all_experimental_scheduler_features=True,
+ # Flag to enable memory tracking scheduling. The default AUTO only enables
+ # it in some situations. Not needed if
+ # xla_tpu_enable_all_experimental_scheduler_features is set to true already.
+ xla_tpu_enable_scheduler_memory_pressure_tracking=True,
+ # Flag controlling the maximum number of overlapping host offloadings.
+ xla_tpu_host_transfer_overlap_limit=24,
+ # Flag to enable the aggressive removal of opt-barriers.
+ xla_tpu_aggressive_opt_barrier_removal=True,
+ # Flag to enable more aggressive scheduling for async ops, such as pushing
+ # the async start to the beginning of the loop body.
+ xla_lhs_prioritize_async_depth_over_stall=True,
+ # Flag to enable pipelining of cross-DCN all-gathers.
+ xla_tpu_enable_ag_backward_pipelining=True,
+ xla_should_allow_loop_variant_parameter_in_chain=True,
+ xla_should_add_loop_invariant_op_in_chain=True,
+ # Flag controlling the maximum number of overlapping cross-DCN send/recv.
+ xla_max_concurrent_host_send_recv=100,
+ # Flag controlling the HBM memory limit as a percentage of the total HBM size.
+ # Default value is 95. Can tune up or down to give more or less memory for the
+ # scheduler. The scheduler favors more on less memory usage when it's under
+ # memory pressure, instead of hiding latency by overlapping more computations
+ # and communications.
+ xla_tpu_scheduler_percent_shared_memory_limit=90,
+ # Flag controlling the number of times the scheduler is run if the scheduled
+ # peak memory usage exceeds the initial memory limit, by setting memory limit
+ # to 90% of the previous memory limit each time. Default value is 1. Sometimes
+ # when the scheduler thinks it goes out memory, it may not actually happen due
+ # to other factors controlled by other compiler passes, or the initial memory
+ # limit is already set too low. Cutting the memory limit to 90% of previous one
+ # though, may make the scheduler weighting too much on the memory usage instead
+ # of latency side.
+ xla_latency_hiding_scheduler_rerun=2,
+ xla_tpu_use_enhanced_launch_barrier=True,
+ # Sparsecore offloading for all reduce.
+ # Uncomment below flags to enable it.
+ # xla_sc_disable_megacore_partitioning=True, | @Ethanlm do you recall why you commented all them off? |
axlearn | github_2023 | python | 882 | apple | chongw | @@ -1252,6 +1278,7 @@ class Config(BaseQKVLinear.Config):
RoFormerSinusoidalPositionalEmbedding.default_config()
)
input_linear: BaseQKVLinear.Config = QKVLinear.default_config()
+ rotary_key: bool = True | nit: add a comment for the rotary_key ? |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -3315,6 +3335,21 @@ def set_ffn_partition_specs(ff_layer: TransformerFeedForwardLayer.Config):
set_attn_partition_specs(layer_cfg.cross_attention.attention)
if isinstance(layer_cfg.feed_forward, TransformerFeedForwardLayer.Config):
set_ffn_partition_specs(layer_cfg.feed_forward)
+
+ # Neuron backend needs fine grained activation sharding.
+ if jax.default_backend() == 'neuron': | As commented on another PR, we should not generate configs based on `jax.default_backend()`. Instead, we can add a separate function that sets finegrain partition specs. |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -2708,6 +2718,13 @@ class Config(BaseLayer.Config):
# TODO(tlei3): deprecate this feature since we use TensorStats.
add_value_rms_norm_summary: Sequence[str] = []
+ # If not None, how to partition pre norm activation values.
+ prenorm_partition_spec: Optional[tuple[Optional[str]]] = None
+ # If not None, how to partition pre MLP activation values.
+ premlp_partition_spec: Optional[tuple[Optional[str]]] = None
+ # If not None, how to partition post MLP activation values.
+ postmlp_partition_spec: Optional[tuple[Optional[str]]] = None | How is this different from setting `linear2.output_partition_spec`? https://github.com/apple/axlearn/blob/2134a258a869f679e4dd2625565a2ca693126495/axlearn/common/layers.py#L664 |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -2771,11 +2788,14 @@ def _linear2(x):
remat_pt2 = "linear2"
if cfg.structure == "prenorm":
+ inputs = maybe_shard(inputs, cfg.prenorm_partition_spec) | Applying it on inputs regardless of `cfg.structure` would be more consistent. If we do so, we should call it `input_partition_spec`. |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -2771,11 +2788,14 @@ def _linear2(x):
remat_pt2 = "linear2"
if cfg.structure == "prenorm":
+ inputs = maybe_shard(inputs, cfg.prenorm_partition_spec)
x = self.norm(inputs)
+ x = maybe_shard(x, cfg.premlp_partition_spec) | Do we need this? I suppose `norm` usually does not change the partition spec? |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -2355,6 +2356,12 @@ class Config(BaseLayer.Config):
# Ref: https://github.com/google/praxis/blob/main/praxis/layers/transformers.py#L1129
# TODO (bwzhang@) Adding a unittest for the hybridnorm.
structure: str = "prenorm"
+ # If not None, how to partition pre norm activation values.
+ prenorm_partition_spec: Optional[tuple[Optional[str]]] = None
+ # If not None, how to partition pre attention activation values.
+ preattention_partition_spec: Optional[tuple[Optional[str]]] = None
+ # If not None, how to partition post attention activation values.
+ postattention_partition_spec: Optional[tuple[Optional[str]]] = None | How is this different from setting https://github.com/apple/axlearn/blob/2134a258a869f679e4dd2625565a2ca693126495/axlearn/common/attention.py#L3319? |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -2355,6 +2356,12 @@ class Config(BaseLayer.Config):
# Ref: https://github.com/google/praxis/blob/main/praxis/layers/transformers.py#L1129
# TODO (bwzhang@) Adding a unittest for the hybridnorm.
structure: str = "prenorm"
+ # If not None, how to partition pre norm activation values.
+ prenorm_partition_spec: Optional[tuple[Optional[str]]] = None | Please see my comment about `input_partition_spec` below. |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -2355,6 +2356,12 @@ class Config(BaseLayer.Config):
# Ref: https://github.com/google/praxis/blob/main/praxis/layers/transformers.py#L1129
# TODO (bwzhang@) Adding a unittest for the hybridnorm.
structure: str = "prenorm"
+ # If not None, how to partition pre norm activation values.
+ prenorm_partition_spec: Optional[tuple[Optional[str]]] = None
+ # If not None, how to partition pre attention activation values.
+ preattention_partition_spec: Optional[tuple[Optional[str]]] = None | ditto. |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -3315,6 +3335,21 @@ def set_ffn_partition_specs(ff_layer: TransformerFeedForwardLayer.Config):
set_attn_partition_specs(layer_cfg.cross_attention.attention)
if isinstance(layer_cfg.feed_forward, TransformerFeedForwardLayer.Config):
set_ffn_partition_specs(layer_cfg.feed_forward)
+
+ # Neuron backend needs fine grained activation sharding.
+ if jax.default_backend() == 'neuron':
+ prenorm_partition_spec = (fsdp_axis_names, tp_axis_names, None)
+ preattention_partition_spec = (fsdp_axis_names, None, None)
+ postattention_partition_spec = (fsdp_axis_names, tp_axis_names, None)
+
+ layer_cfg.self_attention.set(
+ prenorm_partition_spec=prenorm_partition_spec,
+ preattention_partition_spec=preattention_partition_spec,
+ postattention_partition_spec=postattention_partition_spec)
+ layer_cfg.feed_forward.set(
+ prenorm_partition_spec=prenorm_partition_spec,
+ premlp_partition_spec=preattention_partition_spec,
+ postmlp_partition_spec=postattention_partition_spec) | Is `postattention_partition_spec` always the same as `prenorm_partition_spec` for `feed_forward` since the outputs of atten are used as inputs for ffn? |
axlearn | github_2023 | python | 881 | apple | kelvin-zou | @@ -814,8 +821,14 @@ def _create_layer_parameter_specs(self) -> dict[str, ParameterSpec]:
)
def forward(self, x: Tensor) -> Tensor:
+ cfg = self.config | Same question here, can we handle this inside XLA compiler directly instead of making it explicit here? Adding this kind of fine-level sharding spec is a divergence from GSPMD programming paradigm imho. |
axlearn | github_2023 | python | 881 | apple | kelvin-zou | @@ -5091,6 +5091,70 @@ def test_set_double_shard_weights_config_for_list_of_configs(
(fsdp_axis_names, tp_axis_names, None),
)
+ @parameterized.product(
+ self_attention_input_linear_cfg=(
+ QKVLinear.default_config(),
+ FusedQKVLinear.default_config(),
+ ),
+ cross_attention_cfg=(None, TransformerAttentionLayer.default_config()),
+ batch_axis_names=("data", ("replica", "data", "fsdp")),
+ fsdp_axis_names=("fsdp",),
+ tp_axis_names=("model",),
+ seq_axis_names=("seq",),
+ )
+ def test_set_activation_shardings_config_for_list_of_configs(
+ self,
+ self_attention_input_linear_cfg,
+ cross_attention_cfg,
+ batch_axis_names,
+ fsdp_axis_names,
+ tp_axis_names,
+ seq_axis_names,
+ ):
+ cfg_layer: TransformerLayer.Config = TransformerLayer.default_config().set(
+ cross_attention=cross_attention_cfg
+ )
+ cfg_layer.self_attention.structure = "prenorm"
+ cfg_layer.feed_forward.structure = "prenorm"
+ cfg_layer.self_attention.attention.input_linear = self_attention_input_linear_cfg
+ cfg_layers = [cfg_layer, cfg_layer]
+
+ cfg_layer.self_attention.prenorm_partition_spec = (fsdp_axis_names, tp_axis_names, None,) | interesting, is it the real use case you are testing nowadays? |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -444,6 +444,12 @@ def with_sharding_constraint(x, shardings):
return jax.lax.with_sharding_constraint(x, shardings)
+def maybe_shard(x, partition_spec) -> Tensor: | ```suggestion
def maybe_shard(x: Tensor, partition_spec: Optional[PartitionSpec]) -> Tensor:
``` |
axlearn | github_2023 | python | 881 | apple | ruomingp | @@ -443,6 +443,11 @@ def with_sharding_constraint(x, shardings):
return x
return jax.lax.with_sharding_constraint(x, shardings)
+def maybe_shard(x: Tensor, partition_spec: Optional[PartitionSpec]) -> Tensor: | Is `x` a `Nested[Tensor]`? |
axlearn | github_2023 | python | 691 | apple | markblee | @@ -379,6 +379,28 @@ class _SystemCharacteristics:
AcceleratorType["TPU"],
"v5litepod-256",
),
+ # v6e | Is there a reference for these? |
axlearn | github_2023 | python | 691 | apple | Ethanlm | @@ -379,6 +379,28 @@ class _SystemCharacteristics:
AcceleratorType["TPU"],
"v5litepod-256",
),
+ # v6e
+ "v6e-4": _SystemCharacteristics(
+ "2x2", 1, "tpu-v6e-slice", "ct6e-standard-4t", 4, AcceleratorType["TPU"], "v6e-4"
+ ),
+ "v6e-8": _SystemCharacteristics( | Seeing jobset-controller issue with v6e-8
```
sigs.k8s.io/controller-runtime/pkg/internal/controller.(*Controller).Start.func2.2
/go/pkg/mod/sigs.k8s.io/controller-runtime@v0.17.3/pkg/internal/controller/controller.go:227
2024-12-10T22:58:28Z ERROR Reconciler error {"controller": "jobset", "controllerGroup": "jobset.x-k8s.io", "controllerKind": "JobSet", "JobSet": {"name":"ethanli-imagenet-resnet-resnet-2024121014","namespace":"default"}, "namespace": "default", "name": "ethanli-imagenet-resnet-resnet-2024121014", "reconcileID": "946de27a-c3e8-4f44-ab5c-8e377e71e763", "error": "job \"ethanli-imagenet-resnet-resnet-2024121014-job-0\" creation failed with error: admission webhook \"warden-validating.common-webhooks.networking.gke.io\" denied the request: GKE Warden rejected the request because it violates one or more constraints.\nViolations details: {\"[denied by tpu-accelerator-topology-constraints]\":[\"Invalid resource requests for google.com/tpu. It should be equal to one of [8] for accelerator tpu-v6e-slice and topology 2x4. Please request all the tpu chips available on the node.\"]}\nRequested by user: 'system:serviceaccount:jobset-system:jobset-controller-manager', groups: 'system:serviceaccounts,system:serviceaccounts:jobset-system,system:authenticated'."}
sigs.k8s.io/controller-runtime/pkg/internal/controller.(*Controller).reconcileHandler
```
in jobset controller
I think we should remove the support until we have a fix |
axlearn | github_2023 | python | 567 | apple | kelvin-zou | @@ -499,19 +499,29 @@ def add_leaves(i, x):
return jax.tree_util.tree_unflatten(treedef, axes)
-def input_partition_spec() -> PartitionSpec:
- """Returns partition spec for the input batch.
+class DataPartitionType(Enum):
+ # Data are fully partitioned across all devices.
+ FULL = "full"
+ # Data are fully replicated across all devices.
+ REPLICATED = "replicated"
+ # Data are partially partitioned across data axis
+ DATA = "data" | A high level question, what is the purpose of this change?
I see that we have `FULL` partition support already, which partitions on axis=0 which is the data axis, how is `DATA` different from `FULL`? |
axlearn | github_2023 | python | 872 | apple | WeersProductions | @@ -219,11 +219,14 @@ def test_validate_tiers(self):
},
expected_project_limits={"a": {"v4": 5}, "b": {"v4": 5}},
expected_verdicts={"a1": True, "b1": True, "b2": True},
- expected_tiers={"a1": 0, "b1": 0, "b2": 0},
+ # The order of entries in `expected_tiers` should reflect the job priorities.
+ # Here "b1" is ahead of "a1" because it requests less resources. | ```suggestion
# Here "b1" is ahead of "a1" because it requests fewer resources.
``` |
axlearn | github_2023 | python | 872 | apple | WeersProductions | @@ -294,10 +301,12 @@ def test_validate_tiers(self):
},
expected_project_limits={"a": {"v4": 7}, "b": {"v4": 8}},
expected_verdicts={"a1": True, "b1": True, "b2": True},
- expected_tiers={"a1": 0, "b1": 0, "b2": 1},
+ # "b1" is ahead of "a1" since it requests less resource. | ```suggestion
# "b1" is ahead of "a1" since it requests fewer resources.
``` |
axlearn | github_2023 | python | 871 | apple | ruomingp | @@ -424,6 +424,27 @@ def metric_fn(
Returns:
A dictionary of metrics.
+ - number_of_examples: Total number of examples.
+ - number_of_parsing_errors: Total number of examples with parsing errors.
+ - number_of_generation_errors: Total number of examples with generation errors.
+ - accuracy: Accuracy after standardization of argument values including removing spaces,
+ punctuation, and converting to lowercases. Also apply matching rules if provided.
+ - strict_accuracy: Strict accuracy where argument values exactly matches the
+ ground truth or not.
+ - lenient_accuracy: Accuracy after removing spaces, punctuation and a static list of
+ stop words in the argument values.
+ - bow_accuracy: Bag-of-words accuracy. Transforms the argument strings in the same way
+ as the lenient matching. But instead of comparing the resulting strings it checks
+ if the words in the ground truth argument values are contained in the predicted
+ argument values.
+ - func_name_accuracy: Accuracy of matching the ground truth tool names.
+ - number_of_expected_tool_calls: Number of expected tool calls.
+ - num_func_call_intents_ground_truth: Number of assistant turns with tool calls
+ in the ground truth.
+ - num_func_call_intents_pred: Number of assistant turns with tool calls in predictions. | Please use `num_` vs. `number_of_` consistently. |
axlearn | github_2023 | python | 871 | apple | ruomingp | @@ -424,6 +424,27 @@ def metric_fn(
Returns:
A dictionary of metrics.
+ - number_of_examples: Total number of examples.
+ - number_of_parsing_errors: Total number of examples with parsing errors.
+ - number_of_generation_errors: Total number of examples with generation errors.
+ - accuracy: Accuracy after standardization of argument values including removing spaces,
+ punctuation, and converting to lowercases. Also apply matching rules if provided.
+ - strict_accuracy: Strict accuracy where argument values exactly matches the
+ ground truth or not.
+ - lenient_accuracy: Accuracy after removing spaces, punctuation and a static list of
+ stop words in the argument values.
+ - bow_accuracy: Bag-of-words accuracy. Transforms the argument strings in the same way
+ as the lenient matching. But instead of comparing the resulting strings it checks
+ if the words in the ground truth argument values are contained in the predicted
+ argument values.
+ - func_name_accuracy: Accuracy of matching the ground truth tool names.
+ - number_of_expected_tool_calls: Number of expected tool calls.
+ - num_func_call_intents_ground_truth: Number of assistant turns with tool calls
+ in the ground truth.
+ - num_func_call_intents_pred: Number of assistant turns with tool calls in predictions.
+ - func_intent_recall: Recall of tool calls intent.
+ - func_intent_precision": Precision of tool calls intent. | ```suggestion
- func_intent_precision: Precision of tool calls intent.
``` |
axlearn | github_2023 | python | 871 | apple | ruomingp | @@ -424,6 +424,27 @@ def metric_fn(
Returns:
A dictionary of metrics.
+ - number_of_examples: Total number of examples.
+ - number_of_parsing_errors: Total number of examples with parsing errors.
+ - number_of_generation_errors: Total number of examples with generation errors.
+ - accuracy: Accuracy after standardization of argument values including removing spaces,
+ punctuation, and converting to lowercases. Also apply matching rules if provided.
+ - strict_accuracy: Strict accuracy where argument values exactly matches the
+ ground truth or not.
+ - lenient_accuracy: Accuracy after removing spaces, punctuation and a static list of
+ stop words in the argument values. | Point to normalization functions for each type of accuracy? |
axlearn | github_2023 | python | 866 | apple | ruomingp | @@ -370,26 +372,60 @@ def clone_tree(in_tree: NestedTensor) -> NestedTensor:
return jax.tree.map(lambda x: x if isinstance(x, Tensor) else copy.deepcopy(x), in_tree)
-class TensorStoreStateStorageBuilder(Builder):
- """Builds state by restoring from TensorStoreStateStorage."""
-
- SPEC_PREFIX = "tensor_store_state_storage:"
+# pylint: disable-next=abstract-method
+class BaseStateStorageBuilder(Builder):
+ """Builds state by restoring from a checkpoint."""
@config_class
class Config(Builder.Config):
- dir: Required[str] = REQUIRED
+ """Configures BaseStateStorageBuilder.
+
+ Attributes:
+ base_dir: Base directory that contains checkpoints of a trainer, usually containing
+ subdirs, one for each checkpointed step.
+ step: Step number to load. | Please see my question about step=None in the internal PR. |
axlearn | github_2023 | python | 853 | apple | ruomingp | @@ -1544,44 +1642,564 @@ def forward(self, x: Tensor, *, paddings: Tensor) -> tuple[Tensor, Tensor]:
# Apply Conv1D.
output = super().forward(x)
- # TODO(dhwang2): Implement Conv1DTranspose separately for lhs_dilation. It's problematic
- # for lhs_dilation (Conv Transpose) and rhs_dilation (Dilated Convolution) to be part of
- # the same class. Not only are they never used together, but their combined usage would
- # result in undefined behavior. Additionally, the logic for handling explicit padding and
- # paddings is fundamentally different between them, so supporting both in a single class
- # makes the code error-prone.
# Compute paddings conv output.
output_paddings = compute_conv_paddings(
paddings,
window=cfg.window,
stride=cfg.strides,
conv_padding=cfg.padding,
- dilation=cfg.rhs_dilation,
+ dilation=cfg.dilation,
anchor=cfg.anchor,
)
# Apply padding to the outputs.
output = output * (1 - output_paddings[..., None])
return output, output_paddings
-class DepthwiseConv1D(BaseConv):
- """The 1-D depth-wise convolution layer.
+############################## Transposed Convolution ##############################################
- Kernel weights have the WIO layout and in the shape of (window, 1, output_dim=input_dim).
- Both inputs and outputs will be in the NWC layout.
+
+# Based on jax.lax.convolution._conv_transpose_padding, but ours is more intuitive.
+def conv_transpose_explicit_padding(
+ *,
+ window: Sequence[int],
+ strides: Sequence[int],
+ padding: ConvPaddingType,
+ dilation: Sequence[int],
+) -> ConvPaddingType:
+ """Convert str padding to tuple padding for conv_transpose.
+
+ Each mode follows the formulas below,
+ * SAME: (min(window-1, ceil((w+s-2)/2)), max(stride-1, floor((w+s-2)/2)))
+ pad_total = window+stride-2
+ when stride > window -> (window-1, stride-1)
+ * VALID: (window-1, max(stride-1, window-1))
+ pad_total = window+stride-2 + max(window-stride, 0)
+ when stride > window -> (window-1, stride-1)
+ * CAUSAL: (window-1, stride-1)
+ pad_total = window+stride-2
+
+ Note: output_size = input_size*stride - (window+stride-2) + pad_total
+ = input_size*stride <- "SAME", "CAUSAL"
+ = input_size*stride + max(window-stride, 0) <- "VALID"
+
+ Note: In the above equation, `window` will be replaced with `dilate_window` when dilation > 1.
+ dilate_window = (window - 1) * dilation + 1. Check conv_dilate_window()
+
+ The following illustration demonstrates how Conv Transpose operates, assuming all kernel values
+ are set to 1 for simplicity in showcasing output values.
+
+ In the window=3 and stride=1 case, this function creates outputs as follows:
+ * "SAME" padding=(1, 1)
+ pad| |pad
+ paddings: 0|0 0 1 1|0
+ 0 0 0 -> 0
+ 0 0 1 -> 1
+ 0 1 1 -> 2
+ 1 1 0 -> 2
+
+ * "VALID" padding=(2, 2)
+ pad | |pad
+ paddings: 0 0|0 0 1 1|0 0
+ 0 0 0 -> 0
+ 0 0 0 -> 0
+ 0 0 1 -> 1
+ 0 1 1 -> 2
+ 1 1 0 -> 2
+ 1 0 0 -> 1
+
+ * "CAUSAL" padding=(2, 0)
+ pad | |pad
+ paddings: 0 0|0 0 1 1|
+ 0 0 0 -> 0
+ 0 0 0 -> 0
+ 0 0 1 -> 1
+ 0 1 1 -> 2
+
+ In the window=3 and stride=2 case, this function creates outputs as follows:
+ * "SAME" padding=(2, 1)
+ pad | |pad
+ paddings: 0 0|0 * 0 * 1 * 1|0
+ 0 0 0 -> 0
+ 0 0 0 -> 0
+ 0 0 0 -> 0
+ 0 0 0 -> 0
+ 0 0 1 -> 1
+ 0 1 0 -> 1
+ 1 0 1 -> 2
+ 0 1 0 -> 1 | I don't understand why stride=2 but the adjacent conv transpose windows shown are only one position apart from each other. |
axlearn | github_2023 | python | 789 | apple | samos123 | @@ -363,7 +364,7 @@ def model_config(
hidden_dim=hidden_dim,
num_heads=num_heads,
vocab_size=vocab_size,
- stack_cfg=stack_cfg if stack_cfg is not None else RepeatedTransformerLayer.default_config(),
+ stack_cfg=stack_cfg if stack_cfg is not None else StackedTransformerLayer.default_config(), | does weight only offload work with RepeatedTransformerLayer? @hanzhi713 |
axlearn | github_2023 | python | 818 | apple | markblee | @@ -536,71 +539,123 @@ def _mha_backward_kernel(
del out_ref, l_ref # Not needed
seq_len = q_ref.shape[0]
- def outer_loop(start_k, _):
- dv = jnp.zeros([block_k, block_d], dtype=jnp.float32)
- dk = jnp.zeros([block_k, block_d], dtype=jnp.float32)
+ # Parallelize over k/v's seq dimension.
+ # Load a block of K and V of size (block_k, block_d).
+ # Iterate through Q in chunks of (block_q, block_d) to accumulate dK and dV.
+ start_k = pl.program_id(2)
+ slice_k = pl.ds(start_k * block_k, block_k)
+ dv = jnp.zeros([block_k, block_d], dtype=jnp.float32)
+ dk = jnp.zeros([block_k, block_d], dtype=jnp.float32)
+ k = pl.load(k_ref, (slice_k, slice(None)))
+ v = pl.load(v_ref, (slice_k, slice(None)))
+ span_k = start_k * block_k + jnp.arange(block_k)
+ kv_segment_ids = None if s_ref is None else pl.load(s_ref, (slice_k)) | Did you intend for this to be a tuple?
```suggestion
kv_segment_ids = None if s_ref is None else pl.load(s_ref, (slice_k,))
```
(Also fix a few cases below?) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.