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 kuberne... | 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="... | 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
- ... | 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... | 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... | 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 ... | 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.expe... | 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.expe... | ```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,... | 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 axle... | 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 low... | 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 lo... | ```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 lo... | 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 enable... | 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 lo... | 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):
+ """Sa... | 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_m... | 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):
+ """Sa... | 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 th... | 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_co... | 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_co... | 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_co... | 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.SentencePieceVo... | 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_re... | 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, ... | 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_co... | 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_co... | 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 ... | 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 RematRegexSavePat... |
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_... | ```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, ... | 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,
Repeated... | `_*` 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... | 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, ... | 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
... | 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:
... | 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 do... | 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="tru... | 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_... | 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)",
+ ... | 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... | 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... | 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 = j... | 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,... | 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: action... | 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: action... | 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.
+
+ ... | 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... | 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.
+... | 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/run... |
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 ... | 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_c... |
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 ... | @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)
+ ... | 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]]] =... | 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.
... | 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.
... | 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.
... | 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)
+ ... | 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(),
+ )... | 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": "jobs... |
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 a... | 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... | ```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... | ```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.
+ ... | 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.
+ ... | ```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.
+ ... | 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_s... | 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_dila... | 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.def... | 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 dimensio... | 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.