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
992
apple
ruomingp
@@ -277,3 +286,51 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: for config_modifier_fn in self._config_modifiers: cfg = config_modifier_fn(cfg) return cfg + + +class FP8ConfigModifier(ConfigModifier): + """Update the trainer config to use FP8 training.""" + + ...
Can we use update_rules? See https://github.com/apple/axlearn/blob/daec8c530741594eeea12faba1a454bb42b6c03c/axlearn/common/learner_test.py#L343.
axlearn
github_2023
python
992
apple
ruomingp
@@ -1158,6 +1159,55 @@ def prune_tree( return in_tree +def tree_merge_default_override_fn(primary: Any, secondary: Any): + is_primary_empty = False + is_secondary_empty = False + try: + is_primary_empty = len(primary) == 0 + is_secondary_empty = len(secondary) == 0 + except TypeError:...
Consider making them deep copies to be consistent with the jax tree utils. Deep copies are also less error prone by decoupling side effects.
axlearn
github_2023
python
992
apple
ruomingp
@@ -1158,6 +1159,55 @@ def prune_tree( return in_tree +def tree_merge_default_override_fn(primary: Any, secondary: Any): + is_primary_empty = False + is_secondary_empty = False + try: + is_primary_empty = len(primary) == 0 + is_secondary_empty = len(secondary) == 0 + except TypeError:...
Can we be even more strict? ```suggestion if type(primary) != type(secondary): raise ValueError(...) ```
axlearn
github_2023
python
992
apple
ruomingp
@@ -1158,6 +1159,55 @@ def prune_tree( return in_tree +def tree_merge_default_override_fn(primary: Any, secondary: Any): + is_primary_empty = False + is_secondary_empty = False + try: + is_primary_empty = len(primary) == 0 + is_secondary_empty = len(secondary) == 0 + except TypeError:...
```suggestion out_tree[k] = copy.deepcopy(secondary[k]) ```
axlearn
github_2023
python
992
apple
ruomingp
@@ -1158,6 +1159,55 @@ def prune_tree( return in_tree +def tree_merge_default_override_fn(primary: Any, secondary: Any): + is_primary_empty = False + is_secondary_empty = False + try: + is_primary_empty = len(primary) == 0 + is_secondary_empty = len(secondary) == 0 + except TypeError:...
```suggestion return copy.deepcopy(override_fn(primary, secondary)) ```
axlearn
github_2023
python
992
apple
ruomingp
@@ -1158,6 +1159,55 @@ def prune_tree( return in_tree +def tree_merge_default_override_fn(primary: Any, secondary: Any): + is_primary_empty = False + is_secondary_empty = False + try: + is_primary_empty = len(primary) == 0 + is_secondary_empty = len(secondary) == 0 + except TypeError:...
```suggestion leaf_merge_fn: Callable[[Any, Any], Any] = tree_merge_default_override_fn, ```
axlearn
github_2023
python
992
apple
ruomingp
@@ -277,3 +286,51 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: for config_modifier_fn in self._config_modifiers: cfg = config_modifier_fn(cfg) return cfg + + +class FP8ConfigModifier(ConfigModifier): + """Update the trainer config to use FP8 training.""" + + ...
Usually we avoid instantiation when constructing configs to preserve the readability of configs. Can we defer the `maybe_instantiate` call to `OverrideInplaceUpdateTransformation.__init__`?
axlearn
github_2023
python
992
apple
ruomingp
@@ -277,3 +286,51 @@ def __call__(self, cfg: SpmdTrainer.Config) -> SpmdTrainer.Config: for config_modifier_fn in self._config_modifiers: cfg = config_modifier_fn(cfg) return cfg + + +class FP8ConfigModifier(ConfigModifier): + """Update the trainer config to use FP8 training.""" + + ...
I wonder how we can keep this list in sync with quantized_dot_general/layers.py. Consider * Defining them as an enum in `quantized_dot_general/common.py` and enumerate the enum members here * Move this class to `quantized_dot_general/update_transformation.py` * Change quantized_dot_general/layers.py to use the enum...
axlearn
github_2023
python
992
apple
ruomingp
@@ -263,3 +271,77 @@ def mask_tree(tree: dict, *, keep: dict, mask_value: Any) -> dict: tree, is_leaf=lambda x: x is None, ) + + +class OverrideInplaceUpdateTransformation(WrappedPartitionedGradientTransformation): + """An update transformation that provides rules to override inplace updates. ...
Another way to look at this is that we are applying different optimizers to different params. Specifically, we apply a special optimizer for some params where the optimzier simply takes the "gradient" as the new param value. If this makes sense, we can introduce the concept of a composite optimizer containing sub-op...
axlearn
github_2023
python
992
apple
ruomingp
@@ -1512,6 +1519,158 @@ def _check_masking(self, tree: Nested[Any], rule: str): F(learner, method="update", prng_key=None, state=state, inputs=[updates], is_training=True) + @parameterized.parameters(False, True) + def test_fp8_override_update(self, use_override_inplace_update): + """Tests FP8...
Use the constants?
axlearn
github_2023
python
992
apple
ruomingp
@@ -1512,6 +1519,158 @@ def _check_masking(self, tree: Nested[Any], rule: str): F(learner, method="update", prng_key=None, state=state, inputs=[updates], is_training=True) + @parameterized.parameters(False, True) + def test_fp8_override_update(self, use_override_inplace_update): + """Tests FP8...
Use the constants from FP8_AMAX_HISTORY_PARAM_NAMES?
axlearn
github_2023
python
992
apple
ruomingp
@@ -63,6 +64,14 @@ class ClippingChoice(Enum): OUTPUT_ACTIVATION = 1 +FP8_SCALE_PARAM_NAMES = ["input_scale", "kernel_scale", "output_grad_scale"]
Consider using enum: ```suggestion class Fp8ScaleParam(enum.Enum): INPUT_SCALE = "input_scale" ... ``` This avoids spelling mistakes.
axlearn
github_2023
python
992
apple
ruomingp
@@ -174,5 +178,42 @@ def test_chain_config_modifier(self): self.assertEqual(cfg.learner.forward_fn_transformation.steps, 4) +class FP8ConfigModifierTest(test_utils.TestCase): + @parameterized.parameters([True, False]) + def test_fp8_config_modifier(self, use_config_fn): + cfg: SpmdTrainer.Conf...
Use the constant names?
axlearn
github_2023
python
992
apple
ruomingp
@@ -1158,6 +1159,63 @@ def prune_tree( return in_tree +def tree_merge_default_leaf_merge_fn(primary: Any, secondary: Any):
The behavior of this function still seem too complicated to be the default function for tree_merge. Can we ask the user to specify the merge function explicitly?
axlearn
github_2023
python
993
apple
kelvin-zou
@@ -352,6 +354,20 @@ def get_trainer_kwargs( ), *trn2_config.module_modifications, *trn2_config.partition_spec_modifications, + GradientAccumulationModifier.default_config().set( + ...
I am wondering, if we have a default input partition with axis=0 on ("data", "expert", "fsdp") and axis=1 on "seq", do we still need this?
axlearn
github_2023
python
993
apple
kelvin-zou
@@ -73,23 +75,25 @@ def _make_scan_minibatch_inputs( param_noise_key: The `param_noise_key` from the ForwardFn inputs minibatch_size: Size of the minibatch. minibatch_index: Current scan minibatch index. + minibatch_partitioner: If not None, applies additional sharding constraints + ...
To me, it seems rather a hack than a proper solution, that is, we want to have a different `input_partition_spec()` than the default one, then we need this?
axlearn
github_2023
python
993
apple
apghml
@@ -57,39 +59,38 @@ def _make_scan_minibatch_inputs( param_noise_key: Tensor, minibatch_size: int, minibatch_index: int, + minibatch_partitioner: Optional[InputPartitionFn], ) -> tuple[Nested[Tensor], Tensor, Tensor]: """Creates minibatch inputs from inputs. This is a utility function tha...
Could we add unit tests that cover this argument?
axlearn
github_2023
python
993
apple
apghml
@@ -57,39 +59,38 @@ def _make_scan_minibatch_inputs( param_noise_key: Tensor, minibatch_size: int, minibatch_index: int, + minibatch_partitioner: Optional[InputPartitionFn],
Echoing Kelvin's comment, could you explain concretely why we need this functionality? If it's just something that might be useful, maybe we can wait until we are certain that we will need it?
axlearn
github_2023
python
993
apple
apghml
@@ -134,16 +136,32 @@ def with_minibatch_steps( TODO(cemkoc): Investigate the slight difference in loss curves when decorated. + A minibatch_partitioner is used to partition minibatch inputs to the original_func. + Note that if minibatch_partitioner is None, the default minibatch partitioner is used whic...
Can we default this to the same sharding the input is already using along all non-batch axes?
axlearn
github_2023
python
993
apple
apghml
@@ -78,18 +75,16 @@ def _make_scan_minibatch_inputs( A tuple of minibatch inputs which of the same structure as `inputs` and new (carry) forward_key and param_noise_key. """ - minibatch_input = with_sharding_constraint( - jax.tree.map( - lambda x: jax.lax.dynamic_slice_in_dim...
Suppose we have a global input batch of size 100 running on 10 chips (so a per chip size of 10) and we want to switch to doing 10 grad accumulation steps each with a global batch size of 10 (1 per chip per accumulation step). Suppose that the input is originally sharded evenly across the chips (first 10 on first chi...
axlearn
github_2023
python
993
apple
apghml
@@ -172,12 +167,26 @@ def fwd_helper( otherwise None. """ minibatch_size = _compute_minibatch_size(inputs["input_batch"], steps=steps) + + # Create a sample minibatch for the carry buffer creation below
Could you explain in more detail why this is needed?
axlearn
github_2023
python
993
apple
apghml
@@ -172,12 +160,56 @@ def fwd_helper( otherwise None. """ minibatch_size = _compute_minibatch_size(inputs["input_batch"], steps=steps) + + def reshape_for_scan(x: Tensor): + """Helper function that adds a minibatch dimension while evenly dividing + ...
Replace the acronyms with full names?
axlearn
github_2023
python
993
apple
apghml
@@ -172,12 +160,56 @@ def fwd_helper( otherwise None. """ minibatch_size = _compute_minibatch_size(inputs["input_batch"], steps=steps) + + def reshape_for_scan(x: Tensor): + """Helper function that adds a minibatch dimension while evenly dividing + ...
Could we replace these three lines with one line if we use `jnp.moveaxis`?
axlearn
github_2023
python
993
apple
apghml
@@ -1,15 +1,143 @@ # Copyright © 2024 Apple Inc. """Test module for gradient_accumulation.py""" +from typing import Callable + import chex import jax import jax.numpy as jnp +import numpy as np +import pytest from absl.testing import absltest, parameterized +from jax.experimental.pjit import pjit from axlear...
IIUC, the issue you fixed regarding the batch size in the output collection only happens if the output collection contains something with a leading `batch_size` dim, which I couldn't find here? Do the tests in the current version of the PR fail without that specific fix? If not, can we add a test that fails without tha...
axlearn
github_2023
python
993
apple
apghml
@@ -28,11 +157,14 @@ def test_minibatch_steps_grads_and_loss(self, steps): def loss_fn(*, model_params, inputs) -> ForwardOutputs: """Simple ForwardFn.""" - del inputs loss = -jax.nn.log_softmax(model_params["w"] + model_params["b"])[1] output_collection = ne...
Do we have an assert statement somewhere that does an equality / allclose check on this value returned in the output collection to make sure the correct value ultimately gets returned when using minibatching?
axlearn
github_2023
python
993
apple
markblee
@@ -172,12 +167,54 @@ def fwd_helper( otherwise None. """ minibatch_size = _compute_minibatch_size(inputs["input_batch"], steps=steps) + + def reshape_for_scan(x: Tensor): + """Helper function that adds a minibatch dimension while evenly dividing + ...
I guess this retains any sharding annotations on global batch size to the mini batch size -- OOI what happens if the minibatch doesn't divide the global batch sharding? Is it silently ignored?
axlearn
github_2023
python
993
apple
markblee
@@ -172,12 +167,54 @@ def fwd_helper( otherwise None. """ minibatch_size = _compute_minibatch_size(inputs["input_batch"], steps=steps) + + def reshape_for_scan(x: Tensor): + """Helper function that adds a minibatch dimension while evenly dividing + ...
nit -- ```suggestion sample_minibatch_inputs, *_ = _make_scan_minibatch_inputs( ```
axlearn
github_2023
python
993
apple
markblee
@@ -172,12 +167,54 @@ def fwd_helper( otherwise None. """ minibatch_size = _compute_minibatch_size(inputs["input_batch"], steps=steps) + + def reshape_for_scan(x: Tensor): + """Helper function that adds a minibatch dimension while evenly dividing + ...
nit -- ```suggestion Input dimension is [global_logical_batch_size, seq_len], this first reshaped to ``` ditto for below.
axlearn
github_2023
python
932
apple
markblee
@@ -219,6 +221,26 @@ def __init__( super().__init__(cfg, parent=parent) cfg = self.config + self.gcp_workload_monitor = None
The trainer shouldn't have any dependencies on GCP specific logic. BTW, I wonder whether the monitoring events can be inferred from the events recorded by the `measurement` utils -- what are the main differences?
axlearn
github_2023
python
1,055
apple
markblee
@@ -95,6 +96,20 @@ def _cleanup(self): def _get_flink_cluster_name(self) -> str: return f"{self.config.name}-flink-cluster" + def _get_single_node_topology(self) -> str: + """This method returns single node topology for large slice of TPU."""
```suggestion """This method returns the single node topology for the configured TPU type.""" ```
axlearn
github_2023
python
1,055
apple
markblee
@@ -95,6 +96,20 @@ def _cleanup(self): def _get_flink_cluster_name(self) -> str: return f"{self.config.name}-flink-cluster" + def _get_single_node_topology(self) -> str: + """This method returns single node topology for large slice of TPU.""" + tpu_type = infer_tpu_type(self.config.acce...
```suggestion raise RuntimeError(f"Can't find specs for {single_host_tpu_name}.") ```
axlearn
github_2023
python
1,050
apple
markblee
@@ -296,21 +296,21 @@ def check_tpu_splash_attention( ) if has_segment_ids: raise SplashAttentionUnsupportedError( - "The public API for SplashAttention that we " - "currently use does not support segment ids." + "The public API for SplashAttention that we cur...
```suggestion "Please use `tpu_decoding` for decoding." ```
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,303 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Do we still need `window_size`? If so, explain why?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,303 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Add comments for the args?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,303 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Add comments for the internal variables?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,303 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Maybe we can raise StopIteration instead of returning None?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,303 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
How is _parent_sequence_start_state used?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,303 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
How is _parent_sequence_end_state used?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,303 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Comment on when we return None?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,303 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Move this assert before `if`?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,303 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Would it simplify the implementation if we override `__iter__` and use a yield-based implementation? def __iter__(self): end_of_parent = False while not end_of_parent or self._current_token_count > 0: try: while self._current_token_count < self._max_len: ...
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,310 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
```suggestion # Total number of tokens in `self._current_examples_list`. self._current_token_count = 0 ```
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,310 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
```suggestion # The examples in the current buffer. self._current_examples_list = [] ```
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,310 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
```suggestion # If not None, the state of `self._parent` before the last example in `self._current_examples_list` was added. self._parent_sequence_end_state = None ```
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,310 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
```suggestion # If not None, the state of `self._parent` before the first example in `self._current_examples_list` was added. # Must be None if `self._current_token_count == 0`. self._parent_sequence_start_state = None ```
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,310 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Can we inline this method into `set_state`?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,310 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Do we need this variable? When is it different from `self._parent.get_state()`?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,313 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
We are still missing comments for `max_len` and `input_key`.
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,313 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Can we simplify this by (along with a change in set_state) ```suggestion "parent_sequence_start_state": self._parent_sequence_start_state, ```
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,313 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
```suggestion self._parent.set_state(state["parent_sequence_start_state"] or state["parent"]) ```
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,313 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Do we need this as a separate function?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,313 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Add an assert that self._parent.get_state() == state["parent"] if and only if self._current_token_count == 0 ?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,313 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Comment that it will only contain values corresponding to `input_key`?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -23,12 +24,313 @@ def __call__(self, ids: Tensor, *, max_len: int) -> Tensor: ... +_PackingFn = Callable[[Dataset, int, Callable, int, str, grain.ReadOptions], Dataset] + + +class _StreamingPackingDatasetIterator(grain.DatasetIterator): + """An iterator that yields packed examples in a streaming fash...
Ditto?
axlearn
github_2023
python
1,046
apple
ruomingp
@@ -107,6 +411,7 @@ def text_to_lm_training_input( window_size: int = 128, max_padding_fraction: float = 1, read_options: grain.ReadOptions = grain.ReadOptions(num_threads=1, prefetch_buffer_size=16), + packing_fn: Callable = windowed_packing,
Do we have a test that checks that the new packing function is equivalent to the old one with a finite window size?
axlearn
github_2023
python
1,047
apple
ruomingp
@@ -126,7 +127,7 @@ def typestr(self) -> str: def _ckpt_dir(self, info: ocp.type_handlers.ParamInfo) -> str: # Each worker writes its grain checkpoints under a different path. - return os.path.join(info.parent_dir, f"grain_{jax.process_index()}") + return os.path.join(info....
This will break existing checkpoints. Is that OK?
axlearn
github_2023
python
1,044
apple
markblee
@@ -0,0 +1,469 @@ +# Copyright © 2025 Apple Inc. + +"""Unit tests of job_flink.py.""" +import contextlib +import json +import logging +from typing import Optional + +from absl import flags +from absl.testing import parameterized + +from axlearn.cloud.common.bundler import Bundler +from axlearn.cloud.gcp import bundler,...
Add a ref for how it's generated?
axlearn
github_2023
python
1,044
apple
markblee
@@ -531,6 +532,78 @@ def from_flags(cls, fv: flags.FlagValues, **kwargs): return cfg +class FlinkGKERunnerJob(GKERunnerJob): + """A GKERunnerJob that uses FlinkGKEJob.""" + + inner = FlinkTPUGKEJob + pre_provisioner = TPUNodePoolProvisioner + + def _get_status(self) -> GKERunnerJob.Status: + ...
nit -- fix formatting.
axlearn
github_2023
python
1,044
apple
markblee
@@ -0,0 +1,24 @@ +# Copyright © 2024 Apple Inc. +"""Utils of TPU pods.""" + +from typing import Any + + +def get_default_env(tpu_type: str, num_tpu_slices: int, job_name: str) -> dict[str, Any]:
```suggestion def get_default_env(*, tpu_type: str, num_tpu_slices: int, job_name: str) -> dict[str, Any]: ```
axlearn
github_2023
python
1,044
apple
markblee
@@ -531,6 +532,78 @@ def from_flags(cls, fv: flags.FlagValues, **kwargs): return cfg +class FlinkGKERunnerJob(GKERunnerJob): + """A GKERunnerJob that uses FlinkGKEJob.""" + + inner = FlinkTPUGKEJob + pre_provisioner = TPUNodePoolProvisioner + + def _get_status(self) -> GKERunnerJob.Status: + ...
```suggestion """Retrieves the current status of the job. Returns: GKERunnerJob.Status: SUCCEEDED: When the job succeeded. PENDING: When the job hasn't started yet. READY: When the job is running. UNKNOWN: All o...
axlearn
github_2023
python
1,042
apple
markblee
@@ -1386,4 +1389,8 @@ def m_or_g(x, suffix=""): + f" Load Balancing / Dispatch): {cost_stats.get('utilization8{}')}\n" + f" Texture Units (or Rarely Used Compute Units): {cost_stats.get('utilization9{}')}" ) + else: + # Some platforms may return different format unlike CPU...
nit -- Consider logging the warning anyway? Seems useful for users to know that this isn't the 'intended' output.
axlearn
github_2023
python
1,036
apple
apghml
@@ -35,6 +40,7 @@ flags.DEFINE_string("config", None, "The trainer config name.", required=True) flags.DEFINE_string("topology", None, "The TPU topology.") flags.DEFINE_integer("topology_num_slices", 1, "The number of TPU slices.") +flags.DEFINE_boolean("cpu", False, "The number of TPU slices.")
The description of this flag looks incorrect?
axlearn
github_2023
python
1,036
apple
apghml
@@ -91,6 +101,14 @@ def _compile_and_dump_programs( logging.info("Wrote serialized %s to %s", program_name, serialized_compiled_output_path) +def _get_n_devices(topology: Optional[str]) -> int: + if topology is None:
I'm not sure it makes sense to default to 1024. Can we remove the default?
axlearn
github_2023
python
1,036
apple
apghml
@@ -1283,3 +1285,66 @@ def select_mesh_config(trainer_config: SpmdTrainer.Config, *, mesh_selector: str # Override configs from ConfigModifier. mesh_rule_fn = maybe_instantiate(mesh_rule) trainer_config = mesh_rule_fn(trainer_config) + + +def aot_model_analysis(compile...
I think this could be confusing since users might think the left number is the usage and right number is the maximum available. (e.g., they might mistake it for meaning "x mb out of y gb used"). Can we eliminate the mb?
axlearn
github_2023
python
1,036
apple
apghml
@@ -91,6 +101,14 @@ def _compile_and_dump_programs( logging.info("Wrote serialized %s to %s", program_name, serialized_compiled_output_path)
This PR still doesn't deduplicate the the memory printing code in `run_aot_compilation.py` with the new function you have in `trainer.py`?
axlearn
github_2023
python
1,036
apple
apghml
@@ -35,6 +40,7 @@ flags.DEFINE_string("config", None, "The trainer config name.", required=True) flags.DEFINE_string("topology", None, "The TPU topology.")
IIUC, this can now represent CPU topology too? Update the description and explain the format for CPU topology?
axlearn
github_2023
python
1,036
apple
kelvin-zou
@@ -1287,3 +1289,88 @@ def select_mesh_config(trainer_config: SpmdTrainer.Config, *, mesh_selector: str # Override configs from ConfigModifier. mesh_rule_fn = maybe_instantiate(mesh_rule) trainer_config = mesh_rule_fn(trainer_config) + + +def aot_model_analysis(compile...
Did you run regression test on GPU? One of the users is complaining about seeing some error: Wrapped call axlearn.common.trainer.SpmdTrainer.compile_train_step(trainer_state: axlearn.common.trainer.TrainerState, input_batch: dict, compiler_options: dict) File "/opt/axlearn/axlearn/common/trainer.py", line 1164, in...
axlearn
github_2023
python
1,037
apple
markblee
@@ -1072,6 +1091,150 @@ def cast(x: Union[Tensor, TensorSpec]) -> Union[Tensor, TensorSpec]: return jax.tree.map(cast, in_tree) +@runtime_checkable +class PerParamFn(Protocol[T]): + """A callable that operates on each parameter.""" + + def __call__(self, params: Union[Nested[Tensor], Nested[TensorSpec]])...
Looks like some docstring format got lost from copy/paste?
axlearn
github_2023
python
1,029
apple
ruomingp
@@ -822,65 +837,93 @@ def make_gda(x, partition_spec): return jax.tree.map(make_gda, host_arrays, partition_specs) +# TODO(markblee): Remove partition arg. def global_to_host_array( - global_arrays: NestedTensor, *, partition: DataPartitionType = DataPartitionType.FULL -) -> NestedTensor: - """Extracts ...
Nit: maybe `slice` is more readable than `tuple`?
axlearn
github_2023
python
1,028
apple
changlan
@@ -513,29 +519,15 @@ def _bool_value(self) -> Optional[Tensor]: Shape: [batch, target_len, source_len]. Raises: - NotImplementedError. If `target_positions.ndim not in [1,2]`. + ValueError. If `(target|source)_positions.ndim not == 2`. """ - target_positions, s...
fly-by comment: I wonder if we should do the same without introducing extra `einops` dependency.
axlearn
github_2023
python
1,020
apple
markblee
@@ -256,6 +256,14 @@ def define_flags(cls, fv: flags.FlagValues): "not all TPU types support this flag.", **common_kwargs, ) + # Currently only supported in specific clusters with PriorityClass setup. + # TODO(ethanli): infer it from the JobMetadata.priority, and support...
```suggestion # Only supported in clusters with PriorityClass setup. # TODO(ethanli): infer it from the JobMetadata.priority. ``` What's the behavior when specified and not supported? Is it silently ignored or raises an error?
axlearn
github_2023
python
1,018
apple
chunyang-wen
@@ -205,7 +205,10 @@ class BiasAndResidual(BaseAttentionBias, Generic[B]): residual: BaseAttentionBias def _value(self) -> Optional[Tensor]: - return CompositeAttentionBias([self.bias, self.residual]).value() + biases = [self.residual] + if self.bias is not None:
```python biases = [self.bias] if self.bias is not None else [] biases.append(self.residual) ```
axlearn
github_2023
python
1,009
apple
changlan
@@ -701,6 +701,11 @@ def sliding_window_causal_mask(sliding_window_size: int) -> MaskFn: """Returns a causal MaskFn for sliding window attentions of a given window size. Implements the `MaskFn` protocol. + + Note: Setting sliding_window_size = 8 results in a window size of 9, including itself.
nit: Maybe explicitly note that it attends to itself and sliding_window_size tokens on the left. "window size" is not a well defined term.
axlearn
github_2023
python
1,009
apple
changlan
@@ -730,8 +736,12 @@ def make_causal_biases(seq_len: int) -> Tensor: def make_sliding_window_causal_biases(seq_len: int, sliding_window_size: int) -> Tensor: """Generates attention logit biases for sliding window attention. + Note: Setting sliding_window_size = 8 results in attending to 9 tokens - it attends...
```suggestion Note: Each token attends to itself and sliding_window_size tokens to the left (i.e. sliding_window_size + 1 tokens). ```
axlearn
github_2023
python
1,009
apple
changlan
@@ -701,6 +701,12 @@ def sliding_window_causal_mask(sliding_window_size: int) -> MaskFn: """Returns a causal MaskFn for sliding window attentions of a given window size. Implements the `MaskFn` protocol. + + Note: Setting sliding_window_size = 8 results in attending to 9 tokens - it attends to itself
```suggestion Note: Each token attends to itself and sliding_window_size tokens to the left (i.e. sliding_window_size + 1 tokens). ```
axlearn
github_2023
python
995
apple
ruomingp
@@ -735,34 +937,31 @@ def init_states( # If `kv_state` is provided externally, we do not have to maintain key/value in cache. # Otherwise, initialize the cache from provided query, key, value. if kv_state is None: + kv_shape = dict(num_kv_heads=self.num_kv_heads, per_head_dim=cfg.p...
When does this happen? Can we raise a ValueError instead?
axlearn
github_2023
python
995
apple
ruomingp
@@ -843,44 +1042,32 @@ def extend_step( query_positions += time_step[:, None] # Project inputs to key, value and query. Each has shape [B, steps, N, H]. - q_proj, k_proj, v_proj = self.forward(query, **kv_kwargs, query_positions=query_positions) + q_proj, k_proj, v_proj, unused_q_pos, ...
Do we need this child_context?
axlearn
github_2023
python
994
apple
Ethanlm
@@ -334,6 +334,15 @@ class _SystemCharacteristics: "16x20x28", 2240, "tpu-v5p-slice", "ct5p-hightpu-4t", 4, AcceleratorType["TPU"], "v5p-17920" ), # v5litepod + "v5litepod-8": _SystemCharacteristics( + "2x4", + 2, + "tpu-v5-lite-podslice", + "ct5lp-hightpu-4t", + ...
Should this be 4 instead?
axlearn
github_2023
python
820
apple
ruomingp
@@ -0,0 +1,796 @@ +# Copyright © 2024 Apple Inc. + +"""Implements Orbax emergency checkpointing and provide utilities for correct store. + +See the docstring of `OrbaxEmergencyCheckpointer` for more details. +""" + +import copy +import functools +import hashlib +import multiprocessing as mp +import os +import time +fro...
How does this overlap with https://github.com/apple/axlearn/blob/140a18f33d10178dc695469e36d39d7879bd1ed4/axlearn/common/checkpointer_orbax.py#L169?
axlearn
github_2023
python
820
apple
ruomingp
@@ -0,0 +1,814 @@ +# Copyright © 2024 Apple Inc. + +"""Implements Orbax emergency checkpointing and provide utilities for correct store. + +See the docstring of `OrbaxEmergencyCheckpointer` for more details. +""" + +import copy +import functools +import hashlib +import multiprocessing as mp +import os +import time +fro...
RE: "Orbax emergency checkpointer doesn't support non-tensor states" While this is true, it seems that it can be extended to support non-tensor states. Specifically, the local checkpointer manager already writes process metadata: https://github.com/google/orbax/blob/6e80ecc27581a413b1a481d4740e61df7316a4f4/checkp...
axlearn
github_2023
python
820
apple
ruomingp
@@ -0,0 +1,814 @@ +# Copyright © 2024 Apple Inc. + +"""Implements Orbax emergency checkpointing and provide utilities for correct store. + +See the docstring of `OrbaxEmergencyCheckpointer` for more details. +""" + +import copy +import functools +import hashlib +import multiprocessing as mp +import os +import time +fro...
How do we mark the completion of a checkpoint? It should happen only when both tensor and non-tensor states are saved. How is this ensured? Please add a comment.
axlearn
github_2023
python
820
apple
ruomingp
@@ -0,0 +1,814 @@ +# Copyright © 2024 Apple Inc. + +"""Implements Orbax emergency checkpointing and provide utilities for correct store. + +See the docstring of `OrbaxEmergencyCheckpointer` for more details. +""" + +import copy +import functools +import hashlib +import multiprocessing as mp +import os +import time +fro...
Shall we expose `oecp.LocalCheckpointOptions` to users as `Config.local_checkpoint_options`? User can set it to None to disable local checkpoints. We can provide a helper function for users to construct `should_save_fn` from their policy.
axlearn
github_2023
python
820
apple
ruomingp
@@ -0,0 +1,814 @@ +# Copyright © 2024 Apple Inc. + +"""Implements Orbax emergency checkpointing and provide utilities for correct store. + +See the docstring of `OrbaxEmergencyCheckpointer` for more details. +""" + +import copy +import functools +import hashlib +import multiprocessing as mp +import os +import time +fro...
Consider refactoring this logic to a separate function so that it can be tested directly?
axlearn
github_2023
python
820
apple
ruomingp
@@ -0,0 +1,829 @@ +# Copyright © 2024 Apple Inc. + +"""Implements Orbax emergency checkpointing and provide utilities for correct store. + +See the docstring of `OrbaxEmergencyCheckpointer` for more details. +""" + +import copy +import functools +import hashlib +import multiprocessing as mp +import os +import time +fro...
```suggestion """Checkpointer implementation that uses Orbax emergency checkpoint. EXPERIMENTAL. Do not use for actual training runs since the checkpoint layout will likely change in the future. ## Summary: ```
axlearn
github_2023
python
820
apple
apivovarov
@@ -0,0 +1,832 @@ +# Copyright © 2024 Apple Inc. + +"""Implements Orbax emergency checkpointing and provide utilities for correct store. + +See the docstring of `OrbaxEmergencyCheckpointer` for more details. +""" + +import copy +import functools +import hashlib +import multiprocessing as mp +import os +import time +fro...
`local_state_handler` is missing here. CheckpointManager::__init__ does not have default value for local_state_handler ``` def __init__( self, local_directory: epath.PathLike, persistent_directory: epath.PathLike, global_mesh: jax.sharding.Mesh, abstract_state: PyTree, # a singl...
axlearn
github_2023
python
987
apple
apghml
@@ -30,6 +30,8 @@ def _sort_fields(klass: _T) -> _T: klass.__dataclass_fields__ = dict( sorted(klass.__dataclass_fields__.items(), key=lambda x: x[0]) ) + # Return the class after sorting the fields (for functional style) + return klass
It seems like this could be a footgun since people might not realize it also mutates its argument. Whereas trying to use the returned None value will loudly fail.
axlearn
github_2023
python
987
apple
apghml
@@ -803,6 +803,7 @@ def __enter__(self): if self._within_context: raise ValueError("Already in a context.") self._within_context = True + return self
I might be mistaken, but IIRC, it's not required for `__enter__()` to return anything in Python. I'm not necessarily opposed to adding the return here though.
axlearn
github_2023
python
987
apple
apghml
@@ -950,6 +951,7 @@ def __init__(self, cfg: Config, *, parent: Optional[Module]): def __enter__(self): super().__enter__() self._start_gc_thread()
Could you clarify whether the things you are changing in this and your other PR were found with the assistance of AI code checking tools?
axlearn
github_2023
python
939
apple
kelvin-zou
@@ -0,0 +1,142 @@ +# 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 + +# Import needed to enable JAX cache on Neuron +import jax_neuronx # pylint: disable=unused-import
Do we need to install packages? Maybe update pyproject toml as well? Also, can we make it an on demand import, to avoid breaking main execution just in case?
axlearn
github_2023
python
939
apple
kelvin-zou
@@ -0,0 +1,142 @@ +# 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 + +# Import needed to enable JAX cache on Neuron +import jax_neuronx # pylint: disable=unused-import +import neuronxcc.nki.l...
This part is already fixed by caller, you shouldn't need it. Is it not the case in your testing?
axlearn
github_2023
python
939
apple
ruomingp
@@ -276,13 +279,33 @@ def get_segment_ids(segment_ids: SegmentIdAttentionBias) -> Optional[Tensor]: block_size=block_size, ) + elif backend == "neuron":
Maybe only import `neuron_attention` inside this branch?
axlearn
github_2023
python
939
apple
ruomingp
@@ -0,0 +1,142 @@ +# 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 + +# Import needed to enable JAX cache on Neuron +import jax_neuronx # pylint: disable=unused-import +import neuronxcc.nki.l...
Nit: end comments with . (here and everywhere)
axlearn
github_2023
python
939
apple
ruomingp
@@ -0,0 +1,142 @@ +# 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 + +# Import needed to enable JAX cache on Neuron +import jax_neuronx # pylint: disable=unused-import +import neuronxcc.nki.l...
Add comments on args and return value shapes and semantics?
axlearn
github_2023
python
939
apple
kelvin-zou
@@ -0,0 +1,168 @@ +# 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 + +# Import needed to enable JAX cache on Neuron +import jax_neuronx # pylint: disable=unused-import +import neuronxcc.nki.l...
Can we support segment ID? Or a more general masking fn (with optimized handling) is even better.
axlearn
github_2023
python
939
apple
apivovarov
@@ -0,0 +1,168 @@ +# 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 + +# Import needed to enable JAX cache on Neuron +import jax_neuronx # pylint: disable=unused-import +import neuronxcc.nki.l...
``` # even num_heads except 0 if num_heads > 0 and num_heads % 2 == 0: ```
axlearn
github_2023
python
939
apple
apivovarov
@@ -0,0 +1,144 @@ +# 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.mark...
Maybe just ``` per_head_dim**-0.5 ```
axlearn
github_2023
python
939
apple
markblee
@@ -0,0 +1,144 @@ +# 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.mark...
Looks like a number of CI steps are failing -- I think we can either do something like ``` if jax.default_backend() != "neuron": pytest.skip(reason=..., allow_module_level=True) ``` or update `run_tests.sh` to exclude tests marked with `neuron`.
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 ...
This can be simplified to ``` # even num_heads except 0 if num_heads > 0 and num_heads % 2 == 0: ```
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 ...
This can be simplified to ``` # even num_heads except 0 if num_heads > 0 and num_heads % 2 == 0: ```
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...
Maybe just per_head_dim**-0.5