repo_name stringlengths 1 62 | dataset stringclasses 1
value | lang stringclasses 11
values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,179 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin) remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed ... | why seed is hardcoded to [1]? |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,143 @@
+# Copyright © 2024 Amazon Inc.
+"""Tests for Flash attention on Neuron. Tested on trn1 & trn2."""
+
+import chex
+import jax
+import jax.numpy as jnp
+import pytest
+
+from axlearn.common.flash_attention.utils import mha_reference
+
+if jax.default_backend() != "neuron":
+ pytestmark = pytest.skip... | attention_bias_type is str, not bool
```
attention_bias_type: str | None,
``` |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -275,6 +275,28 @@ def get_segment_ids(segment_ids: SegmentIdAttentionBias) -> Optional[Tensor]:
interpret=(backend == "cpu"),
)
+ elif backend == "neuron":
+ # pylint: disable=import-outside-toplevel
+ from axlearn.common.flash_attention.neuron_attention i... | typo: inlcudes -> includes |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,179 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin) remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed ... | Align docstring parameter order with actual function signature |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,179 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin) remove pytype disable when dependencies are public.
+# pytype: disable=import-error
+# Import needed ... | can you add comment with expected dims for each transpose - similar to what you did in _mha_forward? |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,143 @@
+# Copyright © 2024 Amazon Inc.
+"""Tests for Flash attention on Neuron. Tested on trn1 & trn2."""
+
+import chex
+import jax
+import jax.numpy as jnp
+import pytest
+
+from axlearn.common.flash_attention.utils import mha_reference
+
+if jax.default_backend() != "neuron":
+ pytestmark = pytest.skip... | `segment_ids` is set to None which is default param value for it. It can be removed from `ref_fn` signature for consistency with fn/flash_attention above |
axlearn | github_2023 | python | 939 | apple | apivovarov | @@ -0,0 +1,143 @@
+# Copyright © 2024 Amazon Inc.
+"""Tests for Flash attention on Neuron. Tested on trn1 & trn2."""
+
+import chex
+import jax
+import jax.numpy as jnp
+import pytest
+
+from axlearn.common.flash_attention.utils import mha_reference
+
+if jax.default_backend() != "neuron":
+ pytestmark = pytest.skip... | attention_bias_type is str, not bool |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=... | Missing types? |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=... | Looks like a stale docstring? |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=... | Any reason not to raise if user specifies a prng_key? |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=... | Prefer to raise ValueError over assert. Assertion errors are for catching logic bugs. |
axlearn | github_2023 | python | 939 | apple | markblee | @@ -0,0 +1,192 @@
+# Copyright © 2024 Amazon Inc.
+"""Flash attention Kernels using NKI on Neuron. Tested on trn1 & trn2."""
+from functools import partial
+from typing import Optional
+
+import jax
+import jax.numpy as jnp
+
+# TODO(apoorvtintin): remove pytype disable when dependencies are public.
+# pytype: disable=... | Likewise for these. |
axlearn | github_2023 | python | 988 | apple | apghml | @@ -1452,7 +1452,6 @@ def _check_masking(self, tree: Nested[Any], rule: str):
rule: The rule from `cfg.masking_rules` to check agains.
"""
cfg = self.config
- tree: dict | `Nested[Any]` is actually equivalent to `Any` from a type checking perspective since `Nested[XYZ]` allows for a bare `XYZ` not contained in any dict. So they are not equivalent. |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -146,6 +147,67 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier.... | Can you try to extract a common util function named something like
`def replace_module_recursive(target_modules:str, config_key: str, target_config)` and make it applied to both here and RematSpecModifier |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -65,6 +67,26 @@ def test_remat_policy_override(self):
_ = cfg_modifier(cfg)
+class ModelConfigModifierTest(test_utils.TestCase):
+ def test_model_config_override(self):
+ cfg = SpmdTrainer.default_config().set(model=causal_lm.Model.default_config())
+ self.assertRegex(str(cfg.model.... | Can we do exact match here for the config, something like following:
```suggestion
self.assertTrue(cfg.model.decoder is RepeatedTransformerLayer.default_config())
``` |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -65,6 +67,26 @@ def test_remat_policy_override(self):
_ = cfg_modifier(cfg)
+class ModelConfigModifierTest(test_utils.TestCase):
+ def test_model_config_override(self):
+ cfg = SpmdTrainer.default_config().set(model=causal_lm.Model.default_config())
+ self.assertRegex(str(cfg.model.... | Add a test to catch mismatch exception as well? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -17,7 +18,42 @@
from axlearn.common.gradient_accumulation import with_minibatch_steps
from axlearn.common.metrics import MetricAccumulator
from axlearn.common.trainer import SpmdTrainer
-from axlearn.common.utils import HybridMeshShape, MeshShape
+from axlearn.common.utils import HybridMeshShape, MeshShape, Parti... | End comments with .
```suggestion
"""Recursively search for the target module matching module_name in provided cfg.
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -17,7 +18,42 @@
from axlearn.common.gradient_accumulation import with_minibatch_steps
from axlearn.common.metrics import MetricAccumulator
from axlearn.common.trainer import SpmdTrainer
-from axlearn.common.utils import HybridMeshShape, MeshShape
+from axlearn.common.utils import HybridMeshShape, MeshShape, Parti... | Do not return tuples. Return a struct or namedtuple:
https://github.com/apple/axlearn/blob/main/docs/ml_api_style.md#avoid-returning-a-tuple-of-values
|
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -17,7 +18,42 @@
from axlearn.common.gradient_accumulation import with_minibatch_steps
from axlearn.common.metrics import MetricAccumulator
from axlearn.common.trainer import SpmdTrainer
-from axlearn.common.utils import HybridMeshShape, MeshShape
+from axlearn.common.utils import HybridMeshShape, MeshShape, Parti... | Does this need to be a public method? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +175,100 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | Do we need to support this? Users can always omit the entry. |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +175,100 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | Wait, this behavior is not explained in the class comments. So we are not replacing but merging the configs? Maybe we should support a merge function instead? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | Nit: Do we need this vs. accessing it via `self.config.model_cfg_modifications`? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | Please follow Google style guide strictly in terms of linebreaks. |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | `_merge_configs` actually mutates `model_cfg` IIUC. Is it safe to invoke `__call__` multiple times? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | This comment is vague about how merging actually works. Looks like the rule is:
* Use target_cfg.klass
* Use the field value from found_module if the field exists in both configs (and is not "klass")
* Otherwise keep the value from target_cfg |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | How about:
```suggestion
model_cfg_modifications: Dict[str, Callable[[ConfigBase], ConfigBase]] = {}
```
?
That is, the values are config transformer functions. |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -146,6 +186,111 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | In utils.py we have `get_recursively` and `set_recursively` for `Nested[...]`. I wonder if it will be useful to add corresponding methods to ConfigBase. Then we can do something like:
```suggestion
for cfg_path, cfg_modification in self._model_cfg_modifications.items():
child_cfg = cfg.get_recu... |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -146,6 +186,113 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | There is a chain modifier already, should this be something simpler, saying taking two arguments,
1. target_module
2. modified_config
If you rely on chain, you don't really need a dict here. |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -17,7 +18,53 @@
from axlearn.common.gradient_accumulation import with_minibatch_steps
from axlearn.common.metrics import MetricAccumulator
from axlearn.common.trainer import SpmdTrainer
-from axlearn.common.utils import HybridMeshShape, MeshShape
+from axlearn.common.utils import HybridMeshShape, MeshShape, Parti... | nit, maybe name `target_module` to `target_module_key` since it is more approriate?
|
axlearn | github_2023 | python | 916 | apple | markblee | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key strin... | Please see other comment re `get_recursively`; also, I wonder whether we actually need recursion here (seems like a loop would be simpler). |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -146,6 +137,110 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier): | Which part of this class is specific to model? It seems to take generic modifications? |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -146,6 +137,110 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | Outdated? |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -146,6 +137,110 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | ```suggestion
- Klass is not changed, use target cfg.
```
Please end all sentences with punctuations. |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -146,6 +137,110 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config:
return cfg
+class ModelConfigModifier(ConfigModifier):
+ """Update the model config for the trainer config."""
+
+ @config_class
+ class Config(ConfigModifier.Config):
+ """Configure ModelConfigModifier... | ```suggestion
target_cfg: Configuration that will replace found_module.
found_module: Existing configuration whose class will be replaced
``` |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -151,6 +155,60 @@ def get_trainer_kwargs(
rope_theta = ROPE_THETA[version]
+ # TRN2 specific model config modifications
+ trn2_model_modifications = [
+ # Neuron compiler has a module to detect repeating blocks and reuse them during compilation.
+ # So compile time does not grow with the... | A downside of representing these deeply nested configs as string paths is that they are brittle, and can quickly become outdated.
Have we considered using `cfg.visit` to achieve some of these modifications (e.g., https://github.com/apple/axlearn/blob/1c22688c1dc480777c43a1b8c8dd866dccda70e0/axlearn/common/layers.py#... |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key strin... | Does this need to be a public method? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key strin... | Please name consistently with https://github.com/apple/axlearn/blob/a854738ae728989ba2add761ee5ad64e9a41fea6/axlearn/common/utils.py#L907-L910.
```suggestion
def set_recursively(self, path: Sequence[str], *, value: Any):
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key strin... | ```suggestion
def get_recursively(self, path: Sequence[str]) -> Any:
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key strin... | Can path be empty? Maybe it can return `self` if path is empty? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key strin... | Can path be empty? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,66 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ class TraverseResult(NamedTuple):
+ """Result of a recurisve traverse in a nested ConfigBase."""
+
+ # The parent that contains the reulting key.
+ parent: _ConfigBase
+ # The key strin... | Can we do something like:
```suggestion
if not path:
raise ValueError(...)
parent = self.get_recursively(path[:-1])
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the... | ```suggestion
if not path:
return self
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the... | Nit: Can we avoid recursion with a loop? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the... | ```suggestion
if len(path) == 1:
return setattr(self, path[0], value)
child = getattr(self, path[0])
`````` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the... | Avoid recursion? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,54 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the... | Do we need this check? getattr and setattr will raise anyways. |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -434,7 +552,7 @@ def get_trainer_kwargs(
),
learner_kwargs=dict(peak_lr=1.5e-4, weight_decay=0.1),
max_sequence_length=max_sequence_length,
- train_batch_size=train_batch_size,
+ train_batch_size=8, | Is this change intended? |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,58 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the... | ```suggestion
``` |
axlearn | github_2023 | python | 916 | apple | ruomingp | @@ -394,6 +394,58 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the... | ```suggestion
parent = self.get_recursively(path[:-1])
setattr(current, path[-1], value)
``` |
axlearn | github_2023 | python | 916 | apple | kelvin-zou | @@ -151,6 +155,72 @@ def get_trainer_kwargs(
rope_theta = ROPE_THETA[version]
+ # TRN2 specific model config modifications | Can we move all the modifications in a helper function?
saying
def _generate_trainium2_custom_configs():
...
return trn2_model_modifications, trn2_partition_spec_modifications |
axlearn | github_2023 | python | 916 | apple | hanzhi713 | @@ -151,6 +155,72 @@ def get_trainer_kwargs(
rope_theta = ROPE_THETA[version]
+ # TRN2 specific model config modifications
+ trn2_model_modifications = [
+ # Neuron compiler has a module to detect repeating blocks and reuse them during compilation.
+ # So compile time does not grow with the... | Why is there no "data"? Is it because trn2 don't support data and fsdp at the same time? |
axlearn | github_2023 | python | 916 | apple | markblee | @@ -394,6 +394,49 @@ def set(self, **kwargs):
setattr(self, k, v)
return self
+ def get_recursively(self, path: Sequence[str]) -> Any:
+ """Recursively find the target key in the config and return its value.
+
+ Args:
+ path: A sequence of keys for indexing to get the... | Hm, did I miss something or can we just do:
```suggestion
for part in path:
current = getattr(current, part)
```
(In any case, I can make some changes in a follow-up.) |
axlearn | github_2023 | python | 948 | apple | markblee | @@ -516,6 +514,7 @@ def select_fields(fields: Sequence[str]) -> DatasetToDatasetFn:
def remove_fields(fields: Sequence[str]) -> DatasetToDatasetFn:
"""Filter the dataset to remove the fields specified."""
+ from seqio import map_over_dataset # pylint: disable=import-outside-toplevel | (Please see my internal comment.) |
axlearn | github_2023 | python | 978 | apple | ruomingp | @@ -1524,3 +1525,29 @@ def forward(self, x: Tensor) -> Tensor:
self.add_state_update("value", new_moving_average)
self.add_state_update("count", 1 + self.parameters["count"])
return new_moving_average
+
+
+class BaseLossMetrics(BaseLayer): | layers.py doesn't seem the right file for this class. Can we keep it in metrics.py or create a new file? |
axlearn | github_2023 | python | 329 | apple | apivovarov | @@ -141,64 +146,80 @@ def cross_entropy(
targets = _one_hot_with_label_smoothing(
target_labels, num_classes, label_smoothing=label_smoothing
)
- pre_mask_loss, pre_mask_cross_entropy_loss, pre_mask_z_loss = _stable_cross_entropy(
+ per_target_loss, per_target_cross_entropy_loss, pe... | Hi Ruoming, should we use this accuracy inside CrossEntropyLossMetrics::forward() instead of recalculating it in CrossEntropyLossMetrics::forward() ?
see: https://github.com/apple/axlearn/blob/main/axlearn/common/causal_lm.py#L108C1-L117C10
we can use loss_dict["accuracy"] instead of recalculating accuracy in causa... |
axlearn | github_2023 | python | 934 | apple | apivovarov | @@ -32,16 +32,242 @@
from axlearn.common.layers import LayerNorm
from axlearn.common.logit_modifiers import LogitsToLogitsFn
from axlearn.common.loss import cross_entropy
-from axlearn.common.metrics import WeightedScalar
-from axlearn.common.module import Module, NestedTensor, Tensor, child_context
+from axlearn.co... | Hi Mark, do we need a separate accuracy calculation here (above cross_entropy) if the loss_dict from cross_entropy already contains an accuracy entry? @markblee |
axlearn | github_2023 | python | 972 | apple | dongyin92 | @@ -837,25 +837,41 @@ def extend_step(
q_proj, k_proj, v_proj = self.forward(query, **kv_kwargs, query_positions=query_positions)
updated_state = dict(time_step=time_step + num_query_steps)
if kv_state is None:
- # Update the cache via dynamic slice. [B, S, N, H].
+ # Up... | From the doc string of this function, it says `cached_states` contains "key" and "value" of shape [batch, num_heads, per_head_dim, target_length]. Then why does `target_len = cached_key.shape[1]`? |
axlearn | github_2023 | python | 972 | apple | markblee | @@ -837,25 +837,41 @@ def extend_step(
q_proj, k_proj, v_proj = self.forward(query, **kv_kwargs, query_positions=query_positions)
updated_state = dict(time_step=time_step + num_query_steps)
if kv_state is None:
- # Update the cache via dynamic slice. [B, S, N, H].
+ # Up... | I wonder if we can simplify a bit:
```suggestion
source_len = cached_key.shape[1]
# Create a dispatch matrix of shape [B, T=step, S].
oh_indices = jax.nn.one_hot(
time_step[:, None] + jnp.arange(num_query_steps), source_len, dtype=k_proj.dtype
... |
axlearn | github_2023 | python | 972 | apple | ds-hwang | @@ -837,25 +837,22 @@ def extend_step(
q_proj, k_proj, v_proj = self.forward(query, **kv_kwargs, query_positions=query_positions)
updated_state = dict(time_step=time_step + num_query_steps)
if kv_state is None:
- # Update the cache via dynamic slice. [B, S, N, H].
+ # Up... | Could you add comment why we don't use dynamic_update_slice for future code reader? |
axlearn | github_2023 | python | 884 | apple | ruomingp | @@ -607,6 +610,7 @@ def host_to_global_device_array(
host_arrays: Nested[Union[np.ndarray, Tensor]],
*,
partition: DataPartitionType = DataPartitionType.FULL, | I think @markblee plans to remove the `DataPartitionType` enum and rely on https://jax.readthedocs.io/en/latest/_autosummary/jax.make_array_from_process_local_data.html to support flexible partition specs. |
axlearn | github_2023 | python | 884 | apple | kelvin-zou | @@ -423,6 +423,7 @@ def get_trainer_kwargs(
raise NotImplementedError(f"Unknown model size {model_size}.")
model_kwargs = trainer_kwargs.pop("model_kwargs")
model_kwargs.setdefault("vocab_size", vocab_size)
+ trainer_kwargs["input_partition_type"] = None if backend != "neuron" else DataPartitionTy... | Please go with a configmodifier instead of hardcode in the code, otherwise it becomes hard for people to debug
|
axlearn | github_2023 | python | 884 | apple | kelvin-zou | @@ -188,11 +194,11 @@ def _pjit(self, fn: Callable) -> Callable:
in_shardings=(
self._model_param_partition_specs, # model_params.
None, # replicated_inputs (e.g., prng_key).
- utils.input_partition_spec(), # per_example_inputs.
+ utils.dat... | Did you run through pylint? this line seems quite long. |
axlearn | github_2023 | python | 884 | apple | kelvin-zou | @@ -591,14 +591,17 @@ class DataPartitionType(Enum):
FULL = "full"
# Data are fully replicated across all devices.
REPLICATED = "replicated"
+ # Data are partitioned across batch axis only.
+ BATCH = "batch"
-
-def data_partition_type_to_spec(partition: DataPartitionType) -> PartitionSpec:
+def d... | Instead of directly assigning PartitionSpec, maybe extend `input_partition_spec ` with an argument batch_axis_names, with default None? |
axlearn | github_2023 | python | 884 | apple | kelvin-zou | @@ -37,16 +36,15 @@ def is_supported(
)
)
- | Are you using a different pylint style? Those lines should not be removed. |
axlearn | github_2023 | python | 884 | apple | markblee | @@ -1701,6 +1702,31 @@ def test_length(self):
class HostToGlobalArrayTest(TestCase):
"""Tests host_to_global_device_array."""
+ @pytest.mark.neuron
+ def test_partition_batch(self): | Are we able to pass the `test_every_other_process` only relying on `make_array_from_process_local_data`? If not, then it seems that input dispatch may still be needed. |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -4,18 +4,21 @@
from absl import app, flags
-from axlearn.common import launch, launch_trainer, measurement
+from axlearn.common import launch, launch_trainer, measurement, monitoring
from axlearn.common.config import config_for_function
def main(_):
measurement.initialize(flags.FLAGS)
+ monitoring... | Do we need a separate module for this, or can we consolidate into the `measurement` interface? |
axlearn | github_2023 | python | 783 | apple | yiping-ma | @@ -800,13 +805,15 @@ def restore_checkpoint(self, restore_step: Optional[int] = None) -> Optional[int
step,
restore_input_iter,
)
+ self._maybe_record_event(measurement.Event.END_DATA_LOADING) | If this line got skipped due to self.checkpointer.restore() failure, the data loading end time will be missing for this event, is it expected? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +55,48 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELE... | Convert this into a docstring for the method? BTW, we use 100 line length. |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +55,48 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELE... | When do we expect reach this case? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -34,13 +36,46 @@ def test_from_flags(self, spec):
# Recorder is not instantiated until first event.
self.assertIsNone(recorder._recorder)
- def test_record(self):
+ def test_record_and_monitor(self):
fv = flags.FlagValues()
measurement.define_flags(flag_values=fv)
... | ```suggestion
self.assertIsNone(recorder._monitor) # Ensure _monitor is initially None
``` |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -22,7 +23,11 @@ def from_flags(cls, fv: flags.FlagValues) -> "GoodputRecorder":
"""Converts flags to a recorder.
`fv.recorder_spec` will be interpreted as a list of `key=value` pairs; config names
- corresponding to keys will be set to the corresponding values.
+ corresponding to ke... | Should we move the configs to this class for now? I.e., on L19:
```
@config_class
class Config(measurement.Recorder.Config):
"""Configures GoodputRecorder."""
upload_dir: Required[str] = REQUIRED
upload_interval: Required[str] = REQUIRED
``` |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -13,6 +13,7 @@ def main(_):
launch.setup()
trainer_config = launch_trainer.get_trainer_config()
trainer_config.set(recorder=config_for_function(lambda: measurement.global_recorder))
+ measurement.start_monitoring() | I suppose we must do this after `launch.setup` due to `jax.process_index`? If so, maybe we should add a comment to the goodput `start_monitoring` docstring that it assumes jax distributed init. |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +65,50 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELE... | We actually follow the Google style docstrings 🙂
```suggestion
"""Instantiates ml-goodput-measurement's GoodputMonitor to asynchronously calculate
``` |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -324,6 +325,7 @@ def __init__(
model=self.model,
model_param_partition_specs=model_param_partition_specs,
)
+ self._maybe_record_event(measurement.Event.END_ACCELERATOR_INIT) | Can you clarify what accelerator init is supposed to capture? E.g., would `utils_spmd` where we call jax distributed init be more appropriate? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -847,6 +850,7 @@ def _prepare_training(self, prng_key: Tensor) -> bool:
with fs.open(os.path.join(cfg.dir, "model_analysis.txt"), "w") as f:
f.write(model_analysis)
+ self._maybe_record_event(measurement.Event.END_TRAINING_PREPARATION) | What's usually considered part of "training preparation"? Should we count the jit compilation below as a potentially substantial part of it? What about the checkpoint restoration above? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -883,6 +887,7 @@ def restore_checkpoint(self, restore_step: Optional[int] = None) -> Optional[int
restore_input_iter = cfg.save_input_iterator
try:
# Try to restore with `input_iter`.
+ self._maybe_record_event(measurement.Event.START_DATA_LOADING) | Hm, is data loading be in relation to the input loading or the checkpoint or both? Here it seems only capturing the checkpoint restoration? |
axlearn | github_2023 | python | 783 | apple | ruomingp | @@ -49,10 +65,51 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELE... | ```suggestion
)
if not self._monitor:
# This could happen if there are internal errors (such as access errors) from GCP services such as Cloud Logging or Cloud Storage.
logging.log_first_n(
logging.WARNING,
"Goodput up... |
axlearn | github_2023 | python | 783 | apple | ruomingp | @@ -47,6 +59,10 @@ def record(self, event: Event, *args, **kwargs):
"""Records an event with the given name."""
raise NotImplementedError(type(self))
+ def start_monitoring(self, **kwargs):
+ """Starts computing and uploading metrics at some configured interval in the background."""
+ ... | To avoid breaking other subclasses of `Recorder`.
```suggestion
pass
``` |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +65,50 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELE... | ```suggestion
if self._monitor:
self._monitor.start_goodput_uploader(*args, **kwargs)
logging.info("Started Goodput upload to Tensorboard in the background!")
else:
# This could happen if there are internal errors (such as access errors) from GCP services such as... |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -34,13 +36,46 @@ def test_from_flags(self, spec):
# Recorder is not instantiated until first event.
self.assertIsNone(recorder._recorder)
- def test_record(self):
+ def test_record_and_monitor(self):
fv = flags.FlagValues()
measurement.define_flags(flag_values=fv)
... | Does this test the failure scenario? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -47,6 +59,10 @@ def record(self, event: Event, *args, **kwargs):
"""Records an event with the given name."""
raise NotImplementedError(type(self))
+ def start_monitoring(self, **kwargs):
+ """Starts computing and uploading metrics at some configured interval in the background."""
+ ... | Let's `raise NotImplementedError(type(self))` and let subclasses decide whether to implement -- it should be fairly straightforward for a subclass to decide to not monitor, but we want the decision to be explicit. |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +65,50 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELE... | BTW, I just triggered the CI, sorry for not doing so early. (I suspect lines like this will fail pylint for being too long.) |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -49,10 +65,47 @@ def record(self, event: measurement.Event, *args, **kwargs):
self._recorder.record_job_end_time(*args, **kwargs)
elif event == measurement.Event.START_STEP:
self._recorder.record_step_start_time(*args, **kwargs)
+ elif event == measurement.Event.START_ACCELE... | OOI, is there anything here specific to TPUs or can we use the same API for GPUs on GCP? |
axlearn | github_2023 | python | 783 | apple | markblee | @@ -120,3 +136,16 @@ def record_event(event: Event):
logging.log_first_n(logging.INFO, "No recorder configured, ignoring events.", 1)
else:
global_recorder.record(event)
+
+
+def start_monitoring():
+ """Begins monitoring events as per global monitor functionality."""
+ if global_recorder i... | nit -- since `start_monitoring` is only called once, we don't need `log_first_n`. (Not having it may help catch when it's called multiple times.) |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -66,8 +65,7 @@ def __call__(
# Specification of an optimizer state array.
OptStateSpec = TensorSpec
-NestedOptStateSpec = Union[OptStateSpec, dict, Sequence]
-TransformPartitionSpecFn = Callable[[NestedParameterSpec], NestedOptStateSpec]
+TransformPartitionSpecFn = Callable[[Nested[ParameterSpec]], Nested[OptSta... | Thanks for the clean-up. Is this change related to the PR? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2008,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ offload_src: Option... | Also log `offload_src` and `offload_dst`? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2008,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ offload_src: Option... | Do we need Optional since they cannot be None?
```suggestion
offload_src: MemoryKind = "device",
offload_dst: MemoryKind = "pinned_host",
``` |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2008,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ offload_src: Option... | Where does the overhead come from? Is it from the states of `clip_by_global_norm` being offloaded? If so, could we use regular expressions to specify which states to offload? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2008,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ offload_src: Option... | Do we need explicit `device_put` calls here? Is it enough to specify the partition spec with the right memory_kind? |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2015,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ pattern: Union[str,... | ```suggestion
pattern: Regex pattern used to match the path of optimizer states. Fully matched states will be
offloaded. Default to regex that matches all states.
``` |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2015,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ pattern: Union[str,... | Hmmm, we should really use `named_chain` to avoid `/1` and `/0` in paths. |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2015,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ pattern: Union[str,... | ```suggestion
pattern should not depend on model structure, you can use ".*/mu/.*" to offload all `mu`.
``` |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -139,19 +140,40 @@ def update_fn(
return PartitionedGradientTransformation(init=init_fn, update=update_fn, partition=partition_fn)
-def copy_partition(param_specs: NestedParameterSpec) -> NestedPartitionSpec:
+def copy_partition(
+ param_specs: Nested[ParameterSpec],
+ *,
+ pattern: Union[None, str... | Instead of coupling creation of `OptStateSpec` and setting of `memory_kind`, how about having a separate function for setting memory kind?
```
def set_memory_kind(opt_state_spec: Nested[OptStateSpec], *, pattern, memory_kind):
```
This allows `set_memory_kind` to be called multiple times, maybe for different me... |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -1993,3 +2015,93 @@ def _update2(u: Tensor, param: OptParam):
partition=lambda _: OptStateSpec(shape=[], dtype=jnp.int32, mesh_axes=PartitionSpec()),
)
return named_chain(**tx)
+
+
+def offload_optimizer(
+ optimizer: ConfigOr[PartitionedGradientTransformation],
+ *,
+ pattern: Union[str,... | I wonder whether the explicit `device_put` calls mean that we need to move all optimizer states into device before optimizer computation, leading to high device memory usage.
In theory, optimizer computation can be streaming---the optimizer states of variables can be updated separately so we can stream them into and... |
axlearn | github_2023 | python | 867 | apple | ruomingp | @@ -139,19 +140,40 @@ def update_fn(
return PartitionedGradientTransformation(init=init_fn, update=update_fn, partition=partition_fn)
-def copy_partition(param_specs: NestedParameterSpec) -> NestedPartitionSpec:
+def copy_partition(
+ specs: Nested[OptStateSpec],
+ *,
+ pattern: Union[None, str, re.Pa... | ```suggestion
Returns:
``` |
axlearn | github_2023 | python | 956 | apple | ruomingp | @@ -636,6 +637,7 @@ def get_trainer_config_fn(
keep_every_n_steps: int = 50_000,
save_every_n_steps: Optional[int] = None,
init_state_builder: Optional[state_builder.Builder.Config] = None,
+ logical_feed_indices: Optional[Sequence[int]] = None, | Do we need this? I think InputDispatcher can figure it out automatically. |
axlearn | github_2023 | python | 926 | apple | markblee | @@ -1216,18 +1216,37 @@ class Config(BaseLayer.Config):
dim: Required[int] = REQUIRED # The dimensionality of the positional embedding.
theta: float = 10000.0 # The scale of base frequency.
- def forward(self, positions: Tensor) -> Tensor:
+ def default_query_positions(self, max_seq_len: int... | ```suggestion
def _default_query_positions(self, max_seq_len: int) -> Tensor:
```
Users should pass `max_seq_len` rather than calling this method publicly. |
axlearn | github_2023 | python | 926 | apple | markblee | @@ -1216,18 +1216,37 @@ class Config(BaseLayer.Config):
dim: Required[int] = REQUIRED # The dimensionality of the positional embedding.
theta: float = 10000.0 # The scale of base frequency.
- def forward(self, positions: Tensor) -> Tensor:
+ def default_query_positions(self, max_seq_len: int... | ```suggestion
max_seq_len: Max length of sequence, required if positions is not provided.
``` |
axlearn | github_2023 | python | 926 | apple | ruomingp | @@ -1216,18 +1216,37 @@ class Config(BaseLayer.Config):
dim: Required[int] = REQUIRED # The dimensionality of the positional embedding.
theta: float = 10000.0 # The scale of base frequency.
- def forward(self, positions: Tensor) -> Tensor:
+ def default_query_positions(self, max_seq_len: int... | Do we need to support both args? It seems simpler and more readable to take `positions` only and let the caller call `jnp.arange` if necessary. |
axlearn | github_2023 | python | 926 | apple | ruomingp | @@ -1216,18 +1216,37 @@ class Config(BaseLayer.Config):
dim: Required[int] = REQUIRED # The dimensionality of the positional embedding.
theta: float = 10000.0 # The scale of base frequency.
- def forward(self, positions: Tensor) -> Tensor:
+ def default_query_positions(self, max_seq_len: int... | what happens if both `positions` and `max_seq_len` are provided? should we check that they are consistent? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.