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
296
apple
ruomingp
@@ -830,9 +832,13 @@ def cast_floats(in_tree: NestedTensor, to_dtype: Optional[jnp.dtype]) -> NestedT from_dtype = jnp.float32 if to_dtype == jnp.bfloat16 else jnp.bfloat16 - def cast(x: Tensor) -> Tensor: + def cast(x: Union[Tensor, TensorSpec]) -> [Tensor, TensorSpec]: if x.dtype == from_dtype...
To avoid mutating `x`: ```suggestion return dataclasses.replace(x, dtype=to_dtype) ```
axlearn
github_2023
python
293
apple
ruomingp
@@ -416,11 +431,19 @@ def restore_from_dir( spec.tf_ckpt_map, dir=os.path.join(ckpt_dir, f"tf_{jax.process_index()}") ) + # Override dtype to target cast dtype. + # From jax docs, + # Cast while reloading on process to avoid 2 copies on device if the + # casting is do...
How would this handle integer vs float dtypes?
axlearn
github_2023
python
293
apple
ruomingp
@@ -404,7 +404,22 @@ def restore_from_dir( ckpt_dir: str, validation: CheckpointValidationType = CheckpointValidationType.EXACT, concurrent_gb: int = 32, + dtype_cast_func: Optional[Callable[[jnp.dtype], jnp.dtype]] = None, ) -> NestedTensor: + """Restore checkpoints in ten...
```suggestion dtype_cast_func (Optional[Callable[[jnp.dtype], jnp.dtype]]): Function to map saved dtypes to restored dtypes. ```
axlearn
github_2023
python
293
apple
ruomingp
@@ -559,17 +559,27 @@ def test_read_state_spec(self): class TensorStoreStateStorageTest(test_utils.TestCase): - @parameterized.parameters(jnp.float32, jnp.bfloat16, jnp.int32, jnp.int16) - def test_save_and_restore_from_dir(self, restore_floats_as: jnp.dtype): + @parameterized.parameters( + [jnp.fl...
Comment on the difference between `restore_floats_as` and `cast_dtype`? Shouldn't they be the same?
axlearn
github_2023
python
293
apple
ruomingp
@@ -404,7 +404,22 @@ def restore_from_dir( ckpt_dir: str, validation: CheckpointValidationType = CheckpointValidationType.EXACT, concurrent_gb: int = 32, + dtype_cast_func: Optional[Callable[[jnp.dtype], jnp.dtype]] = None,
Reading the unittest again, I'm not sure we need this new arg. It seems that user can manipulate `state` by casting one type to another instead. Would that work?
axlearn
github_2023
python
201
apple
apghml
@@ -0,0 +1,90 @@ +"""Utilities for ahead-of-time compilation. + +Reference: +https://docs.google.com/document/d/1Y5IdmvAZA7UtMHAWkRh8k2PscVoG5FvMH9-E6hygsyY/ +""" +import os + +os.environ["JAX_PLATFORMS"] = "cpu" +os.environ["TPU_SKIP_MDS_QUERY"] = "1" + +import copy +from dataclasses import dataclass +from typing impo...
Is this redundant with the environment variable above?
axlearn
github_2023
python
201
apple
apghml
@@ -0,0 +1,90 @@ +"""Utilities for ahead-of-time compilation. + +Reference: +https://docs.google.com/document/d/1Y5IdmvAZA7UtMHAWkRh8k2PscVoG5FvMH9-E6hygsyY/ +""" +import os + +os.environ["JAX_PLATFORMS"] = "cpu" +os.environ["TPU_SKIP_MDS_QUERY"] = "1" + +import copy +from dataclasses import dataclass +from typing impo...
```suggestion cfg = trainer_cfg.clone() ```
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,90 @@ +"""Utilities for ahead-of-time compilation. + +Reference: +https://docs.google.com/document/d/1Y5IdmvAZA7UtMHAWkRh8k2PscVoG5FvMH9-E6hygsyY/ +""" +import os + +os.environ["JAX_PLATFORMS"] = "cpu" +os.environ["TPU_SKIP_MDS_QUERY"] = "1" + +import copy +from dataclasses import dataclass +from typing impo...
Link to ref in case we need to update? https://github.com/google/maxtext/blob/bff7efbb7a51dfaf7c1739aae22a9cd742386fef/MaxText/accelerator_to_spec_map.py#L33 (FWIW we may eventually want to move to a common file since it is useful on the GKE side.)
axlearn
github_2023
python
201
apple
apghml
@@ -163,7 +178,7 @@ class Config(Module.Config): # increment within this interval. watchdog_timeout_seconds: Optional[float] = None - def __init__(self, cfg: Config, *, parent: Optional[Module]): + def __init__(self, cfg: Config, *, parent: Optional[Module], devices=None):
Add a type annotation for `devices`?
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,90 @@ +"""Utilities for ahead-of-time compilation. + +Reference: +https://docs.google.com/document/d/1Y5IdmvAZA7UtMHAWkRh8k2PscVoG5FvMH9-E6hygsyY/ +""" +import os + +os.environ["JAX_PLATFORMS"] = "cpu" +os.environ["TPU_SKIP_MDS_QUERY"] = "1" + +import copy +from dataclasses import dataclass +from typing impo...
```suggestion trainer_config: The trainer config. topology: A string representing the TPU topology, e.g., "v4-8". Must be a key in USER_FACING_NAME_TO_SYSTEM_CHARACTERISTICS. topology_num_slices: Number of TPU slices. ```
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,90 @@ +"""Utilities for ahead-of-time compilation. + +Reference: +https://docs.google.com/document/d/1Y5IdmvAZA7UtMHAWkRh8k2PscVoG5FvMH9-E6hygsyY/ +""" +import os + +os.environ["JAX_PLATFORMS"] = "cpu" +os.environ["TPU_SKIP_MDS_QUERY"] = "1" + +import copy +from dataclasses import dataclass +from typing impo...
```suggestion cfg = trainer_config.clone(dir="NOT_USED") ``` ?
axlearn
github_2023
python
201
apple
markblee
@@ -70,6 +70,21 @@ def _prune_empty(in_tree: NestedTensor) -> NestedTensor: return prune_tree(in_tree, lambda _, v: isinstance(v, dict) and not v) +def to_jax_dtype(tf_dtype: tf.DType) -> jnp.dtype:
Where is this used?
axlearn
github_2023
python
201
apple
markblee
@@ -70,6 +70,21 @@ def _prune_empty(in_tree: NestedTensor) -> NestedTensor: return prune_tree(in_tree, lambda _, v: isinstance(v, dict) and not v) +def to_jax_dtype(tf_dtype: tf.DType) -> jnp.dtype: + if tf_dtype == tf.int32: + return jnp.int32 + elif tf_dtype == tf.float32: + return jnp.fl...
Same question.
axlearn
github_2023
python
201
apple
markblee
@@ -747,6 +764,23 @@ def _pjit_train_step(self): donate_argnums=(0,), # donate the state ) + def compile_train_step(self) -> Callable: + with self.mesh(): + # Do not run init(), which require real devices. + # trainer_state_specs = jax.eval_shape(self.init, jax.r...
Intentional?
axlearn
github_2023
python
201
apple
apghml
@@ -0,0 +1,70 @@ +# Copyright © 2023 Apple Inc. + +"""AoT (ahead-of-time) compilation config tests. + +pip install 'jax[tpu]==0.4.21' -f https://storage.googleapis.com/jax-releases/libtpu_releases.html + +export TPU_SKIP_MDS_QUERY=1 +python axlearn/experiments/aot_test.py + +Reference: +https://docs.google.com/document...
Are these lines needed in the test? If so, would it make sense to deduplicate them with the similar lines in `_compile_and_dump_programs`?
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,90 @@ +"""Utilities for ahead-of-time compilation.
Missing copyright.
axlearn
github_2023
python
201
apple
apghml
@@ -0,0 +1,90 @@ +"""Utilities for ahead-of-time compilation. + +Reference: +https://docs.google.com/document/d/1Y5IdmvAZA7UtMHAWkRh8k2PscVoG5FvMH9-E6hygsyY/
This Google doc asks me to sign in in order to view it. Is it publicly accessible?
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,70 @@ +# Copyright © 2023 Apple Inc. + +"""AoT (ahead-of-time) compilation config tests. + +pip install 'jax[tpu]==0.4.21' -f https://storage.googleapis.com/jax-releases/libtpu_releases.html + +export TPU_SKIP_MDS_QUERY=1 +python axlearn/experiments/aot_test.py + +Reference: +https://docs.google.com/document...
```suggestion def _jax_backend(self) -> str: ```
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,78 @@ +# Copyright © 2023 Apple Inc.
```suggestion # Copyright © 2023 Apple Inc. ```
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,78 @@ +# Copyright © 2023 Apple Inc. +"""A command-line tool to perform AoT (ahead-of-time) compilation. + +pip install 'jax[tpu]==0.4.21' -f https://storage.googleapis.com/jax-releases/libtpu_releases.html +python axlearn/experiments/run_aot_compilation.py \ + --config_module=text.gpt.c4_trainer \ + -...
```suggestion flags.DEFINE_string("module", None, "The trainer config module.") flags.DEFINE_string("config", None, "The trainer config name.") flags.DEFINE_string("topology", None, "The TPU topology.") ``` For consistency with `launch_trainer`
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,78 @@ +# Copyright © 2023 Apple Inc. +"""A command-line tool to perform AoT (ahead-of-time) compilation. + +pip install 'jax[tpu]==0.4.21' -f https://storage.googleapis.com/jax-releases/libtpu_releases.html +python axlearn/experiments/run_aot_compilation.py \ + --config_module=text.gpt.c4_trainer \ + -...
Would it make sense to have this be in `aot_compilation`? E.g. we seem to do the same thing in aot_test.
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,78 @@ +# Copyright © 2023 Apple Inc. +"""A command-line tool to perform AoT (ahead-of-time) compilation. + +pip install 'jax[tpu]==0.4.21' -f https://storage.googleapis.com/jax-releases/libtpu_releases.html +python axlearn/experiments/run_aot_compilation.py \ + --config_module=text.gpt.c4_trainer \ + -...
```suggestion compile_topology=FLAGS.topology, compile_topology_num_slices=FLAGS.topology_num_slices, ```
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,191 @@ +# Copyright © 2023 Apple Inc. + +"""Utilities for ahead-of-time compilation. + +Reference: +https://docs.google.com/document/d/1Y5IdmvAZA7UtMHAWkRh8k2PscVoG5FvMH9-E6hygsyY/ +""" +import os + +os.environ["TPU_SKIP_MDS_QUERY"] = "1" + +from dataclasses import dataclass +from typing import Callable, Dic...
Since `topology` is user-supplied, consider raising a useful error message if it's an invalid key?
axlearn
github_2023
python
201
apple
markblee
@@ -0,0 +1,54 @@ +# Copyright © 2023 Apple Inc. + +"""AoT (ahead-of-time) compilation config tests. + +pip install 'jax[tpu]==0.4.21' -f https://storage.googleapis.com/jax-releases/libtpu_releases.html + +export TPU_SKIP_MDS_QUERY=1 +python axlearn/experiments/aot_test.py + +Reference: +https://docs.google.com/document...
nit: consider removing if it's going to use the default anyway?
axlearn
github_2023
python
280
apple
apghml
@@ -17,8 +17,8 @@ "resource_type2": 8, }, "project_resources": { - "team1": {"resource_type1": 0.5}, - "team2": {"resource_type1": 0.5, "resource_type2": 1.0}, + "team1": {"resource_type1": 0.3},
Does this test fail without the change? I get: ``` > 4.8+11.2==16 True > 12.8+11.2==24 True > 0.3+0.7==1 True ``` Maybe it would make sense to use: ``` > 0.1 + 0.2 <= 0.3 False ```
axlearn
github_2023
python
273
apple
yqwangustc
@@ -243,6 +248,8 @@ def test_asr_encoder(self, is_training: bool): self.assertEqual(output_paddings.shape, (batch_size, output_shape[1])) self.assertTrue(jnp.all(output_paddings[:2] == output_paddings[2:])) - # If is_training, outputs should always be different due to augmentation. + #...
nit: I am a little confused about why `outputs[:2]` should be the same as `outputs[2:]`, could you add a comment to explain why they are the same in this case ?
axlearn
github_2023
python
251
apple
markblee
@@ -229,13 +229,25 @@ def _delete(self): def _execute(self): cfg: DataflowJob.Config = self.config - # Run the setup command locally, but the launch command via docker. # This is to ensure that the launch environment matches the worker environment. - cmd = ( - "docker...
```suggestion # Disable running from docker on Mac M1 chip due to qemu core dump bug. ```
axlearn
github_2023
python
264
apple
ruomingp
@@ -387,6 +387,8 @@ def process_kv(key: str, val: Any): default_val = field.default if val is default_val and default_val in omit_default_values: return + elif field is None and val in omit_default_values:
I wonder if we could apply this logic only to dataclass fields.
axlearn
github_2023
others
264
apple
ruomingp
@@ -223,7 +221,6 @@ model.decoder.transformer.layer.self_attention.attention.output_linear.param_par model.decoder.transformer.layer.self_attention.attention.output_linear.param_partition_spec[0][1]: 'fsdp' model.decoder.transformer.layer.self_attention.attention.output_linear.param_partition_spec[0][2]: 'seq' model...
Applying it to list/tuple/dict seems going too far, e.g., here it will not be easy for readers to tell that `param_partition_spec` actually has three elements rather than two. WDYT?
axlearn
github_2023
python
264
apple
ruomingp
@@ -371,7 +371,14 @@ def to_flat_dict(self, *, omit_default_values: Collection[Any]) -> Dict[str, Any result = {} def enter(key: str, val: Any, default_result: Optional[List]) -> Optional[List]: - if key and isinstance(val, ConfigBase): + if dataclasses.is_dataclass(val) and no...
```suggestion kvs_to_traverse = [] ```
axlearn
github_2023
python
264
apple
ruomingp
@@ -371,7 +371,14 @@ def to_flat_dict(self, *, omit_default_values: Collection[Any]) -> Dict[str, Any result = {} def enter(key: str, val: Any, default_result: Optional[List]) -> Optional[List]: - if key and isinstance(val, ConfigBase): + if dataclasses.is_dataclass(val) and no...
We should omit only if cur_val is the default value of the dataclass field, e.g., ``` @dataclass class foo: x: Optional[int] = None y: Optional[int] = -1 ``` We should omit if `x is None` but not if `y is None`. This is to make it consistent with the attribute values below.
axlearn
github_2023
python
264
apple
ruomingp
@@ -371,7 +371,23 @@ def to_flat_dict(self, *, omit_default_values: Collection[Any]) -> Dict[str, Any result = {} def enter(key: str, val: Any, default_result: Optional[List]) -> Optional[List]: - if key and isinstance(val, ConfigBase): + if dataclasses.is_dataclass(val) and no...
What if `default_result_dict` contains keys that are not a field? We would've missed them in this loop. It would be more robust to iterate through `default_result_dict` and check they are all fields?
axlearn
github_2023
python
246
apple
markblee
@@ -28,6 +29,7 @@ class SpeechFeatureLayerTest(TestCase): """Tests SpeechFeatureLayer.""" @parameterized.parameters([True, False]) + @pytest.mark.fp64
I wonder why you see these changes? Is this rebased to main?
axlearn
github_2023
python
211
apple
markblee
@@ -28,6 +28,40 @@ from axlearn.common.utils import Nested, Tensor +def is_valid_ctc_seq(logitpaddings, labels, labelpaddings):
```suggestion def _is_valid_ctc_seq(*, paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: ``` In general, can we add type+return annotations and follow existing naming conventions (following https://github.com/apple/axlearn/blob/main/CONTRIBUTING.md) here and elsewhere?
axlearn
github_2023
python
211
apple
markblee
@@ -88,6 +91,80 @@ def test_map_label_sequences( jit_fn(inputs, blank_id=blank_id, pad_id=pad_id), ) +class ValidCtcSeqTest(TestCase): + + def get_logits_and_labels(self, batchsize, timesteps, labelsteps, nclasses): + logits = np.random.randn(batchsize, timesteps, nclasses) + logitpadding...
Shall we also update `test_forward` to make sure we cover the training codepath?
axlearn
github_2023
python
211
apple
markblee
@@ -230,6 +238,16 @@ def assertNestedEqual(self, a, b): if hasattr(a_value, "dtype"): self.assertEqual(a_value.dtype, b_value.dtype) + def assertAllClose(self, x, y, check_dtypes=True, rtol=1e-5, atol=1e-5, **kwargs):
Do we need this, or can we use `assertNestedAllClose`?
axlearn
github_2023
python
211
apple
markblee
@@ -89,6 +91,75 @@ def test_map_label_sequences( ) +class ValidCtcSeqTest(TestCase): + def get_logits_and_labels(self, batchsize, timesteps, labelsteps, nclasses):
Same comment as above re types and naming -- also, should we use `jnp`/`jax.random` here and elsewhere? Besides consistency, we can avoid `np.random` calls that may depend on a global seed?
axlearn
github_2023
python
211
apple
markblee
@@ -28,6 +28,39 @@ from axlearn.common.utils import Nested, Tensor +def is_valid_ctc_seq(logitpaddings, labels, labelpaddings): + """Returns for per example sequence if it passes validity check. + + Note that the above `ctc_loss_with_alignments` returns logeps + (usually a very large number) if the input ...
Fix docstring following rest of repo?
axlearn
github_2023
python
211
apple
markblee
@@ -28,6 +28,39 @@ from axlearn.common.utils import Nested, Tensor +def is_valid_ctc_seq(logitpaddings, labels, labelpaddings): + """Returns for per example sequence if it passes validity check. + + Note that the above `ctc_loss_with_alignments` returns logeps
What is `ctc_loss_with_alignments` referring to?
axlearn
github_2023
python
211
apple
markblee
@@ -89,6 +91,75 @@ def test_map_label_sequences( ) +class ValidCtcSeqTest(TestCase): + def get_logits_and_labels(self, batchsize, timesteps, labelsteps, nclasses): + logits = np.random.randn(batchsize, timesteps, nclasses) + logitpaddings = np.zeros((batchsize, timesteps), dtype=np.int32) ...
nit: Remove debugging prints here and elsewhere?
axlearn
github_2023
python
211
apple
zhiyun
@@ -28,6 +28,43 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq( + paddings: Tensor, + target_labels: Tensor, + target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns logeps (...
Do we need to cast type here, since we cast type in forward?
axlearn
github_2023
python
211
apple
zhiyun
@@ -28,6 +28,43 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq( + paddings: Tensor, + target_labels: Tensor, + target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns logeps (...
Can we give a reference link to optax implementation on this?
axlearn
github_2023
python
211
apple
zhiyun
@@ -28,6 +28,39 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq(paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns -logeps (default to 1e5) if the + ...
Follow the rest of the file, use `[batch_size, num_frames-1]`?
axlearn
github_2023
python
211
apple
zhiyun
@@ -28,6 +28,39 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq(paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns -logeps (default to 1e5) if the + ...
paddings of input frames.
axlearn
github_2023
python
211
apple
zhiyun
@@ -28,6 +28,39 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq(paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns -logeps (default to 1e5) if the + ...
Add a brief explanation, sth like "to account for the extra blank token inserted between the dup tokens."
axlearn
github_2023
python
211
apple
zhiyun
@@ -89,6 +91,97 @@ def test_map_label_sequences( ) +class ValidCtcSeqTest(TestCase): + def get_logits_and_labels( + self, batch_size: int, time_steps: int, target_steps: int, nclasses: int + ) -> tuple[Tensor, Tensor, Tensor, Tensor]:
time_steps -> input_lengths target_steps -> target_lengths nclasses -> vocab_size
axlearn
github_2023
python
211
apple
zhiyun
@@ -89,6 +91,97 @@ def test_map_label_sequences( ) +class ValidCtcSeqTest(TestCase): + def get_logits_and_labels( + self, batch_size: int, time_steps: int, target_steps: int, nclasses: int + ) -> tuple[Tensor, Tensor, Tensor, Tensor]: + prng_key = jax.random.PRNGKey(1234) + logit...
Nit: Use full sentence for comment: start with Capitalize, and end with period `.`
axlearn
github_2023
python
211
apple
zhiyun
@@ -89,6 +91,97 @@ def test_map_label_sequences( ) +class ValidCtcSeqTest(TestCase): + def get_logits_and_labels( + self, batch_size: int, time_steps: int, target_steps: int, nclasses: int + ) -> tuple[Tensor, Tensor, Tensor, Tensor]: + prng_key = jax.random.PRNGKey(1234) + logit...
Same here. Use complete sentence for comment.
axlearn
github_2023
python
211
apple
zhiyun
@@ -230,6 +238,16 @@ def assertNestedEqual(self, a, b): if hasattr(a_value, "dtype"): self.assertEqual(a_value.dtype, b_value.dtype) + def assertTensorAllClose(self, x, y, rtol=1e-5, atol=1e-5, check_dtypes=True, **kwargs): + """assert Tensor are all close.""" + x = np.a...
@markblee to comment if we want to add this util.
axlearn
github_2023
python
211
apple
ruomingp
@@ -28,6 +28,40 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq(paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns -logeps (default to 1e5) if the + ...
```suggestion A float tensor of shape [batch_size] indicating if each (input, label) pair is valid, ```
axlearn
github_2023
python
211
apple
markblee
@@ -28,6 +28,40 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq(paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns -logeps (default to 1e5) if the + ...
```suggestion consecutive duplications, because we need a blank to token to transition between the same labels. When this condition is not met, it should be considered as an invalid sequence and the loss should be ignored. ```
axlearn
github_2023
python
211
apple
markblee
@@ -28,6 +28,40 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq(paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns -logeps (default to 1e5) if the + ...
```suggestion A validity check is passed if for an example when: ```
axlearn
github_2023
python
211
apple
markblee
@@ -28,6 +28,40 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq(paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns -logeps (default to 1e5) if the + ...
```suggestion paddings: A 0/1 Tensor of shape [batch_size, num_frames] representing paddings of input frames. target_labels: An int Tensor of shape [batch_size, num_labels]. target_paddings: A 0/1 Tensor of shape [batch_size, num_labels]. ```
axlearn
github_2023
python
211
apple
markblee
@@ -89,6 +91,99 @@ def test_map_label_sequences( ) +class ValidCtcSeqTest(TestCase): + def get_logits_and_labels( + self, batch_size: int, input_lengths: int, target_lengths: int, vocab_size: int + ) -> tuple[Tensor, Tensor, Tensor, Tensor]: + prng_key = jax.random.PRNGKey(1234) + ...
Consider having a test w/ duplicates but not consecutively?
axlearn
github_2023
python
211
apple
markblee
@@ -89,6 +91,99 @@ def test_map_label_sequences( ) +class ValidCtcSeqTest(TestCase): + def get_logits_and_labels( + self, batch_size: int, input_lengths: int, target_lengths: int, vocab_size: int + ) -> tuple[Tensor, Tensor, Tensor, Tensor]: + prng_key = jax.random.PRNGKey(1234) + ...
Please see @zhiyun 's comment re. comment formatting here and below.
axlearn
github_2023
python
211
apple
markblee
@@ -28,6 +28,40 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq(paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check.
```suggestion def _is_valid_ctc_seq(*, paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: """Returns whether each input sequence passes validity check. ```
axlearn
github_2023
python
211
apple
markblee
@@ -28,6 +28,40 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq(paddings: Tensor, target_labels: Tensor, target_paddings: Tensor) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns -logeps (default to 1e5) if the + ...
I wonder whether we should consider `jnp.logical_or(target_paddings[:, :-1], target_paddings[:, 1:])` when dropping dups?
axlearn
github_2023
python
211
apple
markblee
@@ -28,6 +28,47 @@ from axlearn.common.utils import Nested, Tensor +def _is_valid_ctc_seq( + *, paddings: Tensor, target_labels: Tensor, target_paddings: Tensor +) -> Tensor: + """Returns for per example sequence if it passes validity check. + + Note that `optax.ctc_loss` returns -logeps (default to 1e5) ...
nit -- please use 4 space indents.
axlearn
github_2023
python
253
apple
tgunter
@@ -2358,17 +2373,29 @@ def __init__(self, cfg: Config, *, parent: Module): raise NotImplementedError(cfg.structure) self._add_child("stochastic_depth", cfg.stochastic_depth) + for value in cfg.add_value_rms_norm_summary: + if value != "linear2_outputs": + raise ...
nit: ```suggestion """Applies linear2, optionally logging RMS norm of the output.""" ```
axlearn
github_2023
python
223
apple
markblee
@@ -14,7 +14,17 @@ class Job(Configurable): - """Base Job definition.""" + """Base Job definition. + + Job's main API method is `execute`, which sets up the environment according to `bundler`, + runs the specified `command`, and retries if necessary. + + Subclasses of `Job` further specify the platf...
(As a side note, this is mostly necessary for jobs intended to be run by bastion.)
axlearn
github_2023
python
222
apple
markblee
@@ -350,7 +350,8 @@ def _run_command(self): # Set env vars, run the command and pipe outputs to run log. # Depending on command returncode, emit either success or failure flag. # Note that we use PIPESTATUS[0] to check the returncode of the first command in the pipe. - cmd = f"""mkdir ...
Does it work if we set it in `start_tpu.sh`?
axlearn
github_2023
python
230
apple
zhiyun
@@ -0,0 +1,149 @@ +# Copyright © 2023 Apple Inc. + +"""Base Encoder-Decoder model interface.""" + +from typing import Callable, Dict, Optional, Sequence, Tuple + +from axlearn.common.base_layer import BaseLayer +from axlearn.common.base_model import BaseModel +from axlearn.common.config import REQUIRED, ConfigOr, Requi...
Is `target_labels` required? Can we remove it here? `self._validate_input_batch(input_batch, paths=["source", "target"])`
axlearn
github_2023
python
227
apple
zhiyun
@@ -29,7 +29,7 @@ axlearn gcp dataflow start \ --name=$USER-dataflow \ --bundler_spec=dockerfile=Dockerfile \ - --bundler_spec=base_image=apache/beam_python3.8_sdk:2.38.0 \ + --bundler_spec=base_image=apache/beam_python3.10_sdk:2.52.0 \
3.9_sdk:2.52.0
axlearn
github_2023
python
206
apple
markblee
@@ -1877,8 +1971,8 @@ def _compute_logits(self, q_proj: Tensor, k_proj: Tensor) -> Tensor: # In the original XL-Net code, it applies scale on AC + BD: # # https://github.com/zihangdai/xlnet/blob/bbaa3a6fa0b3a2ee694e8cf66167434f9eca9660/modeling.py#L148 - scale = self.pe...
Intended?
axlearn
github_2023
python
206
apple
ruomingp
@@ -1847,13 +1939,12 @@ def forward( def _compute_logits(self, q_proj: Tensor, k_proj: Tensor) -> Tensor: cfg = self.config - if cfg.per_dim_scale is not None: - # Applies a per dim scale on q_proj. - q_proj = self.per_dim_scale(q_proj) + with child_context("apply_per...
Should we call `scale_query.apply_norm` before `apply_per_dim_scale`?
axlearn
github_2023
python
203
apple
markblee
@@ -19,6 +19,22 @@ --trainer_dir=$OUTPUT_DIR \ --data_dir=$GS_ROOT/tensorflow_datasets \ --mesh_selector=$INSTANCE_TYPE + +wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh; \ +bash Miniconda3-latest-Linux-x86_64.sh; \ +bash +conda create -n axlearn python=3.10; \ +co...
Is this intended for merge, or just to share w/ jax team?
axlearn
github_2023
python
198
apple
ruomingp
@@ -58,6 +59,9 @@ class Config(BaseModel.Config): # These will be used to constrain the sequence axis of relevant inputs. # If None, no batch sequence dim constraints are applied. seq_axis_names: Optional[Tuple[str]] = None + # `aux_loss` can only be collected when `aux_loss_regex` is ...
```suggestion # If not None, collect Tensors from `module_outputs` whose paths fully match the regular # expression and compute the sum as the auxiliary loss, which will be added to the overall # model loss and reported in the summary as `aux_loss`. # # This can be used to...
axlearn
github_2023
python
197
apple
ruomingp
@@ -366,20 +393,65 @@ def __init__( super().__init__( cfg, parent=parent, model=model, model_param_partition_specs=model_param_partition_specs ) - - for name, calculator_cfg in cfg.metric_calculators.items(): - self._add_child( + # Maps dst to (one or more) src ca...
Thanks for adding this check. I envision a more strict check where `dst_key` is required to be globally unique. Strictly speaking it's not necessary, but I think it will make the data model clearer by avoiding confusion on which src produces the dst_key. WDYT?
axlearn
github_2023
python
178
apple
markblee
@@ -176,7 +176,6 @@ def _locate_user_config_file() -> Optional[str]: config_file = None for path in search_paths: if os.path.exists(path): - logging.log_first_n(logging.INFO, "Found user config at %s", 1, path)
Missing a rebase?
axlearn
github_2023
others
163
apple
ruomingp
@@ -1,3 +1,19 @@ # Concepts in the AXLearn Library **This doc is still under construction.** + + +## Input Batch Sharding + +WWhen using `SpmdTrainer`, it is common to read and process inputs across all processes and hosts. For the most common use case where you want each process to have an equal portion of the inp...
```suggestion When using `SpmdTrainer`, it is common to read and process inputs across all processes and hosts. For the most common use case where you want each process to have an equal portion of the input batch, this process is mostly transparent to the user. For more complex use cases, it can be helpful to have...
axlearn
github_2023
python
154
apple
ruomingp
@@ -1528,32 +1595,110 @@ def test_data_types(self, dtype: jnp.dtype, per_dim_scale: Optional[PerDimScale. dtype=(jnp.float32, jnp.float16, jnp.bfloat16), per_dim_scale=(None, PerDimScale.default_config()), atten_logit_cap=(0.0, 20.0), + input_linear=( + None, # Use the defa...
Do we test the cases when bias=False?
axlearn
github_2023
python
138
apple
ruomingp
@@ -0,0 +1,127 @@ +# Copyright © 2023 Apple Inc. + +"""Audio frontends for feature extraction.""" + +from typing import Callable, Dict, Optional, Sequence, Union + +import jax.numpy as jnp + +from axlearn.audio.frontend_utils import ( + WindowType, + linear_to_log_mel_spectrogram, + linear_to_mel_weight_matrix...
```suggestion output_transformation: Optional[InstantiableConfig[Callable[[Tensor], Tensor]]] = None ```
axlearn
github_2023
python
138
apple
ruomingp
@@ -0,0 +1,127 @@ +# Copyright © 2023 Apple Inc. + +"""Audio frontends for feature extraction.""" + +from typing import Callable, Dict, Optional, Sequence, Union + +import jax.numpy as jnp + +from axlearn.audio.frontend_utils import ( + WindowType, + linear_to_log_mel_spectrogram, + linear_to_mel_weight_matrix...
Give an example?
axlearn
github_2023
python
138
apple
ruomingp
@@ -0,0 +1,127 @@ +# Copyright © 2023 Apple Inc. + +"""Audio frontends for feature extraction.""" + +from typing import Callable, Dict, Optional, Sequence, Union + +import jax.numpy as jnp + +from axlearn.audio.frontend_utils import ( + WindowType, + linear_to_log_mel_spectrogram, + linear_to_mel_weight_matrix...
Looks like this is not just scaling, but also shifting. Is `normalize_by_mean_std` a more accurate name?
axlearn
github_2023
python
135
apple
ruomingp
@@ -0,0 +1,54 @@ +# Copyright © 2023 Apple Inc. + +"""Input processing utilities on tf.data for ranking-related tasks.""" +from typing import Dict + +import seqio +import tensorflow as tf + +from axlearn.common import input_tf_data + + +def rank_by_value( + *, input_key: str, output_key: str, ascending: bool = True,...
Nit: remove default values, as they are not obvious choices, so spelling them out explicitly at call sites will make the code more readable. ```suggestion *, input_key: str, output_key: str, ascending: bool, allow_ties: bool, ```
axlearn
github_2023
python
135
apple
ruomingp
@@ -0,0 +1,54 @@ +# Copyright © 2023 Apple Inc. + +"""Input processing utilities on tf.data for ranking-related tasks.""" +from typing import Dict + +import seqio +import tensorflow as tf + +from axlearn.common import input_tf_data + + +def rank_by_value( + *, input_key: str, output_key: str, ascending: bool = True,...
Comment on how we break ties when allow_ties=False.
axlearn
github_2023
python
122
apple
ruomingp
@@ -1108,6 +1110,28 @@ def forward(self, x: Tensor) -> Tensor: return (x * scale).astype(x.dtype) +ScaleFn = Callable[[int], float] # A function mapping per_head_dim to a scale. + + +def constant_scale_config(value: float) -> InstantiableConfig[ScaleFn]: + """A config for a constant scale function for ...
```suggestion def constant_function(per_head_dim: int, value: float) -> float: ```
axlearn
github_2023
python
111
apple
markblee
@@ -8,9 +8,6 @@ # # ofirpress/attention_with_linear_biases: # Copyright (c) Facebook, Inc. and its affiliates. -# -# facebookresearch/llama:
Why is this reverted?
axlearn
github_2023
python
105
apple
markblee
@@ -808,6 +808,41 @@ def test_rope_self_attention(self): ) +class RoFormerSinusoidalPositionalEmbeddingAgainstLLaMATest(TestCase): + def llama_ref_precompute_freqs_cis(self, dim: int, end: int, theta: float = 10000.0): + """Reference LLaMA-1 implemention. + + Ref: + https://github.c...
We may want to add to header: ``` # facebookresearch/llama: # Copyright (c) Meta Platforms, Inc. and affiliates. ```
axlearn
github_2023
python
102
apple
ruomingp
@@ -158,6 +159,8 @@ def visit(tree, prefix): (k, visit(v, _concat(prefix=prefix, suffix=k, separator=separator))) for k, v in tree.items() ) + elif isinstance(tree, flax.struct.PyTreeNode):
Is there a test that can be added to catch the issue?
axlearn
github_2023
python
89
apple
markblee
@@ -176,6 +188,26 @@ def test_layer_norm(self): ref_layer=hf_layer, test_inputs=[inputs], ref_inputs=as_torch_tensor(inputs), + test_torch_to_axlearn=True, + ) + self.assertNestedAllClose(out, hf_out) + + def test_layer_norm_stateless(self):
Consider parameterizing the `test_layer_norm` test? It may also make it easier to check the invalid elementwise_affine codepath.
axlearn
github_2023
python
89
apple
markblee
@@ -583,7 +615,7 @@ def test_roundtrip(self, arch, repeat, fuse_qkv): hf_layer_copy(**hf_inputs).logits, ), ) - self.assertNestedAllClose(expected, actual) + self.assertNestedAllClose(expected, actual, atol=1e-5, rtol=1e-3)
Intended change?
axlearn
github_2023
others
57
apple
markblee
@@ -0,0 +1,72 @@ +# Bastion: Axlearn's Job Scheduler + +## Control Flow of Job Submission +```mermaid +%% elk seems to be more maintained, see: https://github.com/mermaid-js/mermaid/issues/1969 +%% N.B. elk doesn't stop rendering invisible edge operator, i.e. ~~~ +%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%% ...
Actually, submit need not start from github repo. We should be able to launch from a pip install in a different CWD.
axlearn
github_2023
others
57
apple
markblee
@@ -0,0 +1,72 @@ +# Bastion: Axlearn's Job Scheduler + +## Control Flow of Job Submission +```mermaid +%% elk seems to be more maintained, see: https://github.com/mermaid-js/mermaid/issues/1969 +%% N.B. elk doesn't stop rendering invisible edge operator, i.e. ~~~ +%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%% ...
```suggestion bastionLogStore--"Download logs for debug"-->UserMachine ```
axlearn
github_2023
others
57
apple
markblee
@@ -0,0 +1,72 @@ +# Bastion: Axlearn's Job Scheduler + +## Control Flow of Job Submission +```mermaid +%% elk seems to be more maintained, see: https://github.com/mermaid-js/mermaid/issues/1969 +%% N.B. elk doesn't stop rendering invisible edge operator, i.e. ~~~ +%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%% ...
```suggestion WorkerVM_2 --"Sync logs"--> bastionLogStore ``` Should WorkerVM_1 also have the "sync logs" branch?
axlearn
github_2023
others
57
apple
markblee
@@ -0,0 +1,72 @@ +# Bastion: Axlearn's Job Scheduler + +## Control Flow of Job Submission +```mermaid +%% elk seems to be more maintained, see: https://github.com/mermaid-js/mermaid/issues/1969 +%% N.B. elk doesn't stop rendering invisible edge operator, i.e. ~~~ +%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%% ...
```suggestion bastionScheduler_1 --"Spawn/kill"--> bastionJob_1 & bastionJob_2 ```
axlearn
github_2023
others
57
apple
markblee
@@ -0,0 +1,72 @@ +# Bastion: Axlearn's Job Scheduler + +## Control Flow of Job Submission +```mermaid +%% elk seems to be more maintained, see: https://github.com/mermaid-js/mermaid/issues/1969 +%% N.B. elk doesn't stop rendering invisible edge operator, i.e. ~~~ +%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%% ...
```suggestion bastionVmAXLearnPackage(["axlearn package \n (running on shared docker image)"]):::fileCSS ```
axlearn
github_2023
python
37
apple
ruomingp
@@ -1387,7 +1387,7 @@ def forward( ) # Causal mask. return apply_attention_logit_biases(
Great catch! Could you change `apply_attention_logit_biases` to take `apply_attention_logit_biases` as a keyword arg? This also better matches https://docs.google.com/document/d/1tK3MyfZQgXyrvWNg3rt6NQCItuFnFw_FBd6-C7pE2Wk/edit#heading=h.d1xks5sf41jd. Feel free to do so in a follow-up PR.
axlearn
github_2023
python
41
apple
markblee
@@ -422,6 +422,12 @@ class Config(BaseLayer.Config): lm_head: Optional[InstantiableConfig] = None pad_token_id: int = 0 # Int ID of the inputs to be masked for self-attention. eos_token_id: int = 1 # Int ID of the end of sequence token id. + # Specifies how to partition the output lo...
This is fine for now, but I wonder if the inner Tuple should also support len > 2 in theory.
axlearn
github_2023
python
1,070
apple
markblee
@@ -390,8 +391,9 @@ def _build_job_submission_deployment( cfg.builder.accelerator.num_replicas * system.vms_per_slice * system.chips_per_vm ) user_command += ( - f" --flink_master_address={job_manager_ip}" - f" --flink_parallelism={flink_parallelism}" + f"...
```suggestion f" --artifacts_dir={os.path.join(cfg.builder.output_dir, 'artifacts_dir')}" ```
axlearn
github_2023
python
1,070
apple
markblee
@@ -390,8 +391,9 @@ def _build_job_submission_deployment( cfg.builder.accelerator.num_replicas * system.vms_per_slice * system.chips_per_vm ) user_command += ( - f" --flink_master_address={job_manager_ip}" - f" --flink_parallelism={flink_parallelism}" + f"...
What's the motivation of changing `--flink_parallelism` to `--parallelism`? Is there testing for this change?
app-store-server-library-python
github_2023
python
82
apple
alexanderjordanbaker
@@ -17,9 +17,9 @@ class ExtendRenewalDateRequest: extendByDays: Optional[int] = attr.ib(default=None) """ The number of days to extend the subscription renewal date. - + The number of days is a number from 1 to 90.
This doesn't follow the style of the rest of the library, where only the first sentence of a field's documentation is listed. Could you please remove this bit. Discussion about the style of documentation would probably be best in a separate issue
app-store-server-library-python
github_2023
python
82
apple
alexanderjordanbaker
@@ -66,5 +66,5 @@ class TransactionHistoryRequest: revoked: Optional[bool] = attr.ib(default=None) """ - An optional Boolean value that indicates whether the response includes only revoked transactions when the value is true, or contains only nonrevoked transactions when the value is false. By default...
This differs from the official Apple documentation
app-store-server-library-python
github_2023
python
63
apple
alexanderjordanbaker
@@ -15,6 +15,6 @@ long_description_content_type="text/markdown", packages=find_packages(exclude=["tests"]), python_requires=">=3.7, <4", - install_requires=["attrs >= 21.3.0", 'PyJWT >= 2.6.0, < 3', 'requests >= 2.28.0, < 3', 'cryptography >= 40.0.0, < 42', 'pyOpenSSL >= 23.1.1, < 24', 'asn1==2.7.0', ...
Please bump the max to 43, not removing the limit
app-store-server-library-python
github_2023
python
52
apple
izanger
@@ -36,72 +36,405 @@ class APIError(IntEnum): GENERAL_BAD_REQUEST = 4000000 + """ + An error that indicates an invalid request. + + https://developer.apple.com/documentation/appstoreserverapi/generalbadrequesterror + """ + INVALID_APP_IDENTIFIER = 4000002 + """ + An error that indicat...
Suggest a rename to `INVALID_REQUEST_IDENTIFIER`
swift-openapi-generator
github_2023
others
731
apple
czechboy0
@@ -66,7 +66,7 @@ struct Handler: APIProtocol { @main struct HelloWorldVaporServer { static func main() async throws { - let app = Vapor.Application() + let app = try await Application.make(.detect())
Is the `.detect()` part necessary?
swift-openapi-generator
github_2023
others
708
apple
simonjbeaumont
@@ -78,7 +84,10 @@ extension _GenerateOptions { /// Returns the naming strategy requested by the user. /// - Parameter config: The configuration specified by the user. /// - Returns: The naming strategy requestd by the user. - func resolvedNamingStrategy(_ config: _UserConfig?) -> NamingStrategy { con...
Just calling out that we've picked up some asymmetry here with regard to how we handle `accessModifier` and `namingStrategy`. Both of these have defaults, defined as statics in `Config` and both of these must have a value (unlike other options, e.g. filter, where `nil` is reasonable). The `resolveAccessModifier` ...
swift-openapi-generator
github_2023
others
709
apple
simonjbeaumont
@@ -56,4 +55,3 @@ jobs: with: name: "Example packages" matrix_linux_command: "./scripts/test-examples.sh" - matrix_linux_nightly_main_enabled: false
I'm +1 on us having the nightly main enabled for unit tests, but do we gain much by having the integration test and examples here, other than noise. Especially since the examples pipeline is currently the slowest, so the limiting factor on getting PRs green, and IIUC the nightly main setup time is longer than all other...
swift-openapi-generator
github_2023
others
706
apple
simonjbeaumont
@@ -16,36 +16,45 @@ import OpenAPIVapor import Vapor import TracingMiddleware import Tracing -import OpenTelemetry -import OtlpGRPCSpanExporting +import OTel +import OTLPGRPC import NIO struct Handler: APIProtocol { - func getGreeting(_ input: Operations.getGreeting.Input) async throws -> Operations.getGreeti...
Can we drop a comment pointing people to Swift Service Lifecycle here, because this probably isn't what we want folks to do in practice, right? ```suggestion // Consider using Swift Service Lifecycle — https://github.com/swift-server/swift-service-lifecycle try await withThrowingTaskGroup(of: Void....
swift-openapi-generator
github_2023
others
679
apple
simonjbeaumont
@@ -0,0 +1,160 @@ +# SOAR-0013: Optimistic naming strategy + +Introduce an alternative naming strategy for more idiomatic Swift identifiers, including a way to provide custom name overrides. + +## Overview + +- Proposal: SOAR-0013 +- Author(s): [Honza Dvorsky](https://github.com/czechboy0), [Si Beaumont](https://github...
```suggestion When Swift OpenAPI Generator 0.1.0 went open-source in May 2023, it had a simple naming strategy that produced relatively conventional Swift identifiers from OpenAPI names. However, when tested on a large test corpus of around 3000 OpenAPI documents, it produced an unacceptably high number of non-compili...