author int64 658 755k | date stringlengths 19 19 | timezone int64 -46,800 43.2k | hash stringlengths 40 40 | message stringlengths 5 490 | mods list | language stringclasses 20 values | license stringclasses 3 values | repo stringlengths 5 68 | original_message stringlengths 12 491 |
|---|---|---|---|---|---|---|---|---|---|
260,539 | 10.01.2023 11:01:54 | 28,800 | d1edad6a68b97e781e26ff7818fc5d56d39da367 | Typos: suited -> suitable, node -> host | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/distributed.py",
"new_path": "jax/_src/distributed.py",
"diff": "@@ -132,7 +132,7 @@ def initialize(coordinator_address: Optional[str] = None,\nand all processes agree on the port.\nMay be ``None`` only on supported environments, in which case it will be chosen automatically.\nNote that special addresses like ``localhost`` or ``127.0.0.1`` usually mean that the program\n- will bind to a local interface and are not suited when running in a multi-node environment.\n+ will bind to a local interface and are not suitable when running in a multi-host environment.\nnum_processes: Number of processes. May be ``None`` only on supported environments, in\nwhich case it will be chosen automatically.\nprocess_id: The ID number of the current process. The ``process_id`` values across\n"
}
] | Python | Apache License 2.0 | google/jax | Typos: suited -> suitable, node -> host |
260,411 | 04.01.2023 15:47:36 | -7,200 | f7093955dc0cb4de070fa702cab8087958e865fd | [jax2tf] Fixed the shape-polymorphic lowering for lax.pad and dynamic_slice
Generate DynamicPadOp instea of PadOp when the padding
sizes are not constant.
Fix the generation of RealDynamicSliceOp.
Exclude some tests that fail due to unimplemented support
for custom calls with polymorphic shapes. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -3172,11 +3172,10 @@ ad.deflinear2(pad_p, _pad_transpose)\nbatching.primitive_batchers[pad_p] = _pad_batch_rule\ndef _pad_lower(ctx, x, padding_value, *, padding_config):\n+ aval_out, = ctx.avals_out\nlow, high, interior = util.unzip3(padding_config)\n- return hlo.PadOp(x, padding_value,\n- mlir.dense_int_elements(low),\n- mlir.dense_int_elements(high),\n- mlir.dense_int_elements(interior)).results\n+ return [mlir.pad(ctx, aval_out, x, padding_value, low, high, interior)]\n+\nmlir.register_lowering(pad_p, _pad_lower)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"diff": "@@ -1270,6 +1270,8 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\njax2tf.convert(lambda x: jnp.reshape(x, (-1, x.shape[0])),\npolymorphic_shapes=[\"(b1, b2, ...)\"])(np.ones((4, 5, 6)))\n+ if not config.jax2tf_default_experimental_native_lowering:\n+ # Does not support 2*b constraints\njax2tf.convert(lambda x: jnp.reshape(x, (2, -1)),\npolymorphic_shapes=[\"(2*b, ...)\"])(np.ones((4, 5, 7)))\n@@ -1495,12 +1497,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# List containing either harnesses, or lists of harnesses\n_POLY_SHAPE_TEST_HARNESSES = [\n- PolyHarness(\"simple_binary\", \"\",\n- lambda x, y: x + jnp.sin(y),\n- arg_descriptors=[RandArg((3, 4), _f32), RandArg((3, 4), _f32)],\n- input_signature=[tf.TensorSpec([2, None]), tf.TensorSpec([2, 3])],\n- polymorphic_shapes=\"_, h\",\n- expected_output_signature=tf.TensorSpec([2, 3])),\nPolyHarness(\"add\", \"\",\njnp.add,\narg_descriptors=[RandArg((3, 4), _f32), RandArg((2, 3, 4), _f32)],\n@@ -2332,7 +2328,12 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n\"householder_product:cpu\", \"householder_product:gpu\",\n\"vmap_geqrf:cpu\", \"vmap_geqrf:gpu\",\n\"vmap_lu:cpu\", \"vmap_lu:gpu\", \"vmap_qr:cpu\", \"vmap_qr:gpu\",\n- \"vmap_svd:cpu\", \"vmap_svd:gpu\"}\n+ \"vmap_svd:cpu\", \"vmap_svd:gpu\",\n+ \"random_gamma:gpu\", \"vmap_random_gamma:gpu\",\n+ \"random_categorical:gpu\", \"vmap_random_categorical:gpu\",\n+ \"random_randint:gpu\", \"vmap_random_randint:gpu\",\n+ \"random_uniform:gpu\", \"vmap_random_uniform:gpu\",\n+ \"vmap_random_split:gpu\"}\nif f\"{harness.group_name}:{jtu.device_under_test()}\" in custom_call_harnesses:\nraise unittest.SkipTest(\"native lowering with shape polymorphism not implemented for custom calls; b/261671778\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -1341,7 +1341,8 @@ def dynamic_slice(ctx: LoweringRuleContext, aval_out, x, *,\nreturn hlo.RealDynamicSliceOp(\naval_to_ir_type(aval_out), x,\nshape_tensor(start_indices),\n- shape_tensor(slice_sizes),\n+ hlo.AddOp(shape_tensor(start_indices),\n+ shape_tensor(slice_sizes)).result,\nshape_tensor([1] * len(slice_sizes))\n).result\nelse:\n@@ -1361,6 +1362,23 @@ def dynamic_update_slice(ctx: LoweringRuleContext, aval_out, x, update, *,\nelse:\nreturn hlo.DynamicUpdateSliceOp(x, update, start_indices).result\n+def pad(ctx: LoweringRuleContext, aval_out,\n+ x, padding_value,\n+ padding_low, padding_high, padding_interior) -> ir.Value:\n+ if all(core.is_constant_shape(s) for s in (padding_low,\n+ padding_high, padding_interior)):\n+ return hlo.PadOp(x, padding_value,\n+ dense_int_elements(padding_low),\n+ dense_int_elements(padding_high),\n+ dense_int_elements(padding_interior)).result\n+ else:\n+ padding_low = shape_tensor(eval_dynamic_shape(ctx, padding_low))\n+ padding_high = shape_tensor(eval_dynamic_shape(ctx, padding_high))\n+ padding_interior = shape_tensor(eval_dynamic_shape(ctx, padding_interior))\n+ return hlo.DynamicPadOp(\n+ aval_to_ir_type(aval_out),\n+ x, padding_value, padding_low, padding_high, padding_interior).result\n+\ndef full_like_aval(ctx: LoweringRuleContext, value, aval: core.ShapedArray) -> ir.Value:\n\"\"\"Returns an IR constant shaped full of `value` shaped like `aval`.\"\"\"\nzero = ir_constant(np.array(value, aval.dtype))\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fixed the shape-polymorphic lowering for lax.pad and dynamic_slice
Generate DynamicPadOp instea of PadOp when the padding
sizes are not constant.
Fix the generation of RealDynamicSliceOp.
Exclude some tests that fail due to unimplemented support
for custom calls with polymorphic shapes. |
260,335 | 10.01.2023 13:39:25 | 28,800 | 8b585302db6f63c422a5fa5f4e5335ea863c9aa3 | add pjit partial_eval_jaxpr_custom rule
fix some issues with closed_call's partial_eval_jaxpr_custom rule | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/core.py",
"new_path": "jax/_src/core.py",
"diff": "@@ -146,6 +146,7 @@ class ClosedJaxpr:\ndef __init__(self, jaxpr: Jaxpr, consts: Sequence):\nassert len(consts) == len(jaxpr.constvars)\n+ # assert not any(isinstance(c, Tracer) for c in consts) # TODO(mattjj): enable\nself.jaxpr = jaxpr\nself.consts = list(consts)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/pjit.py",
"new_path": "jax/_src/pjit.py",
"diff": "@@ -1955,3 +1955,41 @@ def _get_pspec_from_executable(\nout_partition_spec = _get_partition_spec(out_ppspec)\nin_partition_spec = _get_partition_spec(in_ppspec)\nreturn tuple(in_partition_spec), tuple(out_partition_spec)\n+\n+def _pjit_partial_eval_custom_params_updater(\n+ unks_in: Sequence[bool], inst_in: Sequence[bool],\n+ kept_outs_known: Sequence[bool], kept_outs_staged: Sequence[bool],\n+ num_res: int, params_known: dict, params_staged: dict\n+ ) -> Tuple[dict, dict]:\n+ # prune inputs to jaxpr_known according to unks_in\n+ donated_invars_known, _ = pe.partition_list(unks_in, params_known['donated_invars'])\n+ in_shardings_known, _ = pe.partition_list(unks_in, params_known['in_shardings'])\n+ if num_res == 0:\n+ residual_shardings = []\n+ else:\n+ residual_shardings = [_UNSPECIFIED] * num_res\n+ _, out_shardings_known = pe.partition_list(kept_outs_known, params_known['out_shardings'])\n+ new_params_known = dict(params_known,\n+ in_shardings=tuple(in_shardings_known),\n+ out_shardings=(*out_shardings_known, *residual_shardings),\n+ donated_invars=tuple(donated_invars_known))\n+ assert len(new_params_known['in_shardings']) == len(params_known['jaxpr'].in_avals)\n+ assert len(new_params_known['out_shardings']) == len(params_known['jaxpr'].out_avals)\n+\n+ # added num_res new inputs to jaxpr_staged, and pruning according to inst_in\n+ _, donated_invars_staged = pe.partition_list(inst_in, params_staged['donated_invars'])\n+ donated_invars_staged = [False] * num_res + donated_invars_staged\n+ _, in_shardings_staged = pe.partition_list(inst_in, params_staged['in_shardings'])\n+ in_shardings_staged = [*residual_shardings, *in_shardings_staged]\n+ _, out_shardings_staged = pe.partition_list(kept_outs_staged, params_staged['out_shardings'])\n+ new_params_staged = dict(params_staged,\n+ in_shardings=tuple(in_shardings_staged),\n+ out_shardings=tuple(out_shardings_staged),\n+ donated_invars=tuple(donated_invars_staged))\n+ assert len(new_params_staged['in_shardings']) == len(params_staged['jaxpr'].in_avals)\n+ assert len(new_params_staged['out_shardings']) == len(params_staged['jaxpr'].out_avals)\n+ return new_params_known, new_params_staged\n+\n+pe.partial_eval_jaxpr_custom_rules[pjit_p] = \\\n+ partial(pe.closed_call_partial_eval_custom_rule, 'jaxpr',\n+ _pjit_partial_eval_custom_params_updater)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1257,34 +1257,37 @@ def call_partial_eval_custom_rule(\nreturn eqn_known, eqn_staged, unks_out, inst_out, new_inst + residuals\ndef closed_call_partial_eval_custom_rule(\n- jaxpr_param_name: str,\n+ jaxpr_param_name: str, params_updater: ParamsUpdater,\nsaveable: Callable[..., bool], unks_in: List[bool], inst_in: List[bool],\neqn: JaxprEqn, *, res_aval: ResAvalUpdater = _default_res_aval_updater,\n) -> Tuple[JaxprEqn, JaxprEqn, Sequence[bool], Sequence[bool], List[Var]]:\n# TODO(sharadmv,mattjj): dedup this rule with call_partial_eval_custom_rule.\nclosed_jaxpr = eqn.params[jaxpr_param_name]\n- jaxpr = convert_constvars_jaxpr(closed_jaxpr.jaxpr)\n- unks_in = [False] * len(closed_jaxpr.consts) + list(unks_in)\n- inst_in = [False] * len(closed_jaxpr.consts) + list(inst_in)\n- jaxpr_known, jaxpr_staged, unks_out, inst_out, num_res = \\\n- partial_eval_jaxpr_custom(jaxpr, unks_in, inst_in, False, False, saveable)\n+ jaxpr_known_, jaxpr_staged_, unks_out, inst_out, num_res = \\\n+ partial_eval_jaxpr_custom(closed_jaxpr.jaxpr, unks_in, inst_in,\n+ False, False, saveable)\n+ # Forming these fresh ClosedJaxprs defeats caching, but caller handles caching\n+ jaxpr_known = core.ClosedJaxpr(jaxpr_known_, closed_jaxpr.consts)\n+ jaxpr_staged = core.ClosedJaxpr(jaxpr_staged_, closed_jaxpr.consts)\nins_known, _ = partition_list(unks_in, eqn.invars)\nout_binders_known, _ = partition_list(unks_out, eqn.outvars)\n_, ins_staged = partition_list(inst_in, eqn.invars)\n_, out_binders_staged = partition_list(inst_out, eqn.outvars)\n- newvar = core.gensym([jaxpr_known, jaxpr_staged])\n- params_known = {**eqn.params, jaxpr_param_name: core.ClosedJaxpr(jaxpr_known,\n- ())}\n- params_staged = {**eqn.params, jaxpr_param_name:\n- core.ClosedJaxpr(jaxpr_staged, ())}\n- residuals = [newvar(res_aval(params_known, var.aval))\n- for var in jaxpr_staged.invars[:num_res]]\n+ newvar = core.gensym([jaxpr_known.jaxpr, jaxpr_staged.jaxpr])\n+ params_known = {**eqn.params, jaxpr_param_name: jaxpr_known}\n+ params_staged = {**eqn.params, jaxpr_param_name: jaxpr_staged}\n+ params_known, params_staged = params_updater(\n+ unks_in, inst_in, map(op.not_, unks_out), inst_out, num_res, params_known,\n+ params_staged)\n+ residuals = [newvar(res_aval(params_known, a))\n+ for a in jaxpr_staged.in_avals[:num_res]]\neqn_known = new_jaxpr_eqn(ins_known, [*out_binders_known, *residuals],\n- eqn.primitive, params_known, jaxpr_known.effects, eqn.source_info)\n+ eqn.primitive, params_known, jaxpr_known.effects,\n+ eqn.source_info)\neqn_staged = new_jaxpr_eqn([*residuals, *ins_staged], out_binders_staged,\n- eqn.primitive, params_staged,\n- jaxpr_staged.effects, eqn.source_info)\n- assert len(eqn_staged.invars) == len(jaxpr_staged.invars)\n+ eqn.primitive, params_staged, jaxpr_staged.effects,\n+ eqn.source_info)\n+ assert len(eqn_staged.invars) == len(jaxpr_staged.in_avals)\nnew_inst = [x for x, inst in zip(eqn.invars, inst_in)\nif type(x) is Var and not inst]\nreturn eqn_known, eqn_staged, unks_out, inst_out, new_inst + residuals\n@@ -1293,7 +1296,8 @@ partial_eval_jaxpr_custom_rules[core.call_p] = \\\npartial(call_partial_eval_custom_rule, 'call_jaxpr',\nlambda _, __, ___, ____, _____, x, y: (x, y))\npartial_eval_jaxpr_custom_rules[core.closed_call_p] = \\\n- partial(closed_call_partial_eval_custom_rule, 'call_jaxpr')\n+ partial(closed_call_partial_eval_custom_rule, 'call_jaxpr',\n+ lambda _, __, ___, ____, _____, x, y: (x, y))\ndef _jaxpr_forwarding(jaxpr: Jaxpr) -> List[Optional[int]]:\n"
}
] | Python | Apache License 2.0 | google/jax | add pjit partial_eval_jaxpr_custom rule
fix some issues with closed_call's partial_eval_jaxpr_custom rule
Co-authored-by: Yash Katariya <yashkatariya@google.com> |
260,419 | 09.01.2023 11:42:20 | 21,600 | b86030d86fc461e4323f933ad5081043cff3a994 | Add Open MPI automatic distributed initialization | [
{
"change_type": "MODIFY",
"old_path": "docs/multi_process.md",
"new_path": "docs/multi_process.md",
"diff": "@@ -78,11 +78,12 @@ jax.distributed.initialize(coordinator_address=\"192.168.0.1:1234\",\nprocess_id=0)\n```\n-On Cloud TPU and Slurm environments, you can simply call {func}`jax.distributed.initialize()` with no\n+On Cloud TPU, Slurm and Open MPI environments, you can simply call {func}`jax.distributed.initialize()` with no\narguments. Default values for the arguments will be chosen automatically.\n-When running on GPUs with Slurm, it is assumed that one process is started per GPU, i.e. each process will\n+When running on GPUs with Slurm and Open MPI, it is assumed that one process is started per GPU, i.e. each process will\nbe assigned only one visible local device. Otherwise it is assumed that one process is started per host,\ni.e. each process will be assigned all local devices.\n+The Open MPI auto-initialization is only used when the JAX processes are launched via `mpirun`/`mpiexec`.\n```python\nimport jax\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/clusters/__init__.py",
"new_path": "jax/_src/clusters/__init__.py",
"diff": "@@ -20,5 +20,6 @@ from .cluster import ClusterEnv\n# the user did not explicitly provide the arguments\n# to :func:`jax.distributed.initialize`, the first\n# available one from the list will be picked.\n+from .ompi_cluster import OmpiCluster\nfrom .slurm_cluster import SlurmCluster\nfrom .cloud_tpu_cluster import TpuCluster\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/_src/clusters/ompi_cluster.py",
"diff": "+# Copyright 2023 The JAX Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import os\n+import re\n+from typing import Optional\n+from jax._src.clusters import ClusterEnv\n+\n+# OMPI_MCA_orte_hnp_uri exists only when processes are launched via mpirun or mpiexec\n+_ORTE_URI = 'OMPI_MCA_orte_hnp_uri'\n+_PROCESS_COUNT = 'OMPI_COMM_WORLD_SIZE'\n+_PROCESS_ID = 'OMPI_COMM_WORLD_RANK'\n+_LOCAL_PROCESS_ID = 'OMPI_COMM_WORLD_LOCAL_RANK'\n+\n+class OmpiCluster(ClusterEnv):\n+ @classmethod\n+ def is_env_present(cls) -> bool:\n+ return _ORTE_URI in os.environ\n+\n+ @classmethod\n+ def get_coordinator_address(cls) -> str:\n+ # Examples of orte_uri:\n+ # 1531576320.0;tcp://10.96.0.1,10.148.0.1,10.108.0.1:34911\n+ # 1314521088.0;tcp6://[fe80::b9b:ac5d:9cf0:b858,2620:10d:c083:150e::3000:2]:43370\n+ orte_uri = os.environ[_ORTE_URI]\n+ job_id_str = orte_uri.split('.', maxsplit=1)[0]\n+ # The jobid is always a multiple of 2^12, let's divide it by 2^12\n+ # to reduce likelihood of port conflict between jobs\n+ job_id = int(job_id_str) // 2**12\n+ # Pick port in ephemeral range [(65535 - 2^12 + 1), 65535]\n+ port = job_id % 2**12 + (65535 - 2**12 + 1)\n+ launcher_ip_match = re.search(r\"tcp://(.+?)[,:]|tcp6://\\[(.+?)[,\\]]\", orte_uri)\n+ if launcher_ip_match is None:\n+ raise RuntimeError('Could not parse coordinator IP address from Open MPI environment.')\n+ launcher_ip = next(i for i in launcher_ip_match.groups() if i is not None)\n+ return f'{launcher_ip}:{port}'\n+\n+ @classmethod\n+ def get_process_count(cls) -> int:\n+ return int(os.environ[_PROCESS_COUNT])\n+\n+ @classmethod\n+ def get_process_id(cls) -> int:\n+ return int(os.environ[_PROCESS_ID])\n+\n+ @classmethod\n+ def get_local_process_id(cls) -> Optional[int]:\n+ return int(os.environ[_LOCAL_PROCESS_ID])\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/distributed.py",
"new_path": "jax/_src/distributed.py",
"diff": "@@ -119,7 +119,7 @@ def initialize(coordinator_address: Optional[str] = None,\n* it performs health checking, ensuring that all processes shut down if any process dies, and\n* it is used for distributed checkpointing.\n- If you are using TPU or Slurm, all arguments are optional: if omitted, they\n+ If you are using TPU, Slurm, or Open MPI, all arguments are optional: if omitted, they\nwill be chosen automatically.\nOtherwise, you must provide the ``coordinator_address``,\n@@ -140,7 +140,7 @@ def initialize(coordinator_address: Optional[str] = None,\nMay be ``None`` only on supported environments; if ``None`` it will be chosen automatically.\nlocal_device_ids: Restricts the visible devices of the current process to ``local_device_ids``.\nIf ``None``, defaults to all local devices being visible to the process except when processes\n- are launched via Slurm on GPUs. In that case, it will default to a single device per process.\n+ are launched via Slurm and Open MPI on GPUs. In that case, it will default to a single device per process.\nRaises:\nRuntimeError: If :func:`~jax.distributed.initialize` is called more than once.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/multiprocess_gpu_test.py",
"new_path": "tests/multiprocess_gpu_test.py",
"diff": "import contextlib\nimport os\n+import shutil\nimport subprocess\nimport sys\nimport threading\n@@ -187,6 +188,45 @@ class MultiProcessGpuTest(jtu.JaxTestCase):\nfor proc in subprocesses:\nproc.kill()\n+ def test_gpu_ompi_distributed_initialize(self):\n+ if jtu.device_under_test() != 'gpu':\n+ raise unittest.SkipTest('Tests only for GPU.')\n+ if shutil.which('mpirun') is None:\n+ raise unittest.SkipTest('Tests only for MPI (mpirun not found).')\n+\n+ num_gpus = 4\n+ num_gpus_per_task = 1\n+\n+ with contextlib.ExitStack() as exit_stack:\n+ args = [\n+ 'mpirun',\n+ '--oversubscribe',\n+ '--allow-run-as-root',\n+ '-n',\n+ str(num_gpus),\n+ sys.executable,\n+ '-c',\n+ ('import jax, os; '\n+ 'jax.distributed.initialize(); '\n+ 'print(f\\'{jax.local_device_count()},{jax.device_count()}\\' if jax.process_index() == 0 else \\'\\', end=\"\")'\n+ )\n+ ]\n+ env = os.environ.copy()\n+ # In case the job was launched via Slurm,\n+ # prevent OpenMPI from detecting Slurm environment\n+ env.pop('SLURM_JOBID', None)\n+ proc = subprocess.Popen(args, env=env, stdout=subprocess.PIPE,\n+ stderr=subprocess.PIPE, universal_newlines=True)\n+ proc = exit_stack.enter_context(proc)\n+\n+ try:\n+ out, _ = proc.communicate()\n+ self.assertEqual(proc.returncode, 0)\n+ self.assertEqual(out, f'{num_gpus_per_task},{num_gpus}')\n+ finally:\n+ proc.kill()\n+\n+\n@unittest.skipIf(\nos.environ.get(\"SLURM_JOB_NUM_NODES\", None) != \"2\",\n\"Slurm environment with at least two nodes needed!\")\n"
}
] | Python | Apache License 2.0 | google/jax | Add Open MPI automatic distributed initialization |
260,689 | 12.01.2023 12:57:30 | -3,600 | 6b8125b3204e8541911460e0271eff7c68f756bf | mgrid: Fix zero-length meshgrid | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/index_tricks.py",
"new_path": "jax/_src/numpy/index_tricks.py",
"diff": "@@ -54,7 +54,11 @@ class _IndexGrid(abc.ABC):\nwith jax.numpy_dtype_promotion('standard'):\noutput = _promote_dtypes(*output)\noutput_arr = jnp.meshgrid(*output, indexing='ij', sparse=self.sparse)\n- return output_arr if self.sparse else jnp.stack(output_arr, 0)\n+ if self.sparse:\n+ return output_arr\n+ if len(output_arr) == 0:\n+ return jnp.arange(0)\n+ return jnp.stack(output_arr, 0)\nclass _Mgrid(_IndexGrid):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -4353,6 +4353,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n# wrap indexer for appropriate dtype defaults.\nnp_mgrid = _indexer_with_default_outputs(np.mgrid)\nassertAllEqual = partial(self.assertAllClose, atol=0, rtol=0)\n+ assertAllEqual(np_mgrid[()], jnp.mgrid[()])\nassertAllEqual(np_mgrid[:4], jnp.mgrid[:4])\nassertAllEqual(np_mgrid[:4,], jnp.mgrid[:4,])\nassertAllEqual(np_mgrid[:4], jax.jit(lambda: jnp.mgrid[:4])())\n"
}
] | Python | Apache License 2.0 | google/jax | mgrid: Fix zero-length meshgrid |
260,510 | 12.01.2023 22:57:49 | 28,800 | c9a57e1b44875ab6b09c9ad92ba955f554def9bc | Delete `jax.experimental.callback` | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -8,6 +8,9 @@ Remember to align the itemized text with the first line of an item within a list\n## jax 0.4.2\n+* Breaking changes\n+ * Deleted `jax.experimental.callback`\n+\n## jaxlib 0.4.2\n## jax 0.4.1 (Dec 13, 2022)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/BUILD",
"new_path": "jax/BUILD",
"diff": "@@ -187,13 +187,6 @@ pytype_library(\ndeps = [\":jax\"],\n)\n-pytype_library(\n- name = \"callback\",\n- srcs = [\"experimental/callback.py\"],\n- visibility = [\"//visibility:public\"],\n- deps = [\":jax\"],\n-)\n-\n# TODO(apaszke): Remove this target\npytype_library(\nname = \"maps\",\n"
},
{
"change_type": "DELETE",
"old_path": "jax/experimental/callback.py",
"new_path": null,
"diff": "-# Copyright 2020 The JAX Authors.\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-from functools import partial\n-import itertools as it\n-\n-from typing import Any, Callable, Dict, Sequence, Union\n-\n-import jax.numpy as jnp\n-\n-from jax import core\n-from jax.core import Trace, Tracer, jaxpr_as_fun\n-from jax import lax\n-from jax import custom_derivatives as cd\n-from jax.interpreters import partial_eval as pe\n-from jax._src import linear_util as lu\n-from jax._src.util import safe_map, wraps, split_list\n-from jax._src.lax import control_flow as lcf\n-\n-import inspect\n-from jax._src.api_util import flatten_fun_nokwargs\n-from jax.tree_util import tree_flatten, tree_unflatten, tree_structure, tree_map\n-\n-map = safe_map\n-\n-### Public\n-\n-def callback_transform(\n- fun: Callable, callback: Callable, strip_calls: bool=False) -> Callable:\n- _check_callable(fun)\n-\n- @wraps(fun)\n- def wrapped_fun(*args):\n- args_flat, in_tree = tree_flatten(args)\n- f = lu.wrap_init(fun)\n- flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\n- out_flat = callback_fun(flat_fun, args_flat, callback, strip_calls)\n- return tree_unflatten(out_tree(), out_flat)\n-\n- return wrapped_fun\n-\n-### Example Transform\n-\n-def find_by_value(fun: Callable, queries) -> Callable:\n- def find_callback(\n- prim: core.Primitive,\n- vals: Sequence[core.Tracer],\n- params: Dict[str, Any]) -> Union[core.Tracer, Sequence[core.Tracer]]:\n- vals = prim.bind(*vals, **params)\n- _contains_query(vals, queries)\n- return vals\n- return callback_transform(fun, find_callback, True)\n-\n-def rewrite(fun: Callable, rules) -> Callable:\n- assert isinstance(rules, dict)\n- def rewrite_callback(\n- prim: core.Primitive,\n- vals: Sequence[core.Tracer],\n- params: Dict[str, Any]) -> Union[core.Tracer, Sequence[core.Tracer]]:\n- if prim in rules:\n- return rules[prim](*vals, **params)\n- return prim.bind(*vals, **params)\n- return callback_transform(fun, rewrite_callback)\n-\n-class FoundValue(Exception):\n- pass\n-\n-def _contains_query(vals, query):\n- if isinstance(query, tuple):\n- return map(partial(_contains_query, vals), query)\n-\n- if jnp.isnan(query):\n- if jnp.any(jnp.isnan(vals)):\n- raise FoundValue('NaN')\n- elif jnp.isinf(query):\n- if jnp.any(jnp.isinf(vals)):\n- raise FoundValue('Found Inf')\n- elif jnp.isscalar(query):\n- if jnp.any(vals == query):\n- raise FoundValue(str(query))\n- else:\n- raise ValueError(f'Malformed Query: {query}')\n-\n-### Helper Functions\n-\n-def callback_fun(fun : lu.WrappedFun, in_vals, callback, strip_calls):\n- fun = callback_subtrace(fun)\n- fun = _callback_fun(fun, callback, strip_calls)\n- return fun.call_wrapped(*in_vals)\n-\n-@lu.transformation\n-def callback_subtrace(main, *in_vals, **params):\n- trace = main.with_cur_sublevel()\n- in_tracers = [CallbackTracer(trace, val) for val in in_vals]\n- outs = yield in_tracers, params\n- out_tracers = map(trace.full_raise, outs)\n- out_vals = [t.val for t in out_tracers]\n- yield out_vals\n-\n-@lu.transformation\n-def _callback_fun(callback, strip_calls, *in_vals, **params):\n- with core.new_main(CallbackTrace, callback=callback,\n- strip_calls=strip_calls) as main:\n- out_vals = yield (main,) + in_vals, params\n- del main\n- yield out_vals\n-\n-def callback_jaxpr(closed_jaxpr, callback, strip_calls):\n- fun = lu.wrap_init(jaxpr_as_fun(closed_jaxpr))\n- fun = callback_subtrace(fun)\n- fun = _callback_fun(fun, callback, strip_calls)\n- avals_in = closed_jaxpr.in_avals\n- jaxpr_out, consts = cd._initial_style_jaxpr(fun, avals_in)\n- return core.ClosedJaxpr(jaxpr_out, consts)\n-\n-def _check_callable(fun):\n- if not callable(fun):\n- raise TypeError(f\"Expected a callable value, got {fun}\")\n- if inspect.isgeneratorfunction(fun):\n- raise TypeError(f\"Expected a function, got a generator function: {fun}\")\n-\n-### Tracer\n-\n-class CallbackTracer(Tracer):\n- __slots__ = ['val']\n-\n- def __init__(self, trace, val):\n- self._trace = trace\n- self.val = val\n-\n- @property\n- def aval(self):\n- return core.get_aval(self.val)\n-\n- def full_lower(self):\n- return self\n-\n-class CallbackTrace(Trace):\n- def __init__(self, *args, callback, strip_calls):\n- super().__init__(*args)\n- self.callback = callback\n- self.strip_calls = strip_calls\n-\n- def pure(self, val):\n- return CallbackTracer(self, val)\n-\n- def lift(self, val):\n- return CallbackTracer(self, val)\n-\n- def sublift(self, val):\n- return CallbackTracer(self, val.val)\n-\n- def process_primitive(self, primitive, tracers, params):\n- if primitive in custom_callback_rules:\n- return custom_callback_rules[primitive](self, *tracers, **params)\n- vals_in = [t.val for t in tracers]\n- vals_out = self.callback(primitive, vals_in, params) # type: ignore\n- if primitive.multiple_results:\n- return [CallbackTracer(self, val) for val in vals_out]\n- return CallbackTracer(self, vals_out)\n-\n- def process_call(self, call_primitive, f: lu.WrappedFun, tracers, params):\n- if self.strip_calls: # type: ignore\n- return f.call_wrapped(*tracers)\n- vals_in = [t.val for t in tracers]\n- f = callback_subtrace(f, self.main)\n- vals_out = call_primitive.bind(f, *vals_in, **params)\n- return [CallbackTracer(self, val) for val in vals_out]\n-\n- def process_custom_jvp_call(self, primitive, fun, jvp, tracers):\n- vals_in = [t.val for t in tracers]\n- fun = callback_subtrace(fun, self.main)\n- jvp = callback_subtrace(jvp, self.main)\n- out = primitive.bind(fun, jvp, *vals_in)\n- return safe_map(self.pure, out)\n-\n- def process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers,\n- out_trees):\n- vals_in = [t.val for t in tracers]\n- fun = callback_subtrace(fun, self.main)\n- fwd = callback_subtrace(fwd, self.main)\n- bwd = callback_subtrace(bwd, self.main)\n- out = primitive.bind(fun, fwd, bwd, *vals_in, out_trees=out_trees)\n- return safe_map(self.pure, out)\n-\n-custom_callback_rules: Dict[Any, Any] = {}\n-\n-def _scan_callback_rule(trace, *tracers, reverse, length, num_consts, num_carry,\n- jaxpr, linear, unroll):\n- const_tracers, carry_tracers, xs_tracers = split_list(tracers, [num_consts, num_carry])\n- carry_avals, xs_avals = tree_map(lambda x: x.aval, (carry_tracers, xs_tracers))\n- const_vals, carry_vals, xs_vals = tree_map(lambda x: x.val, (const_tracers, carry_tracers, xs_tracers))\n-\n- x_tracers = [t[0] for t in xs_tracers]\n- x_avals = [t.aval for t in x_tracers]\n-\n- body_fun = jaxpr_as_fun(jaxpr)\n-\n- def new_body(*vals):\n- out = body_fun(*vals)\n- out_carry, y = split_list(out, [num_carry])\n- return out_carry, y\n- new_body = callback_transform(new_body, trace.callback,\n- strip_calls=trace.strip_calls) # type: ignore\n- in_tree = tree_structure(carry_avals + xs_avals)\n- new_jaxpr, new_consts, _ = lcf._initial_style_jaxpr(\n- new_body, in_tree, tuple(carry_avals + x_avals))\n- vals = tuple(it.chain(new_consts, carry_vals, xs_vals))\n- out_vals = lax.scan_p.bind(*vals, reverse=reverse, length=length,\n- num_consts=len(new_consts), num_carry=num_carry,\n- jaxpr=new_jaxpr, linear=linear, unroll=unroll)\n- return safe_map(trace.pure, out_vals)\n-\n-custom_callback_rules[lax.scan_p] = _scan_callback_rule\n-\n-\n-def _while_callback_rule(trace, *tracers, cond_jaxpr, body_jaxpr,\n- cond_nconsts, body_nconsts):\n- cond_const_tracers, body_const_tracers, init_tracers = split_list(\n- tracers, [cond_nconsts, body_nconsts])\n- init_avals = safe_map(lambda x: x.aval, init_tracers)\n- cond_const_vals, body_const_vals, init_vals = tree_map(\n- lambda x: x.val, (cond_const_tracers, body_const_tracers, init_tracers))\n-\n- body_fun = jaxpr_as_fun(body_jaxpr)\n- cond_fun = jaxpr_as_fun(cond_jaxpr)\n-\n- def cond(*carry):\n- return cond_fun(*it.chain(cond_const_vals, carry))\n-\n- def body(*carry):\n- return body_fun(*it.chain(body_const_vals, carry))\n-\n- new_cond = callback_transform(cond, trace.callback, strip_calls=trace.strip_calls) # type: ignore\n- new_body = callback_transform(body, trace.callback, strip_calls=trace.strip_calls) # type: ignore\n- in_tree = tree_structure(init_avals)\n-\n- new_cond_jaxpr, new_cond_consts, _ = lcf._initial_style_jaxpr(new_cond, in_tree, tuple(init_avals))\n- new_body_jaxpr, new_body_consts, _ = lcf._initial_style_jaxpr(new_body, in_tree, tuple(init_avals))\n- out = lcf.while_p.bind(\n- *it.chain(new_cond_consts, new_body_consts, init_vals),\n- cond_nconsts=len(new_cond_consts),\n- body_nconsts=len(new_body_consts),\n- cond_jaxpr=new_cond_jaxpr,\n- body_jaxpr=new_body_jaxpr)\n- return safe_map(trace.pure, out)\n-\n-custom_callback_rules[lax.while_p] = _while_callback_rule\n-\n-def _custom_derivative_call_jaxpr_callback_rule(primitive, trace, *tracers,\n- fun_jaxpr, num_consts, **params):\n- main = trace.main\n- vals = [t.val for t in tracers]\n-\n- new_closed_jaxpr = callback_jaxpr(fun_jaxpr, trace.callback, strip_calls=trace.strip_calls)\n- if primitive == cd.custom_vjp_call_jaxpr_p:\n- thunk_name = 'fwd_jaxpr_thunk'\n- params['bwd'] = callback_subtrace(params['bwd'], main)\n- else:\n- raise NotImplementedError(primitive)\n-\n- thunk = params.pop(thunk_name)\n- @pe._memoize\n- def new_thunk():\n- thunk_jaxpr = core.ClosedJaxpr(*thunk())\n- closed_jaxpr = callback_jaxpr(thunk_jaxpr, trace.callback, trace.strip_calls)\n- return closed_jaxpr.jaxpr, closed_jaxpr.literals\n-\n- params[thunk_name] = new_thunk\n- new_fun_jaxpr, new_consts = new_closed_jaxpr.jaxpr, new_closed_jaxpr.literals\n- closed_fun_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(new_fun_jaxpr), ())\n- new_num_consts = len(new_consts) + num_consts\n- out = primitive.bind(*it.chain(new_consts, vals), fun_jaxpr=closed_fun_jaxpr,\n- num_consts=new_num_consts, **params)\n- return safe_map(trace.pure, out)\n-\n-custom_callback_rules[cd.custom_vjp_call_jaxpr_p] = partial(\n- _custom_derivative_call_jaxpr_callback_rule, cd.custom_vjp_call_jaxpr_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -66,12 +66,6 @@ jax_test(\n},\n)\n-jax_test(\n- name = \"callback_test\",\n- srcs = [\"callback_test.py\"],\n- deps = [\"//jax:callback\"],\n-)\n-\njax_test(\nname = \"core_test\",\nsrcs = [\"core_test.py\"],\n"
},
{
"change_type": "DELETE",
"old_path": "tests/callback_test.py",
"new_path": null,
"diff": "-# Copyright 2020 The JAX Authors.\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-from absl.testing import absltest\n-\n-import jax\n-from jax._src import test_util as jtu\n-from jax.experimental.callback import find_by_value, rewrite, FoundValue\n-import jax.numpy as jnp\n-from jax import lax\n-from jax import jit\n-from jax import grad\n-\n-from jax.config import config\n-config.parse_flags_with_absl()\n-\n-class CallbackTest(jtu.JaxTestCase):\n- @jtu.sample_product(value=[jnp.inf, jnp.nan])\n- def testFindByValueFound(self, value):\n- def f(x):\n- y = x ** 2\n- z = 1 - y\n- r = 1 / z\n- return r * 0\n-\n- with self.assertRaises(FoundValue):\n- find_by_value(f, value)(jnp.array([1.0, 2.0, 3.0]))\n-\n- @jtu.sample_product(value=[jnp.inf, jnp.nan])\n- def testFindByValueFoundJIT(self, value):\n- def f(x):\n- @jit\n- def g(x):\n- y = x ** 2\n- z = 1 - y\n- r = 1 / z\n- return r * 0\n- return g(x)\n- with self.assertRaises(FoundValue):\n- find_by_value(f, value)(jnp.array([1.0, 2.0, 3.0]))\n-\n- @jtu.sample_product(value=[jnp.inf, jnp.nan])\n- def testFindByValueNotFound(self, value):\n- def f(x):\n- y = x ** 2\n- z = 1 - y\n- return z\n-\n- find_by_value(f, value)(jnp.array([1.0, 2.0, 3.0]))\n-\n- def testRewrite(self):\n- def f(x):\n- return x * 2\n-\n- x = jnp.array([2.0, 4.0])\n- self.assertAllClose(f(x), jnp.array([4.0, 8.0]))\n-\n- self.assertAllClose(\n- rewrite(f, {lax.mul_p: lambda x, y: x + y})(x),\n- jnp.array([4.0, 6.0]))\n-\n- def testRewriteJIT(self):\n- def f(x):\n- @jit\n- def g(x):\n- return x * 2\n- return g(x)\n-\n- x = jnp.array([2.0, 4.0])\n- self.assertAllClose(f(x), jnp.array([4.0, 8.0]))\n-\n- self.assertAllClose(\n- rewrite(f, {lax.mul_p: lambda x, y: x + y})(x),\n- jnp.array([4.0, 6.0]))\n-\n- def testRewriteWithCustomGradients(self):\n- def f(x):\n- return jax.nn.relu(x)\n-\n- x = jnp.array([2.0, 4.0])\n- self.assertAllClose(f(x), jnp.array([2.0, 4.0]))\n-\n- self.assertAllClose(\n- rewrite(f, {})(x),\n- jnp.array([2.0, 4.0]))\n-\n- def testRewriteThroughScan(self):\n- def f(xs):\n- def body(carry, x):\n- carry = carry * 2.\n- return carry, x - 2.\n- return lax.scan(body, 1., xs)\n-\n- xs = jnp.arange(4.)\n- carry, ys = f(xs)\n- self.assertAllClose(carry, 16.)\n- self.assertAllClose(ys, jnp.arange(4.) - 2.)\n-\n- rewrites = {\n- lax.mul_p: lambda x, y: x + y,\n- lax.sub_p: lambda x, y: x / y\n- }\n- carry, ys = rewrite(f, rewrites)(xs)\n- self.assertAllClose(carry, 1. + 8.)\n- self.assertAllClose(ys, jnp.arange(4.) / 2.)\n-\n-\n- def testRewriteThroughWhile(self):\n- def f(x):\n- def cond(x):\n- return x < 5\n- def body(x):\n- return x + 1\n- return lax.while_loop(cond, body, x)\n-\n- x = 0\n- self.assertAllClose(f(x), 5)\n-\n- rewrites = {\n- lax.add_p: lambda x, y: x + y + 100,\n- }\n- self.assertAllClose(rewrite(f, rewrites)(x), 101)\n-\n- rewrites = {\n- lax.lt_p: lambda x, y: x < y + 5\n- }\n- self.assertAllClose(rewrite(f, rewrites)(x), 10)\n-\n-\n- def testRewriteThroughForLoop(self):\n- def f(x):\n- def body(i, x):\n- return x * i\n- return lax.fori_loop(1, 5, body, x)\n-\n- x = 1\n- self.assertAllClose(f(x), 24)\n-\n- rewrites = {\n- lax.mul_p: lambda x, y: x + y\n- }\n- self.assertAllClose(rewrite(f, rewrites)(x), 11)\n-\n- def testRewriteThroughCustomVJP(self):\n-\n- @jax.custom_gradient\n- def f(x):\n- return x * 2, lambda g: g + x\n-\n- x = 2.\n- self.assertAllClose(f(x), 4.)\n- self.assertAllClose(grad(f)(x), 3.)\n-\n- rewrites = {\n- lax.mul_p: lambda x, y: x / y\n- }\n- g = rewrite(f, rewrites)\n-\n- self.assertAllClose(g(x), 1.)\n- self.assertAllClose(grad(g)(x), 3.)\n-\n- rewrites = {\n- lax.add_p: lambda x, y: x - y\n- }\n- g = rewrite(f, rewrites)\n-\n- self.assertAllClose(g(x), 4.)\n- self.assertAllClose(grad(g)(x), -1.)\n-\n- def testRewriteThroughCustomVJPInScan(self):\n-\n- @jax.custom_gradient\n- def foo(x):\n- return x * 2, lambda g: g + x\n-\n- def f(x):\n- out, _ = lax.scan(lambda c, _: (foo(c), None), x, None, length=1)\n- return out\n-\n- x = 2.\n- self.assertAllClose(f(x), 4.)\n- self.assertAllClose(grad(f)(x), 3.)\n-\n- rewrites = {\n- lax.mul_p: lambda x, y: x / y\n- }\n- g = rewrite(f, rewrites)\n-\n- self.assertAllClose(g(x), 1.)\n- self.assertAllClose(grad(g)(x), 3.)\n-\n- rewrites = {\n- lax.add_p: lambda x, y: x * y\n- }\n- g = rewrite(f, rewrites)\n-\n- self.assertAllClose(g(x), 4.)\n- self.assertAllClose(grad(g)(x), 2.)\n-\n- def testRewriteThroughCustomJVP(self):\n-\n- @jax.custom_jvp\n- def f(x):\n- return x + 2\n-\n- @f.defjvp\n- def f_jvp(primals, tangents):\n- x, = primals\n- d, = tangents\n- return f(x), x * d\n-\n- x = 2.\n- self.assertAllClose(f(x), 4.)\n- f_primal, jvp = jax.jvp(f, (x,), (1.,))\n- self.assertAllClose(f_primal, 4.)\n- self.assertAllClose(jvp, 2.)\n- self.assertAllClose(grad(f)(x), 2.)\n-\n- rewrites = {\n- lax.add_p: lambda x, y: x - y\n- }\n- g = rewrite(f, rewrites)\n-\n- self.assertAllClose(g(x), 0.)\n- g_primal, jvp = jax.jvp(g, (x,), (1.,))\n- self.assertAllClose(g_primal, 0.)\n- self.assertAllClose(jvp, 2.)\n- self.assertAllClose(grad(g)(x), 2.)\n-\n- def testRewriteThroughCustomJVPInScan(self):\n-\n- @jax.custom_jvp\n- def foo(x):\n- return x + 2\n-\n- @foo.defjvp\n- def foo_jvp(primals, tangents):\n- x, = primals\n- d, = tangents\n- return f(x), x * d\n- def f(x):\n- out, _ = lax.scan(lambda c, _: (foo(c), None), x, None, length=1)\n- return out\n-\n- x = 2.\n- self.assertAllClose(f(x), 4.)\n- f_primal, jvp = jax.jvp(f, (x,), (1.,))\n- self.assertAllClose(f_primal, 4.)\n- self.assertAllClose(jvp, 2.)\n- self.assertAllClose(grad(f)(x), 2.)\n-\n- rewrites = {\n- lax.add_p: lambda x, y: x - y\n- }\n- g = rewrite(f, rewrites)\n-\n- self.assertAllClose(g(x), 0.)\n- g_primal, jvp = jax.jvp(g, (x,), (1.,))\n- self.assertAllClose(g_primal, 0.)\n- self.assertAllClose(jvp, 2.)\n- self.assertAllClose(grad(g)(x), 2.)\n-\n- rewrites = {\n- lax.mul_p: lambda x, y: x + y\n- }\n- g = rewrite(f, rewrites)\n-\n- self.assertAllClose(g(x), 4.)\n- g_primal, jvp = jax.jvp(g, (x,), (1.,))\n- self.assertAllClose(g_primal, 4.)\n- self.assertAllClose(jvp, 3.)\n- self.assertAllClose(grad(g)(x), 1.)\n-\n-\n-if __name__ == \"__main__\":\n- absltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Delete `jax.experimental.callback`
PiperOrigin-RevId: 501760507 |
260,356 | 13.01.2023 09:59:40 | 28,800 | 2257e2075dff0cf6b030b61ce8b419937d76d34c | Update doc landing page | [
{
"change_type": "MODIFY",
"old_path": "docs/_static/style.css",
"new_path": "docs/_static/style.css",
"diff": "@import url(\"theme.css\");\n+:root {\n+ --block-bg-opacity: .5;\n+}\n+\n.wy-side-nav-search {\nbackground-color: #fff;\n}\n+\n+.getting-started {\n+ background-color: rgba(78, 150, 253, var(--block-bg-opacity));\n+}\n+\n+.user-guides {\n+ background-color: rgba(0, 169, 154, var(--block-bg-opacity));\n+}\n+\n+.developer-docs {\n+ background-color: rgba(171, 0, 182, var(--block-bg-opacity));\n+}\n+\n+.key-ideas\n+{\n+ border: 0px\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/advanced_guide.rst",
"diff": "+.. _advanced_guide:\n+\n+Advanced Tutorials\n+==================\n+\n+.. toctree::\n+ :maxdepth: 1\n+\n+ notebooks/autodiff_cookbook\n+ multi_process\n+ notebooks/Distributed_arrays_and_automatic_parallelization\n+ notebooks/vmapped_log_probs\n+ notebooks/neural_network_with_tfds_data\n+ notebooks/Custom_derivative_rules_for_Python_code\n+ notebooks/How_JAX_primitives_work\n+ notebooks/Writing_custom_interpreters_in_Jax\n+ notebooks/Neural_Network_and_Data_Loading\n+ notebooks/xmap_tutorial\n+ notebooks/external_callbacks\n+ Custom_Operation_for_GPUs\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/beginner_guide.rst",
"diff": "+:orphan:\n+\n+.. _beginner-guide:\n+\n+\n+Beginner Guide\n+==============\n+\n+Welcome to the beginners guide for JAX.\n+On this page we will introduce you to the key ideas of JAX,\n+show you how to get JAX running\n+and provide you some tutorials to get started.\n+\n+If looking to jump straight in take a look at the JAX quickstart.\n+\n+.. toctree::\n+ :maxdepth: 1\n+\n+ notebooks/quickstart\n+\n+For most users starting out the key functionalities of JAX to become familiar with are :code:`jax.jit`,\n+:code:`jax.grad`, and :code:`jax.vmap`.\n+A good way to get familiar with this is with the Jax-101 tutorials.\n+\n+.. toctree::\n+ :maxdepth: 2\n+\n+ jax-101/index\n+\n+If you're familiar with doing array-oriented computing with NumPy, you may find the following\n+resources useful:\n+\n+.. toctree::\n+ :maxdepth: 1\n+\n+ notebooks/thinking_in_jax\n+ notebooks/Common_Gotchas_in_JAX\n+ faq\n+\n+If you prefer a video introduction here is one from JAX contributor Jake Vanderplas:\n+\n+.. raw:: html\n+\n+ <iframe width=\"640\" height=\"360\" src=\"https://www.youtube.com/embed/WdTeDXsOSj4\"\n+ title=\"Intro to JAX: Accelerating Machine Learning research\"\n+ frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\"\n+ allowfullscreen></iframe>\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/conf.py",
"new_path": "docs/conf.py",
"diff": "@@ -40,7 +40,7 @@ sys.path.insert(0, os.path.abspath('..'))\n# -- Project information -----------------------------------------------------\nproject = 'JAX'\n-copyright = '2020, The JAX Authors. NumPy and SciPy documentation are copyright the respective authors.'\n+copyright = '2023, The JAX Authors. NumPy and SciPy documentation are copyright the respective authors.'\nauthor = 'The JAX authors'\n# The short X.Y version\n@@ -72,6 +72,7 @@ extensions = [\n\"sphinx_remove_toctrees\",\n'sphinx_copybutton',\n'jax_extensions',\n+ 'sphinx_design'\n]\nintersphinx_mapping = {\n@@ -174,6 +175,10 @@ html_favicon = '_static/favicon.png'\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n+html_css_files = [\n+ 'style.css',\n+]\n+\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/contributor_guide.rst",
"diff": "+.. _contributor-guide:\n+\n+Developer Documentation\n+=======================\n+\n+JAX welcomes contributions from the community.\n+See below for various install guides to get setup as a developer\n+as well as developer-focused resources such as Jax Enhancement Proposals.\n+\n+.. toctree::\n+ :maxdepth: 1\n+\n+ contributing\n+ developer\n+ jax_internal_api\n+ autodidax\n+ jep/index\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/index.rst",
"new_path": "docs/index.rst",
"diff": "-JAX reference documentation\n-===========================\n+JAX: High-Performance Array Computing\n+=====================================\n-JAX is Autograd_ and XLA_, brought together for high-performance numerical computing and machine learning research.\n-It provides composable transformations of Python+NumPy programs: differentiate, vectorize,\n-parallelize, Just-In-Time compile to GPU/TPU, and more.\n+JAX is Autograd_ and XLA_, brought together for high-performance numerical computing.\n+\n+.. grid:: 3\n+\n+ .. grid-item::\n+\n+ .. card:: Familiar API\n+ :class-card: key-ideas\n+ :shadow: None\n+\n+ JAX provides a familiar NumPy-style API for ease of adoption by researchers and engineers.\n+\n+ .. grid-item::\n+\n+ .. card:: Transformations\n+ :class-card: key-ideas\n+ :shadow: None\n+\n+ JAX includes composable function transformations for compilation, batching, automatic differentiation, and parallelization.\n+\n+ .. grid-item::\n+\n+ .. card:: Run Anywhere\n+ :class-card: key-ideas\n+ :shadow: None\n+\n+ The same code executes on multiple backends, including CPU, GPU, & TPU\n.. note::\nJAX 0.4.1 introduces new parallelism APIs, including breaking changes to :func:`jax.experimental.pjit` and a new unified ``jax.Array`` type.\nPlease see `Distributed arrays and automatic parallelization <https://jax.readthedocs.io/en/latest/notebooks/Distributed_arrays_and_automatic_parallelization.html>`_ tutorial and the :ref:`jax-array-migration`\nguide for more information.\n-.. toctree::\n- :maxdepth: 1\n- :caption: Getting Started\n- installation\n- notebooks/quickstart\n- notebooks/thinking_in_jax\n- notebooks/Common_Gotchas_in_JAX\n+.. grid:: 3\n-.. toctree::\n- :maxdepth: 1\n+ .. grid-item::\n- jax-101/index\n+ .. card:: :material-regular:`rocket_launch;2em` Getting Started\n+ :link: beginner-guide\n+ :link-type: ref\n+ :class-card: getting-started\n-.. toctree::\n- :maxdepth: 2\n+ .. grid-item::\n- debugging/index\n+ .. card:: :material-regular:`library_books;2em` User Guides\n+ :link: user-guides\n+ :link-type: ref\n+ :class-card: user-guides\n-.. toctree::\n- :maxdepth: 1\n- :caption: Reference Documentation\n+ .. grid-item::\n- faq\n- async_dispatch\n- aot\n- jaxpr\n- notebooks/convolutions\n- pytrees\n- jax_array_migration\n- type_promotion\n- errors\n- transfer_guard\n- glossary\n- changelog\n+ .. card:: :material-regular:`laptop_chromebook;2em` Developer Docs\n+ :link: contributor-guide\n+ :link-type: ref\n+ :class-card: developer-docs\n-.. toctree::\n- :maxdepth: 1\n- :caption: Advanced JAX Tutorials\n-\n- notebooks/autodiff_cookbook\n- multi_process\n- notebooks/Distributed_arrays_and_automatic_parallelization\n- notebooks/vmapped_log_probs\n- notebooks/neural_network_with_tfds_data\n- notebooks/Custom_derivative_rules_for_Python_code\n- notebooks/How_JAX_primitives_work\n- notebooks/Writing_custom_interpreters_in_Jax\n- notebooks/Neural_Network_and_Data_Loading\n- notebooks/xmap_tutorial\n- notebooks/external_callbacks\n- Custom_Operation_for_GPUs\n+Installation\n+------------\n+.. code-block:: bash\n-.. toctree::\n- :maxdepth: 1\n- :caption: Developer documentation\n+ pip install \"jax[cpu]\"\n+\n+For installation on accelerators (GPU, TPU) and other installation options,\n+see the `Install Guide`_ in the project README.\n- contributing\n- developer\n- jax_internal_api\n- autodidax\n- jep/index\n.. toctree::\n+ :hidden:\n:maxdepth: 1\n- :caption: API documentation\n+ :caption: Getting Started\n- jax\n+ installation\n+ notebooks/quickstart\n+ notebooks/thinking_in_jax\n+ notebooks/Common_Gotchas_in_JAX\n+ faq\n.. toctree::\n+ :hidden:\n:maxdepth: 1\n- :caption: Notes\n- api_compatibility\n- deprecation\n- concurrency\n- gpu_memory_allocation\n- profiling\n- device_memory_profiling\n- rank_promotion_warning\n+ jax-101/index\n-Indices and tables\n-==================\n+.. toctree::\n+ :hidden:\n+ :maxdepth: 2\n+ :caption: Further Resources\n-* :ref:`genindex`\n-* :ref:`modindex`\n-* :ref:`search`\n+ user_guides\n+ advanced_guide\n+ contributor_guide\n+ notes\n+ jax\n.. _Autograd: https://github.com/hips/autograd\n.. _XLA: https://www.tensorflow.org/xla\n+.. _Install Guide: https://github.com/google/jax#installation\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax-101/index.rst",
"new_path": "docs/jax-101/index.rst",
"diff": "+:orphan:\n+\n+.. _Jax-101:\n+\nTutorial: JAX 101\n=================\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/notes.rst",
"diff": "+.. _notes:\n+\n+Notes\n+-----\n+\n+.. toctree::\n+ :maxdepth: 1\n+\n+ api_compatibility\n+ deprecation\n+ concurrency\n+ gpu_memory_allocation\n+ profiling\n+ device_memory_profiling\n+ rank_promotion_warning\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/requirements.txt",
"new_path": "docs/requirements.txt",
"diff": "@@ -8,6 +8,7 @@ sphinx-book-theme>=0.3.3\nsphinx-copybutton>=0.5.0\nsphinx-remove-toctrees\njupyter-sphinx>=0.3.2\n+sphinx-design\nmyst-nb\n# Packages used for CI tests.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/user_guides.rst",
"diff": "+.. _user-guides:\n+\n+User Guides\n+===========\n+\n+\n+.. toctree::\n+ :maxdepth: 1\n+\n+ async_dispatch\n+ aot\n+ jaxpr\n+ notebooks/convolutions\n+ pytrees\n+ jax_array_migration\n+ type_promotion\n+ errors\n+ transfer_guard\n+ glossary\n+ changelog\n+ debugging/index\n\\ No newline at end of file\n"
}
] | Python | Apache License 2.0 | google/jax | Update doc landing page
Co-authored-by: 8bitmp3 <19637339+8bitmp3@users.noreply.github.com>
Co-authored-by: Jake VanderPlas <jakevdp@google.com> |
260,411 | 12.01.2023 08:44:53 | -3,600 | ade56916300e2c6e50d47609d93742cb160355e4 | [call_tf] Add has_side_effects parameter
The CallTfEffect was added recently as an internal workaround for
DCE removing instances of call_tf. Here we add a parameter to
`call_tf` to be able to declare if the called computation is
effectful and should not be removed by DCE. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -11,6 +11,11 @@ Remember to align the itemized text with the first line of an item within a list\n* Breaking changes\n* Deleted `jax.experimental.callback`\n+* Changes\n+ * {func}`jax2tf.call_tf` has a new parameter `has_side_effects` (default `True`)\n+ that can be used to declare whether an instance can be removed or replicated\n+ by JAX optimizations such as dead-code elimination ({jax-issue}`#13980`).\n+\n## jaxlib 0.4.2\n## jax 0.4.1 (Dec 13, 2022)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -59,7 +59,7 @@ TfConcreteFunction = Any\n# DLPack, if we are careful.\n_DLPACK_PLATFORMS = (\"gpu\",)\n-def call_tf(callable_tf: Callable) -> Callable:\n+def call_tf(callable_tf: Callable, has_side_effects=True) -> Callable:\n\"\"\"Calls a TensorFlow function from JAX, with support for reverse autodiff.\nThe ``callable_tf`` will be called with TensorFlow-compatible arguments (\n@@ -85,6 +85,9 @@ def call_tf(callable_tf: Callable) -> Callable:\nArgs:\ncallable_tf: a TensorFlow Callable that can take a pytree of TensorFlow\narguments.\n+ has_side_effects: if True then it ensures that instances of this primitive\n+ are not removed or replicated by JAX optimizations such as dead-code\n+ elimination.\nReturns: a JAX callable that can be invoked with JAX pytree arguments, in\nop-by-op mode or in a staged context. This callable can be used with\n@@ -153,7 +156,8 @@ def call_tf(callable_tf: Callable) -> Callable:\n# Carry the actual function such that op-by-op call can call in TF eager mode.\ncallable_flat_tf=callable_flat_tf,\nfunction_flat_tf=function_flat_tf,\n- args_flat_sig_tf=args_flat_sig_tf)\n+ args_flat_sig_tf=args_flat_sig_tf,\n+ has_side_effects=has_side_effects)\nreturn res_treedef.unflatten(res_jax_flat)\n# Define the fwd and bwd custom_vjp functions\n@@ -254,6 +258,7 @@ def _get_concrete_function_tf(function_flat_tf, args_flat_sig_tf): # -> tf.Conc\nreturn function_flat_tf.get_concrete_function(*args_flat_sig_tf)\n+# Mark the effectful instancess of call_tf\nCallTfEffect = enum.Enum('CallTfEffect', ['EFFECT'])\nmlir.lowerable_effects.add(CallTfEffect.EFFECT)\n@@ -264,7 +269,8 @@ custom_derivatives.allowed_effects.add(CallTfEffect.EFFECT)\ndef _call_tf_abstract_eval(*_,\nfunction_flat_tf,\n- args_flat_sig_tf, **__):\n+ args_flat_sig_tf,\n+ has_side_effects, **__):\n# Called only when we form a Jaxpr, i.e., under jit, scan, etc.\nconcrete_function_flat_tf = _get_concrete_function_tf(function_flat_tf,\n@@ -272,6 +278,7 @@ def _call_tf_abstract_eval(*_,\ndef is_fully_known_shape(s):\nreturn s.rank is not None and all([d is not None for d in s])\n+ effects = {CallTfEffect.EFFECT} if has_side_effects else set()\nif all([is_fully_known_shape(s)\nfor s in concrete_function_flat_tf.output_shapes]):\nreturn (\n@@ -281,7 +288,7 @@ def _call_tf_abstract_eval(*_,\nfor dtype, shape in zip(concrete_function_flat_tf.output_dtypes,\nconcrete_function_flat_tf.output_shapes)\n]),\n- {CallTfEffect.EFFECT})\n+ effects)\n# There are some cases when TF shape inference is not powerful enough to\n# figure out the output shapes (e.g., b/128924522), even in situations where\n@@ -292,9 +299,7 @@ def _call_tf_abstract_eval(*_,\n# it should not matter which platform we use.\n_, result_avals = _code_generator_and_avals(function_flat_tf, args_flat_sig_tf,\n\"CPU\")\n- # Add an effect to the abstract eval rule of call_tf so that JAX's DCE pass\n- # doesn't prune args passed to call_tf.\n- return tuple(result_avals), {CallTfEffect.EFFECT}\n+ return tuple(result_avals), effects\ncall_tf_p.def_effectful_abstract_eval(_call_tf_abstract_eval)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -624,6 +624,16 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = tf.function(f_tf2, autograph=False)(x)\nself.assertAllClose(res.numpy(), f_jax(x))\n+ def test_effectful(self):\n+ if not config.jax_array:\n+ raise unittest.SkipTest(\"Test not intended to work without jax.Array\")\n+\n+ x = np.ones((3,), dtype=np.float32)\n+ lower_effect = jax.jit(jax2tf.call_tf(tf.math.sin, has_side_effects=True)).lower(x)\n+ self.assertNotEmpty(lower_effect._lowering.compile_args[\"unordered_effects\"])\n+\n+ lower_no_effect = jax.jit(jax2tf.call_tf(tf.math.sin, has_side_effects=False)).lower(x)\n+ self.assertEmpty(lower_no_effect._lowering.compile_args[\"unordered_effects\"])\ndef test_module_documentation(self):\ndef cos_tf(x):\n"
}
] | Python | Apache License 2.0 | google/jax | [call_tf] Add has_side_effects parameter
The CallTfEffect was added recently as an internal workaround for
DCE removing instances of call_tf. Here we add a parameter to
`call_tf` to be able to declare if the called computation is
effectful and should not be removed by DCE. |
260,335 | 14.01.2023 20:55:34 | 28,800 | 1da24b61fc63ea035f56b454119d2a4693d6f6fe | fix transcription error for initial_step_size (thanks
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ode.py",
"new_path": "jax/experimental/ode.py",
"diff": "@@ -90,7 +90,7 @@ def initial_step_size(fun, t0, y0, order, rtol, atol, f0):\nh1 = jnp.where((d1 <= 1e-15) & (d2 <= 1e-15),\njnp.maximum(1e-6, h0 * 1e-3),\n- (0.01 / jnp.max(d1 + d2)) ** (1. / (order + 1.)))\n+ (0.01 / jnp.maximum(d1, d2)) ** (1. / (order + 1.)))\nreturn jnp.minimum(100. * h0, h1)\n"
}
] | Python | Apache License 2.0 | google/jax | fix transcription error for initial_step_size (thanks @AlbertMitjans)
fixes #13983 |
260,335 | 16.01.2023 10:29:59 | 28,800 | e516d41180bb07767ef64a5d8e0581c8bcec5533 | cond transpose, use UndefinedPrimal not `linear` for transpose inputs | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/conditionals.py",
"new_path": "jax/_src/lax/control_flow/conditionals.py",
"diff": "@@ -687,7 +687,9 @@ def _transpose_cond_jaxpr(jaxpr, num_res, reduce_axes):\nreturn _make_closed_jaxpr(transposed, res_avals + jaxpr.out_avals)\ndef _cond_transpose(reduce_axes, cts, *args, branches, linear):\n+ del linear # could use for error checking, but see #14026\nindex, *ops = args\n+ linear = [type(x) is ad.UndefinedPrimal for x in ops]\nin_avals = map(raise_to_shaped, branches[0].in_avals)\nnum_res = len(ops) - sum(linear)\nif any(isinstance(eff, state.RefEffect) for branch in branches for eff in\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -2564,5 +2564,45 @@ class LaxControlFlowTest(jtu.JaxTestCase):\njax.grad(f)(1.) # doesn't crash\n+ def test_custom_jvp_tangent_cond_transpose(self):\n+ # https://github.com/google/jax/issues/14026\n+ def mask_fun(arr, choice):\n+ out = (1 - choice) * arr.sum() + choice * (1 - arr.sum())\n+ return out\n+\n+ def switch_fun(arr, choice):\n+ choice = jnp.floor(choice).astype(jnp.int32)\n+ out = jax.lax.switch(choice, [lambda x: x.sum(), lambda x: 1 - x.sum()], arr)\n+ return out\n+\n+ test_arr = jnp.arange(3.)\n+ test_val = 0.\n+\n+ expected1 = jax.grad(mask_fun)(test_arr, test_val)\n+ expected2 = jax.grad(switch_fun)(test_arr, test_val)\n+\n+ def good_switchfun_jvp(primals, tangents):\n+ arr, choice = primals\n+ arr_dot, choice_dot = tangents\n+ return switch_fun(arr, choice), mask_fun(arr_dot, choice)\n+\n+ def bad_switchfun_jvp(primals, tangents):\n+ arr, choice = primals\n+ arr_dot, choice_dot = tangents\n+ return switch_fun(arr, choice), switch_fun(arr_dot, choice)\n+\n+ good_custom_switchfun = jax.custom_jvp(switch_fun)\n+ good_custom_switchfun.defjvp(good_switchfun_jvp)\n+ expected3 = jax.grad(good_custom_switchfun)(test_arr, test_val)\n+\n+ bad_custom_switchfun = jax.custom_jvp(switch_fun)\n+ bad_custom_switchfun.defjvp(bad_switchfun_jvp)\n+ actual = jax.grad(bad_custom_switchfun)(test_arr, test_val)\n+\n+ self.assertAllClose(expected1, expected2)\n+ self.assertAllClose(expected2, expected3)\n+ self.assertAllClose(expected3, actual)\n+\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | cond transpose, use UndefinedPrimal not `linear` for transpose inputs |
260,510 | 16.01.2023 14:44:06 | 28,800 | a58e59d98f516187bf8689e4107d3e6356bf06b4 | Add in effects_barrier for the pmap unordered callback test | [
{
"change_type": "MODIFY",
"old_path": "tests/jaxpr_effects_test.py",
"new_path": "tests/jaxpr_effects_test.py",
"diff": "@@ -688,7 +688,6 @@ class ParallelEffectsTest(jtu.JaxTestCase):\njax.pmap(f)(jnp.arange(jax.local_device_count()))\n@jtu.pytest_mark_if_available('pjrt_c_api_unimplemented') # host callback\n- @jtu.skip_on_devices(\"tpu\") # TODO(b/264013537): flaky on TPUs.\ndef test_can_pmap_unordered_callback(self):\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n# supported\n@@ -709,6 +708,7 @@ class ParallelEffectsTest(jtu.JaxTestCase):\nx, callback=log_value, effect='unordered_log', out_avals=[])\nreturn x + 1\nf(jnp.arange(2)).block_until_ready()\n+ jax.effects_barrier()\nself.assertSetEqual({0, 1}, log)\nclass ControlFlowEffectsTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Add in effects_barrier for the pmap unordered callback test
PiperOrigin-RevId: 502434258 |
260,310 | 16.01.2023 22:42:42 | 28,800 | 469a8eb520baf8ad2c62aaa9271ce09ae81d2425 | Change args_tf_flat to tf.TensorSpec in jax2tf.call_tf. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -352,14 +352,24 @@ def _code_generator_and_avals(\nelse:\ncaptured_inputs.append(inp)\n- # TODO(necula): It seems that we need concrete tensors for get_compiler_ir?\n- # We know of one case when TF is sensitive to the values of the tensors that\n- # affect shapes in the computation. In those cases, however, those tensors\n- # are inlined in the computation, which we detect below.\n+ # TODO(b/265073174): Currently TensorSpec get_compiler_ir does not support\n+ # tf.function captured variables. We can elminate this after it is fixed.\n+ if tf.executing_eagerly():\nargs_tf_flat = [\n- tf.constant((0 if a.dtype != tf.bool else False),\n- shape=a.shape,\n- dtype=a.dtype) for a in args_flat_sig_tf]\n+ tf.constant(\n+ (0 if a.dtype != tf.bool else False), shape=a.shape, dtype=a.dtype\n+ )\n+ for a in args_flat_sig_tf\n+ ]\n+ else:\n+\n+ def maybe_convert_to_spec(x):\n+ if isinstance(x, tf.TensorSpec):\n+ return x\n+ else:\n+ return tf.TensorSpec.from_tensor(x)\n+\n+ args_tf_flat = [maybe_convert_to_spec(a) for a in args_flat_sig_tf]\nwith jax2tf_internal.inside_call_tf():\n# When the TF computation uses variables on a particular device, we must\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -817,6 +817,21 @@ class RoundTripToJaxTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaises(TypeError):\n_ = jax.grad(f_rt)(x)\n+ def test_call_tf_under_function_context(self):\n+ def fun_jax(x, y):\n+ z = jax2tf.call_tf(tf.math.sin)(x) + jnp.cos(y)\n+ return z\n+\n+ x = np.array([-1.0, 0.0, 1.0], dtype=np.float32)\n+ y = np.array([-0.5, 0.0, 0.5], dtype=np.float32)\n+\n+ converted_fun = tf.function(\n+ jax2tf.convert(fun_jax, experimental_native_lowering=True)\n+ )\n+ expected = np.sin(x) + np.cos(y)\n+ res = tf.function(converted_fun, jit_compile=True, autograph=False)(x, y)\n+ self.assertAllClose(expected, res.numpy(), atol=1e-5, rtol=1e-5)\n+\nclass RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\n\"Reloading output of call_tf into TF with jax2tf.\"\n"
}
] | Python | Apache License 2.0 | google/jax | Change args_tf_flat to tf.TensorSpec in jax2tf.call_tf.
PiperOrigin-RevId: 502492762 |
260,411 | 17.01.2023 10:42:20 | -7,200 | cf4e568e2105945fe65efe4e7f18b9d446bd1c90 | [shape_poly] Improve error message from vmap axis size inconsistency
vmap tries hard to give nice error messages when the mapped axes
for different arguments have different sizes, but the code to
compute the error message can run into InconsistentDimensionOperation
in presence of dimension polynomials. Ensure that the comparisons
are done symbolically. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -1685,8 +1685,13 @@ def _mapped_axis_size(fn, tree, vals, dims, name):\nfor x, d in zip(vals, dims)]\nsize_counts = collections.Counter(s for s in all_sizes if s is not None)\n(sz, ct), *other_counts = counts = size_counts.most_common()\n- ex, *examples = [key_paths[all_sizes.index(sz)] for sz, _ in counts]\n- ax, *axs = [dims[all_sizes.index(sz)] for sz, _ in counts]\n+ def _all_sizes_index(sz):\n+ for i, isz in enumerate(all_sizes):\n+ if core.symbolic_equal_dim(isz, sz): return i\n+ assert False, (sz, all_sizes)\n+\n+ ex, *examples = [key_paths[_all_sizes_index(sz)] for sz, _ in counts]\n+ ax, *axs = [dims[_all_sizes_index(sz)] for sz, _ in counts]\nif ct == 1:\nmsg.append(f\" * one axis had size {sz}: axis {ax} of {ex};\\n\")\nelse:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"diff": "@@ -1461,6 +1461,21 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec((None, 3), dtype=tf.float32)\n)\n+ def test_vmap_error(self):\n+ # vmap is careful to give nice error messages when mapped axes have\n+ # different sizes, but this can be foiled by InconsistentDimensionOperation\n+ x = y = np.ones((3, 5), dtype=np.float32)\n+ with self.assertRaisesRegex(ValueError,\n+ \"vmap got inconsistent sizes for array axes to be mapped\"):\n+ jax2tf.convert(jax.vmap(lambda x, y: x + y),\n+ polymorphic_shapes=[\"b, ...\", None])(x, y)\n+\n+ z = x\n+ with self.assertRaisesRegex(ValueError,\n+ \"vmap got inconsistent sizes for array axes to be mapped\"):\n+ jax2tf.convert(jax.vmap(lambda x, y, z: x + y + z),\n+ polymorphic_shapes=[\"b, ...\", \"c, ...\", None])(x, y, z)\n+\ndef test_reshape_compiled(self):\n# We compile the result of conversion for two shapes, hence we need to\n# involve the TF compiler twice, but we trace only once with shape polymorphism\n"
}
] | Python | Apache License 2.0 | google/jax | [shape_poly] Improve error message from vmap axis size inconsistency
vmap tries hard to give nice error messages when the mapped axes
for different arguments have different sizes, but the code to
compute the error message can run into InconsistentDimensionOperation
in presence of dimension polynomials. Ensure that the comparisons
are done symbolically. |
260,510 | 10.11.2022 12:00:21 | 28,800 | 3de5c2b7165e7e4374089fc5a6824cc9c20390d2 | Add IO callback | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -3347,7 +3347,7 @@ def block_until_ready(x):\nreturn jax.tree_util.tree_map(try_to_block, x)\ndef pure_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\n- *args: Any, **kwargs: Any):\n+ *args: Any, vectorized: bool = False, **kwargs: Any):\n\"\"\"Applies a functionally pure Python callable. Works under :func:`jit`/:func:`~pmap`/etc.\n``pure_callback`` enables calling a Python function in JIT-ed JAX functions.\n@@ -3390,14 +3390,15 @@ def pure_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\nvia `jax.vmap`, it will be called directly on inputs with leading batch\ndimensions instead of executing ``callback`` on each mapped input\nindividually. The callback should also return outputs batched across the\n- leading axis.\n+ leading axis. By default, ``vectorized`` is ``False``.\n**kwargs: The keyword arguments to the callback. Must be PyTrees of JAX\ntypes.\nReturns:\nThe value of ``callback(*args, **kwargs)``.\n\"\"\"\n- return jcb.pure_callback(callback, result_shape_dtypes, *args, **kwargs)\n+ return jcb.pure_callback(callback, result_shape_dtypes, *args,\n+ vectorized=vectorized, **kwargs)\ndef clear_backends():\n\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/callback.py",
"new_path": "jax/_src/callback.py",
"diff": "@@ -23,11 +23,11 @@ from jax._src import core\nfrom jax._src import dtypes\nfrom jax._src import util\nfrom jax._src import dispatch\n+from jax._src.lib import xla_client as xc\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\nimport numpy as np\n-from jax._src.lib import xla_client as xc\n# `pure_callback_p` is the main primitive for staging out Python pure callbacks.\npure_callback_p = core.Primitive(\"pure_callback\")\n@@ -150,3 +150,106 @@ def pure_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\n*flat_args, callback=_flat_callback,\nresult_avals=tuple(flat_result_avals), vectorized=vectorized)\nreturn tree_util.tree_unflatten(out_tree, out_flat)\n+\n+\n+# IO Callback\n+\n+io_callback_p = core.Primitive(\"io_callback\")\n+io_callback_p.multiple_results = True\n+\n+class IOEffect:\n+ __str__ = lambda _: \"IO\"\n+class OrderedIOEffect:\n+ __str__ = lambda _: \"OrderedIO\"\n+_IOEffect = IOEffect()\n+_OrderedIOEffect = OrderedIOEffect()\n+mlir.lowerable_effects.add(_IOEffect)\n+mlir.lowerable_effects.add(_OrderedIOEffect)\n+core.control_flow_allowed_effects.add(_IOEffect)\n+core.control_flow_allowed_effects.add(_OrderedIOEffect)\n+core.ordered_effects.add(_OrderedIOEffect)\n+\n+\n+def io_callback_impl(*args, result_avals, callback: Callable[..., Any],\n+ ordered: bool):\n+ del result_avals, ordered\n+ return callback(*args)\n+io_callback_p.def_impl(functools.partial(dispatch.apply_primitive,\n+ io_callback_p))\n+\n+@io_callback_p.def_effectful_abstract_eval\n+def io_callback_abstract_eval(*avals, callback: Callable[..., Any],\n+ result_avals, ordered: bool):\n+ del avals, callback\n+ effect = _OrderedIOEffect if ordered else _IOEffect\n+ return result_avals, {effect}\n+\n+def io_callback_jvp_rule(*args, **kwargs):\n+ del args, kwargs\n+ raise ValueError(\"IO callbacks do not support JVP.\")\n+ad.primitive_jvps[io_callback_p] = io_callback_jvp_rule\n+\n+\n+def io_callback_transpose_rule(*args, **kwargs):\n+ del args, kwargs\n+ raise ValueError(\"IO callbacks do not support transpose.\")\n+ad.primitive_transposes[io_callback_p] = io_callback_transpose_rule\n+\n+\n+def io_callback_batching_rule(args, dims, callback, result_avals, ordered):\n+ if ordered:\n+ raise ValueError(\"Cannot `vmap` ordered IO callback.\")\n+ return pure_callback_batching_rule(args, dims, callback=callback,\n+ vectorized=False, result_avals=result_avals)\n+batching.primitive_batchers[io_callback_p] = io_callback_batching_rule\n+\n+def io_callback_lowering(ctx, *args, callback, ordered, **params):\n+\n+ def _callback(*flat_args):\n+ return tuple(io_callback_impl(*flat_args, callback=callback,\n+ ordered=ordered, **params))\n+\n+ # TODO(sharadmv): figure out the best API for sharding callbacks. For now, we\n+ # can only safely maximally shard. Should we allow device_index to be passed\n+ # in like host_callback?\n+ if isinstance(ctx.module_context.axis_context,\n+ (mlir.SPMDAxisContext, mlir.ShardingContext)):\n+ # Apply maximal sharding so pjit only executes the callback on device 0.\n+ sharding = xc.OpSharding()\n+ sharding.type = xc.OpSharding.Type.MAXIMAL\n+ sharding.tile_assignment_dimensions = [1]\n+ sharding.tile_assignment_devices = [0]\n+ else:\n+ sharding = None\n+\n+ if ordered:\n+ token = ctx.tokens_in.get(_OrderedIOEffect)[0]\n+ result, token, keepalive = mlir.emit_python_callback(\n+ ctx, _callback, token, list(args), ctx.avals_in, ctx.avals_out, True,\n+ sharding=sharding)\n+ ctx.set_tokens_out(mlir.TokenSet({_OrderedIOEffect: (token,)}))\n+ else:\n+ result, token, keepalive = mlir.emit_python_callback(\n+ ctx, _callback, None, list(args), ctx.avals_in, ctx.avals_out, True,\n+ sharding=sharding)\n+ ctx.module_context.add_keepalive(keepalive)\n+ return result\n+mlir.register_lowering(io_callback_p, io_callback_lowering)\n+\n+def io_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\n+ *args: Any, ordered: bool = False, **kwargs: Any):\n+ def _flat_callback(*flat_args):\n+ args, kwargs = tree_util.tree_unflatten(in_tree, flat_args)\n+ return tree_util.tree_leaves(callback(*args, **kwargs))\n+\n+ flat_args, in_tree = tree_util.tree_flatten((args, kwargs))\n+ tree_util.tree_map(_check_shape_dtype, result_shape_dtypes)\n+ flat_shape_dtypes, out_tree = tree_util.tree_flatten(result_shape_dtypes)\n+ flat_result_avals = map(lambda x: core.ShapedArray(x.shape, x.dtype),\n+ flat_shape_dtypes)\n+ flat_args = map(core.raise_as_much_as_possible, flat_args)\n+ out_flat = io_callback_p.bind(\n+ *flat_args, callback=_flat_callback,\n+ result_avals=tuple(flat_result_avals),\n+ ordered=ordered)\n+ return tree_util.tree_unflatten(out_tree, out_flat)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/core.py",
"new_path": "jax/_src/core.py",
"diff": "@@ -63,6 +63,7 @@ Effect = Hashable\nEffects = Set[Effect]\nno_effects: Effects = set()\nordered_effects: Set[Effect] = set()\n+control_flow_allowed_effects: Set[Effect] = set()\nclass Jaxpr:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/common.py",
"new_path": "jax/_src/lax/control_flow/common.py",
"diff": "import os\nfrom functools import partial\n-from typing import Callable, Optional, Sequence, Set\n+from typing import Callable, Optional, Sequence\n-from jax import core\n+from jax._src import core\nfrom jax._src import linear_util as lu\n-from jax.api_util import flatten_fun_nokwargs\n-from jax.interpreters import partial_eval as pe\n+from jax._src.core import control_flow_allowed_effects as allowed_effects\nfrom jax._src.lax import lax\nfrom jax._src import ad_util\nfrom jax._src import util\nfrom jax._src.util import cache, weakref_lru_cache, safe_map, unzip3\n+from jax.api_util import flatten_fun_nokwargs\n+from jax.interpreters import partial_eval as pe\nfrom jax.tree_util import tree_map, tree_unflatten\nmap, unsafe_map = safe_map, map\n-allowed_effects: Set[core.Effect] = set()\nallowed_effects.add(lax.InOutFeedEffect.Infeed)\nallowed_effects.add(lax.InOutFeedEffect.Outfeed)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/conditionals.py",
"new_path": "jax/_src/lax/control_flow/conditionals.py",
"diff": "@@ -337,10 +337,17 @@ def _bcast_select_n(pred, *cases):\ndef _cond_batching_rule(axis_size, axis_name, main_type, args, dims, branches, linear):\nindex, *ops = args\nindex_dim, *op_dims = dims\n+ # TODO(sharadmv): clean this up by adding a specific blocklist\nif any(isinstance(eff, state.RefEffect) for branch in branches for eff in\nbranch.jaxpr.effects):\nraise NotImplementedError(\n- \"State effect not supported in cond vmap.\")\n+ \"State effect not supported in vmap-of-cond.\")\n+ from jax._src.callback import _IOEffect, _OrderedIOEffect\n+ if any(eff in branch.effects for eff in [_IOEffect, _OrderedIOEffect]\n+ for branch in branches):\n+ raise NotImplementedError(\n+ \"IO effect not supported in vmap-of-cond.\")\n+\nif index_dim is not batching.not_mapped:\n# Convert to a lax.select. While we could get away with not broadcasting\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/loops.py",
"new_path": "jax/_src/lax/control_flow/loops.py",
"diff": "@@ -1143,6 +1143,12 @@ def _while_loop_abstract_eval(*args, cond_jaxpr, body_jaxpr, **kwargs):\ndef _while_loop_batching_rule(axis_size, axis_name, main_type, args, dims,\ncond_nconsts, cond_jaxpr,\nbody_nconsts, body_jaxpr):\n+ from jax._src.callback import _IOEffect, _OrderedIOEffect\n+ if any(eff in branch.effects for eff in [_IOEffect, _OrderedIOEffect]\n+ for branch in [body_jaxpr, cond_jaxpr]):\n+ raise NotImplementedError(\n+ \"IO effect not supported in vmap-of-while.\")\n+\norig_batched = [d is not batching.not_mapped for d in dims]\ncconst_bat, bconst_bat, init_bat = split_list(orig_batched, [cond_nconsts, body_nconsts])\ncconsts, bconsts, init = split_list(args, [cond_nconsts, body_nconsts])\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/__init__.py",
"new_path": "jax/experimental/__init__.py",
"diff": "@@ -22,3 +22,6 @@ from jax.experimental.x64_context import (\nenable_x64 as enable_x64,\ndisable_x64 as disable_x64,\n)\n+from jax._src.callback import (\n+ io_callback as io_callback\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -972,6 +972,9 @@ jax_test(\njax_test(\nname = \"python_callback_test\",\nsrcs = [\"python_callback_test.py\"],\n+ deps = [\n+ \"//jax:experimental\",\n+ ],\n)\njax_test(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/python_callback_test.py",
"new_path": "tests/python_callback_test.py",
"diff": "@@ -24,17 +24,18 @@ from jax import lax\nfrom jax import tree_util\nfrom jax._src import debugging\nfrom jax._src import dispatch\n+from jax._src import sharding\nfrom jax._src import test_util as jtu\nfrom jax._src import util\nfrom jax._src.lib import xla_bridge\nfrom jax._src.lib import xla_client\n-from jax.experimental.maps import Mesh\n-from jax.experimental.pjit import PartitionSpec as P\n-from jax.experimental.pjit import pjit\n-from jax.experimental.maps import xmap\nfrom jax.config import config\nfrom jax.experimental import maps\n+from jax.experimental import pjit\nfrom jax.interpreters import mlir\n+from jax.experimental.maps import Mesh\n+from jax.experimental.maps import xmap\n+from jax.experimental import io_callback\nimport jax.numpy as jnp\nimport numpy as np\n@@ -682,7 +683,7 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\ntry:\nmesh = Mesh(np.array(jax.devices()), axis_names=('x',))\n- spec = P('x')\n+ spec = pjit.PartitionSpec('x')\ndef f(x):\naxis_resources = {v: v for v in mesh.axis_names}\n@@ -699,7 +700,7 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\nwith mesh:\ninp = jnp.arange(float(jax.local_device_count()))\n- out = pjit(f, in_axis_resources=spec, out_axis_resources=spec)(inp)\n+ out = pjit.pjit(f, in_axis_resources=spec, out_axis_resources=spec)(inp)\nnp.testing.assert_allclose(\nout, np.sin(np.arange(jax.local_device_count()))\n)\n@@ -708,7 +709,7 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(\nNotImplementedError, 'when all mesh axes are partitioned manually'\n):\n- pjit(\n+ pjit.pjit(\nwithout_xmap_f, in_axis_resources=spec, out_axis_resources=spec\n)(inp)\n@@ -879,5 +880,157 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\nx = np.arange(6, dtype=np.int32).reshape((3, 2))\nnp.testing.assert_allclose(g(x), x)\n+class IOPythonCallbackTest(jtu.JaxTestCase):\n+\n+ def setUp(self):\n+ super().setUp()\n+ if xla_bridge.get_backend().runtime_type == 'stream_executor':\n+ raise unittest.SkipTest('Host callback not supported for runtime type: stream_executor.')\n+\n+ def tearDown(self):\n+ super().tearDown()\n+ dispatch.runtime_tokens.clear()\n+\n+ def test_io_callback_can_mutate_state(self):\n+ x = 0\n+ def cb():\n+ nonlocal x\n+ x += 1\n+ return np.array(x, np.int32)\n+\n+ def f():\n+ return io_callback(cb, jax.ShapeDtypeStruct((), jnp.int32))\n+ f()\n+ jax.effects_barrier()\n+ self.assertEqual(x, 1)\n+ f()\n+ jax.effects_barrier()\n+ self.assertEqual(x, 2)\n+\n+ def test_io_callback_can_be_batched_if_unordered(self):\n+ _mut = 0\n+ def cb(x):\n+ nonlocal _mut\n+ _mut += 1\n+ return x\n+\n+ x = jnp.arange(4)\n+ def f(x):\n+ return io_callback(cb, jax.ShapeDtypeStruct((), x.dtype), x)\n+ jax.vmap(f)(x)\n+ jax.effects_barrier()\n+ self.assertEqual(_mut, 4)\n+ jax.vmap(f)(x)\n+ jax.effects_barrier()\n+ self.assertEqual(_mut, 8)\n+\n+ def test_cannot_call_ordered_io_in_pmap(self):\n+ def f(x):\n+ return io_callback(\n+ lambda x: x, jax.ShapeDtypeStruct((), jnp.int32), x, ordered=True)\n+ with self.assertRaisesRegex(\n+ ValueError, \"Ordered effects not supported in `pmap`\"):\n+ jax.pmap(f)(jnp.arange(jax.local_device_count()))\n+\n+ def test_cannot_call_ordered_io_in_xmap(self):\n+ def f(x):\n+ return io_callback(\n+ lambda x: x, jax.ShapeDtypeStruct((), jnp.int32), x, ordered=True)\n+ with self.assertRaisesRegex(\n+ ValueError, \"Cannot `vmap` ordered IO callback\"):\n+ maps.xmap(f, in_axes=([0],), out_axes=[0])(jnp.arange(16))\n+\n+ def test_cannot_call_ordered_io_in_vmap(self):\n+ def f(x):\n+ return io_callback(\n+ lambda x: x, jax.ShapeDtypeStruct((), jnp.int32), x, ordered=True)\n+ with self.assertRaisesRegex(\n+ ValueError, \"Cannot `vmap` ordered IO callback\"):\n+ jax.vmap(f)(jnp.arange(4))\n+\n+ def test_cannot_use_io_callback_in_jvp(self):\n+ def f(x):\n+ return io_callback(lambda x: x, jax.ShapeDtypeStruct((), jnp.float32), x)\n+ with self.assertRaisesRegex(\n+ ValueError, \"IO callbacks do not support JVP.\"):\n+ jax.jvp(f, (0.,), (1.,))\n+\n+ def test_cannot_use_io_callback_in_linearize(self):\n+ def f(x):\n+ return io_callback(lambda x: x, jax.ShapeDtypeStruct((), jnp.float32), x)\n+ with self.assertRaisesRegex(\n+ ValueError, \"IO callbacks do not support JVP.\"):\n+ jax.linearize(f, 0.)\n+\n+ def test_cannot_use_io_callback_in_transpose(self):\n+ x = jnp.array(1.)\n+\n+ def f(x):\n+ return io_callback(lambda x: x, jax.ShapeDtypeStruct((), x.dtype), x)\n+ with self.assertRaisesRegex(\n+ ValueError, \"IO callbacks do not support transpose.\"):\n+ jax.linear_transpose(f, x)(x)\n+\n+ def test_cannot_vmap_of_cond_io_callback(self):\n+ def f(pred):\n+ def true_fun():\n+ io_callback(lambda: print(\"true\"), None)\n+ def false_fun():\n+ io_callback(lambda: print(\"false\"), None)\n+ return lax.cond(pred, false_fun, true_fun)\n+ with self.assertRaisesRegex(NotImplementedError,\n+ \"IO effect not supported in vmap-of-cond.\"):\n+ jax.vmap(f)(jnp.array([True, True]))\n+\n+ def test_cannot_vmap_of_while_io_callback(self):\n+ def check(x):\n+ assert np.all(x < 5)\n+\n+ def f(i):\n+ def cond(i):\n+ return i < 5\n+ def body(i):\n+ io_callback(check, None, i)\n+ return i + 1\n+ return lax.while_loop(cond, body, i)\n+ with self.assertRaisesRegex(NotImplementedError,\n+ \"IO effect not supported in vmap-of-while.\"):\n+ jax.vmap(f)(jnp.array([0, 4]))\n+\n+ def test_cannot_use_io_callback_in_checkpoint(self):\n+ @jax.grad\n+ @jax.checkpoint\n+ def f(x, y):\n+ io_callback(lambda x: x, y, y)\n+ return x\n+\n+ with self.assertRaisesRegex(NotImplementedError,\n+ \"Effects not supported in partial-eval of `checkpoint`\"):\n+ f(2., 3.)\n+\n+ def test_can_use_io_callback_in_pjit(self):\n+\n+ _mut = 0\n+ def _cb(x):\n+ nonlocal _mut\n+ _mut = x.sum()\n+\n+ def f(x):\n+ io_callback(_cb, None, x)\n+ return x\n+\n+ mesh = maps.Mesh(np.array(jax.devices()), ['dev'])\n+ if config.jax_array:\n+ spec = sharding.NamedSharding(mesh, pjit.PartitionSpec('dev'))\n+ out_spec = sharding.NamedSharding(mesh, pjit.PartitionSpec())\n+ else:\n+ spec = pjit.PartitionSpec('dev')\n+ out_spec = pjit.PartitionSpec()\n+ f = pjit.pjit(f, in_axis_resources=spec, out_axis_resources=out_spec)\n+ with mesh:\n+ f(jnp.arange(mesh.size))\n+ jax.effects_barrier()\n+ self.assertEqual(_mut, jnp.arange(mesh.size).sum())\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add IO callback |
260,411 | 18.01.2023 12:56:48 | -7,200 | 58035a7b53cd07a826934d89bc7fea8bfbc2a3e0 | [shape_poly] Fix handling of weak_type for conversions of symbolic dimensions to Array
In presence of static shapes `jnp.array(x.shape[0])` has weak_type. We must
preserve that behavior even with symbolic dimensions. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -461,6 +461,7 @@ class _DimPolynomial():\ncore.pytype_aval_mappings[_DimPolynomial] = _DimPolynomial.get_aval\nxla.pytype_aval_mappings[_DimPolynomial] = _DimPolynomial.get_aval\n+dtypes._weak_types.append(_DimPolynomial)\ndef _ensure_poly(p: DimSize,\noperation_name: str) -> _DimPolynomial:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"diff": "@@ -42,6 +42,7 @@ from jax.experimental.jax2tf.tests import tf_test_util\nimport tensorflow as tf # type: ignore[import]\nfrom jax.config import config\n+from jax._src.config import numpy_dtype_promotion\nconfig.parse_flags_with_absl()\n@@ -1444,6 +1445,25 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\narg_descriptors=[RandArg((3, 4), _f32)],\npoly_axes=[0])\n+ def test_dim_as_value_weak_type(self):\n+ def f_jax(x): # x: f32[b]\n+ d0 = jnp.array(x.shape[0]) # in JAX should have weak_type=True\n+ if isinstance(d0, core.Tracer):\n+ self.assertTrue(d0.aval.weak_type), d0\n+\n+ # And an implicit conversion to array\n+ d1 = x.shape[0] + jnp.array(4)\n+ if isinstance(d1, core.Tracer):\n+ self.assertTrue(d1.aval.weak_type), d1\n+ return d0 + np.array(5., dtype=np.float32) + d1\n+\n+ with numpy_dtype_promotion(\"strict\"):\n+ # strict type promotion is sensitive to weak_types\n+ check_shape_poly(self,\n+ f_jax,\n+ arg_descriptors=[RandArg((3,), _f32)],\n+ poly_axes=[0])\n+\n@unittest.skip('Failing at HEAD. Reenable after b/264913007 is fixed')\ndef test_vmap_while(self):\ndef cond_func(x): # x: f32[3]\n"
}
] | Python | Apache License 2.0 | google/jax | [shape_poly] Fix handling of weak_type for conversions of symbolic dimensions to Array
In presence of static shapes `jnp.array(x.shape[0])` has weak_type. We must
preserve that behavior even with symbolic dimensions. |
260,631 | 18.01.2023 16:42:29 | 28,800 | 5f4e95b6c7e8d3531ba8630c8dc4965869682bf7 | Add gcs support to serialization for internal tensor spec. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/gda_serialization/serialization.py",
"new_path": "jax/experimental/gda_serialization/serialization.py",
"diff": "@@ -109,21 +109,23 @@ def _spec_has_metadata(tree):\nreturn 'metadata' in tree or any(\n_spec_has_metadata(subtree) for _, subtree in tree.items())\n-\n-def get_tensorstore_spec(ckpt_path: str):\n- spec = {'driver': 'zarr', 'kvstore': {}}\n-\n- if ckpt_path.startswith('gs://'):\n+def _get_kvstore_for_gcs(ckpt_path: str):\nm = re.fullmatch('^gs://([^/]*)/(.*)$', ckpt_path, re.DOTALL)\nif m is None:\nraise ValueError('The ckpt_path should contain the bucket name and the '\nf'file path inside the bucket. Got: {ckpt_path}')\ngcs_bucket = m.group(1)\npath_without_bucket = m.group(2)\n- spec['kvstore'] = {'driver': 'gcs', 'bucket': gcs_bucket,\n- 'path': path_without_bucket}\n+ return {'driver': 'gcs', 'bucket': gcs_bucket, 'path': path_without_bucket}\n+\n+def get_tensorstore_spec(ckpt_path: str):\n+ spec = {'driver': 'zarr', 'kvstore': {}}\n+\n+ if ckpt_path.startswith('gs://'):\n+ spec['kvstore'] = _get_kvstore_for_gcs(ckpt_path)\nelse:\nspec['kvstore'] = {'driver': 'file', 'path': ckpt_path}\n+\nreturn spec\n"
}
] | Python | Apache License 2.0 | google/jax | Add gcs support to serialization for internal tensor spec.
PiperOrigin-RevId: 503013068 |
260,582 | 12.01.2023 16:20:48 | 28,800 | 45c2f31887c9cc5bb94dea92c9e82b1d675ac095 | Added shape error checking for compute_fans
Update tests/nn_test.py | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/nn/initializers.py",
"new_path": "jax/_src/nn/initializers.py",
"diff": "@@ -157,6 +157,10 @@ def _compute_fans(shape: core.NamedShape,\nAxes not in in_axis, out_axis, or batch_axis are assumed to constitute the\n\"receptive field\" of a convolution (kernel spatial dimensions).\n\"\"\"\n+ if shape.rank <= 1:\n+ raise ValueError(f\"Can't compute input and output sizes of a {shape.rank}\"\n+ \"-dimensional weights tensor. Must be at least 2D.\")\n+\nif isinstance(in_axis, int):\nin_size = shape[in_axis]\nelse:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/nn_test.py",
"new_path": "tests/nn_test.py",
"diff": "@@ -314,6 +314,19 @@ class NNInitializersTest(jtu.JaxTestCase):\nself.assertEqual(shape, jnp.shape(val))\n+ def testVarianceScalingError(self):\n+ rng = random.PRNGKey(0)\n+ shape = (5,)\n+ initializer = nn.initializers.variance_scaling(\n+ scale=1.0, mode='fan_avg', distribution='truncated_normal')\n+\n+ with self.assertRaisesRegex(\n+ ValueError,\n+ \"Can't compute input and output sizes of a 1\"\n+ \"-dimensional weights tensor. Must be at least 2D.\"\n+ ):\n+ initializer(rng, shape)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Added shape error checking for compute_fans
Update tests/nn_test.py
Co-authored-by: Jake Vanderplas <jakevdp@google.com> |
260,631 | 20.01.2023 08:47:45 | 28,800 | cd5b26a0b97762a76ab53d6bcdc8f66b02886394 | Fix typo "invalud" -> "invalid" in error message. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -286,7 +286,7 @@ def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name,\n\"decorator were removed) was called in an attempt to get a more \"\n\"precise error message. However, the de-optimized function did not \"\n\"produce invalid values during its execution. This behavior can \"\n- \"result from `jit` optimizations causing the invalud value to be \"\n+ \"result from `jit` optimizations causing the invalid value to be \"\n\"produced. It may also arise from having nan/inf constants as \"\n\"outputs, like `jax.jit(lambda ...: jax.numpy.nan)(...)`. \"\n\"\\n\\n\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/pjit.py",
"new_path": "jax/_src/pjit.py",
"diff": "@@ -1161,7 +1161,7 @@ def _pjit_call_impl(*args, jaxpr,\n\"decorator were removed) was called in an attempt to get a more \"\n\"precise error message. However, the de-optimized function did not \"\n\"produce invalid values during its execution. This behavior can \"\n- \"result from `jit` optimizations causing the invalud value to be \"\n+ \"result from `jit` optimizations causing the invalid value to be \"\n\"produced. It may also arise from having nan/inf constants as \"\n\"outputs, like `jax.jit(lambda ...: jax.numpy.nan)(...)`. \"\n\"\\n\\n\"\n"
}
] | Python | Apache License 2.0 | google/jax | Fix typo "invalud" -> "invalid" in error message.
PiperOrigin-RevId: 503452691 |
260,335 | 20.01.2023 10:51:02 | 28,800 | cea2b6b6f82c5b7f68eafd4812e6881d751fa0cf | specialize tree prefix error message for list/tuple | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/tree_util.py",
"new_path": "jax/_src/tree_util.py",
"diff": "@@ -492,13 +492,29 @@ def _prefix_error(key_path: KeyPath, prefix_tree: Any, full_tree: Any,\nf\" {type(full_tree)}.\".format(name=name))\nreturn # don't look for more errors in this subtree\n- # Or they may disagree if their roots have different numbers of children (note\n- # that because both prefix_tree and full_tree have the same type at this\n- # point, and because prefix_tree is not a leaf, each can be flattened once):\n+ # Or they may disagree if their roots have different numbers or keys of\n+ # children. Because both prefix_tree and full_tree have the same type at this\n+ # point, and because prefix_tree is not a leaf, each can be flattened once:\nprefix_tree_children, prefix_tree_meta = flatten_one_level(prefix_tree)\nfull_tree_children, full_tree_meta = flatten_one_level(full_tree)\nprefix_tree_keys = _child_keys(prefix_tree)\nfull_tree_keys = _child_keys(full_tree)\n+ # First we check special case types (list and tuple, though if they were\n+ # pytrees we could check strings and sets here, basically Sequences) so that\n+ # we can report length disagreement rather than integer keys:\n+ if isinstance(prefix_tree, (list, tuple)):\n+ if len(prefix_tree) != len(full_tree):\n+ ty = type(prefix_tree)\n+ yield lambda name: ValueError(\n+ f\"pytree structure error: different lengths of {ty.__name__} at key path\\n\"\n+ f\" {{name}}{key_path.pprint()}\\n\"\n+ f\"At that key path, the prefix pytree {{name}} has a subtree of type \"\n+ f\"{ty.__name__} of length {len(prefix_tree)}, but the full pytree \"\n+ f\"has a subtree of the same type but of length {len(full_tree)}.\"\n+ .format(name=name))\n+ return # don't look for more errors in this subtree\n+ else:\n+ # Next we handle the general case of checking child keys.\ntry:\ndiff = set(prefix_tree_keys).symmetric_difference(set(full_tree_keys))\nexcept:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/tree_util_test.py",
"new_path": "tests/tree_util_test.py",
"diff": "@@ -507,8 +507,25 @@ class TreePrefixErrorsTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, expected):\nraise e2('in_axes')\n- def test_different_num_children(self):\n+ def test_different_num_children_tuple(self):\ne, = prefix_errors((1,), (2, 3))\n+ expected = (\"pytree structure error: different lengths of tuple \"\n+ \"at key path\\n\"\n+ \" in_axes tree root\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\n+ def test_different_num_children_list(self):\n+ e, = prefix_errors([1], [2, 3])\n+ expected = (\"pytree structure error: different lengths of list \"\n+ \"at key path\\n\"\n+ \" in_axes tree root\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\n+\n+ def test_different_num_children_generic(self):\n+ e, = prefix_errors({'hi': 1}, {'hi': 2, 'bye': 3})\nexpected = (\"pytree structure error: different numbers of pytree children \"\n\"at key path\\n\"\n\" in_axes tree root\")\n@@ -517,7 +534,7 @@ class TreePrefixErrorsTest(jtu.JaxTestCase):\ndef test_different_num_children_nested(self):\ne, = prefix_errors([[1]], [[2, 3]])\n- expected = (\"pytree structure error: different numbers of pytree children \"\n+ expected = (\"pytree structure error: different lengths of list \"\n\"at key path\\n\"\nr\" in_axes\\[0\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\n@@ -525,12 +542,12 @@ class TreePrefixErrorsTest(jtu.JaxTestCase):\ndef test_different_num_children_multiple(self):\ne1, e2 = prefix_errors([[1], [2]], [[3, 4], [5, 6]])\n- expected = (\"pytree structure error: different numbers of pytree children \"\n+ expected = (\"pytree structure error: different lengths of list \"\n\"at key path\\n\"\nr\" in_axes\\[0\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e1('in_axes')\n- expected = (\"pytree structure error: different numbers of pytree children \"\n+ expected = (\"pytree structure error: different lengths of list \"\n\"at key path\\n\"\nr\" in_axes\\[1\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\n"
}
] | Python | Apache License 2.0 | google/jax | specialize tree prefix error message for list/tuple |
260,539 | 19.01.2023 15:53:01 | 28,800 | 59c71250eebb13aa04bdd743c319fefa079e5e4b | Adding to jax.experimental API doc | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/jax.experimental.custom_partitioning.rst",
"diff": "+``jax.experimental.custom_partitioning`` module\n+===============================================\n+\n+.. automodule:: jax.experimental.custom_partitioning\n+\n+API\n+---\n+\n+.. autofunction:: custom_partitioning\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax.experimental.rst",
"new_path": "docs/jax.experimental.rst",
"diff": "@@ -21,6 +21,7 @@ Experimental Modules\njax.experimental.pjit\njax.experimental.sparse\njax.experimental.jet\n+ jax.experimental.custom_partitioning\nExperimental APIs\n-----------------\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/custom_partitioning.py",
"new_path": "jax/experimental/custom_partitioning.py",
"diff": "@@ -130,8 +130,11 @@ def _default_propagate_user_shardings(sharding, shape):\nclass custom_partitioning:\n\"\"\"Inserts a CustomCallOp into the XLA graph with custom SPMD lowering rules.\n- Usage:\n- ```\n+ Usage\n+ -----\n+\n+ .. code-block:: python\n+\n@custom_partitioning\ndef f(*args):\nreturn ...\n@@ -150,19 +153,167 @@ class custom_partitioning:\n'''Compute the result sharding from the sharding of the operands.'''\nf.def_partition(partition, propagate_user_sharding, infer_sharding_from_operands)\n- ```\n- The args to def_partition are as follows:\n+ The args to ``def_partition`` are as follows:\n- propagate_user_sharding: Callable which takes the sharding of a user (in the dag)\n- and returns a suggestion for a new NamedSharding. The default\n+ * ``propagate_user_sharding``: Callable which takes the sharding of a user (in the dag)\n+ and returns a suggestion for a new `NamedSharding`. The default\nimplementation is just to return the suggested sharding.\n- partition: Callable which takes the SPMD suggested partition shapes and\n+ * ``partition``: Callable which takes the SPMD suggested partition shapes and\npartition specs and returns a per-shard lowering function and the final\ninput and output sharding specs (the SPMD partitioner will repartition the\ninputs to match).\n- infer_sharding_from_operands: Callable which computes an output\n- NamedSharding from the NamedSharding chosen for each argument.\n+ * ``infer_sharding_from_operands``: Callable which computes an output ``NamedSharding``\n+ from the ``NamedSharding`` chosen for each argument.\n+\n+ Example\n+ -------\n+\n+ Assume we want to enhance the existing ``jax.numpy.fft.fft``. This function computes the\n+ discrete Fourier transform of an N-dimensional input along the last dimension, and is batched\n+ along the first N-1 dimensions.\n+ By default, however, it will ignore the sharding of the input and gather the input on all devices.\n+ However, since ``jax.numpy.fft.fft`` is batched along the first N-1 dimensions,\n+ this is unnecessary. We will create a new ``my_fft`` op that, instead, does not alter the sharding\n+ along the first `N-1` dimensions, and only gathers the input along the last dimension if needed.\n+\n+ .. code-block:: python\n+\n+ import jax\n+ from jax._src.sharding import NamedSharding\n+ from jax.experimental.custom_partitioning import custom_partitioning\n+ from jax.experimental.pjit import pjit\n+ from jax.sharding import PartitionSpec as P\n+ from jax.experimental.maps import Mesh\n+ from jax.numpy.fft import fft\n+ import numpy as np\n+\n+ # For an N-D input, keeps sharding along the first N-1 dimensions\n+ # but replicate along the last dimension\n+ def supported_sharding(sharding, shape):\n+ rank = len(shape.shape)\n+ max_shared_dims = min(len(sharding.spec), rank-1)\n+ names = tuple(sharding.spec[:max_shared_dims]) + tuple(None for _ in range(rank - max_shared_dims))\n+ return NamedSharding(sharding.mesh, P(*names))\n+\n+ def partition(arg_shapes, arg_shardings, result_shape, result_sharding):\n+ return fft, \\\n+ supported_sharding(arg_shardings[0], arg_shapes[0]), \\\n+ [supported_sharding(arg_shardings[0], arg_shapes[0])]\n+\n+ def infer_sharding_from_operands(arg_shapes, arg_shardings, shape):\n+ return supported_sharding(arg_shardings[0], arg_shapes[0])\n+\n+ @custom_partitioning\n+ def my_fft(x):\n+ return fft(x)\n+\n+ my_fft.def_partition(\n+ infer_sharding_from_operands=infer_sharding_from_operands,\n+ partition=partition)\n+\n+ Now create a 2D array sharded along the first axis, pass it through ``my_fft``\n+ and notice how it is still sharded as expected, and identical to the output\n+ of ``fft``. However, the output of ``fft`` is replicated\n+\n+ >>> with Mesh(np.array(jax.devices()), ('x',)):\n+ ... x = np.asarray(np.random.randn(32*1024, 1024), dtype=np.complex64)\n+ ... y = pjit(lambda x: x, in_axis_resources=None, out_axis_resources=P('x'))(x)\n+ ... pjit_my_fft = pjit(my_fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n+ ... pjit_fft = pjit(fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n+ ... print(pjit_my_fft(y))\n+ ... print(pjit_fft(y))\n+\n+ .. code-block::\n+\n+ # my_fft\n+ [[-38.840824 +0.j -40.649452 +11.845365j\n+ ...\n+ -1.6937828 +0.8402481j 15.999859 -4.0156755j]]\n+\n+ # jax.numpy.fft.fft\n+ [[-38.840824 +0.j -40.649452 +11.845365j\n+ ...\n+ -1.6937828 +0.8402481j 15.999859 -4.0156755j]]\n+\n+ If we dump the HLO using ``XLA_FLAGS=\"--xla_dump_to=$(pwd)\"``, we see that ``pjit_fft`` compiles\n+ to\n+\n+ .. code-block::\n+\n+ HloModule pjit_fft, entry_computation_layout={(c64[16384,1024]{1,0})->c64[16384,1024]{1,0}}\n+\n+ fused_computation {\n+ ...\n+ ROOT dynamic-slice.2 = c64[16384,1024]{1,0} dynamic-slice(param_1, multiply.3, constant_7), dynamic_slice_sizes={16384,1024}, metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n+ }\n+\n+ ENTRY main.8_spmd {\n+ param = c64[16384,1024]{1,0} parameter(0), sharding={devices=[2,1]0,1}\n+ all-gather = c64[32768,1024]{1,0} all-gather(param), channel_id=1, replica_groups={{0,1}}, dimensions={0}, use_global_device_ids=true, metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n+ fft.1 = c64[32768,1024]{1,0} fft(all-gather), fft_type=FFT, fft_length={1024}, metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n+ partition-id = u32[] partition-id(), metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n+ ROOT fusion = c64[16384,1024]{1,0} fusion(fft.1, partition-id), kind=kLoop, calls=fused_computation, metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n+ }\n+\n+ Where the ``all-gather`` before the FFT and the dynamic-slice after are both clearly visible.\n+ This means that the input is gathered on all devices prior to the FFT, and sliced after.\n+\n+ ``pjit_my_fft``, on the other hand, simply compiles to\n+\n+ .. code-block::\n+\n+ HloModule pjit__unnamed_wrapped_function_, entry_computation_layout={(c64[16384,1024]{1,0})->c64[16384,1024]{1,0}}\n+\n+ ENTRY main.5_spmd {\n+ param = c64[16384,1024]{1,0} parameter(0), sharding={devices=[2,1]0,1}\n+ ROOT fft.0 = c64[16384,1024]{1,0} fft(param), fft_type=FFT, fft_length={1024}, metadata={op_name=\"jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=41}\n+ }\n+\n+ where no unnecessary sharding is taking place.\n+\n+ Because of the logic in ``supported_sharding``, ``my_fft`` also works on 1-dimensional arrays.\n+\n+ >>> with Mesh(np.array(jax.devices()), ('x',)):\n+ ... x = np.asarray(np.random.randn(32*1024*1024), dtype=np.complex64)\n+ ... y = pjit(lambda x: x, in_axis_resources=None, out_axis_resources=P('x'))(x)\n+ ... pjit_my_fft = pjit(my_fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n+ ... pjit_fft = pjit(fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n+ ... print(pjit_my_fft(y))\n+ ... print(pjit_fft(y))\n+\n+ .. code-block::\n+\n+ # my_fft\n+ [ 7.217285 +0.j -3012.4937 +4287.635j -405.83594 +3042.984j\n+ ... 1422.4502 +7271.4297j -405.84033 -3042.983j\n+ -3012.4963 -4287.6343j]\n+\n+ # jax.numpy.fft.fft\n+ [ 7.217285 +0.j -3012.4937 +4287.635j -405.83594 +3042.984j\n+ ... 1422.4502 +7271.4297j -405.84033 -3042.983j\n+ -3012.4963 -4287.6343j]\n+\n+ In this case, the HLO of ``my_fft`` does show an all-gather and dynamic-slice, since the last dimension\n+ is the dimension along which FFTs are calculated.\n+\n+ .. code-block::\n+\n+ HloModule pjit__unnamed_wrapped_function_, entry_computation_layout={(c64[16777216]{0})->c64[16777216]{0}}\n+\n+ fused_computation {\n+ ...\n+ ROOT dynamic-slice.2 = c64[16777216]{0} dynamic-slice(param_1, multiply.3), dynamic_slice_sizes={16777216}, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/custom_partitioning[partition=<function partition at 0x7f73a1fbc820> propagate_user_sharding=<function _default_propagate_user_shardings at 0x7f73a1fbc550> infer_sharding_from_operands=<function infer_sharding_from_operands at 0x7f73a1fbc8b0> in_tree=PyTreeDef((*,)) out_tree=PyTreeDef(*)]\" source_file=\"doc.py\" source_line=51}\n+ }\n+\n+ ENTRY main.5_spmd {\n+ param = c64[16777216]{0} parameter(0), sharding={devices=[2]0,1}\n+ all-gather = c64[33554432]{0} all-gather(param), channel_id=1, replica_groups={{0,1}}, dimensions={0}, use_global_device_ids=true, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/custom_partitioning[partition=<function partition at 0x7f73a1fbc820> propagate_user_sharding=<function _default_propagate_user_shardings at 0x7f73a1fbc550> infer_sharding_from_operands=<function infer_sharding_from_operands at 0x7f73a1fbc8b0> in_tree=PyTreeDef((*,)) out_tree=PyTreeDef(*)]\" source_file=\"doc.py\" source_line=51}\n+ fft.0 = c64[33554432]{0} fft(all-gather), fft_type=FFT, fft_length={33554432}, metadata={op_name=\"jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(33554432,)]\" source_file=\"doc.py\" source_line=51}\n+ partition-id = u32[] partition-id(), metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/custom_partitioning[partition=<function partition at 0x7f73a1fbc820> propagate_user_sharding=<function _default_propagate_user_shardings at 0x7f73a1fbc550> infer_sharding_from_operands=<function infer_sharding_from_operands at 0x7f73a1fbc8b0> in_tree=PyTreeDef((*,)) out_tree=PyTreeDef(*)]\" source_file=\"doc.py\" source_line=51}\n+ ROOT fusion = c64[16777216]{0} fusion(fft.0, partition-id), kind=kLoop, calls=fused_computation, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/custom_partitioning[partition=<function partition at 0x7f73a1fbc820> propagate_user_sharding=<function _default_propagate_user_shardings at 0x7f73a1fbc550> infer_sharding_from_operands=<function infer_sharding_from_operands at 0x7f73a1fbc8b0> in_tree=PyTreeDef((*,)) out_tree=PyTreeDef(*)]\" source_file=\"doc.py\" source_line=51}\n+ }\n+\n\"\"\"\ndef __init__(self, fun):\n"
}
] | Python | Apache License 2.0 | google/jax | Adding @custom_partitioning to jax.experimental API doc |
260,335 | 20.01.2023 11:40:22 | 28,800 | 358775f9010fdfc98cd2823fda6dbaaf630cee2d | update pjit test | [
{
"change_type": "MODIFY",
"old_path": "tests/pjit_test.py",
"new_path": "tests/pjit_test.py",
"diff": "@@ -3405,12 +3405,9 @@ class PJitErrorTest(jtu.JaxTestCase):\n# pjit(lambda x: x, p, p)([x, x, x]) # Error, but make sure we hint at singleton tuple\nerror = re.escape(\n- \"pytree structure error: different numbers of pytree children at \"\n+ \"pytree structure error: different lengths of list at \"\n\"key path\\n\"\n- \" pjit out_axis_resources tree root\\n\"\n- \"At that key path, the prefix pytree pjit out_axis_resources has a \"\n- \"subtree of type\\n\"\n- \" <class 'list'>\\n\")\n+ \" pjit out_axis_resources tree root\\n\")\nwith self.assertRaisesRegex(ValueError, error):\npjit(lambda x: x, (p,), [p, None])([x, x, x]) # Error, we raise a generic tree mismatch message\n"
}
] | Python | Apache License 2.0 | google/jax | update pjit test |
260,499 | 22.01.2023 21:33:09 | 0 | 73ed511d3945246467b0e3e12da326d40a3fe153 | Adding info to CG and BICGSTAB | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/scipy/sparse/linalg.py",
"new_path": "jax/_src/scipy/sparse/linalg.py",
"diff": "@@ -133,9 +133,9 @@ def _cg_solve(A, b, x0=None, *, maxiter, tol=1e-5, atol=0.0, M=_identity):\ngamma0 = _vdot_real_tree(r0, z0).astype(dtype)\ninitial_value = (x0, r0, gamma0, p0, 0)\n- x_final, *_ = lax.while_loop(cond_fun, body_fun, initial_value)\n-\n- return x_final\n+ x_final, r, gamma, _, k = lax.while_loop(cond_fun, body_fun, initial_value)\n+ rs = gamma.real if M is _identity else _vdot_real_tree(r, r)\n+ return x_final, (k, rs)\n# aliases for working with pytrees\n@@ -182,9 +182,9 @@ def _bicgstab_solve(A, b, x0=None, *, maxiter, tol=1e-5, atol=0.0, M=_identity):\n1, *dtypes._lattice_result_type(*tree_leaves(b)))\ninitial_value = (x0, r0, r0, alpha0, omega0, rho0, r0, r0, 0)\n- x_final, *_ = lax.while_loop(cond_fun, body_fun, initial_value)\n-\n- return x_final\n+ x_final, r, *_, k = lax.while_loop(cond_fun, body_fun, initial_value)\n+ rs = _vdot_real_tree(r, r)\n+ return x_final, (k, rs)\ndef _shapes(pytree):\n@@ -192,7 +192,7 @@ def _shapes(pytree):\ndef _isolve(_isolve_solve, A, b, x0=None, *, tol=1e-5, atol=0.0,\n- maxiter=None, M=None, check_symmetric=False):\n+ maxiter=None, M=None, check_symmetric=False, has_info=False):\nif x0 is None:\nx0 = tree_map(jnp.zeros_like, b)\n@@ -225,11 +225,14 @@ def _isolve(_isolve_solve, A, b, x0=None, *, tol=1e-5, atol=0.0,\nreturn not issubclass(x.dtype.type, np.complexfloating)\nsymmetric = all(map(real_valued, tree_leaves(b))) \\\nif check_symmetric else False\n- x = lax.custom_linear_solve(\n+\n+ x_maybe_info = lax.custom_linear_solve(\nA, b, solve=isolve_solve, transpose_solve=isolve_solve,\n- symmetric=symmetric)\n- info = None\n- return x, info\n+ symmetric=symmetric, has_aux=has_info)\n+ if has_info:\n+ return x_maybe_info\n+ else:\n+ return x_maybe_info, None\ndef cg(A, b, x0=None, *, tol=1e-5, atol=0.0, maxiter=None, M=None):\n@@ -259,9 +262,8 @@ def cg(A, b, x0=None, *, tol=1e-5, atol=0.0, maxiter=None, M=None):\n-------\nx : array or tree of arrays\nThe converged solution. Has the same structure as ``b``.\n- info : None\n- Placeholder for convergence information. In the future, JAX will report\n- the number of iterations when convergence is not achieved, like SciPy.\n+ info : A a pair with the number of iterations run until convergence and the\n+ squared norm of the residual at the last iteration.\nOther Parameters\n----------------\n@@ -287,7 +289,7 @@ def cg(A, b, x0=None, *, tol=1e-5, atol=0.0, maxiter=None, M=None):\n\"\"\"\nreturn _isolve(_cg_solve,\nA=A, b=b, x0=x0, tol=tol, atol=atol,\n- maxiter=maxiter, M=M, check_symmetric=True)\n+ maxiter=maxiter, M=M, check_symmetric=True, has_info=True)\ndef _safe_normalize(x, thresh=None):\n@@ -734,9 +736,8 @@ def bicgstab(A, b, x0=None, *, tol=1e-5, atol=0.0, maxiter=None, M=None):\n-------\nx : array or tree of arrays\nThe converged solution. Has the same structure as ``b``.\n- info : None\n- Placeholder for convergence information. In the future, JAX will report\n- the number of iterations when convergence is not achieved, like SciPy.\n+ info : A a pair with the number of iterations run until convergence and the\n+ squared norm of the residual at the last iteration.\nOther Parameters\n----------------\n@@ -763,4 +764,4 @@ def bicgstab(A, b, x0=None, *, tol=1e-5, atol=0.0, maxiter=None, M=None):\nreturn _isolve(_bicgstab_solve,\nA=A, b=b, x0=x0, tol=tol, atol=atol,\n- maxiter=maxiter, M=M)\n+ maxiter=maxiter, M=M, has_info=True)\n"
}
] | Python | Apache License 2.0 | google/jax | Adding info to CG and BICGSTAB |
260,311 | 23.01.2023 08:16:45 | 28,800 | 13e875f8b8d8dd9152045c7e3b5045a9bb0d7db0 | benchmarks: add math unary benchmarks
These will be used for benchmarking FP approximations in XLA. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "benchmarks/math_benchmark.py",
"diff": "+# Copyright 2023 The JAX Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Microbenchmarks for floating point operations.\"\"\"\n+\n+import functools\n+\n+import google_benchmark as benchmark\n+import jax\n+import jax.numpy as jnp\n+import numpy as np\n+\n+from google_benchmark import Counter\n+\n+\n+def math_benchmark(*args):\n+ def decorator(func):\n+ for test_case in args[0]:\n+\n+ @benchmark.register(name=f\"{func.__name__}_{test_case['name']}\")\n+ @functools.wraps(func)\n+ def wrapper(state, test_case=test_case):\n+ return func(state, **test_case)\n+\n+ return wrapper\n+\n+ return decorator\n+\n+\n+@math_benchmark(\n+ [\n+ {\n+ 'name': f'{op.__name__}_{shape}_{dtype}',\n+ 'shape': shape,\n+ 'dtype': dtype,\n+ 'op': op,\n+ }\n+ for op in [\n+ jnp.exp,\n+ jnp.exp2,\n+ jnp.expm1,\n+ jnp.log,\n+ jnp.log2,\n+ jnp.log1p,\n+ jnp.tanh,\n+ ]\n+ for shape in [2**i for i in range(10, 15, 2)]\n+ for dtype in ['float32']\n+ ]\n+)\n+def jax_unary(state, **kwargs):\n+ shape = kwargs['shape']\n+ dtype = kwargs['dtype']\n+ op = kwargs['op']\n+ input0 = np.random.random(shape).astype(dtype)\n+ f = op\n+ f_jitted = jax.jit(f)\n+ f_jitted(input0).block_until_ready()\n+ while state:\n+ f_jitted(input0).block_until_ready()\n+ state.counters['items_per_second'] = Counter(\n+ input0.size * state.iterations, Counter.kIsRate\n+ )\n+\n+\n+if __name__ == '__main__':\n+ benchmark.main()\n"
}
] | Python | Apache License 2.0 | google/jax | benchmarks: add math unary benchmarks
These will be used for benchmarking FP approximations in XLA.
PiperOrigin-RevId: 503991586 |
260,539 | 23.01.2023 14:38:34 | 28,800 | 3c3a2eea5089c922e70d8fbc807231768b7d0be3 | Removing HLO dump from docstring, using assert(re.search(...)) | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/custom_partitioning.py",
"new_path": "jax/experimental/custom_partitioning.py",
"diff": "@@ -186,8 +186,12 @@ class custom_partitioning:\nfrom jax.sharding import PartitionSpec as P\nfrom jax.experimental.maps import Mesh\nfrom jax.numpy.fft import fft\n+ import regex as re\nimport numpy as np\n+ # Pattern to detect all-gather or dynamic-slice in the generated HLO\n+ _PATTERN = '(dynamic-slice|all-gather)'\n+\n# For an N-D input, keeps sharding along the first N-1 dimensions\n# but replicate along the last dimension\ndef supported_sharding(sharding, shape):\n@@ -214,7 +218,9 @@ class custom_partitioning:\nNow create a 2D array sharded along the first axis, pass it through ``my_fft``\nand notice how it is still sharded as expected, and identical to the output\n- of ``fft``. However, the output of ``fft`` is replicated\n+ of ``fft``. However, inspecting the HLO\n+ (using ``lower(x).compile().runtime_executable().hlo_modules()``) reveals that\n+ ``my_fft`` does not create any all-gather or dynamic-slice, while ``fft`` does.\n>>> with Mesh(np.array(jax.devices()), ('x',)):\n... x = np.asarray(np.random.randn(32*1024, 1024), dtype=np.complex64)\n@@ -223,6 +229,10 @@ class custom_partitioning:\n... pjit_fft = pjit(fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n... print(pjit_my_fft(y))\n... print(pjit_fft(y))\n+ ... # dynamic-slice or all-gather are not present in the HLO for my_fft, because x is a 2D array\n+ ... assert(re.search(_PATTERN, pjit_my_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is None)\n+ ... # dynamic-slice or all-gather are present in the HLO for fft\n+ ... assert(re.search(_PATTERN, pjit_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is not None)\n.. code-block::\n@@ -236,43 +246,10 @@ class custom_partitioning:\n...\n-1.6937828 +0.8402481j 15.999859 -4.0156755j]]\n- If we dump the HLO using ``XLA_FLAGS=\"--xla_dump_to=$(pwd)\"``, we see that ``pjit_fft`` compiles\n- to\n-\n- .. code-block::\n-\n- HloModule pjit_fft, entry_computation_layout={(c64[16384,1024]{1,0})->c64[16384,1024]{1,0}}\n-\n- fused_computation {\n- ...\n- ROOT dynamic-slice.2 = c64[16384,1024]{1,0} dynamic-slice(param_1, multiply.3, constant_7), dynamic_slice_sizes={16384,1024}, metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n- }\n-\n- ENTRY main.8_spmd {\n- param = c64[16384,1024]{1,0} parameter(0), sharding={devices=[2,1]0,1}\n- all-gather = c64[32768,1024]{1,0} all-gather(param), channel_id=1, replica_groups={{0,1}}, dimensions={0}, use_global_device_ids=true, metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n- fft.1 = c64[32768,1024]{1,0} fft(all-gather), fft_type=FFT, fft_length={1024}, metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n- partition-id = u32[] partition-id(), metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n- ROOT fusion = c64[16384,1024]{1,0} fusion(fft.1, partition-id), kind=kLoop, calls=fused_computation, metadata={op_name=\"pjit(fft)/jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=42}\n- }\n-\n- Where the ``all-gather`` before the FFT and the dynamic-slice after are both clearly visible.\n- This means that the input is gathered on all devices prior to the FFT, and sliced after.\n-\n- ``pjit_my_fft``, on the other hand, simply compiles to\n-\n- .. code-block::\n-\n- HloModule pjit__unnamed_wrapped_function_, entry_computation_layout={(c64[16384,1024]{1,0})->c64[16384,1024]{1,0}}\n-\n- ENTRY main.5_spmd {\n- param = c64[16384,1024]{1,0} parameter(0), sharding={devices=[2,1]0,1}\n- ROOT fft.0 = c64[16384,1024]{1,0} fft(param), fft_type=FFT, fft_length={1024}, metadata={op_name=\"jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(1024,)]\" source_file=\"doc.py\" source_line=41}\n- }\n-\n- where no unnecessary sharding is taking place.\n-\nBecause of the logic in ``supported_sharding``, ``my_fft`` also works on 1-dimensional arrays.\n+ However, in this case, the HLO of ``my_fft`` does show a a dynamic-slice, since the last dimension\n+ is the dimension along which FFTs are calculated and needs to be replicated on all devices before\n+ the computation can be done.\n>>> with Mesh(np.array(jax.devices()), ('x',)):\n... x = np.asarray(np.random.randn(32*1024*1024), dtype=np.complex64)\n@@ -281,6 +258,10 @@ class custom_partitioning:\n... pjit_fft = pjit(fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n... print(pjit_my_fft(y))\n... print(pjit_fft(y))\n+ ... # dynamic-slice or all-gather are present in the HLO for my_fft, because x is a 1D array\n+ ... assert(re.search(_PATTERN, pjit_my_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is None)\n+ ... # dynamic-slice or all-gather are present in the HLO for fft\n+ ... assert(re.search(_PATTERN, pjit_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is not None)\n.. code-block::\n@@ -294,26 +275,6 @@ class custom_partitioning:\n... 1422.4502 +7271.4297j -405.84033 -3042.983j\n-3012.4963 -4287.6343j]\n- In this case, the HLO of ``my_fft`` does show an all-gather and dynamic-slice, since the last dimension\n- is the dimension along which FFTs are calculated.\n-\n- .. code-block::\n-\n- HloModule pjit__unnamed_wrapped_function_, entry_computation_layout={(c64[16777216]{0})->c64[16777216]{0}}\n-\n- fused_computation {\n- ...\n- ROOT dynamic-slice.2 = c64[16777216]{0} dynamic-slice(param_1, multiply.3), dynamic_slice_sizes={16777216}, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/custom_partitioning[partition=<function partition at 0x7f73a1fbc820> propagate_user_sharding=<function _default_propagate_user_shardings at 0x7f73a1fbc550> infer_sharding_from_operands=<function infer_sharding_from_operands at 0x7f73a1fbc8b0> in_tree=PyTreeDef((*,)) out_tree=PyTreeDef(*)]\" source_file=\"doc.py\" source_line=51}\n- }\n-\n- ENTRY main.5_spmd {\n- param = c64[16777216]{0} parameter(0), sharding={devices=[2]0,1}\n- all-gather = c64[33554432]{0} all-gather(param), channel_id=1, replica_groups={{0,1}}, dimensions={0}, use_global_device_ids=true, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/custom_partitioning[partition=<function partition at 0x7f73a1fbc820> propagate_user_sharding=<function _default_propagate_user_shardings at 0x7f73a1fbc550> infer_sharding_from_operands=<function infer_sharding_from_operands at 0x7f73a1fbc8b0> in_tree=PyTreeDef((*,)) out_tree=PyTreeDef(*)]\" source_file=\"doc.py\" source_line=51}\n- fft.0 = c64[33554432]{0} fft(all-gather), fft_type=FFT, fft_length={33554432}, metadata={op_name=\"jit(main)/jit(fft)/fft[fft_type=FftType.FFT fft_lengths=(33554432,)]\" source_file=\"doc.py\" source_line=51}\n- partition-id = u32[] partition-id(), metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/custom_partitioning[partition=<function partition at 0x7f73a1fbc820> propagate_user_sharding=<function _default_propagate_user_shardings at 0x7f73a1fbc550> infer_sharding_from_operands=<function infer_sharding_from_operands at 0x7f73a1fbc8b0> in_tree=PyTreeDef((*,)) out_tree=PyTreeDef(*)]\" source_file=\"doc.py\" source_line=51}\n- ROOT fusion = c64[16777216]{0} fusion(fft.0, partition-id), kind=kLoop, calls=fused_computation, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/custom_partitioning[partition=<function partition at 0x7f73a1fbc820> propagate_user_sharding=<function _default_propagate_user_shardings at 0x7f73a1fbc550> infer_sharding_from_operands=<function infer_sharding_from_operands at 0x7f73a1fbc8b0> in_tree=PyTreeDef((*,)) out_tree=PyTreeDef(*)]\" source_file=\"doc.py\" source_line=51}\n- }\n-\n\"\"\"\ndef __init__(self, fun):\n"
}
] | Python | Apache License 2.0 | google/jax | Removing HLO dump from docstring, using assert(re.search(...)) |
260,424 | 24.01.2023 06:44:51 | 28,800 | 7064be1a769a3c3cbcf4ada2504e08796e06ae28 | Skip unneccessary unflattening of avals in pjit lowering path.
The avals get flattened again when calling `from_flat_info` (here:
https://github.com/google/jax/blob/1641c8f1415a837f6f6c2537110f4be698621055/jax/_src/stages.py#L347),
so skip unflattening here. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/pjit.py",
"new_path": "jax/_src/pjit.py",
"diff": "@@ -266,13 +266,12 @@ def post_infer_params(fun, infer_params_fn, static_argnums, static_argnames,\nif kwargs:\nargs_kwargs_in_tree = in_tree\n- local_in_avals = in_tree.unflatten(flat_local_in_avals)\nelse:\nargs_kwargs_in_tree = treedef_tuple([in_tree, tree_flatten({})[1]])\n- local_in_avals = args_kwargs_in_tree.unflatten(flat_local_in_avals)\nreturn stages.Lowered.from_flat_info(\n- lowering, args_kwargs_in_tree, local_in_avals, donate_argnums, out_tree)\n+ lowering, args_kwargs_in_tree, flat_local_in_avals, donate_argnums,\n+ out_tree)\nwrapped.lower = lower\nreturn wrapped\n"
}
] | Python | Apache License 2.0 | google/jax | Skip unneccessary unflattening of avals in pjit lowering path.
The avals get flattened again when calling `from_flat_info` (here:
https://github.com/google/jax/blob/1641c8f1415a837f6f6c2537110f4be698621055/jax/_src/stages.py#L347),
so skip unflattening here.
PiperOrigin-RevId: 504260643 |
260,447 | 24.01.2023 11:46:15 | 28,800 | 5aea7d95e0a23e046c3d90b903d34cf8d034a0d4 | [sparse] Add function that fixes out-of-bound indices. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcoo.py",
"new_path": "jax/experimental/sparse/bcoo.py",
"diff": "@@ -1508,6 +1508,23 @@ def _unique_indices_unbatched(indices, *, shape, return_inverse=False,\nout = (*out[:-1], nse)\nreturn out\n+def _fix_oob_indices_unbatched(data, indices, *, shape):\n+ \"\"\"Set out-of-bound (OOB) indices and the corresponding data to zero.\"\"\"\n+ n_batch, n_sparse, n_dense, _ = _validate_bcoo_indices(indices, shape)\n+ assert n_dense == 0, \"not implemented\"\n+ assert n_batch == 0\n+ mask = indices >= jnp.array(shape[:n_sparse])[None, :]\n+ new_indices = jnp.where(mask, 0, indices)\n+ new_data = jnp.where(mask.any(-1), 0, data)\n+ return new_data, new_indices\n+\n+def _fix_oob_indices(data, indices, *, spinfo):\n+ \"\"\"Set out-of-bound (OOB) indices and the corresponding data to zero.\"\"\"\n+ props = _validate_bcoo_indices(indices, spinfo.shape)\n+ f = partial(_fix_oob_indices_unbatched, shape=spinfo.shape[props.n_batch:])\n+ f = nfold_vmap(f, props.n_batch)\n+ return f(data, indices)\n+\n@bcoo_sum_duplicates_p.def_abstract_eval\ndef _bcoo_sum_duplicates_abstract_eval(data, indices, *, spinfo, nse):\nif nse is None:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -1693,6 +1693,36 @@ class BCOOTest(sptu.SparseTestCase):\nself.assertArraysEqual(x.indices, y.indices)\nself.assertArraysEqual(x.data, y.data)\n+ def test_bcoo_fix_oob_indices(self):\n+ data = jnp.array([1, 2, 3, 4, 0, 0])\n+ indices = jnp.array([1, 3, 0, 2, 2, 4])[:, None]\n+ x1 = sparse.BCOO((data, indices), shape=(2,))\n+ data_unbatched, indices_unbatched = sparse_bcoo._fix_oob_indices(\n+ x1.data, x1.indices, spinfo=x1._info)\n+ expected_data_unbatched = jnp.array([1, 0, 3, 0, 0, 0])\n+ expected_indices_unbatched = jnp.array([[1], [0], [0], [0], [0], [0]])\n+ with self.subTest('unbatched data'):\n+ self.assertArraysEqual(data_unbatched, expected_data_unbatched)\n+ with self.subTest('unbatched indices'):\n+ self.assertArraysEqual(indices_unbatched, expected_indices_unbatched)\n+\n+ data = jnp.array([[0, 1, 2, 3],\n+ [4, 5, 6, 7]])\n+ indices = jnp.array([[[0, 0], [1, 1], [3, 4], [4, 5]],\n+ [[2, 1], [1, 0], [2, 3], [1, 1]]])\n+ x2 = sparse.BCOO((data, indices), shape=(2, 3, 2))\n+ data_batched, indices_batched = sparse_bcoo._fix_oob_indices(\n+ x2.data, x2.indices, spinfo=x2._info)\n+ expected_data_batched = jnp.array([[0, 1, 0, 0],\n+ [4, 5, 0, 7]])\n+ expected_indices_batched = jnp.array(\n+ [[[0, 0], [1, 1], [0, 0], [0, 0]],\n+ [[2, 1], [1, 0], [2, 0], [1, 1]]])\n+ with self.subTest('batched data'):\n+ self.assertArraysEqual(data_batched, expected_data_batched)\n+ with self.subTest('batched indices'):\n+ self.assertArraysEqual(indices_batched, expected_indices_batched)\n+\n@jtu.sample_product(\n[dict(shape=shape, n_batch=layout.n_batch, n_dense=layout.n_dense, axes=axes)\nfor shape in [(5,), (5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Add function that fixes out-of-bound indices.
PiperOrigin-RevId: 504335149 |
260,539 | 24.01.2023 15:55:17 | 28,800 | df89c77b0620312040bb41692b29e8bbe7880671 | Fix trailing whiteshape + failing doc test + removing first section title | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/custom_partitioning.py",
"new_path": "jax/experimental/custom_partitioning.py",
"diff": "@@ -130,9 +130,6 @@ def _default_propagate_user_shardings(sharding, shape):\nclass custom_partitioning:\n\"\"\"Inserts a CustomCallOp into the XLA graph with custom SPMD lowering rules.\n- Usage\n- -----\n-\n.. code-block:: python\n@custom_partitioning\n@@ -166,11 +163,10 @@ class custom_partitioning:\n* ``infer_sharding_from_operands``: Callable which computes an output ``NamedSharding``\nfrom the ``NamedSharding`` chosen for each argument.\n- Example\n- -------\n+ Example:\n- Assume we want to enhance the existing ``jax.numpy.fft.fft``. This function computes the\n- discrete Fourier transform of an N-dimensional input along the last dimension, and is batched\n+ As an example, assume we want to enhance the existing ``jax.numpy.fft.fft``. This function computes\n+ the discrete Fourier transform of an N-dimensional input along the last dimension, and is batched\nalong the first N-1 dimensions.\nBy default, however, it will ignore the sharding of the input and gather the input on all devices.\nHowever, since ``jax.numpy.fft.fft`` is batched along the first N-1 dimensions,\n@@ -222,17 +218,19 @@ class custom_partitioning:\n(using ``lower(x).compile().runtime_executable().hlo_modules()``) reveals that\n``my_fft`` does not create any all-gather or dynamic-slice, while ``fft`` does.\n- >>> with Mesh(np.array(jax.devices()), ('x',)):\n- ... x = np.asarray(np.random.randn(32*1024, 1024), dtype=np.complex64)\n- ... y = pjit(lambda x: x, in_axis_resources=None, out_axis_resources=P('x'))(x)\n- ... pjit_my_fft = pjit(my_fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n- ... pjit_fft = pjit(fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n- ... print(pjit_my_fft(y))\n- ... print(pjit_fft(y))\n- ... # dynamic-slice or all-gather are not present in the HLO for my_fft, because x is a 2D array\n- ... assert(re.search(_PATTERN, pjit_my_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is None)\n- ... # dynamic-slice or all-gather are present in the HLO for fft\n- ... assert(re.search(_PATTERN, pjit_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is not None)\n+ .. code-block::\n+\n+ with Mesh(np.array(jax.devices()), ('x',)):\n+ x = np.asarray(np.random.randn(32*1024, 1024), dtype=np.complex64)\n+ y = pjit(lambda x: x, in_axis_resources=None, out_axis_resources=P('x'))(x)\n+ pjit_my_fft = pjit(my_fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n+ pjit_fft = pjit(fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n+ print(pjit_my_fft(y))\n+ print(pjit_fft(y))\n+ # dynamic-slice or all-gather are not present in the HLO for my_fft, because x is a 2D array\n+ assert(re.search(_PATTERN, pjit_my_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is None)\n+ # dynamic-slice or all-gather are present in the HLO for fft\n+ assert(re.search(_PATTERN, pjit_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is not None)\n.. code-block::\n@@ -251,17 +249,19 @@ class custom_partitioning:\nis the dimension along which FFTs are calculated and needs to be replicated on all devices before\nthe computation can be done.\n- >>> with Mesh(np.array(jax.devices()), ('x',)):\n- ... x = np.asarray(np.random.randn(32*1024*1024), dtype=np.complex64)\n- ... y = pjit(lambda x: x, in_axis_resources=None, out_axis_resources=P('x'))(x)\n- ... pjit_my_fft = pjit(my_fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n- ... pjit_fft = pjit(fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n- ... print(pjit_my_fft(y))\n- ... print(pjit_fft(y))\n- ... # dynamic-slice or all-gather are present in the HLO for my_fft, because x is a 1D array\n- ... assert(re.search(_PATTERN, pjit_my_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is None)\n- ... # dynamic-slice or all-gather are present in the HLO for fft\n- ... assert(re.search(_PATTERN, pjit_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is not None)\n+ .. code-block::\n+\n+ with Mesh(np.array(jax.devices()), ('x',)):\n+ x = np.asarray(np.random.randn(32*1024*1024), dtype=np.complex64)\n+ y = pjit(lambda x: x, in_axis_resources=None, out_axis_resources=P('x'))(x)\n+ pjit_my_fft = pjit(my_fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n+ pjit_fft = pjit(fft, in_axis_resources=P('x'), out_axis_resources=P('x'))\n+ print(pjit_my_fft(y))\n+ print(pjit_fft(y))\n+ # dynamic-slice or all-gather are present in the HLO for my_fft, because x is a 1D array\n+ assert(re.search(_PATTERN, pjit_my_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is None)\n+ # dynamic-slice or all-gather are present in the HLO for fft\n+ assert(re.search(_PATTERN, pjit_fft.lower(x).compile().runtime_executable().hlo_modules()[0].to_string()) is not None)\n.. code-block::\n"
}
] | Python | Apache License 2.0 | google/jax | Fix trailing whiteshape + failing doc test + removing first section title |
260,424 | 24.01.2023 19:35:14 | 0 | 641b61b164d4bc44b73009240ab3c868905b28f4 | Checkify: Validate format arguments to make sure they're arrays | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -1117,6 +1117,11 @@ def _check(pred, msg, debug, *fmt_args, **fmt_kwargs):\nif not is_scalar_pred(pred):\nprim_name = 'debug_check' if debug else 'check'\nraise TypeError(f'{prim_name} takes a scalar pred as argument, got {pred}')\n+ for arg in jtu.tree_leaves((fmt_args, fmt_kwargs)):\n+ if not isinstance(arg, (jax.Array, np.ndarray)):\n+ raise TypeError('Formatting arguments to checkify.check need to be '\n+ 'PyTrees of arrays, but got '\n+ f'{repr(arg)} of type {type(arg)}.')\nnew_error = FailedCheckError(summary(), msg, *fmt_args, **fmt_kwargs)\nerror = assert_func(init_error, jnp.logical_not(pred), new_error)\n_check_error(error, debug=debug)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -1173,6 +1173,20 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"1.0 cannot be 1.0\")\n+ def test_fmt_args_array_type_error(self):\n+ args_error = lambda: checkify.check(False, \"{} world\", \"hello\")\n+ with self.assertRaisesRegex(TypeError, \"Formatting arguments\"):\n+ checkify.checkify(args_error)()\n+\n+ kwargs_error = lambda: checkify.check(False, \"{hello} world\", hello=\"hello\")\n+ with self.assertRaisesRegex(TypeError, \"Formatting arguments\"):\n+ checkify.checkify(kwargs_error)()\n+\n+ np_arrays_ok = lambda: checkify.check(False, \"{} world\", np.array(1.))\n+ checkify.checkify(np_arrays_ok)()\n+\n+ trees_ok = lambda: checkify.check(False, \"{}\", {\"hello\": jnp.array(1.)})\n+ checkify.checkify(trees_ok)()\nclass LowerableChecksTest(jtu.JaxTestCase):\ndef setUp(self):\n"
}
] | Python | Apache License 2.0 | google/jax | Checkify: Validate format arguments to make sure they're arrays |
260,631 | 25.01.2023 09:12:17 | 28,800 | d14e144651fff7cd0e736949ddb461f71cfa0785 | Use pareto optimal step size for computing numerical Jacobians in JAX. This allows us to tighten the tolerances in gradient unit testing significantly, especially for float64 and complex128. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/public_test_util.py",
"new_path": "jax/_src/public_test_util.py",
"diff": "@@ -16,7 +16,7 @@ from functools import partial\nimport operator\nfrom jax import config\n-from jax.tree_util import tree_map, tree_reduce\n+from jax.tree_util import tree_map, tree_reduce, tree_leaves\nfrom jax._src import api\nfrom jax._src import dtypes as _dtypes\nfrom jax._src.config import flags\n@@ -33,10 +33,9 @@ __all__ = ['check_grads', 'check_jvp', 'check_vjp']\nFLAGS = flags.FLAGS\n-EPS = 1e-4\n+EPS = 1.0 / 2048\n_fp8_enabled = xla_client._version >= 117\n-\ndef _dtype(x):\nif hasattr(x, 'dtype'):\nreturn x.dtype\n@@ -197,7 +196,20 @@ def rand_like(rng, x):\nreturn result.item() if is_python_scalar(x) else result\n-def numerical_jvp(f, primals, tangents, eps=EPS):\n+def numerical_jvp(f, primals, tangents, eps=None):\n+ if eps is None:\n+ t = _dtypes.result_type(*tree_leaves(primals))\n+ # Assuming the roundoff error in the evaluation of the finite difference\n+ # below is a few times eps_m*(|f_pos| + |f_neg|), where\n+ # eps_m = np.finfo(t).eps, then the pareto optimal step size that roughly\n+ # balances roundof error and truncation error is O(eps_m^1/3).\n+ # The constant was determined heuristically to minimize the error\n+ # tolerances in the testOpGrad unit test.\n+ eps = (np.finfo(t).eps ** (1.0 / 3.0)) / 8\n+ # Find the nearest power of 2 for eps. This makes the multiplications\n+ # and divisions by eps below lossless in floating point, and improves\n+ # the accuracy of the finite difference approximation in some cases.\n+ eps = 2.0 ** np.floor(np.log2(eps))\ndelta = scalar_mul(tangents, eps)\nf_pos = f(*add(primals, delta))\nf_neg = f(*sub(primals, delta))\n@@ -215,7 +227,7 @@ def _merge_tolerance(tol, default):\nreturn out\n-def check_jvp(f, f_jvp, args, atol=None, rtol=None, eps=EPS, err_msg=''):\n+def check_jvp(f, f_jvp, args, atol=None, rtol=None, eps=None, err_msg=''):\natol = _merge_tolerance(atol, default_gradient_tolerance)\nrtol = _merge_tolerance(rtol, default_gradient_tolerance)\nrng = np.random.RandomState(0)\n@@ -234,7 +246,7 @@ def check_jvp(f, f_jvp, args, atol=None, rtol=None, eps=EPS, err_msg=''):\nerr_msg=f'{err_msg} tangent' if err_msg else 'tangent')\n-def check_vjp(f, f_vjp, args, atol=None, rtol=None, eps=EPS, err_msg=''):\n+def check_vjp(f, f_vjp, args, atol=None, rtol=None, eps=None, err_msg=''):\natol = _merge_tolerance(atol, default_gradient_tolerance)\nrtol = _merge_tolerance(rtol, default_gradient_tolerance)\n_rand_like = partial(rand_like, np.random.RandomState(0))\n@@ -274,7 +286,6 @@ def check_grads(f, args, order,\nAssertionError: if gradients do not match.\n\"\"\"\nargs = tuple(args)\n- eps = eps or EPS\n_check_jvp = partial(check_jvp, atol=atol, rtol=rtol, eps=eps)\n_check_vjp = partial(check_vjp, atol=atol, rtol=rtol, eps=eps)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -1645,7 +1645,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\natol = 1e-5\nself.assertAllClose(ans, expected, check_dtypes=False, rtol=rtol, atol=atol)\n- rtol = 5e-3 if scan is not scan_with_new_checkpoint2 else 5e-2\n+ rtol = 6e-3 if scan is not scan_with_new_checkpoint2 else 5e-2\natol = 5e-2 if \"tpu\" in jtu.device_under_test() else 1e-3\njtu.check_grads(partial(scan, f), (c, as_), order=2, modes=[\"rev\"],\natol=atol, rtol=rtol)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_indexing_test.py",
"new_path": "tests/lax_numpy_indexing_test.py",
"diff": "@@ -62,7 +62,6 @@ def check_grads(f, args, order, atol=None, rtol=None, eps=None):\ndefault_tol = 1e-6 if config.x64_enabled else 1e-2\natol = atol or default_tol\nrtol = rtol or default_tol\n- eps = eps or default_tol\njtu.check_jvp(f, partial(jax.jvp, f), args, atol, rtol, eps)\njtu.check_vjp(f, partial(jax.vjp, f), args, atol, rtol, eps)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -5075,13 +5075,16 @@ class NumpyGradTests(jtu.JaxTestCase):\n@jax.numpy_dtype_promotion('standard') # This test explicitly exercises mixed type promotion\ndef testOpGrad(self, op, rng_factory, shapes, dtype, order, tol):\nrng = rng_factory(self.rng())\n- tol = jtu.join_tolerance(tol, {np.float32: 1e-1, np.float64: 1e-3,\n- np.complex64: 1e-1, np.complex128: 1e-3})\n- if jtu.device_under_test() == 'tpu' and op == jnp.arctanh:\n- tol = jtu.join_tolerance(tol, {np.float32: 2e-1})\n-\n+ if jtu.device_under_test() == 'tpu':\n+ # TODO(rmlarsen): These tolerances are dominated by the inaccurate\n+ # implementation of float32 logarithms on TPUs. Remove this exception\n+ # when TPU logarithms are improved.\n+ tol = jtu.join_tolerance(tol, {np.float32: 5e-2, np.complex64: 5e-2})\n+ else:\n+ tol = jtu.join_tolerance(tol, {np.float32: 2e-3,np.float64: 1e-8,\n+ np.complex64: 2e-3, np.complex128: 1e-8})\nargs = tuple(rng(shape, dtype) for shape in shapes)\n- check_grads(op, args, order, [\"fwd\", \"rev\"], tol, tol)\n+ check_grads(op, args, order, ['fwd', 'rev'], tol, tol)\n@parameterized.parameters(itertools.chain.from_iterable(\njtu.sample_product_testcases(\n@@ -5090,8 +5093,10 @@ class NumpyGradTests(jtu.JaxTestCase):\n)\nfor rec in GRAD_SPECIAL_VALUE_TEST_RECORDS))\ndef testOpGradSpecialValue(self, op, special_value, order):\n- check_grads(op, (special_value,), order, [\"fwd\", \"rev\"],\n- atol={np.float32: 3e-3})\n+ tol = None\n+ if jtu.device_under_test() == 'tpu' and op == jnp.arccosh:\n+ tol = 4e-3\n+ check_grads(op, (special_value,), order, ['fwd', 'rev'], tol, tol)\ndef testSincAtZero(self):\n# Some manual tests for sinc at zero, since it doesn't have well-behaved\n@@ -5143,11 +5148,11 @@ class NumpyGradTests(jtu.JaxTestCase):\ndef testGradLogaddexpComplex(self, shapes, dtype):\nrng = jtu.rand_default(self.rng())\nargs = tuple(jnp.array(rng(shape, dtype)) for shape in shapes)\n- if jtu.device_under_test() == \"tpu\":\n- tol = 5e-2\n+ if jtu.device_under_test() != 'tpu' and config.jax_enable_x64:\n+ tol = 1e-5\nelse:\n- tol = 3e-2\n- check_grads(jnp.logaddexp, args, 1, [\"fwd\", \"rev\"], tol, tol)\n+ tol = 2e-2\n+ check_grads(jnp.logaddexp, args, 1, ['fwd', 'rev'], tol, tol)\n@jtu.sample_product(\nshapes=filter(_shapes_are_broadcast_compatible,\n@@ -5158,11 +5163,11 @@ class NumpyGradTests(jtu.JaxTestCase):\ndef testGradLogaddexp2Complex(self, shapes, dtype):\nrng = jtu.rand_default(self.rng())\nargs = tuple(jnp.array(rng(shape, dtype)) for shape in shapes)\n- if jtu.device_under_test() == \"tpu\":\n- tol = 5e-2\n+ if jtu.device_under_test() != 'tpu' and config.jax_enable_x64:\n+ tol = 1e-5\nelse:\n- tol = 3e-2\n- check_grads(jnp.logaddexp2, args, 1, [\"fwd\", \"rev\"], tol, tol)\n+ tol = 2e-2\n+ check_grads(jnp.logaddexp2, args, 1, ['fwd', 'rev'], tol, tol)\nclass NumpySignaturesTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Use pareto optimal step size for computing numerical Jacobians in JAX. This allows us to tighten the tolerances in gradient unit testing significantly, especially for float64 and complex128.
PiperOrigin-RevId: 504579516 |
260,631 | 25.01.2023 09:50:56 | 28,800 | e6e513a6e961449d7ebe01242fa28cfc8477c62e | Add environment variable check in additional to libtpu check for cloud tpu vm | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/cloud_tpu_init.py",
"new_path": "jax/_src/cloud_tpu_init.py",
"diff": "@@ -16,6 +16,25 @@ import os\nrunning_in_cloud_tpu_vm = False\n+\n+def maybe_import_libtpu():\n+ try:\n+ # pylint: disable=import-outside-toplevel\n+ # pytype: disable=import-error\n+ import libtpu\n+\n+ # pytype: enable=import-error\n+ # pylint: enable=import-outside-toplevel\n+ except ImportError:\n+ return None\n+ else:\n+ return libtpu\n+\n+\n+def jax_force_tpu_init() -> bool:\n+ return 'JAX_FORCE_TPU_INIT' in os.environ\n+\n+\ndef cloud_tpu_init():\n\"\"\"Automatically sets Cloud TPU topology and other env vars.\n@@ -33,20 +52,18 @@ def cloud_tpu_init():\nset.\n\"\"\"\nglobal running_in_cloud_tpu_vm\n- try:\n- # pylint: disable=import-outside-toplevel\n- # pytype: disable=import-error\n- import libtpu\n- # pytype: enable=import-error\n- # pylint: enable=import-outside-toplevel\n- except ImportError:\n- # We assume libtpu is installed iff we're in a correctly-configured Cloud\n- # TPU environment. Exit early if we're not running on Cloud TPU.\n+\n+ # We assume we are in a correctly-configured Cloud TPU environment\n+ # if the following hold: a) libtpu is installed b) JAX_FORCE_TPU_INIT is set\n+ # Exit early if we're not running on Cloud TPU.\n+ libtpu_module = maybe_import_libtpu()\n+ if libtpu_module is not None:\n+ libtpu_module.configure_library_path()\n+ elif not jax_force_tpu_init():\nreturn\nrunning_in_cloud_tpu_vm = True\n- libtpu.configure_library_path()\nos.environ.setdefault('GRPC_VERBOSITY', 'ERROR')\nos.environ.setdefault('JAX_PLATFORMS', 'tpu,cpu')\nos.environ['TPU_ML_PLATFORM'] = 'JAX'\n"
}
] | Python | Apache License 2.0 | google/jax | Add environment variable check in additional to libtpu check for cloud tpu vm
PiperOrigin-RevId: 504588621 |
260,631 | 25.01.2023 12:15:00 | 28,800 | 78599e65d11a418bd81c7763a3d4fdab960c7bc0 | Roll-back due to downstream test failures | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/public_test_util.py",
"new_path": "jax/_src/public_test_util.py",
"diff": "@@ -16,7 +16,7 @@ from functools import partial\nimport operator\nfrom jax import config\n-from jax.tree_util import tree_map, tree_reduce, tree_leaves\n+from jax.tree_util import tree_map, tree_reduce\nfrom jax._src import api\nfrom jax._src import dtypes as _dtypes\nfrom jax._src.config import flags\n@@ -33,9 +33,10 @@ __all__ = ['check_grads', 'check_jvp', 'check_vjp']\nFLAGS = flags.FLAGS\n-EPS = 1.0 / 2048\n+EPS = 1e-4\n_fp8_enabled = xla_client._version >= 117\n+\ndef _dtype(x):\nif hasattr(x, 'dtype'):\nreturn x.dtype\n@@ -196,20 +197,7 @@ def rand_like(rng, x):\nreturn result.item() if is_python_scalar(x) else result\n-def numerical_jvp(f, primals, tangents, eps=None):\n- if eps is None:\n- t = _dtypes.result_type(*tree_leaves(primals))\n- # Assuming the roundoff error in the evaluation of the finite difference\n- # below is a few times eps_m*(|f_pos| + |f_neg|), where\n- # eps_m = np.finfo(t).eps, then the pareto optimal step size that roughly\n- # balances roundof error and truncation error is O(eps_m^1/3).\n- # The constant was determined heuristically to minimize the error\n- # tolerances in the testOpGrad unit test.\n- eps = (np.finfo(t).eps ** (1.0 / 3.0)) / 8\n- # Find the nearest power of 2 for eps. This makes the multiplications\n- # and divisions by eps below lossless in floating point, and improves\n- # the accuracy of the finite difference approximation in some cases.\n- eps = 2.0 ** np.floor(np.log2(eps))\n+def numerical_jvp(f, primals, tangents, eps=EPS):\ndelta = scalar_mul(tangents, eps)\nf_pos = f(*add(primals, delta))\nf_neg = f(*sub(primals, delta))\n@@ -227,7 +215,7 @@ def _merge_tolerance(tol, default):\nreturn out\n-def check_jvp(f, f_jvp, args, atol=None, rtol=None, eps=None, err_msg=''):\n+def check_jvp(f, f_jvp, args, atol=None, rtol=None, eps=EPS, err_msg=''):\natol = _merge_tolerance(atol, default_gradient_tolerance)\nrtol = _merge_tolerance(rtol, default_gradient_tolerance)\nrng = np.random.RandomState(0)\n@@ -246,7 +234,7 @@ def check_jvp(f, f_jvp, args, atol=None, rtol=None, eps=None, err_msg=''):\nerr_msg=f'{err_msg} tangent' if err_msg else 'tangent')\n-def check_vjp(f, f_vjp, args, atol=None, rtol=None, eps=None, err_msg=''):\n+def check_vjp(f, f_vjp, args, atol=None, rtol=None, eps=EPS, err_msg=''):\natol = _merge_tolerance(atol, default_gradient_tolerance)\nrtol = _merge_tolerance(rtol, default_gradient_tolerance)\n_rand_like = partial(rand_like, np.random.RandomState(0))\n@@ -286,6 +274,7 @@ def check_grads(f, args, order,\nAssertionError: if gradients do not match.\n\"\"\"\nargs = tuple(args)\n+ eps = eps or EPS\n_check_jvp = partial(check_jvp, atol=atol, rtol=rtol, eps=eps)\n_check_vjp = partial(check_vjp, atol=atol, rtol=rtol, eps=eps)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -1645,7 +1645,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\natol = 1e-5\nself.assertAllClose(ans, expected, check_dtypes=False, rtol=rtol, atol=atol)\n- rtol = 6e-3 if scan is not scan_with_new_checkpoint2 else 5e-2\n+ rtol = 5e-3 if scan is not scan_with_new_checkpoint2 else 5e-2\natol = 5e-2 if \"tpu\" in jtu.device_under_test() else 1e-3\njtu.check_grads(partial(scan, f), (c, as_), order=2, modes=[\"rev\"],\natol=atol, rtol=rtol)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_indexing_test.py",
"new_path": "tests/lax_numpy_indexing_test.py",
"diff": "@@ -62,6 +62,7 @@ def check_grads(f, args, order, atol=None, rtol=None, eps=None):\ndefault_tol = 1e-6 if config.x64_enabled else 1e-2\natol = atol or default_tol\nrtol = rtol or default_tol\n+ eps = eps or default_tol\njtu.check_jvp(f, partial(jax.jvp, f), args, atol, rtol, eps)\njtu.check_vjp(f, partial(jax.vjp, f), args, atol, rtol, eps)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -5075,16 +5075,13 @@ class NumpyGradTests(jtu.JaxTestCase):\n@jax.numpy_dtype_promotion('standard') # This test explicitly exercises mixed type promotion\ndef testOpGrad(self, op, rng_factory, shapes, dtype, order, tol):\nrng = rng_factory(self.rng())\n- if jtu.device_under_test() == 'tpu':\n- # TODO(rmlarsen): These tolerances are dominated by the inaccurate\n- # implementation of float32 logarithms on TPUs. Remove this exception\n- # when TPU logarithms are improved.\n- tol = jtu.join_tolerance(tol, {np.float32: 5e-2, np.complex64: 5e-2})\n- else:\n- tol = jtu.join_tolerance(tol, {np.float32: 2e-3,np.float64: 1e-8,\n- np.complex64: 2e-3, np.complex128: 1e-8})\n+ tol = jtu.join_tolerance(tol, {np.float32: 1e-1, np.float64: 1e-3,\n+ np.complex64: 1e-1, np.complex128: 1e-3})\n+ if jtu.device_under_test() == 'tpu' and op == jnp.arctanh:\n+ tol = jtu.join_tolerance(tol, {np.float32: 2e-1})\n+\nargs = tuple(rng(shape, dtype) for shape in shapes)\n- check_grads(op, args, order, ['fwd', 'rev'], tol, tol)\n+ check_grads(op, args, order, [\"fwd\", \"rev\"], tol, tol)\n@parameterized.parameters(itertools.chain.from_iterable(\njtu.sample_product_testcases(\n@@ -5093,10 +5090,8 @@ class NumpyGradTests(jtu.JaxTestCase):\n)\nfor rec in GRAD_SPECIAL_VALUE_TEST_RECORDS))\ndef testOpGradSpecialValue(self, op, special_value, order):\n- tol = None\n- if jtu.device_under_test() == 'tpu' and op == jnp.arccosh:\n- tol = 4e-3\n- check_grads(op, (special_value,), order, ['fwd', 'rev'], tol, tol)\n+ check_grads(op, (special_value,), order, [\"fwd\", \"rev\"],\n+ atol={np.float32: 3e-3})\ndef testSincAtZero(self):\n# Some manual tests for sinc at zero, since it doesn't have well-behaved\n@@ -5148,11 +5143,11 @@ class NumpyGradTests(jtu.JaxTestCase):\ndef testGradLogaddexpComplex(self, shapes, dtype):\nrng = jtu.rand_default(self.rng())\nargs = tuple(jnp.array(rng(shape, dtype)) for shape in shapes)\n- if jtu.device_under_test() != 'tpu' and config.jax_enable_x64:\n- tol = 1e-5\n+ if jtu.device_under_test() == \"tpu\":\n+ tol = 5e-2\nelse:\n- tol = 2e-2\n- check_grads(jnp.logaddexp, args, 1, ['fwd', 'rev'], tol, tol)\n+ tol = 3e-2\n+ check_grads(jnp.logaddexp, args, 1, [\"fwd\", \"rev\"], tol, tol)\n@jtu.sample_product(\nshapes=filter(_shapes_are_broadcast_compatible,\n@@ -5163,11 +5158,11 @@ class NumpyGradTests(jtu.JaxTestCase):\ndef testGradLogaddexp2Complex(self, shapes, dtype):\nrng = jtu.rand_default(self.rng())\nargs = tuple(jnp.array(rng(shape, dtype)) for shape in shapes)\n- if jtu.device_under_test() != 'tpu' and config.jax_enable_x64:\n- tol = 1e-5\n+ if jtu.device_under_test() == \"tpu\":\n+ tol = 5e-2\nelse:\n- tol = 2e-2\n- check_grads(jnp.logaddexp2, args, 1, ['fwd', 'rev'], tol, tol)\n+ tol = 3e-2\n+ check_grads(jnp.logaddexp2, args, 1, [\"fwd\", \"rev\"], tol, tol)\nclass NumpySignaturesTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Roll-back https://github.com/google/jax/pull/14144 due to downstream test failures
PiperOrigin-RevId: 504628432 |
260,276 | 26.01.2023 23:01:06 | 0 | 96707f09b1304e909a4031cb841e4a66b967bd8f | Removed deprecated polar_unitary as per comment. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -7,6 +7,9 @@ Remember to align the itemized text with the first line of an item within a list\n-->\n## jax 0.4.3\n+ * Breaking changes\n+ * Deleted {func}`jax.scipy.linalg.polar_unitary`, which was a deprecated JAX\n+ extension to the scipy API. Use {func}`jax.scipy.linalg.polar` instead.\n## jaxlib 0.4.3\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax.scipy.rst",
"new_path": "docs/jax.scipy.rst",
"diff": "@@ -36,7 +36,6 @@ jax.scipy.linalg\nlu_factor\nlu_solve\npolar\n- polar_unitary\nqr\nrsf2csf\nschur\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/scipy/linalg.py",
"new_path": "jax/_src/scipy/linalg.py",
"diff": "@@ -875,22 +875,6 @@ def polar(a: ArrayLike, side: str = 'right', *, method: str = 'qdwh', eps: Optio\nreturn unitary, posdef\n-def polar_unitary(a: ArrayLike, *, method: str = \"qdwh\", eps: Optional[float] = None,\n- max_iterations: Optional[int] = None) -> Tuple[Array, Array]:\n- \"\"\" Computes the unitary factor u in the polar decomposition ``a = u p``\n- (or ``a = p u``).\n-\n- .. warning::\n- This function is deprecated. Use :func:`jax.scipy.linalg.polar` instead.\n- \"\"\"\n- # TODO(phawkins): delete this function after 2022/8/11.\n- warnings.warn(\"jax.scipy.linalg.polar_unitary is deprecated. Call \"\n- \"jax.scipy.linalg.polar instead.\",\n- DeprecationWarning)\n- unitary, _ = polar(a, method, eps, max_iterations)\n- return unitary\n-\n-\n@jit\ndef _sqrtm_triu(T: Array) -> Array:\n\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/linalg.py",
"new_path": "jax/scipy/linalg.py",
"diff": "@@ -31,7 +31,6 @@ from jax._src.scipy.linalg import (\nlu_factor as lu_factor,\nlu_solve as lu_solve,\npolar as polar,\n- polar_unitary as polar_unitary,\nqr as qr,\nrsf2csf as rsf2csf,\nschur as schur,\n"
}
] | Python | Apache License 2.0 | google/jax | Removed deprecated polar_unitary as per comment. |
260,473 | 01.02.2023 00:06:48 | 0 | 278ff25ae1d9e1397547170081f490a88b6ff77c | Update docs that jax.debug is unsupported on Cloud TPUs | [
{
"change_type": "MODIFY",
"old_path": "docs/debugging/print_breakpoint.md",
"new_path": "docs/debugging/print_breakpoint.md",
"diff": "@@ -223,6 +223,7 @@ Furthermore, when using `jax.debug.print` with `jax.pjit`, a global synchronizat\n#### Limitations\n* Adding print statements is a manual process\n* Can have performance impacts\n+* Unsupported on Cloud TPUs\n## Interactive inspection with `jax.debug.breakpoint()`\n@@ -293,3 +294,4 @@ Because `jax.debug.breakpoint` is a just an application of `jax.debug.callback`,\n#### Limitations\n* Need to potentially use many breakpoints to pinpoint the source of an error\n* Materializes many intermediates\n+* Unsupported on Cloud TPUs\n"
}
] | Python | Apache License 2.0 | google/jax | Update docs that jax.debug is unsupported on Cloud TPUs |
260,335 | 01.02.2023 10:19:47 | 28,800 | 684846bd0fb01af64a168d0209a110ebca941a67 | checkify: cache jaxpr formation so we don't always retrace | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -31,7 +31,7 @@ from jax._src.lax import control_flow as cf\nfrom jax._src.sharding import OpShardingSharding\nfrom jax._src.typing import Array\nfrom jax._src.util import (as_hashable_function, split_list, safe_map, safe_zip,\n- unzip3)\n+ unzip3, weakref_lru_cache)\nfrom jax.api_util import flatten_fun\nfrom jax.experimental import maps\nfrom jax.experimental import pjit\n@@ -383,6 +383,20 @@ def default_checkify_rule(primitive: core.Primitive, error: Error,\ndef get_shaped_aval(val):\nreturn core.raise_to_shaped(core.get_aval(val))\n+def initial_style_jaxpr(\n+ fun: Callable, in_tree: PyTreeDef, in_avals: Sequence[core.AbstractValue]\n+ ) -> Tuple[core.Jaxpr, List[Any], PyTreeDef]:\n+ return _initial_style_jaxpr(fun, in_tree, tuple(in_avals))\n+\n+@weakref_lru_cache\n+def _initial_style_jaxpr(fun, in_tree, in_avals):\n+ # like control_flow._initial_style_jaxpr, but use flatten_fun not _nokwargs\n+ fun_, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n+ debug = pe.debug_info(fun_, in_tree, False, 'checkify')\n+ jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(fun_, in_avals, debug)\n+ return jaxpr, consts, out_tree()\n+\n+\ndef checkify_jaxpr(jaxpr: core.ClosedJaxpr, enabled_errors,\nerror: Error, *args) -> Tuple[Error, List[core.Value]]:\nerr_vals, err_tree = jtu.tree_flatten(error)\n@@ -1065,16 +1079,14 @@ def checkify(f: Callable[..., Out],\n@traceback_util.api_boundary\ndef checked_fun(*args, **kwargs):\n# stage:\n- fun = lu.wrap_init(f)\n- flat_args, in_tree = jtu.tree_flatten((args, kwargs))\n- flat_fun, out_tree = flatten_fun(fun, in_tree)\n- flat_avals = map(get_shaped_aval, flat_args)\n- jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(flat_fun, flat_avals)\n- out_tree = out_tree()\n+ flat_args, in_tree = tree_flatten((args, kwargs))\n+ in_avals = map(get_shaped_aval, flat_args)\n+ jaxpr_, consts, out_tree = initial_style_jaxpr(f, in_tree, in_avals)\n+ jaxpr = pe.close_jaxpr(pe.convert_constvars_jaxpr(jaxpr_))\n# checkify:\nflat_args = jtu.tree_leaves((args, kwargs))\n- error, out_flat = checkify_jaxpr(core.ClosedJaxpr(jaxpr, consts), errors,\n- init_error, *flat_args)\n+ error, out_flat = checkify_jaxpr(jaxpr, errors, init_error,\n+ *consts, *flat_args)\nreturn error, jtu.tree_unflatten(out_tree, out_flat)\nreturn checked_fun\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -773,6 +773,13 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, _ = checked_f(jnp.ones((2, 4)))\nself.assertIsNone(err.get())\n+ def test_retracing(self):\n+ f = checkify.checkify(jax.jit(lambda x: jnp.sin(x) ** 2))\n+ _ = f(3.)\n+ with jtu.count_primitive_compiles() as count:\n+ _ = f(3.)\n+ self.assertEqual(count[0], 0)\n+\n@jtu.with_config(jax_check_tracer_leaks=True)\nclass AssertPrimitiveTests(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | checkify: cache jaxpr formation so we don't always retrace |
260,310 | 01.02.2023 14:30:35 | 28,800 | 0cd3dee349473a9d167cf1a816fb00ed933f47f0 | Consolidate the experimental_get_compiler_ir eager and tf function path in jax2tf.call_tf. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -352,24 +352,13 @@ def _code_generator_and_avals(\nelse:\ncaptured_inputs.append(inp)\n- # TODO(b/265073174): Currently TensorSpec get_compiler_ir does not support\n- # tf.function captured variables. We can elminate this after it is fixed.\n- if tf.executing_eagerly():\n- args_tf_flat = [\n- tf.constant(\n- (0 if a.dtype != tf.bool else False), shape=a.shape, dtype=a.dtype\n- )\n- for a in args_flat_sig_tf\n- ]\n- else:\n-\n- def maybe_convert_to_spec(x):\n+ def convert_to_spec(x):\nif isinstance(x, tf.TensorSpec):\nreturn x\nelse:\nreturn tf.TensorSpec.from_tensor(x)\n- args_tf_flat = [maybe_convert_to_spec(a) for a in args_flat_sig_tf]\n+ args_tf_flat = [convert_to_spec(a) for a in args_flat_sig_tf]\nwith jax2tf_internal.inside_call_tf():\n# When the TF computation uses variables on a particular device, we must\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -528,8 +528,9 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(x[0:x[1]], res1)\n# Now under jit, should fail because the function is not compileable\n- with self.assertRaisesRegex(ValueError,\n- \"Compiled TensorFlow function has unexpected parameter types\"):\n+ with self.assertRaisesRegex(\n+ ValueError, \"Compiled TensorFlow function has dynamic output shape\"\n+ ):\nfun_jax = jax.jit(jax2tf.call_tf(fun_tf))\nfun_jax(x)\n@@ -583,7 +584,6 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\n# Call get_compiler_ir in a function context\nx = np.array([2., 3., 4.], dtype=np.float32)\n-\ndef fun_tf_outer(x):\nx_const = tf.constant(0, shape=x.shape, dtype=x.dtype)\n_ = tf.function(tf.math.sin, jit_compile=True, autograph=False).experimental_get_compiler_ir(x_const)()\n"
}
] | Python | Apache License 2.0 | google/jax | Consolidate the experimental_get_compiler_ir eager and tf function path in jax2tf.call_tf.
PiperOrigin-RevId: 506424270 |
260,335 | 01.02.2023 20:17:28 | 28,800 | cd615b6be8c0c80fcbfff3d8503fc0ce17f78c93 | skip custom_jvp/vjp tests which dont work with initial-style staging
These tests, involving nondiff_argnums and/or closing over tracers, happen to
work with final-style JIT but not our initial-style primitives. We shouldn't
support this behavior anyway; there are good alternatives. | [
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -6511,6 +6511,16 @@ class CustomJVPTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef test_nondiff_arg_jit_tracer(self):\n+ # This test would pass with \"final-style\" JIT tracing, but that was\n+ # misleading: it doesn't work with \"initial-style\" staging, i.e. control\n+ # flow primitives like jax.lax.scan or even pjit. The behavior isn't very\n+ # useful either: instead of using nondiff_argnums here, a user can just pass\n+ # such inputs as ordinary arguments, and ignore the corresponding tangents.\n+ # Then nondiff_argnums can be reserved for (1) non jaxtype data (like a\n+ # string- or callable-valued argument which parameterizes the function or\n+ # rule) or (2) static data (e.g. integers which parameterize shapes).\n+ raise unittest.SkipTest(\"behavior no longer supported\")\n+\n@partial(api.custom_jvp, nondiff_argnums=(0,))\ndef f(x, y):\nreturn x * y\n@@ -6527,6 +6537,22 @@ class CustomJVPTest(jtu.JaxTestCase):\nexpected = (6., 5.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_nondiff_arg_vmap_tracer(self):\n+ @partial(api.custom_jvp, nondiff_argnums=(0,))\n+ def f(x, y):\n+ return x * y\n+ def f_jvp(x, primals, tangents):\n+ (y,), (t_y,) = primals, tangents\n+ return f(x, y), 5 * t_y\n+ f.defjvp(f_jvp)\n+\n+ g = jax.vmap(f)\n+\n+ ans = api.jvp(lambda y: g(jnp.array([2.]), y),\n+ (jnp.array([3.]),), (jnp.array([1.]),))\n+ expected = (jnp.array([6.]), jnp.array([5.]))\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef test_nondiff_arg_hiding_jvp_tracer(self):\ndef f(x):\n@partial(api.custom_jvp, nondiff_argnums=(0,))\n@@ -7526,7 +7552,10 @@ class CustomVJPTest(jtu.JaxTestCase):\nexpected = (2., jnp.cos(1.))\nself.assertAllClose(ans, expected, check_dtypes=False)\n- def test_closed_over_tracer(self):\n+ def test_closed_over_jit_tracer(self):\n+ # See the comment in CustomJVPTest.test_nondiff_arg_jit_tracer.\n+ raise unittest.SkipTest(\"behavior no longer supported\")\n+\n# This test is similar to test_nondiff_arg_tracer except it uses lexical\n# closure rather than the nondiff_argnums mechanism. We decided to disallow\n# tracers in nondiff_argnums to greatly simplify bookkeeping while still\n@@ -7554,7 +7583,7 @@ class CustomVJPTest(jtu.JaxTestCase):\nexpected = jnp.cos(3.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- def test_closed_over_tracer2(self):\n+ def test_closed_over_vmap_tracer(self):\ndef outer(x):\n@api.custom_vjp\ndef f(y):\n"
}
] | Python | Apache License 2.0 | google/jax | skip custom_jvp/vjp tests which dont work with initial-style staging
These tests, involving nondiff_argnums and/or closing over tracers, happen to
work with final-style JIT but not our initial-style primitives. We shouldn't
support this behavior anyway; there are good alternatives. |
260,335 | 02.02.2023 20:24:26 | 28,800 | 644d3b650f0f1dcc19492cff6c1cddbad700dc0d | minor tweaks to type annotations, specialize code on those types
I noticed some slightly-too-general type annotations in core.py. By tightening
them we could simplify the code too. (I think these were leftovers from
pre-omnistaging...) | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/core.py",
"new_path": "jax/_src/core.py",
"diff": "@@ -1139,7 +1139,7 @@ def find_top_trace(xs) -> Trace:\ndynamic = thread_local_state.trace_state.trace_stack.dynamic\ntop_main = (dynamic if top_main is None or dynamic.level > top_main.level\nelse top_main)\n- return top_main and top_main.with_cur_sublevel() # type: ignore\n+ return top_main.with_cur_sublevel() # type: ignore\ndef get_referent(x: Any) -> Any:\nreturn x.get_referent() if isinstance(x, Tracer) else x\n@@ -2076,7 +2076,7 @@ class CallPrimitive(Primitive):\ndef call_bind_with_continuation(primitive: CallPrimitive, fun, *args, **params):\ntop_trace = find_top_trace(args)\nfun_, env_trace_todo = process_env_traces_call(\n- fun, primitive, top_trace and top_trace.level, tuple(params.items()))\n+ fun, primitive, top_trace.level, tuple(params.items()))\ntracers = map(top_trace.full_raise, args)\nfun_ = lu.annotate(fun_, fun.in_type)\n@@ -2085,18 +2085,16 @@ def call_bind_with_continuation(primitive: CallPrimitive, fun, *args, **params):\nreturn call_bind_continuation, top_trace, fun_, tracers, params\n@lu.transformation_with_aux\n-def process_env_traces_call(primitive: CallPrimitive, level: Optional[int],\n+def process_env_traces_call(primitive: CallPrimitive, level: int,\nparams_tuple: tuple, *args):\nouts = yield args, {}\nparams = dict(params_tuple)\ntodo = []\nwhile True:\n- tracers = [x for x in outs if isinstance(x, Tracer)\n- and (level is None or x._trace.level > level)]\n- if tracers:\n- ans = max(tracers, key=lambda x: x._trace.level)\n- else:\n+ tracers = [x for x in outs if isinstance(x, Tracer) and x._trace.level > level]\n+ if not tracers:\nbreak\n+ ans = max(tracers, key=operator.attrgetter('_trace.level'))\ntrace = ans._trace.main.with_cur_sublevel()\nouts = map(trace.full_raise, outs)\nouts, cur_todo = trace.post_process_call(primitive, outs, params)\n@@ -2223,10 +2221,9 @@ def process_env_traces_map(primitive: MapPrimitive, level: int,\nwhile True:\ntracers = [x for x in outs if isinstance(x, Tracer)\nand (level is None or x._trace.level > level)]\n- if tracers:\n- ans = max(tracers, key=lambda x: x._trace.level)\n- else:\n+ if not tracers:\nbreak\n+ ans = max(tracers, key=operator.attrgetter('_trace.level'))\ntrace = ans._trace.main.with_cur_sublevel()\nouts = map(trace.full_raise, outs)\nouts, (cur_todo, cur_xform) = primitive.post_process(trace, outs, params)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/custom_derivatives.py",
"new_path": "jax/_src/custom_derivatives.py",
"diff": "@@ -334,7 +334,7 @@ class CustomJVPCallPrimitive(core.Primitive):\ntracers = map(top_trace.full_raise, args) # type: ignore\nouts = top_trace.process_custom_jvp_call(self, fun, jvp, tracers) # type: ignore\n_, env_trace_todo = lu.merge_linear_aux(env_trace_todo1, env_trace_todo2)\n- return _apply_todos(env_trace_todo, map(core.full_lower, outs))\n+ return core.apply_todos(env_trace_todo, map(core.full_lower, outs))\ndef impl(self, fun, _, *args):\nwith core.new_sublevel():\n@@ -377,12 +377,6 @@ def process_env_traces(primitive, level: int, jvp_was_run: bool, *args):\ntodo.append(cur_todo)\nyield outs, tuple(todo) # Ensure the aux output is immutable\n-def _apply_todos(todos, outs):\n- todos_list = list(todos)\n- while todos_list:\n- outs = map(core.full_lower, todos_list.pop()(outs))\n- return outs\n-\nallowed_effects: Set[core.Effect] = set()\nallowed_effects.add(lax.InOutFeedEffect.Infeed)\n@@ -673,11 +667,11 @@ class CustomVJPCallPrimitive(core.CallPrimitive):\nout_trees=out_trees)\nfst, env_trace_todo = lu.merge_linear_aux(env_trace_todo1, env_trace_todo2)\nif fst:\n- return _apply_todos(env_trace_todo, map(core.full_lower, outs))\n+ return core.apply_todos(env_trace_todo, map(core.full_lower, outs))\nelse:\nenv_trace_todo, bwd_transform = env_trace_todo\nbwd = _apply_bwd_transform(bwd_transform, bwd)\n- return _apply_todos(env_trace_todo, map(core.full_lower, outs))\n+ return core.apply_todos(env_trace_todo, map(core.full_lower, outs))\ndef impl(self, fun, fwd, bwd, *args, out_trees):\ndel fwd, bwd, out_trees\n"
}
] | Python | Apache License 2.0 | google/jax | minor tweaks to type annotations, specialize code on those types
I noticed some slightly-too-general type annotations in core.py. By tightening
them we could simplify the code too. (I think these were leftovers from
pre-omnistaging...) |
260,411 | 03.02.2023 11:25:27 | -7,200 | f147e82fa7d0956f87ae011ccd3f3c4f83c679d1 | [shape_poly] Add support for evaluating div/mod for DimExpr
We have added the ability to represent floordiv and mod to
DimExper. Here we add support for evaluating these dimensions
for the native lowering. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -56,7 +56,7 @@ TfVal = Any\n# A dimension environment maps dimension variables to expressions that\n# compute the values of the dimension. An expression must support addition\n# and multiplication with other expressions or with int32/int64, e.g.,\n-# by overloading __add__, __radd__, __mul__, __rmul__.\n+# by overloading __add__, __radd__, __mul__, __rmul__, __divmod__, __rdivmod__.\nShapeEnv = Dict[str, Any]\nDType = Any\n@@ -942,19 +942,29 @@ def _parse_spec(spec: Optional[Union[str, PolyShape]],\ndef _evaluate_add(v1, v2):\n- if isinstance(v1, (int, np.int32, np.int64)) and v1 == 0:\n+ try:\n+ if op.index(v1) == 0:\nreturn v2\n- elif isinstance(v2, (int, np.int32, np.int64)) and v2 == 0:\n+ except:\n+ pass\n+ try:\n+ if op.index(v2) == 0:\nreturn v1\n- else:\n+ except:\n+ pass\nreturn v1 + v2\ndef _evaluate_multiply(v1, v2):\n- if isinstance(v1, (int, np.int32, np.int64)) and v1 == 1:\n+ try:\n+ if op.index(v1) == 1:\nreturn v2\n- elif isinstance(v2, (int, np.int32, np.int64)) and v2 == 1:\n+ except:\n+ pass\n+ try:\n+ if op.index(v2) == 1:\nreturn v1\n- else:\n+ except:\n+ pass\nreturn v1 * v2\ndef _is_known_constant(v) -> Optional[int]:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"diff": "@@ -651,6 +651,16 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(jax2tf.convert(f_jax, polymorphic_shapes=\"(b, _, _)\")(x),\nf_jax(x))\n+ def test_non_trivial_dim_expr(self):\n+ check_shape_poly(\n+ self,\n+ lambda x: (x[0] + x.shape[0] + x.shape[0] * x.shape[0] + (5 * x.shape[0]) +\n+ x.shape[0] // 2 + (5 + x.shape[0]) // x.shape[0] +\n+ 17 // x.shape[0] +\n+ x.shape[0] % 3 + 17 % x.shape[0]),\n+ arg_descriptors=[RandArg((3,), np.int64)],\n+ poly_axes=[0])\n+\ndef test_static_shape_result(self):\n\"\"\"The result has static shape.\"\"\"\n@@ -972,7 +982,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\narg_descriptors=[RandArg((3, 4), _f32)],\npoly_axes=[(0, 1)])\n- def test_non_trivial_polynomials(self):\n+ def test_non_trivial_polynomials_spec(self):\nif config.jax_dynamic_shapes:\nraise unittest.SkipTest(\"--jax_dynamic_shapes supports only trivial polynomials\")\n# We can handle non-trivial polynomials in the input shape,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -583,28 +583,37 @@ def sharded_aval(aval: core.ShapedArray,\nreturn aval.update(tuple(sharded_shape))\n-class DimPolyEvaluator:\n+class DimExprEvaluator:\n# A wrapper for an ir.Value that overloads + and * to be used for evaluating\n- # dimension polynomials.\n+ # symbolic dimensions.\n+ __array_priority__ = 1000 # Same as tracer, for __radd__ and others on ndarray\ndef __init__(self, value: ir.Value):\nself.value = value\n- def __add__(self, other: Union[np.int32, np.int64, DimPolyEvaluator]):\n- if not isinstance(other, DimPolyEvaluator):\n- other = DimPolyEvaluator(ir_constant(other))\n- return DimPolyEvaluator(hlo.AddOp(self.value, other.value).result)\n+ def __add__(self, other: Union[np.int32, np.int64, DimExprEvaluator]):\n+ if not isinstance(other, DimExprEvaluator):\n+ other = DimExprEvaluator(ir_constant(other))\n+ return DimExprEvaluator(hlo.AddOp(self.value, other.value).result)\ndef __radd__(self, other: Union[np.int32, np.int64]):\n- return DimPolyEvaluator(hlo.AddOp(ir_constant(other), self.value).result)\n+ return DimExprEvaluator(ir_constant(other)).__add__(self)\n- def __mul__(self, other: Union[np.int32, np.int64, DimPolyEvaluator]):\n- if not isinstance(other, DimPolyEvaluator):\n- other = DimPolyEvaluator(ir_constant(other))\n- return DimPolyEvaluator(hlo.MulOp(self.value, other.value).result)\n+ def __mul__(self, other: Union[np.int32, np.int64, DimExprEvaluator]):\n+ if not isinstance(other, DimExprEvaluator):\n+ other = DimExprEvaluator(ir_constant(other))\n+ return DimExprEvaluator(hlo.MulOp(self.value, other.value).result)\ndef __rmul__(self, other: Union[np.int32, np.int64]):\n- return DimPolyEvaluator(hlo.MulOp(ir_constant(other), self.value).result)\n+ return DimExprEvaluator(ir_constant(other)).__mul__(self)\n+ def __divmod__(self, divisor: Union[np.int32, np.int64, DimExprEvaluator]):\n+ if not isinstance(divisor, DimExprEvaluator):\n+ divisor = DimExprEvaluator(ir_constant(divisor))\n+ return (DimExprEvaluator(hlo.DivOp(self.value, divisor.value).result),\n+ DimExprEvaluator(hlo.RemOp(self.value, divisor.value).result))\n+\n+ def __rdivmod__(self, dividend: Union[np.int32, np.int64]):\n+ return DimExprEvaluator(ir_constant(dividend)).__divmod__(self)\ndef eval_dynamic_shape(ctx: LoweringRuleContext,\nshape: core.Shape) -> Tuple[Union[int, Value], ...]:\n@@ -612,7 +621,7 @@ def eval_dynamic_shape(ctx: LoweringRuleContext,\nif config.jax_dynamic_shapes:\nreturn tuple(ctx.axis_size_env.get(d, d) for d in shape) # type: ignore\nelse:\n- dim_var_env = {dv_name : DimPolyEvaluator(dv_val[0])\n+ dim_var_env = {dv_name : DimExprEvaluator(dv_val[0])\nfor dv_name, dv_val in zip(ctx.module_context.dim_vars, ctx.dim_var_values)}\ndef eval_dim(d: core.DimSize) -> Union[int, ir.Value]:\ntry:\n"
}
] | Python | Apache License 2.0 | google/jax | [shape_poly] Add support for evaluating div/mod for DimExpr
We have added the ability to represent floordiv and mod to
DimExper. Here we add support for evaluating these dimensions
for the native lowering. |
260,411 | 04.02.2023 08:30:44 | -7,200 | 15be538ebe0196ddde907e60ef114dd9ad4c9ab4 | [shape_poly] Fix the hashing and equality of symbolic dimensions | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3209,7 +3209,10 @@ def _einsum(operands: Sequence,\nassert jax.config.jax_dynamic_shapes or _all(\nname in lhs_names and name in rhs_names and\nlhs.shape[lhs_names.index(name)] == rhs.shape[rhs_names.index(name)]\n- for name in contracted_names)\n+ for name in contracted_names), (\n+ \"Incompatible reduction dimensions: \"\n+ f\"lhs.shape={lhs.shape} lhs_names={lhs_names} \"\n+ f\"rhs.shape={rhs.shape} rhs_names={rhs_names}\")\n# contract using lax.dot_general\nbatch_names_str = ''.join(batch_names)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -91,13 +91,10 @@ from jax._src.core import (\n_check_jaxpr as _check_jaxpr,\n_check_map as _check_map,\n_compact_eqn_should_include as _compact_eqn_should_include,\n- _dim_handler_and_canonical as _dim_handler_and_canonical,\n- _dimension_handler_int as _dimension_handler_int,\n_dtype_object as _dtype_object,\n_effect_free_abstract_eval as _effect_free_abstract_eval,\n_encode_digits_alphabetic as _encode_digits_alphabetic,\n_forward_to_value as _forward_to_value,\n- _get_special_dim_handler as _get_special_dim_handler,\n_initialize_jax_jit_thread_local_state as _initialize_jax_jit_thread_local_state,\n_invalid_shape_error as _invalid_shape_error,\n_jaxpr_type_to_callable_annotation as _jaxpr_type_to_callable_annotation,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -287,8 +287,8 @@ therefore outside of the `XlaSharding` wrapper.\n## Shape-polymorphic conversion\n-**The shape polymorphism support is work in progress. It is meant to be sound,\n-but it may raise errors on some programs. Please report any bugs you encounter.**\n+**The shape polymorphism support is work in progress.\n+Please report any bugs you encounter.**\nWe described above how to include in the SavedModel several specializations\nof a lowered function for a few specific input shapes. `jax2tf` can\n@@ -366,11 +366,6 @@ the latter invocation may happen after the `f_tf` has been serialized\nto a SavedModel and reloaded in an environment where `f_jax` and the JAX\ntracing machinery are not available anymore.\n-Correctness is very important because it would be nasty to debug a subtle discrepancy\n-of the code loaded from a SavedModel from the expected behavior written in JAX.\n-We help ensure correctness\n-by reusing the same JAX tracing and shape checking mechanism as when the shapes are fully known.\n-\n### Coverage of shape-polymorphic tracing\nBesides correctness, a secondary goal is to be able to lower many shape-polymorphic programs,\n@@ -545,16 +540,13 @@ results are used as shapes, e.g., instead of `np.arange(n) * x.shape[0]` write\nInside JAX there are a number of equality and inequality comparisons\ninvolving shapes, e.g., for doing shape checking or even for choosing\nthe implementation for some primitives. Comparisons are supported\n-is as follows:\n+as follows:\n- * equality is partially supported: if the two symbolic dimensions denote the same\n+ * equality is supported with a caveat: if the two symbolic dimensions denote the same\nvalue under all valuations for dimension variables, then equality evaluates to `True`,\n- e.g., for `b + b == 2*b`; if they denote different values under all valuations,\n- then equality evaluates to `False`, e.g., for `b + 1 == b` or `b == 0`.\n- Otherwise, equality raises an exception `core.InconclusiveDimensionOperation`,\n- e.g., when comparing `b == 1` or `a == b`.\n- * disequality is always the negation of equality (and results in an exception\n- if equality would result in an exception).\n+ e.g., for `b + b == 2*b`; otherwise the equality evaluates to `False`. See below\n+ for a discussion of important consequences of this behavior.\n+ * disequality is always the negation of equality.\n* inequality is partially supported, in a similar way as partial equality.\nHowever, in this\ncase we take into consideration that dimension variables range over strictly positive\n@@ -563,17 +555,35 @@ is as follows:\nFor example, the following code raises the exception\n`core.InconclusiveDimensionOperation` with the message\n-`Dimension polynomial comparison 'a + 1' == 'b' is inconclusive`.\n+`Dimension polynomial comparison 'a + 1' >= 'b' is inconclusive`.\n```python\n-jax2tf.convert(lambda x: 0 if x.shape[0] + 1 == x.shape[1] else 1,\n+jax2tf.convert(lambda x: 0 if x.shape[0] + 1 >= x.shape[1] else 1,\npolymorphic_shapes=[\"(a, b)\"])(np.ones((3, 4)))\n```\n-Note that it would be unsound for JAX to compute `x.shape[0] + 1 == x.shape[1]`\n-as `False` and produce a lowered function that returns `1` just because the dimension polynomials\n-are not identical: there are some concrete input shapes for which the function\n-should return `0`.\n+The equality comparison returns `False` for `b + 1 == b` or `b == 0`\n+(in which case it is certain that the dimensions are different for all valuations),\n+but also for `b == 1` and for `a == b`. This is unsound, and we\n+ought to raise `core.InconclusiveDimensionOperation` because under\n+some valuations the result should be `True` and under other\n+valuations it should be `False`. We choose to make equality total\n+thus allowing unsoundness because otherwise we may get spurious errors\n+in presence of hash collisions\n+when hashing dimension expressions or objects that include\n+them (shapes, `core.AbstractValue`, `core.Jaxpr`).\n+Besides the hashing errors, a partial semantics of equality\n+leads to errors for the following expressions `b == a or b == b` or `b in [a, b]`\n+even though the error is avoided if we change the order of the comparisons.\n+\n+We attempted to retain soundness and hashability by creating both hashable and unhashable\n+kinds of symbolic dimensions [PR #14200](https://github.com/google/jax/pull/14200),\n+but it turned out to be very hard to diagnose hashing failures in user programs because\n+often hashing is implicit when using sets or memo tables.\n+\n+Code of the form `if x.shape[0] != 1: raise NiceErrorMessage` is sound even\n+with this treatment of equality, but code of the form `if x.shape[0] != 1: return 1`\n+is unsound.\n### Division of symbolic dimensions is partially supported\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -419,13 +419,10 @@ class _DimExpr():\nlb, ub = _ensure_poly(self - other, \"eq\").bounds()\nif lb == ub == 0:\nreturn True\n- if lb > 0:\n+ if lb > 0 or ub < 0:\nreturn False\n- if ub < 0:\n+ # See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#comparison-of-symbolic-dimensions-is-partially-supported\nreturn False\n- raise InconclusiveDimensionOperation(\n- f\"Symbolic dimension comparison '{self}' == '{other}' is inconclusive.\\n\"\n- \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#comparison-of-symbolic-dimensions-is-partially-supported.\")\ndef ge(self, other: DimSize) -> bool:\nlb, ub = _ensure_poly(self - other, \"ge\").bounds()\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"diff": "@@ -28,6 +28,7 @@ import jax\nfrom jax import core\nfrom jax.experimental import jax2tf\nfrom jax.experimental.jax2tf import shape_poly\n+from jax.experimental import pjit\nfrom jax import lax\nimport jax.numpy as jnp\nfrom jax import random\n@@ -113,29 +114,16 @@ class DimExprTest(tf_test_util.JaxToTfTestCase):\nself.assertEqual(True, a == a)\nself.assertEqual(True, a == a1)\nself.assertEqual(False, a != a)\n- with self.assertRaisesRegex(\n- core.InconclusiveDimensionOperation,\n- \"Symbolic dimension comparison 'a' == 'b' is inconclusive\"):\n- a.eq(b)\n- with self.assertRaisesRegex(\n- core.InconclusiveDimensionOperation,\n- \"Symbolic dimension comparison 'a' == 'b' is inconclusive\"):\n- a == b\n-\n- with self.assertRaisesRegex(\n- core.InconclusiveDimensionOperation,\n- \"Symbolic dimension comparison 'a' == 'b' is inconclusive\"):\n- a != b\n+ self.assertFalse(a == b)\n+ self.assertTrue(a != b)\nself.assertLen({a, a}, 1)\nself.assertLen({a, b}, 2)\nself.assertIn(a, {a, b})\nself.assertIn(b, {a, b})\nself.assertIn(a, [a, b])\n- with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n- \"Symbolic dimension comparison .* is inconclusive\"):\n- b in [a, b]\n+ self.assertIn(b, [a, b])\ndef test_get_vars(self):\na, b = shape_poly._parse_spec(\"a, b\", (2, 3))\n@@ -256,9 +244,8 @@ class DimExprTest(tf_test_util.JaxToTfTestCase):\nself.assertFalse((2 * a * b * a).eq(a * b * a))\nself.assertFalse((2 * a * b * a + 1).eq(a * b * a))\nself.assertFalse((3 * a * b * a - 1).eq(a * b * a))\n- with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n- re.escape(\"Symbolic dimension comparison '3*a^2*b + -2' == 'a^2*b' is inconclusive\")):\n- (3 * a * b * a - 2).eq(a * b * a)\n+\n+ self.assertFalse((3 * a * b * a - 2).eq(a * b * a))\nself.assertTrue(a % b == a % b)\nself.assertTrue(a % b - a % b == 0)\n@@ -270,7 +257,7 @@ class DimExprTest(tf_test_util.JaxToTfTestCase):\nself.assertTrue(a, a + (a + b) // b - (b + a) // b)\n- # Test the normaliation (a // b) * b == a - a % b\n+ # Test the normalization (a // b) * b == a - a % b\nself.assertTrue((a // 2) * 2 == a - a % 2)\nself.assertTrue((a // 2) + (a // 2) == a - a % 2)\nself.assertTrue((a // 2) * 6 == 3 * a - 3 * (a % 2))\n@@ -1337,8 +1324,8 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\ncore.InconclusiveDimensionOperation,\n- re.escape(\"Symbolic dimension comparison 'a + 1' == 'b' is inconclusive\")):\n- jax2tf.convert(lambda x: 0 if x.shape[0] + 1 == x.shape[1] else 1,\n+ re.escape(\"Symbolic dimension comparison 'a + 1' >= 'b' is inconclusive\")):\n+ jax2tf.convert(lambda x: 0 if x.shape[0] + 1 >= x.shape[1] else 1,\npolymorphic_shapes=[\"(a, b)\"])(np.ones((4, 4)))\n# Unsoundness: not checking that the shape is 0\n@@ -1418,6 +1405,29 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[\"b1, b2, ...\"])(xv)\nself.assertAllClose(res_iter, res_vmap_tf.numpy())\n+ def test_with_hash_collision_vmap(self):\n+ # Batching caches based on Jaxpr, and Jaxpr include _DimExpr. If we have\n+ # a collision for the hashing of a _DimExpr, then Python will call the\n+ # equality, which will raise InconclusiveDimensionOperation.\n+\n+ def f_jax(x):\n+ return jnp.reshape(x, (2, -1,))\n+ try:\n+ # Override the hashing to create collisions\n+ orig_hash = getattr(shape_poly._DimExpr, \"__hash__\")\n+ def collision_hash(obj):\n+ return hash(5)\n+\n+ setattr(shape_poly._DimExpr, \"__hash__\", collision_hash)\n+ xs = np.ones((3, 5, 6), dtype=np.float32)\n+ f_toconvert = jax.vmap(pjit.pjit(f_jax))\n+ res_1 = jax2tf.convert(f_toconvert)(xs)\n+ res_2 = jax2tf.convert(f_toconvert,\n+ polymorphic_shapes = \"b1, b2, ...\")(xs)\n+ self.assertAllClose(res_1, res_2)\n+ finally:\n+ setattr(shape_poly._DimExpr, \"__hash__\", orig_hash)\n+\n@parameterized.named_parameters([\ndict(testcase_name=f\"_{op_name}\",\nop=op)\n@@ -1539,7 +1549,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\narg_descriptors=[RandArg((3,), _f32)],\npoly_axes=[0])\n- @unittest.skip('Failing at HEAD. Reenable after b/264913007 is fixed')\ndef test_vmap_while(self):\ndef cond_func(x): # x: f32[3]\nreturn jnp.sum(x) >= 0.\n@@ -1881,8 +1890,8 @@ _POLY_SHAPE_TEST_HARNESSES = [\narg_descriptors=[RandArg((2, 3), _f32), RandArg((2, 3), _f32)],\npolymorphic_shapes=[\"(2, b0)\", \"(2, b1)\"],\ninput_signature=[tf.TensorSpec((2, None)), tf.TensorSpec((2, None))],\n- expect_error=(core.InconclusiveDimensionOperation,\n- \"Symbolic dimension comparison 'b1' == 'b0' is inconclusive\")),\n+ expect_error=(AssertionError,\n+ \"Incompatible reduction dimensions\")),\nPolyHarness(\"eye\", \"N=poly_M=None\",\nlambda x: jnp.eye(x.shape[0]),\narg_descriptors=[RandArg((3, 4), _f32)],\n"
}
] | Python | Apache License 2.0 | google/jax | [shape_poly] Fix the hashing and equality of symbolic dimensions |
260,510 | 03.02.2023 22:51:28 | 28,800 | c231171fb6616bdd88175460ab19701bfac8a80e | Fix checkify caching with nested call primitives | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -351,9 +351,8 @@ def default_checkify_rule(primitive: core.Primitive, error: Error,\n# call_jaxpr handling\ncall_jaxpr = params.pop('call_jaxpr')\n- partial_checkify = lu.wrap_init(\n- functools.partial(checkify_jaxpr_flat, call_jaxpr, (), enabled_errors,\n- err_tree))\n+ partial_checkify = lu.hashable_partial(lu.wrap_init(\n+ checkify_jaxpr_flat), call_jaxpr, (), enabled_errors, err_tree)\npartial_checkify, metadata = _flatten_and_get_error_metadata_thunk(\npartial_checkify)\n@@ -688,6 +687,7 @@ error_checks[lax.scatter_max_p] = functools.partial(scatter_error_check,\n# HOP error check rules\n+@weakref_lru_cache\ndef jaxpr_to_checkify_jaxpr(\njaxpr: core.ClosedJaxpr, enabled_errors, err_tree: PyTreeDef,\n*flat_err_and_in_vals) -> Tuple[core.ClosedJaxpr, PyTreeDef, Set[ErrorEffect]]:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -775,7 +775,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef test_retracing(self):\nf = checkify.checkify(jax.jit(lambda x: jnp.sin(x) ** 2))\n_ = f(3.)\n- with jtu.count_primitive_compiles() as count:\n+ with jtu.count_jit_and_pmap_compiles() as count:\n_ = f(3.)\nself.assertEqual(count[0], 0)\n"
}
] | Python | Apache License 2.0 | google/jax | Fix checkify caching with nested call primitives |
260,335 | 06.02.2023 12:51:01 | 28,800 | 6db3f4865613420a2fa9a6ddb691b9ceff08e78d | [shard_map] add rep rule for axis_index, trivial test | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/shard_map.py",
"new_path": "jax/experimental/shard_map.py",
"diff": "@@ -669,6 +669,11 @@ def _all_to_all_rule(_, in_rep, *, split_axis, concat_axis, axis_name,\nif axis_index_groups is not None: raise NotImplementedError\nreturn in_rep - {axis_name} # removes replication\n+@register_rule(lax_parallel.axis_index_p)\n+def _axis_index_rule(mesh, *, axis_name):\n+ axis_name = (axis_name,) if not isinstance(axis_name, tuple) else axis_name\n+ return set(mesh.shape) - set(axis_name)\n+\n@register_rule(pjit.pjit_p)\ndef _pjit_rule(mesh, *in_rep, jaxpr, **kwargs):\nreturn _output_rep(mesh, jaxpr.jaxpr, in_rep)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/shard_map_test.py",
"new_path": "tests/shard_map_test.py",
"diff": "@@ -377,6 +377,17 @@ class ShardMapTest(jtu.JaxTestCase):\ny_dot_expected = jnp.sin(jnp.arange(8.)) * (jnp.cos(x) * x).sum()\nself.assertAllClose(y_dot, y_dot_expected, check_dtypes=False)\n+ @jtu.skip_on_devices(\"cpu\")\n+ def test_axis_index(self):\n+ mesh = Mesh(np.array(jax.devices()[:4]), ('x',))\n+\n+ @partial(shard_map, mesh=mesh, in_specs=(), out_specs=P('x'))\n+ def f():\n+ return jax.lax.axis_index('x')[None]\n+\n+ x = f()\n+ self.assertAllCLose(x, jnp.arange(4), check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [shard_map] add rep rule for axis_index, trivial test |
260,335 | 06.02.2023 17:45:24 | 28,800 | 198bfe3df9c9766c7158f31b3b6d7f814ebcadf5 | [shard_map] add a lot of trivial rules | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/shard_map.py",
"new_path": "jax/experimental/shard_map.py",
"diff": "@@ -16,6 +16,7 @@ from __future__ import annotations\nimport enum\nfrom functools import partial, lru_cache\nimport inspect\n+import itertools as it\nimport operator as op\nfrom typing import (Any, Callable, Dict, Hashable, List, Optional, Sequence,\nSet, Tuple, TypeVar, Union, Protocol)\n@@ -28,11 +29,13 @@ from jax.core import Tracer\nfrom jax.sharding import NamedSharding, PartitionSpec, Mesh\nfrom jax._src import ad_util\nfrom jax._src import linear_util as lu\n+from jax._src import ops\nfrom jax._src import pjit\nfrom jax._src import source_info_util\nfrom jax._src import traceback_util\nfrom jax._src import util\n-from jax._src.lax import lax, parallel as lax_parallel\n+from jax._src.lax import (lax, parallel as lax_parallel, slicing,\n+ windowed_reductions, fft, linalg)\nfrom jax._src.util import (prod, HashableFunction, unzip2, as_hashable_function,\nmemoize, partition_list, merge_lists)\nfrom jax.api_util import flatten_fun_nokwargs, shaped_abstractify\n@@ -636,7 +639,9 @@ register_standard = lambda prim: _rep_rules.setdefault(prim, _standard_rep_rule)\ndef _standard_rep_rule(_, *in_rep, **__):\nreturn set.intersection(*in_rep)\n-for o in lax.__dict__.values():\n+for o in it.chain(lax.__dict__.values(), slicing.__dict__.values(),\n+ windowed_reductions.__dict__.values(), fft.__dict__.values(),\n+ linalg.__dict__.values(), ops.__dict__.values()):\nif isinstance(o, core.Primitive): register_standard(o)\nregister_standard(ad_util.add_any_p)\n"
}
] | Python | Apache License 2.0 | google/jax | [shard_map] add a lot of trivial rules |
260,453 | 07.02.2023 12:07:00 | 18,000 | 82519570256e8ecfb46e664a435b4c01227c6f50 | Added scipy.stats.rankdata | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -11,6 +11,9 @@ Remember to align the itemized text with the first line of an item within a list\n* Deleted {func}`jax.scipy.linalg.polar_unitary`, which was a deprecated JAX\nextension to the scipy API. Use {func}`jax.scipy.linalg.polar` instead.\n+ * Changes\n+ * Added {func}`jax.scipy.stats.rankdata`.\n+\n## jaxlib 0.4.3\n## jax 0.4.2 (Jan 24, 2023)\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax.scipy.rst",
"new_path": "docs/jax.scipy.rst",
"diff": "@@ -148,6 +148,7 @@ jax.scipy.stats\n:toctree: _autosummary\nmode\n+ rankdata\njax.scipy.stats.bernoulli\n~~~~~~~~~~~~~~~~~~~~~~~~~\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/scipy/stats/_core.py",
"new_path": "jax/_src/scipy/stats/_core.py",
"diff": "-# Copyright 2022 The JAX Authors.\n+# Copyright 2023 The JAX Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n@@ -23,7 +23,7 @@ from jax._src import dtypes\nfrom jax._src.api import vmap\nfrom jax._src.numpy.lax_numpy import _check_arraylike\nfrom jax._src.numpy.util import _wraps\n-from jax._src.typing import ArrayLike\n+from jax._src.typing import ArrayLike, Array\nfrom jax._src.util import canonicalize_axis, prod\nModeResult = namedtuple('ModeResult', ('mode', 'count'))\n@@ -39,7 +39,7 @@ def mode(a: ArrayLike, axis: Optional[int] = 0, nan_policy: str = \"propagate\", k\nif nan_policy not in [\"propagate\", \"omit\", \"raise\"]:\nraise ValueError(\nf\"Illegal nan_policy value {nan_policy!r}; expected one of \"\n- \"{'propoagate', 'omit', 'raise'}\"\n+ \"{'propagate', 'omit', 'raise'}\"\n)\nif nan_policy == \"omit\":\n# TODO: return answer without nans included.\n@@ -81,3 +81,65 @@ def mode(a: ArrayLike, axis: Optional[int] = 0, nan_policy: str = \"propagate\", k\nx = x.reshape(x.shape[0], prod(x.shape[1:]))\nvals, counts = vmap(_mode_helper, in_axes=1)(x)\nreturn ModeResult(vals.reshape(output_shape), counts.reshape(output_shape))\n+\n+def invert_permutation(i: Array) -> Array:\n+ \"\"\"Helper function that inverts a permutation array.\"\"\"\n+ return jnp.empty_like(i).at[i].set(jnp.arange(i.size, dtype=i.dtype))\n+\n+@_wraps(scipy.stats.rankdata, lax_description=\"\"\"\\\n+Currently the only supported nan_policy is 'propagate'\n+\"\"\")\n+@partial(jit, static_argnames=[\"method\", \"axis\", \"nan_policy\"])\n+def rankdata(\n+ a: ArrayLike,\n+ method: str = \"average\",\n+ *,\n+ axis: Optional[int] = None,\n+ nan_policy: str = \"propagate\",\n+) -> Array:\n+\n+ _check_arraylike(\"rankdata\", a)\n+\n+ if nan_policy not in [\"propagate\", \"omit\", \"raise\"]:\n+ raise ValueError(\n+ f\"Illegal nan_policy value {nan_policy!r}; expected one of \"\n+ \"{'propoagate', 'omit', 'raise'}\"\n+ )\n+ if nan_policy == \"omit\":\n+ raise NotImplementedError(\n+ f\"Logic for `nan_policy` of {nan_policy} is not implemented\"\n+ )\n+ if nan_policy == \"raise\":\n+ raise NotImplementedError(\n+ \"In order to best JIT compile `mode`, we cannot know whether `x` \"\n+ \"contains nans. Please check if nans exist in `x` outside of the \"\n+ \"`rankdata` function.\"\n+ )\n+\n+ if method not in (\"average\", \"min\", \"max\", \"dense\", \"ordinal\"):\n+ raise ValueError(f\"unknown method '{method}'\")\n+\n+ a = jnp.asarray(a)\n+\n+ if axis is not None:\n+ return jnp.apply_along_axis(rankdata, axis, a, method)\n+\n+ arr = jnp.ravel(a)\n+ sorter = jnp.argsort(arr)\n+ inv = invert_permutation(sorter)\n+\n+ if method == \"ordinal\":\n+ return inv + 1\n+ arr = arr[sorter]\n+ obs = jnp.insert(arr[1:] != arr[:-1], 0, True)\n+ dense = obs.cumsum()[inv]\n+ if method == \"dense\":\n+ return dense\n+ count = jnp.nonzero(obs, size=arr.size + 1, fill_value=len(obs))[0]\n+ if method == \"max\":\n+ return count[dense]\n+ if method == \"min\":\n+ return count[dense - 1] + 1\n+ if method == \"average\":\n+ return .5 * (count[dense] + count[dense - 1] + 1).astype(dtypes.canonicalize_dtype(jnp.float_))\n+ raise ValueError(f\"unknown method '{method}'\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/__init__.py",
"new_path": "jax/scipy/stats/__init__.py",
"diff": "@@ -37,5 +37,5 @@ from jax.scipy.stats import betabinom as betabinom\nfrom jax.scipy.stats import gennorm as gennorm\nfrom jax.scipy.stats import truncnorm as truncnorm\nfrom jax._src.scipy.stats.kde import gaussian_kde as gaussian_kde\n-from jax._src.scipy.stats._core import mode as mode\n+from jax._src.scipy.stats._core import mode as mode, rankdata as rankdata\nfrom jax.scipy.stats import vonmises as vonmises\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -1129,5 +1129,26 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\ntol=tol)\nself._CompileAndCheck(lax_fun, args_maker, rtol=tol)\n+ @jtu.sample_product(\n+ [dict(shape=shape, axis=axis)\n+ for shape in [(0,), (7,), (47, 8), (0, 2, 3), (10, 5, 21)]\n+ for axis in [None, *range(len(shape))\n+ ]],\n+ dtype=jtu.dtypes.integer + jtu.dtypes.floating,\n+ method=['average', 'min', 'max', 'dense', 'ordinal']\n+ )\n+ def testRankData(self, shape, dtype, axis, method):\n+\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+\n+ scipy_fun = partial(osp_stats.rankdata, method=method, axis=axis)\n+ lax_fun = partial(lsp_stats.rankdata, method=method, axis=axis)\n+ tol_spec = {np.float32: 2e-4, np.float64: 5e-6}\n+ tol = jtu.tolerance(dtype, tol_spec)\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n+ tol=tol)\n+ self._CompileAndCheck(lax_fun, args_maker, rtol=tol)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Added scipy.stats.rankdata |
260,294 | 07.02.2023 20:07:38 | 0 | 01a10a1d06f45de030195175b1f2e03fad6eaf9c | [ROCm] Re-enable some linalg and sparse tests | [
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -523,7 +523,6 @@ class NumpyLinalgTest(jtu.JaxTestCase):\ndtype=float_types + complex_types,\ncompute_uv=[False, True],\n)\n- @jtu.skip_on_devices(\"rocm\") # will be fixed in ROCm-5.1\n@jax.default_matmul_precision(\"float32\")\ndef testSVD(self, b, m, n, dtype, full_matrices, compute_uv, hermitian):\nrng = jtu.rand_default(self.rng())\n@@ -831,7 +830,6 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nfor hermitian in ([False, True] if shape[-1] == shape[-2] else [False])],\ndtype=float_types + complex_types,\n)\n- @jtu.skip_on_devices(\"rocm\") # will be fixed in ROCm-5.1\ndef testPinv(self, shape, hermitian, dtype):\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -345,7 +345,6 @@ class cuSparseTest(sptu.SparseTestCase):\ndtype=all_dtypes,\ntranspose=[True, False],\n)\n- @jtu.skip_on_devices(\"rocm\") # will be fixed in rocm-5.1\ndef test_csr_matvec(self, shape, dtype, transpose):\nop = lambda M: M.T if transpose else M\n@@ -445,7 +444,6 @@ class cuSparseTest(sptu.SparseTestCase):\ndtype=all_dtypes,\ntranspose=[True, False],\n)\n- @jtu.skip_on_devices(\"rocm\") # will be fixed in rocm-5.1\ndef test_coo_matmat(self, shape, dtype, transpose):\nop = lambda M: M.T if transpose else M\n@@ -1043,7 +1041,6 @@ class BCOOTest(sptu.SparseTestCase):\n],\ndtype=jtu.dtypes.floating + jtu.dtypes.complex,\n)\n- @jtu.skip_on_devices(\"rocm\")\n@jax.default_matmul_precision(\"float32\")\ndef test_bcoo_batched_matmat_cusparse(\nself, n_batch, lhs_shape, rhs_shape, dtype, lhs_contracting,\n@@ -1102,7 +1099,6 @@ class BCOOTest(sptu.SparseTestCase):\n],\ndtype=jtu.dtypes.floating + jtu.dtypes.complex,\n)\n- @jtu.skip_on_devices(\"rocm\")\ndef test_bcoo_batched_matmat_default_lowering(\nself, n_batch, lhs_shape, rhs_shape, dtype, lhs_contracting,\nrhs_contracting):\n"
}
] | Python | Apache License 2.0 | google/jax | [ROCm] Re-enable some linalg and sparse tests |
260,335 | 08.02.2023 11:12:50 | 28,800 | 58d3f552d73a86bacc0d37db504f6c4299fab213 | [shard-map] add remat support, very basic test | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/shard_map.py",
"new_path": "jax/experimental/shard_map.py",
"diff": "@@ -908,6 +908,39 @@ def _shard_map_axis_subst(params, subst, traverse):\nreturn dict(params, jaxpr=new_jaxpr)\ncore.axis_substitution_rules[shard_map_p] = _shard_map_axis_subst\n+# Remat\n+\n+def _pe_custom_params(\n+ unks_in: List[bool], inst_in: List[bool], kept_outs_known: List[bool],\n+ kept_outs_staged: List[bool], num_res: int, params_known: Dict[str, Any],\n+ params_staged: Dict[str, Any]\n+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:\n+ # prune inputs to jaxpr_known according to unks_in\n+ mesh = params_known['mesh']\n+ in_names_known, _ = partition_list(unks_in, params_known['in_names'])\n+ _, out_names_known = partition_list(kept_outs_known, params_known['out_names'])\n+ out_names_known = out_names_known + [{0: (*mesh.axis_names,)}] * num_res\n+ new_params_known = dict(params_known, in_names=tuple(in_names_known),\n+ out_names=tuple(out_names_known))\n+\n+ # added num_res new inputs to jaxpr_staged, pruning according to inst_in\n+ _, in_names_staged = partition_list(inst_in, params_staged['in_names'])\n+ in_names_staged = [{0: (*mesh.axis_names,)}] * num_res + in_names_staged\n+ _, out_names_staged = partition_list(kept_outs_staged, params_staged['out_names'])\n+ new_params_staged = dict(params_staged, in_names=tuple(in_names_staged),\n+ out_names=tuple(out_names_staged), check_rep=False)\n+ return new_params_known, new_params_staged\n+\n+def _pe_custom_res(params_known, aval):\n+ mesh = params_known['mesh']\n+ return _unshard_aval(mesh, {0: (*mesh.axis_names,)}, aval)\n+\n+pe.partial_eval_jaxpr_custom_rules[shard_map_p] = \\\n+ partial(pe.call_partial_eval_custom_rule, 'jaxpr', _pe_custom_params,\n+ res_aval=_pe_custom_res)\n+\n+# Misc\n+\n# TODO(mattjj): move this to _src/util.py\nclass HashablePartial:\ndef __init__(self, f, *args, **kwargs):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/shard_map_test.py",
"new_path": "tests/shard_map_test.py",
"diff": "@@ -388,6 +388,28 @@ class ShardMapTest(jtu.JaxTestCase):\nx = f()\nself.assertAllCLose(x, jnp.arange(4), check_dtypes=False)\n+ def test_remat_basic(self):\n+ mesh = Mesh(np.array(jax.devices()[:4]), ('x',))\n+\n+ # check param updating is handled\n+ @jax.remat\n+ @partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))\n+ def f(x):\n+ return jnp.sin(x)\n+\n+ x = jnp.arange(4.)\n+ g = jax.grad(lambda x: f(x).sum())(x) # doesn't crash\n+ self.assertAllClose(g, jnp.cos(x), check_dtypes=False)\n+\n+ # also check residuals are handled correctly\n+ @partial(jax.remat, policy=jax.checkpoint_policies.everything_saveable)\n+ @partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))\n+ def f2(x):\n+ return jnp.sin(x)\n+\n+ g2 = jax.grad(lambda x: f2(x).sum())(x) # doesn't crash\n+ self.assertAllClose(g2, jnp.cos(x), check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [shard-map] add remat support, very basic test |
260,631 | 08.02.2023 12:30:55 | 28,800 | 1254d44dbdd74e0171e87a2fe2bc8d6d8c6a308d | Remove silent data corruption runtime flags from persistent cache key.
These flags have no effect on the compiled executable, just the runtime execution. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/compilation_cache.py",
"new_path": "jax/experimental/compilation_cache/compilation_cache.py",
"diff": "@@ -213,6 +213,8 @@ _xla_flags_to_exclude_from_cache_key = [\n\"--xla_force_host_platform_device_count\",\n\"--xla_dump_disable_metadata\",\n\"--xla_dump_hlo_pipeline_re\",\n+ \"--xla_tpu_sdc_checker_streamz_metric\",\n+ \"--xla_tpu_sdc_checker_enable_sdc_event_callbacks\",\n]\nextra_flag_prefixes_to_include_in_cache_key: List[str] = []\n"
}
] | Python | Apache License 2.0 | google/jax | Remove silent data corruption runtime flags from persistent cache key.
These flags have no effect on the compiled executable, just the runtime execution.
PiperOrigin-RevId: 508152877 |
260,335 | 08.02.2023 15:42:35 | 28,800 | 1a03f343834d27d86682d7e3c617cd8e6f977514 | [shard-map] if check_rep=False, don't call rep rules in eager | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/shard_map.py",
"new_path": "jax/experimental/shard_map.py",
"diff": "@@ -491,7 +491,7 @@ def _shard_map_impl(trace, prim, fun, args, *, mesh, in_names, out_names_thunk,\ndel prim\nargs = map(partial(_unmatch_spec, mesh), in_names, args)\nin_rep = map(partial(_in_names_to_rep, mesh), in_names)\n- with core.new_base_main(ShardMapTrace, mesh=mesh) as main:\n+ with core.new_base_main(ShardMapTrace, mesh=mesh, check=check_rep) as main:\nwith core.new_sublevel(), core.extend_axis_env_nd(mesh.shape.items()):\nt = main.with_cur_sublevel()\nin_tracers = map(partial(ShardMapTracer, t), in_rep, args)\n@@ -546,10 +546,12 @@ def _add_singleton(x): return x.reshape(1, *x.shape)\nclass ShardMapTrace(core.Trace):\nmesh: Mesh\n+ check: bool\n- def __init__(self, *args, mesh):\n+ def __init__(self, *args, mesh, check):\nsuper().__init__(*args)\nself.mesh = mesh\n+ self.check = check\ndef pure(self, val):\nval_ = _unmatch_spec(self.mesh, {}, val)\n@@ -564,7 +566,7 @@ class ShardMapTrace(core.Trace):\nwith core.eval_context(), jax.disable_jit(False):\nout_vals = jax.jit(f)(*in_vals)\nrule = _rep_rules.get(prim, partial(_rep_rule, prim))\n- out_rep = rule(self.mesh, *in_rep, **params)\n+ out_rep = rule(self.mesh, *in_rep, **params) if self.check else set()\nif prim.multiple_results:\nout_rep = [out_rep] * len(out_vals) if type(out_rep) is set else out_rep\nreturn map(partial(ShardMapTracer, self), out_rep, out_vals)\n@@ -578,7 +580,10 @@ class ShardMapTrace(core.Trace):\n_rep_rules[fake_primitive] = lambda *_, **__: set()\nout_tracers_ = self.process_primitive(fake_primitive, tracers, params)\nout_vals = [t.val for t in out_tracers_]\n+ if self.check:\nout_rep = _output_rep(self.mesh, jaxpr(), [t.rep for t in tracers])\n+ else:\n+ out_rep = [set()] * len(out_vals)\nreturn map(partial(ShardMapTracer, self), out_rep, out_vals)\n@lu.transformation_with_aux\n@@ -624,11 +629,13 @@ def _prim_applier(prim, params_tup, mesh, *args):\ndef apply(*args):\nouts = prim.bind(*map(_rem_singleton, args), **dict(params_tup))\nreturn tree_map(_add_singleton, outs)\n- return shard_map(apply, mesh, P(mesh.axis_names), P(mesh.axis_names))(*args)\n+ spec = P(mesh.axis_names)\n+ return shard_map(apply, mesh, spec, spec, False)(*args)\n# Static replication checking\n-def _rep_rule(prim, mesh, *in_rep, **params):\n+def _rep_rule(prim: core.Primitive, mesh: Mesh, *in_rep: Set[AxisName],\n+ **params: Any) -> Union[Set[AxisName], List[Set[AxisName]]]:\nraise NotImplementedError(f\"no replication rule for {prim}\")\n_rep_rules: Dict[core.Primitive, Callable] = {}\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/shard_map_test.py",
"new_path": "tests/shard_map_test.py",
"diff": "@@ -157,6 +157,7 @@ class ShardMapTest(jtu.JaxTestCase):\nc = fwd(a)\nself.assertAllClose(c[1, :], a[0, :])\n+ @jtu.skip_on_devices(\"cpu\") # all_to_all has a warning on cpu\ndef test_all_to_all(self):\ndevices = np.array(jax.devices())\nmesh = Mesh(devices, axis_names=('x'))\n@@ -410,6 +411,37 @@ class ShardMapTest(jtu.JaxTestCase):\ng2 = jax.grad(lambda x: f2(x).sum())(x) # doesn't crash\nself.assertAllClose(g2, jnp.cos(x), check_dtypes=False)\n+ def test_check_rep_false_doesnt_hit_rep_rules(self):\n+ mesh = Mesh(np.array(jax.devices()[:4]), ('x',))\n+\n+ prim = jax.core.Primitive('prim') # no rep rule here!\n+ prim.multiple_results = True\n+ prim.def_impl(lambda: [])\n+ prim.def_abstract_eval(lambda: [])\n+\n+ @partial(shard_map, mesh=mesh, in_specs=(), out_specs=None, check_rep=True)\n+ def f():\n+ prim.bind()\n+\n+ with self.assertRaises(NotImplementedError):\n+ f()\n+ with self.assertRaises(NotImplementedError):\n+ jax.jit(f)()\n+\n+ @partial(shard_map, mesh=mesh, in_specs=(), out_specs=None, check_rep=False)\n+ def f2():\n+ prim.bind()\n+\n+ f2()\n+ jax.jit(f2)()\n+\n+ @partial(shard_map, mesh=mesh, in_specs=(), out_specs=None, check_rep=False)\n+ def f3():\n+ jax.jit(prim.bind)()\n+\n+ f3()\n+ jax.jit(f3)()\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [shard-map] if check_rep=False, don't call rep rules in eager |
260,335 | 08.02.2023 23:31:07 | 28,800 | 6fb3ace5d0aa426408a09880e4f8a576c39a7add | [shard-map] add vmap spmd_axis_name support, fix vmap rule bug | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/shard_map.py",
"new_path": "jax/experimental/shard_map.py",
"diff": "@@ -371,7 +371,8 @@ def _shard_map_staging(\nwith core.extend_axis_env_nd(mesh.shape.items()):\njaxpr = pe.convert_constvars_jaxpr(jaxpr)\nparams = dict(mesh=mesh, in_names=in_names_staged,\n- out_names=out_names_thunk(), jaxpr=jaxpr, check_rep=check_rep)\n+ out_names=tuple(out_names_thunk()), jaxpr=jaxpr,\n+ check_rep=check_rep)\neqn = pe.new_jaxpr_eqn([*constvars, *invars], outvars, prim, params,\njaxpr.effects, source_info)\ntrace.frame.add_eqn(eqn)\n@@ -701,18 +702,25 @@ def _shard_map_batch(\nif all(bdim is batching.not_mapped for bdim in in_dims):\nreturn prim.bind(fun, *in_vals, mesh=mesh, in_names=in_names,\nout_names_thunk=out_names_thunk, check_rep=check_rep)\n- if trace.spmd_axis_name is not None:\n- raise NotImplementedError # TODO add named axis to specs\nif any(isinstance(d, batching.ConcatAxis) for d in in_dims):\nraise NotImplementedError\nfun, out_dims = batching.batch_subtrace(fun, trace.main, tuple(in_dims))\n- new_in_names = [{ax + (d is not batching.not_mapped and ax <= d): names[ax] # type: ignore\n+ new_in_names = [{ax + (d is not batching.not_mapped and d <= ax): names[ax] # type: ignore\nfor ax in names} for names, d in zip(in_names, in_dims)]\n+ spmd_axis_name = trace.spmd_axis_name\n+ if spmd_axis_name is not None:\n+ new_in_names = [{**ns, d:(spmd_axis_name,)} if d is not batching.not_mapped # type: ignore\n+ else ns for ns, d in zip(new_in_names, in_dims)]\n@as_hashable_function(closure=out_names_thunk)\ndef new_out_names_thunk():\nout_names = out_names_thunk()\n- return [{ax + (d is not batching.not_mapped and ax <= d): names[ax]\n+ out_names_ = [{ax + (d is not batching.not_mapped and d <= ax): names[ax]\nfor ax in names} for names, d in zip(out_names, out_dims())]\n+ if spmd_axis_name is not None:\n+ out_names_ = [{**ns, d:(spmd_axis_name,)} if d is not batching.not_mapped\n+ else ns for ns, d in zip(out_names_, out_dims())]\n+ return out_names_\n+\nnew_params = dict(mesh=mesh, in_names=new_in_names,\nout_names_thunk=new_out_names_thunk, check_rep=check_rep)\nout_vals = prim.bind(fun, *in_vals, **new_params)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/shard_map_test.py",
"new_path": "tests/shard_map_test.py",
"diff": "@@ -442,6 +442,21 @@ class ShardMapTest(jtu.JaxTestCase):\nf3()\njax.jit(f3)()\n+ def test_vmap_spmd_axis_name(self):\n+ mesh = Mesh(np.array(jax.devices()[:4]).reshape(2, 2), ('x', 'y'))\n+\n+ @partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))\n+ def f(x):\n+ return x\n+\n+ x = jnp.arange(4 * 4).reshape(4, 4)\n+ jaxpr = jax.make_jaxpr(jax.vmap(f, spmd_axis_name='y'))(x).jaxpr\n+ e, = jaxpr.eqns\n+ self.assertIn('in_names', e.params)\n+ self.assertEqual(e.params['in_names'], ({0: ('y',), 1: ('x',)},))\n+ self.assertIn('out_names', e.params)\n+ self.assertEqual(e.params['out_names'], ({0: ('y',), 1: ('x',)},))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [shard-map] add vmap spmd_axis_name support, fix vmap rule bug |
260,294 | 07.02.2023 18:50:36 | 0 | 023226e181d2dcafa018f7ba8ed846d93f7f0774 | [ROCm]: Move dockerfile to ROCm5.4 | [
{
"change_type": "MODIFY",
"old_path": "build/rocm/Dockerfile.rocm",
"new_path": "build/rocm/Dockerfile.rocm",
"diff": "FROM ubuntu:focal\n-MAINTAINER Reza Rahimi <reza.rahimi@amd.com>\n+MAINTAINER Rahul Batra<rahbatra@amd.com>\n-ARG ROCM_DEB_REPO=http://repo.radeon.com/rocm/apt/5.3/\n+ARG ROCM_DEB_REPO=http://repo.radeon.com/rocm/apt/5.4/\nARG ROCM_BUILD_NAME=ubuntu\nARG ROCM_BUILD_NUM=main\n-ARG ROCM_PATH=/opt/rocm-5.3.0\n+ARG ROCM_PATH=/opt/rocm-5.4.0\nARG DEBIAN_FRONTEND=noninteractive\nENV HOME /root/\n"
}
] | Python | Apache License 2.0 | google/jax | [ROCm]: Move dockerfile to ROCm5.4 |
260,294 | 09.02.2023 20:18:00 | 0 | 7d0d9b706eceb89ab18ccd33c93ffb5cc788f504 | [ROCm]: Re-enable Dirichlet Tests on ROCm | [
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -861,7 +861,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nalpha=[np.array([0.2, 1., 5.]),],\ndtype=jtu.dtypes.floating,\n)\n- @jtu.skip_on_devices(\"tpu\",\"rocm\") # TODO(mattjj): slow compilation times\n+ @jtu.skip_on_devices(\"tpu\") # TODO(mattjj): slow compilation times\ndef testDirichlet(self, alpha, dtype):\nkey = self.seed_prng(0)\nrand = lambda key, alpha: random.dirichlet(key, alpha, (10000,), dtype)\n@@ -876,7 +876,6 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor i, a in enumerate(alpha):\nself._CheckKolmogorovSmirnovCDF(samples[..., i], scipy.stats.beta(a, alpha_sum - a).cdf)\n- @jtu.skip_on_devices(\"rocm\")\ndef testDirichletSmallAlpha(self, dtype=np.float32):\n# Regression test for https://github.com/google/jax/issues/9896\nkey = self.seed_prng(0)\n"
}
] | Python | Apache License 2.0 | google/jax | [ROCm]: Re-enable Dirichlet Tests on ROCm |
260,335 | 09.02.2023 11:02:24 | 28,800 | a964dc3b9a7e8c26fe979e00b782f79ba824f042 | simpler pretty-print for pjit, tweak custom pp rule signature | [
{
"change_type": "MODIFY",
"old_path": "docs/jaxpr.rst",
"new_path": "docs/jaxpr.rst",
"diff": "@@ -416,10 +416,6 @@ which the computation should run. For example\n{ lambda ; a:f32[]. let\nb:f32[] = sub a 2.0\nc:f32[1] = pjit[\n- donated_invars=(False, False)\n- in_positional_semantics=(<_PositionalSemantics.GLOBAL: 1>, <_PositionalSemantics.GLOBAL: 1>)\n- in_shardings=(<jax._src.interpreters.pxla.UnspecifiedValue object ...>, <jax._src.interpreters.pxla.UnspecifiedValue object ...>)\n- inline=False\njaxpr={ lambda ; d:f32[] e:f32[]. let\nf:f32[1] = broadcast_in_dim[broadcast_dimensions=() shape=(1,)] 1.0\ng:f32[] = convert_element_type[new_dtype=float32 weak_type=False] d\n@@ -427,11 +423,7 @@ which the computation should run. For example\ni:f32[] = convert_element_type[new_dtype=float32 weak_type=False] e\nj:f32[1] = add i h\nin (j,) }\n- keep_unused=False\nname=inner\n- out_positional_semantics=_PositionalSemantics.GLOBAL\n- out_shardings=(<jax._src.interpreters.pxla.UnspecifiedValue object ...>,)\n- resource_env=None\n] a b\nk:f32[] = convert_element_type[new_dtype=float32 weak_type=False] a\nl:f32[1] = add k c\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/core.py",
"new_path": "jax/_src/core.py",
"diff": "@@ -2867,19 +2867,22 @@ def pp_kv_pairs(kv_pairs, context: JaxprPpContext, settings: JaxprPpSettings) ->\n+ pp.brk(\"\") + pp.text(\"]\")\n)\n-def pp_eqn(eqn, context: JaxprPpContext, settings: JaxprPpSettings) -> pp.Doc:\n+def pp_eqn(eqn: JaxprEqn, context: JaxprPpContext, settings: JaxprPpSettings\n+ ) -> pp.Doc:\n+ rule = (_pp_eqn if not settings.custom_pp_eqn_rules else\n+ pp_eqn_rules.get(eqn.primitive, _pp_eqn))\n+ return rule(eqn, context, settings)\n+\n+def _pp_eqn(eqn, context, settings) -> pp.Doc:\nannotation = (source_info_util.summarize(eqn.source_info)\nif settings.source_info else None)\n- rule = pp_eqn_rules.get(eqn.primitive)\nname_stack_annotation = f'[{eqn.source_info.name_stack}]' if settings.name_stack else None\n- if rule and settings.custom_pp_eqn_rules:\n- return pp.concat(rule(eqn, context, settings))\nlhs = pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\nrhs = [pp.text(eqn.primitive.name, annotation=name_stack_annotation),\npp_kv_pairs(sorted(eqn.params.items()), context, settings),\npp.text(\" \") + pp_vars(eqn.invars, context)]\nreturn pp.concat([lhs, pp.text(\" = \", annotation=annotation), *rhs])\n-CustomPpEqnRule = Callable[[JaxprEqn, JaxprPpContext, JaxprPpSettings], Sequence[pp.Doc]]\n+CustomPpEqnRule = Callable[[JaxprEqn, JaxprPpContext, JaxprPpSettings], pp.Doc]\npp_eqn_rules: Dict[Primitive, CustomPpEqnRule] = {}\ndef pp_eqns(eqns, context: JaxprPpContext, settings: JaxprPpSettings) -> pp.Doc:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/interpreters/xla.py",
"new_path": "jax/_src/interpreters/xla.py",
"diff": "@@ -21,8 +21,8 @@ from functools import partial\nimport itertools as it\nimport operator\nimport re\n-from typing import (Any, Callable, Dict, List, NamedTuple, Optional,\n- Protocol, Sequence, Set, Type, Tuple, Union)\n+from typing import (Any, Callable, Dict, NamedTuple, Optional, Protocol,\n+ Sequence, Set, Type, Tuple, Union)\nimport numpy as np\n@@ -475,19 +475,13 @@ pe.padding_rules[xla_call_p] = partial(pe.call_padding_rule, xla_call_p)\ndef _pp_xla_call(eqn: core.JaxprEqn, context: core.JaxprPpContext,\nsettings: core.JaxprPpSettings,\n- ) -> List[pp.Doc]:\n+ ) -> pp.Doc:\nprinted_params = {k:v for k, v in eqn.params.items() if\nk == 'call_jaxpr' or k == 'name' or\nk == 'backend' and v is not None or\nk == 'device' and v is not None or\nk == 'donated_invars' and any(v)}\n- annotation = (source_info_util.summarize(eqn.source_info)\n- if settings.source_info else None)\n- lhs = core.pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\n- rhs = [pp.text(eqn.primitive.name),\n- core.pp_kv_pairs(sorted(printed_params.items()), context, settings),\n- pp.text(\" \") + core.pp_vars(eqn.invars, context)]\n- return [lhs, pp.text(\" = \", annotation=annotation), *rhs]\n+ return core._pp_eqn(eqn.replace(params=printed_params), context, settings)\ncore.pp_eqn_rules[xla_call_p] = _pp_xla_call\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/loops.py",
"new_path": "jax/_src/lax/control_flow/loops.py",
"diff": "@@ -20,7 +20,7 @@ from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar\nimport jax\nimport weakref\n-from jax import core\n+from jax._src import core\nfrom jax._src import linear_util as lu\nfrom jax.config import config\nfrom jax.core import ConcreteArray, ShapedArray, raise_to_shaped\n@@ -29,7 +29,6 @@ from jax.interpreters import batching\nfrom jax._src.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n-import jax._src.pretty_printer as pp\nfrom jax.tree_util import (tree_flatten, tree_unflatten, treedef_is_leaf,\ntree_map)\nfrom jax._src import ad_checkpoint\n@@ -964,14 +963,7 @@ def _scan_pp_rule(eqn, context, settings):\ndel printed_params['num_consts']\nif not printed_params['reverse']:\ndel printed_params['reverse']\n- lhs = core.pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\n- rhs = [pp.text(eqn.primitive.name),\n- core.pp_kv_pairs(sorted(printed_params.items()), context, settings),\n- pp.text(\" \") + core.pp_vars(eqn.invars, context)]\n- annotation = (source_info_util.summarize(eqn.source_info)\n- if settings.source_info else None)\n- return [lhs, pp.text(\" = \", annotation=annotation), *rhs]\n-\n+ return core._pp_eqn(eqn.replace(params=printed_params), context, settings)\ndef scan_bind(*args, **params):\nif config.jax_enable_checks:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -2383,16 +2383,10 @@ def _convert_elt_type_fwd_rule(eqn):\ndef _convert_elt_type_pp_rule(eqn, context, settings):\n# don't print new_dtype because the output binder shows it, don't print\n# weak_type when false\n- printed_params = {}\n- if eqn.params['weak_type']:\n- printed_params['weak_type'] = True\n- lhs = core.pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\n- rhs = [pp.text(eqn.primitive.name),\n- core.pp_kv_pairs(sorted(printed_params.items()), context, settings),\n- pp.text(\" \") + core.pp_vars(eqn.invars, context)]\n- annotation = (source_info_util.summarize(eqn.source_info)\n- if settings.source_info else None)\n- return [lhs, pp.text(\" = \", annotation=annotation), *rhs]\n+ params = dict(eqn.params)\n+ del params['new_dtype'] # output binder shows it\n+ if not params['weak_type']: del params['weak_type'] # don't show trivial case\n+ return core._pp_eqn(eqn.replace(params=params), context, settings)\nconvert_element_type_p = Primitive('convert_element_type')\nconvert_element_type_p.def_impl(partial(xla.apply_primitive, convert_element_type_p))\n@@ -2685,21 +2679,14 @@ def _dot_general_padding_rule(in_avals, out_avals, lhs, rhs, *,\nlhs_ = _replace_masked_values(lhs, 0, padded_axes)\nreturn [dot_general(lhs_, rhs, dimension_numbers=dimension_numbers, **params)]\n-def _dot_general_pp_rule(eqn, context, settings):\n+def _dot_general_pp_rule(eqn, context, settings) -> pp.Doc:\n# * suppress printing precision or preferred_element_type when None.\n# * print dimension_numbers as list-of-lists to be shorter.\nprinted_params = {k: v for k, v in eqn.params.items() if v is not None}\n(lhs_cont, rhs_cont), (lhs_batch, rhs_batch) = eqn.params['dimension_numbers']\nprinted_params['dimension_numbers'] = (\n(list(lhs_cont), list(rhs_cont)), (list(lhs_batch), list(rhs_batch)))\n- lhs = core.pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\n- rhs = [pp.text(eqn.primitive.name),\n- core.pp_kv_pairs(sorted(printed_params.items()), context, settings),\n- pp.text(\" \") + core.pp_vars(eqn.invars, context)]\n- annotation = (source_info_util.summarize(eqn.source_info)\n- if settings.source_info else None)\n- return [lhs, pp.text(\" = \", annotation=annotation), *rhs]\n-\n+ return core._pp_eqn(eqn.replace(params=printed_params), context, settings)\ndot_general_p = standard_primitive(_dot_general_shape_rule,\n_dot_general_dtype_rule, 'dot_general')\n@@ -2917,13 +2904,8 @@ def _broadcast_in_dim_pp_rule(eqn, context, settings):\nprinted_params = {}\nif eqn.params['broadcast_dimensions']:\nprinted_params['broadcast_dimensions'] = eqn.params['broadcast_dimensions']\n- lhs = core.pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\n- rhs = [pp.text(eqn.primitive.name),\n- core.pp_kv_pairs(sorted(printed_params.items()), context, settings),\n- pp.text(\" \") + core.pp_vars(eqn.invars[:1], context)]\n- annotation = (source_info_util.summarize(eqn.source_info)\n- if settings.source_info else None)\n- return [lhs, pp.text(\" = \", annotation=annotation), *rhs]\n+ new_eqn = eqn.replpace(params=printed_params, invars=eqn.invars[:1])\n+ return core._pp_eqn(new_eqn, context, settings)\ndef _broadcast_in_dim_abstract_eval(x, *dyn_shape, shape, broadcast_dimensions):\nif dyn_shape: raise NotImplementedError\n@@ -4521,13 +4503,7 @@ def _iota_pp_rule(eqn, context, settings):\nprinted_params = {}\nif len(eqn.params['shape']) > 1:\nprinted_params['dimension'] = eqn.params['dimension']\n- lhs = core.pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\n- rhs = [pp.text(eqn.primitive.name),\n- core.pp_kv_pairs(sorted(printed_params.items()), context, settings),\n- pp.text(\" \") + core.pp_vars(eqn.invars, context)]\n- annotation = (source_info_util.summarize(eqn.source_info)\n- if settings.source_info else None)\n- return [lhs, pp.text(\" = \", annotation=annotation), *rhs]\n+ return core._pp_eqn(eqn.replace(params=printed_params), context, settings)\n# core.pp_eqn_rules[iota_p] = _iota_pp_rule\ndef _iota_padding_rule(in_avals, out_avals, *dyn_shape, dtype, shape, dimension):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/pjit.py",
"new_path": "jax/_src/pjit.py",
"diff": "@@ -24,7 +24,7 @@ import threading\nimport warnings\nimport jax\n-from jax import core\n+from jax._src import core\nfrom jax import stages\nfrom jax.errors import JAXTypeError\nfrom jax.experimental.global_device_array import GlobalDeviceArray as GDA\n@@ -1841,6 +1841,29 @@ def _resource_typing_pjit(avals, params, source_info, resource_env, named_axis_r\npxla.custom_resource_typing_rules[pjit_p] = _resource_typing_pjit\n+def _pjit_pp_rule(eqn, context, settings):\n+ params = dict(eqn.params)\n+ del params['inline']\n+ if not any(params['donated_invars']):\n+ del params['donated_invars']\n+ if all(p == pxla._PositionalSemantics.GLOBAL\n+ for p in params['in_positional_semantics']):\n+ del params['in_positional_semantics']\n+ if params['out_positional_semantics'] == pxla._PositionalSemantics.GLOBAL:\n+ del params['out_positional_semantics']\n+ if all(pxla._is_unspecified(s) for s in params['in_shardings']):\n+ del params['in_shardings']\n+ if all(pxla._is_unspecified(s) for s in params['out_shardings']):\n+ del params['out_shardings']\n+ if not params['keep_unused']:\n+ del params['keep_unused']\n+ if (params['resource_env'] is None or\n+ params['resource_env'].physical_mesh.empty):\n+ del params['resource_env']\n+ return core._pp_eqn(eqn.replace(params=params), context, settings)\n+core.pp_eqn_rules[pjit_p] = _pjit_pp_rule\n+\n+\n# -------------------- with_sharding_constraint --------------------\ndef with_sharding_constraint(x, axis_resources):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/primitives.py",
"new_path": "jax/_src/state/primitives.py",
"diff": "@@ -227,19 +227,18 @@ def _pp_idx(context, non_slice_idx, indexed_dims):\nassert next(idx_iter, None) is None\nreturn pp.text(idx)\n-def _get_pp_rule(eqn, context, settings):\n+def _get_pp_rule(eqn, context, settings) -> pp.Doc:\n# Pretty prints `a = get x i` as `x[i] <- a`\ny, = eqn.outvars\nx, *idx = eqn.invars\nidx = _pp_idx(context, idx, eqn.params[\"indexed_dims\"])\nlhs = core.pp_vars([y], context, print_shapes=settings.print_shapes)\n# TODO more general get\n- return [lhs, pp.text(' <- '), pp_ref(pp.concat([\n- pp.text(core.pp_var(x, context)), pp.text('['), idx, pp.text(']')\n- ]))]\n+ return pp.concat([lhs, pp.text(' <- '), pp_ref(pp.concat([\n+ pp.text(core.pp_var(x, context)), pp.text('['), idx, pp.text(']')]))])\ncore.pp_eqn_rules[get_p] = _get_pp_rule\n-def _swap_pp_rule(eqn, context, settings):\n+def _swap_pp_rule(eqn, context, settings) -> pp.Doc:\ny, = eqn.outvars\nx, v, *idx = eqn.invars\nidx = _pp_idx(context, idx, eqn.params[\"indexed_dims\"])\n@@ -247,30 +246,31 @@ def _swap_pp_rule(eqn, context, settings):\n# In the case of a set (ignored return value),\n# pretty print `_ = swap x v i` as `x[i] <- v`\ndel y\n- return [\n+ return pp.concat([\npp_ref(pp.concat([\npp.text(core.pp_var(x, context)),\npp.text('['), idx, pp.text(']')\n- ])), pp.text(' <- '), pp.text(core.pp_var(v, context))]\n+ ])), pp.text(' <- '), pp.text(core.pp_var(v, context))])\nelse:\n# pretty-print `y:T = swap x v i` as `y:T, x[i] <- x[i], v`\nx_i = pp.concat([pp.text(core.pp_var(x, context)),\npp.text('['), idx, pp.text(']')])\ny = core.pp_vars([y], context, print_shapes=settings.print_shapes)\n- return [y, pp.text(', '), pp_ref(x_i), pp.text(' <- '),\n- pp_ref(x_i), pp.text(', '), pp.text(core.pp_var(v, context))]\n+ return pp.concat([y, pp.text(', '), pp_ref(x_i), pp.text(' <- '),\n+ pp_ref(x_i), pp.text(', '),\n+ pp.text(core.pp_var(v, context))])\ncore.pp_eqn_rules[swap_p] = _swap_pp_rule\n-def _addupdate_pp_rule(eqn, context, settings):\n+def _addupdate_pp_rule(eqn, context, settings) -> pp.Doc:\n# pretty-print ` = addupdate x i v` as `x[i] += v`\n() = eqn.outvars\nx, v, *idx = eqn.invars\nidx = _pp_idx(context, idx, eqn.params[\"indexed_dims\"])\n- return [\n+ return pp.concat([\npp_ref(pp.concat([\npp.text(core.pp_var(x, context)),\npp.text('['), idx, pp.text(']')\n- ])), pp.text(' += '), pp.text(core.pp_var(v, context))]\n+ ])), pp.text(' += '), pp.text(core.pp_var(v, context))])\ncore.pp_eqn_rules[addupdate_p] = _addupdate_pp_rule\n## get/swap/addupdate JVP rules\n"
}
] | Python | Apache License 2.0 | google/jax | simpler pretty-print for pjit, tweak custom pp rule signature |
260,542 | 09.02.2023 14:33:05 | 28,800 | 668b82d529e2649f1dbf7cdf9ec8d934fda09a19 | [PJRT C API] Register a backend factory for every PJRT plugin set in PJRT_NAMES_AND_LIBRARY_PATHS.
Loading TPU PJRT plugin is moved to make_tpu_client.
This change is based on | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lib/xla_bridge.py",
"new_path": "jax/_src/lib/xla_bridge.py",
"diff": "@@ -254,6 +254,71 @@ if hasattr(xla_client, \"make_plugin_device_client\"):\nregister_backend_factory(\"plugin\", xla_client.make_plugin_device_client,\npriority=400)\n+\n+def _get_pjrt_plugin_names_and_library_paths(\n+ plugins_from_env: str,\n+) -> Dict[str, str]:\n+ \"\"\"Gets the names and library paths of PJRT plugins to load from env var.\n+\n+ Args:\n+ plugins_from_env: plugin name and pathes from env var. It is in the format\n+ of 'name1:path1,name2:path2' ('name1;path1,name2;path2' for windows).\n+\n+ Returns:\n+ A dict of {plugin_name: library path} for the PJRT plugins to load.\n+ \"\"\"\n+ if not plugins_from_env:\n+ return {}\n+\n+ pjrt_plugins = {}\n+ for plugin in plugins_from_env.split(','):\n+ try:\n+ name, library_path = plugin.split(os.path.pathsep)\n+ pjrt_plugins[name] = library_path\n+ except ValueError:\n+ logger.warning(\n+ 'invalid value %s in env var PJRT_NAMES_AND_LIBRARY_PATHS %s',\n+ plugin,\n+ plugins_from_env,\n+ )\n+ return pjrt_plugins\n+\n+\n+def register_pjrt_plugin_factories(plugins_from_env: str):\n+ \"\"\"Registers backend factories for PJRT plugins.\n+\n+ A backend factory will be registered for every PJRT plugin in the input\n+ string, in the format of 'name1:path1,name2:path2' ('name1;path1,name2;path2'\n+ for windows). TPU PJRT plugin will be loaded and registered separately in\n+ make_tpu_client.\n+ \"\"\"\n+\n+ def make_factory(name, path):\n+ def factory():\n+ xla_client.load_pjrt_plugin_dynamically(name, path)\n+ return xla_client.make_c_api_client(name)\n+\n+ return factory\n+\n+ pjrt_plugins = _get_pjrt_plugin_names_and_library_paths(plugins_from_env)\n+ for plugin_name, library_path in pjrt_plugins.items():\n+ logger.debug(\n+ 'registering PJRT plugin %s from %s', plugin_name, library_path\n+ )\n+ # It is assumed that if a plugin is installed, then the user wants to use\n+ # the plugin by default. Therefore, plugins get the highest priority.\n+ # For a PJRT plugin, its plugin_name is the same as its platform_name.\n+ register_backend_factory(\n+ plugin_name, make_factory(plugin_name, library_path), priority=400\n+ )\n+\n+\n+if lib.xla_extension_version >= 126:\n+ # The plugin names and paths are set in env var PJRT_NAMES_AND_LIBRARY_PATHS,\n+ # in the format of 'name1:path1,name2:path2' ('name1;path1,name2;path2' for\n+ # windows).\n+ register_pjrt_plugin_factories(os.getenv('PJRT_NAMES_AND_LIBRARY_PATHS', ''))\n+\nif iree is not None:\nregister_backend_factory(\"iree\", iree.iree_client_factory, priority=-100)\n@@ -328,8 +393,6 @@ def backends():\n(platform, priority) for platform, (_, priority)\nin _backend_factories.items())\ndefault_priority = -1000\n- if hasattr(xla_client, \"maybe_load_pjrt_plugins\"):\n- xla_client.maybe_load_pjrt_plugins()\nfor platform, priority in platforms_and_priorites:\ntry:\nbackend = _init_backend(platform)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/xla_bridge_test.py",
"new_path": "tests/xla_bridge_test.py",
"diff": "@@ -89,6 +89,30 @@ class XlaBridgeTest(jtu.JaxTestCase):\nside_effect=_mock_tpu_client):\nxb.tpu_client_timer_callback(0.01)\n+ def test_register_plugin(self):\n+ if xc._version < 126:\n+ return\n+\n+ with self.assertLogs(level=\"WARNING\") as log_output:\n+ xb.register_pjrt_plugin_factories(\"name1:path1,name2:path2,name3\")\n+ client_factory, priotiy = xb._backend_factories[\"name1\"]\n+ with mock.patch.object(xc, \"make_c_api_client\", autospec=True) as mock_make:\n+ with mock.patch.object(\n+ xc, \"load_pjrt_plugin_dynamically\", autospec=True\n+ ) as mock_load_plugin:\n+ client_factory()\n+\n+ self.assertRegex(\n+ log_output[1][0],\n+ r\"invalid value name3 in env var PJRT_NAMES_AND_LIBRARY_PATHS\"\n+ r\" name1:path1,name2:path2,name3\",\n+ )\n+ self.assertIn(\"name1\", xb._backend_factories)\n+ self.assertIn(\"name2\", xb._backend_factories)\n+ self.assertEqual(priotiy, 400)\n+ mock_load_plugin.assert_called_once_with(\"name1\", \"path1\")\n+ mock_make.assert_called_once_with(\"name1\")\n+\nclass GetBackendTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | [PJRT C API] Register a backend factory for every PJRT plugin set in PJRT_NAMES_AND_LIBRARY_PATHS.
Loading TPU PJRT plugin is moved to make_tpu_client.
This change is based on https://github.com/google/jax/pull/14011.
PiperOrigin-RevId: 508477737 |
287,654 | 09.01.2017 10:42:41 | 28,800 | b41be2b74d5990891b6f3bac9b16be55760e7df2 | Remove compact call on Array and Set in sanitizer. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -64,6 +64,10 @@ adheres to [Semantic Versioning](http://semver.org/).\n- The deprecated `Honeybadger::Rack::MetricsReporter` middleware has been\nremoved.\n+### Fixed\n+- Arrays are no longer compacted during sanitization (`nil` values will be sent\n+ as they originally appeared).\n+\n## [2.7.2] - 2016-12-12\n### Fixed\n- Pass whole exception to `notify_or_ignore` (includes causes). -@CGamesPlay\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/util/sanitizer.rb",
"new_path": "lib/honeybadger/util/sanitizer.rb",
"diff": "@@ -84,7 +84,7 @@ module Honeybadger\nreturn '[max depth reached]'.freeze if depth >= max_depth\ndata.to_a.map do |value|\nsanitize(value, depth+1, stack, parents)\n- end.compact\n+ end\nwhen Numeric, TrueClass, FalseClass, NilClass\ndata\nwhen String\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Remove compact call on Array and Set in sanitizer. |
287,654 | 09.01.2017 10:54:44 | 28,800 | 05c54c6e3545c2f6170c8728bf33f41998f9058b | Release 3.0.0.beta3 | [
{
"change_type": "MODIFY",
"old_path": "gemfiles/binding_of_caller.gemfile",
"new_path": "gemfiles/binding_of_caller.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"binding_of_caller\"\ngemspec :path => \"../\"\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/delayed_job.gemfile",
"new_path": "gemfiles/delayed_job.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"delayed_job\", \"< 4.1.2\"\ngemspec :path => \"../\"\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/rack.gemfile",
"new_path": "gemfiles/rack.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"rack\", \">= 2.0.0\"\ngemspec :path => \"../\"\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/rack_1.gemfile",
"new_path": "gemfiles/rack_1.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"rack\", \"< 2.0\"\ngemspec :path => \"../\"\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/rails.gemfile",
"new_path": "gemfiles/rails.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\", \"~> 3.0\"\ngem \"rake\"\n+gem \"listen\"\ngem \"rails\", :github => \"rails/rails\"\ngem \"rack\", :github => \"rack/rack\"\ngem \"arel\", :github => \"rails/arel\"\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/rails3.2.gemfile",
"new_path": "gemfiles/rails3.2.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\", \"~> 2.0\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"rails\", \"~> 3.2.12\"\ngem \"better_errors\", :require => false, :platforms => [:ruby_20, :ruby_21]\ngem \"rack-mini-profiler\", :require => false\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/rails4.0.gemfile",
"new_path": "gemfiles/rails4.0.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"rails\", \"~> 4.0.0\"\ngem \"better_errors\", :require => false, :platforms => [:ruby_20, :ruby_21]\ngem \"rack-mini-profiler\", :require => false\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/rails4.1.gemfile",
"new_path": "gemfiles/rails4.1.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"rails\", \"~> 4.1.4\"\ngem \"better_errors\", :require => false, :platforms => [:ruby_20, :ruby_21]\ngem \"rack-mini-profiler\", :require => false\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/rails4.2.gemfile",
"new_path": "gemfiles/rails4.2.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"rails\", \"~> 4.2.4\"\ngem \"better_errors\", :require => false, :platforms => [:ruby_20, :ruby_21]\ngem \"rack-mini-profiler\", :require => false\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/rails5.0.gemfile",
"new_path": "gemfiles/rails5.0.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"rails\", \"~> 5.0.0\"\ngem \"better_errors\", :require => false, :platforms => [:ruby_20, :ruby_21]\ngem \"rack-mini-profiler\", :require => false\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/sinatra.gemfile",
"new_path": "gemfiles/sinatra.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"sinatra\", \"~> 2.0.0.beta1\"\ngem \"rack-test\"\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/sinatra_1.gemfile",
"new_path": "gemfiles/sinatra_1.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,6 +17,7 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngem \"sinatra\", \"< 2.0\"\ngem \"rack-test\"\n"
},
{
"change_type": "MODIFY",
"old_path": "gemfiles/standalone.gemfile",
"new_path": "gemfiles/standalone.gemfile",
"diff": "@@ -7,7 +7,6 @@ gem \"appraisal\", \"~> 2.1\"\ngem \"aruba\", \"~> 0.14\"\ngem \"guard\"\ngem \"guard-rspec\"\n-gem \"listen\", \"~> 3.0.8\"\ngem \"pry\"\ngem \"pry-byebug\", :platforms => :mri\ngem \"rdoc\"\n@@ -18,5 +17,6 @@ gem \"timecop\"\ngem \"webmock\"\ngem \"capistrano\"\ngem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\ngemspec :path => \"../\"\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/version.rb",
"new_path": "lib/honeybadger/version.rb",
"diff": "module Honeybadger\n# Public: The current String Honeybadger version.\n- VERSION = '3.0.0.beta2'.freeze\n+ VERSION = '3.0.0.beta3'.freeze\nend\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Release 3.0.0.beta3 |
287,654 | 16.01.2017 09:00:03 | 28,800 | 8fdf1d1c57ae0755eb4a055b3d68826692c16536 | Update allocation_stats traceer. | [
{
"change_type": "MODIFY",
"old_path": "tools/allocation_stats.rb",
"new_path": "tools/allocation_stats.rb",
"diff": "@@ -10,15 +10,18 @@ group_by = if ENV['GROUP']\nputs Benchmark.measure {\nstats = AllocationStats.trace do\n- if Honeybadger.start({:api_key => 'badgers', :backend => 'null'})\n+ Honeybadger.configure do |config|\n+ config.api_key = 'badgers'\n+ config.backend = 'null'\n+ end\n+\n1000.times do\nHoneybadger.notify(error_class: 'RubyProf', error_message: 'Profiling Honeybadger -- this should never actually be reported.')\nend\nend\n- end\n- Honeybadger::Agent.at_exit do\n+ Honeybadger.flush\n+\nputs \"\\n\\n\"\nputs stats.allocations(alias_paths: true).group_by(*group_by).to_text\n- end\n}\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Update allocation_stats traceer. |
287,654 | 16.01.2017 09:00:38 | 28,800 | 45e1919273b0c519a9bb3d1cd62404aff229f477 | Allocate fewer arrays when fetching config values. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/config.rb",
"new_path": "lib/honeybadger/config.rb",
"diff": "@@ -31,6 +31,8 @@ module Honeybadger\nNOT_BLANK = Regexp.new('\\S').freeze\n+ IVARS = [:@ruby, :@env, :@yaml, :@framework].freeze\n+\ndef initialize(opts = {})\n@ruby = opts.freeze\n@env = {}.freeze\n@@ -78,7 +80,7 @@ module Honeybadger\nend\ndef get(key)\n- [:@ruby, :@env, :@yaml, :@framework].each do |var|\n+ IVARS.each do |var|\nsource = instance_variable_get(var)\nif source.has_key?(key)\nreturn source[key]\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Allocate fewer arrays when fetching config values. |
287,654 | 16.01.2017 09:27:21 | 28,800 | 2a311e6a72ec357298648363ed0433be214106a0 | Allocate fewer arrays in backtrace. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/backtrace.rb",
"new_path": "lib/honeybadger/backtrace.rb",
"diff": "@@ -37,8 +37,11 @@ module Honeybadger\nend\nif filtered_line\n- _, file, number, method = unparsed_line.match(INPUT_FORMAT).to_a\n- _, *filtered_args = filtered_line.match(INPUT_FORMAT).to_a\n+ match = unparsed_line.match(INPUT_FORMAT) || [].freeze\n+ fmatch = filtered_line.match(INPUT_FORMAT) || [].freeze\n+\n+ file, number, method = match[1], match[2], match[3]\n+ filtered_args = [fmatch[1], fmatch[2], fmatch[3]]\nnew(file, number, method, *filtered_args, opts.fetch(:source_radius, 2))\nelse\nnil\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Allocate fewer arrays in backtrace. |
287,654 | 16.01.2017 10:30:30 | 28,800 | 874b0726b203187dd4a0b44a97ab7918cf8af7fe | Add tests for deploy and exec cli commands. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/cli/deploy.rb",
"new_path": "lib/honeybadger/cli/deploy.rb",
"diff": "@@ -22,9 +22,8 @@ module Honeybadger\nlocal_username: options['user']\n}\n- http = Util::HTTP.new(config)\n- result = http.post('/v1/deploys', payload)\n- if result.code == '201'\n+ result = config.backend.notify(:deploys, payload)\n+ if result.success?\nsay(\"Deploy notification complete.\", :green)\nelse\nsay(\"Invalid response from server: #{result.code}\", :red)\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/cli/exec.rb",
"new_path": "lib/honeybadger/cli/exec.rb",
"diff": "@@ -74,16 +74,14 @@ MSG\n}\n}\n- http = Util::HTTP.new(config)\n-\nbegin\n- response = http.post('/v1/notices', payload)\n+ response = config.backend.notify(:notices, payload)\nrescue\nsay(result.msg)\nraise\nend\n- if response.code != '201'\n+ if !response.success?\nsay(result.msg)\nsay(\"\\nFailed to notify Honeybadger: #{response.code}\", :red)\nexit(1)\n@@ -110,9 +108,10 @@ MSG\ndef exec_cmd\nstdout, stderr, status = Open3.capture3(args.join(' '))\n+ success = status.success? && stderr =~ BLANK\npid = status.pid\ncode = status.to_i\n- msg = ERB.new(FAILED_TEMPLATE).result(binding) unless status.success?\n+ msg = ERB.new(FAILED_TEMPLATE).result(binding) unless success\nOpenStruct.new(\nmsg: msg,\n@@ -120,7 +119,7 @@ MSG\ncode: code,\nstdout: stdout,\nstderr: stderr,\n- success: status.success? && stderr =~ BLANK\n+ success: success\n)\nrescue Errno::EACCES, Errno::ENOEXEC\nOpenStruct.new(\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "spec/features/deploy_spec.rb",
"diff": "+require 'honeybadger'\n+\n+feature \"Running the deploy cli command\" do\n+ before { set_environment_variable('HONEYBADGER_BACKEND', 'debug') }\n+\n+ it \"notifies Honeybadger of the deploy\" do\n+ expect(run('honeybadger deploy --api-key=test-api-key --environment=test-env --revision=test-rev --repository=test-repo --user=test-user')).to be_successfully_executed\n+ end\n+\n+ context \"when the options are invalid\" do\n+ it \"notifies the user\" do\n+ expect(run('honeybadger deploy --api-key= --environment=test-env --revision=test-rev --repository=test-repo --user=test-user')).not_to be_successfully_executed\n+ expect(all_output).to match(/required.+api-key/i)\n+ end\n+ end\n+\n+ context \"when there is a server error\" do\n+ before { set_environment_variable('DEBUG_BACKEND_STATUS', '500') }\n+\n+ it \"notifies the user\" do\n+ expect(run('honeybadger deploy --api-key=test-api-key --environment=test-env --revision=test-rev --repository=test-repo --user=test-user')).not_to be_successfully_executed\n+ expect(all_output).to match(/invalid response/i)\n+ end\n+ end\n+end\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "spec/features/exec_spec.rb",
"diff": "+require 'honeybadger'\n+\n+feature \"Running the exec cli command\", :focus do\n+ before { set_environment_variable('HONEYBADGER_BACKEND', 'debug') }\n+\n+ it \"quietly executes the requested command\" do\n+ expect(run('honeybadger exec --api-key=test-api-key ls')).to be_successfully_executed\n+ expect(all_output).to be_empty\n+ end\n+\n+ context \"when the options are invalid\" do\n+ it \"notifies the user\" do\n+ expect(run('honeybadger exec --api-key= ls')).not_to be_successfully_executed\n+ expect(all_output).to match(/required.+api-key/i)\n+ end\n+ end\n+\n+ context \"when the command fails due to a non-zero exit code\" do\n+ it \"notifies Honeybadger of the failure\" do\n+ expect(run('honeybadger exec --api-key=test-api-key this-command-should-not-exist')).to be_successfully_executed\n+ expect(all_output).to match(/failed.+this-command-should-not-exist/im)\n+ expect(all_output).to match(/Successfully notified Honeybadger/i)\n+ end\n+ end\n+\n+ context \"when the command fails due to standard error output\" do\n+ it \"notifies Honeybadger of the failure\" do\n+ expect(run('honeybadger exec --api-key=test-api-key echo \"test stderr\" 1>&2')).to be_successfully_executed\n+ expect(all_output).to match(/failure/i)\n+ expect(all_output).to match(/test stderr/i)\n+ expect(all_output).to match(/Successfully notified Honeybadger/i)\n+ end\n+ end\n+end\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add tests for deploy and exec cli commands. |
287,654 | 16.01.2017 10:30:43 | 28,800 | 15b33c24f68a71bb0e5482e7773085879f8f9bf1 | Add pwd to honeybadger exec context. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/cli/exec.rb",
"new_path": "lib/honeybadger/cli/exec.rb",
"diff": "@@ -63,7 +63,8 @@ MSG\ncontext: {\nexecutable: args.first,\ncode: result.code,\n- pid: result.pid\n+ pid: result.pid,\n+ pwd: Dir.pwd\n}\n},\nserver: {\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add pwd to honeybadger exec context. |
287,654 | 16.01.2017 10:44:42 | 28,800 | 918d97cb4e834a2fae985ff5bc285464ae124a24 | Add some extra context to honeybadger exec | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/cli/exec.rb",
"new_path": "lib/honeybadger/cli/exec.rb",
"diff": "@@ -52,6 +52,7 @@ MSG\nresult = exec_cmd\nreturn if result.success\n+ executable = args.first.to_s[/\\S+/]\npayload = {\napi_key: config.get(:api_key),\nnotifier: NOTIFIER,\n@@ -60,11 +61,13 @@ MSG\nmessage: result.msg\n},\nrequest: {\n+ component: executable,\ncontext: {\n- executable: args.first,\n+ command: args.join(' '),\ncode: result.code,\npid: result.pid,\n- pwd: Dir.pwd\n+ pwd: Dir.pwd,\n+ path: ENV['PATH']\n}\n},\nserver: {\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add some extra context to honeybadger exec |
287,654 | 16.01.2017 14:21:16 | 28,800 | 1c1c7caea88d8a90d0f9e6da7290572d7a24c497 | Delegate to full constant. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/singleton.rb",
"new_path": "lib/honeybadger/singleton.rb",
"diff": "@@ -8,7 +8,7 @@ module Honeybadger\nextend Forwardable\nextend self\n- def_delegators :'Agent.instance', :init!, :config, :configure,\n+ def_delegators :'Honeybadger::Agent.instance', :init!, :config, :configure,\n:context, :get_context, :flush, :stop, :with_rack_env, :exception_filter,\n:exception_fingerprint, :backtrace_filter\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Delegate to full constant. |
287,654 | 16.01.2017 18:07:06 | 28,800 | 347736b24b3f2f759b0f4adb947a03773f15047c | Don't test Ruby 2.4.0/Rails 4.x
See | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -42,6 +42,12 @@ matrix:\ngemfile: gemfiles/rack.gemfile\n- rvm: 2.1.10\ngemfile: gemfiles/sinatra.gemfile\n+ - rvm: 2.4.0\n+ gemfile: gemfiles/rails4.0.gemfile\n+ - rvm: 2.4.0\n+ gemfile: gemfiles/rails4.1.gemfile\n+ - rvm: 2.4.0\n+ gemfile: gemfiles/rails4.2.gemfile\nenv:\nglobal:\nsecure: DwQI6QHuRRaMoKvE9rnXmw3U1KLKH6Y1ZTXCcDN34Zkq7QG5KPt195zvL6XPbsefvd2fOHq4es5D6jxgLlEdKB7njhWX8XNMgb/eprz6zTxSAS/ep31zYHEJ3krWSPM6a7fXJOjdYIzXhVl7I0NRDZGy/Sf6LgHIBMpaGVKGc34=\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Don't test Ruby 2.4.0/Rails 4.x
See https://github.com/rails/rails/issues/25125 |
287,654 | 16.01.2017 18:36:10 | 28,800 | 822937ac24a2f5ff4a8be3e2b68669711452899d | Remove forced encoding for invalid UTF8
This doesn't seem to do anything except blow up JRuby and was originally
added for Ruby 1.9 which is no longer supported. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/util/sanitizer.rb",
"new_path": "lib/honeybadger/util/sanitizer.rb",
"diff": "@@ -151,13 +151,8 @@ module Honeybadger\ndef valid_encoding(string)\nreturn string if valid_encoding?(string)\n-\n- if string.encoding == Encoding::UTF_8\n- string.encode(Encoding::UTF_16, ENCODE_OPTS).encode!(Encoding::UTF_8)\n- else\nstring.encode(Encoding::UTF_8, ENCODE_OPTS)\nend\n- end\ndef enumerable?(data)\ndata.kind_of?(Hash) || data.kind_of?(Array) || data.kind_of?(Set)\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Remove forced encoding for invalid UTF8
This doesn't seem to do anything except blow up JRuby and was originally
added for Ruby 1.9 which is no longer supported. |
287,654 | 16.01.2017 18:47:05 | 28,800 | 254e85e861aaf1c9eede3f9bf013ac3742e4a981 | Remove extra Ruby 2.3 and allow Rails-head failures. | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -23,7 +23,6 @@ gemfile:\nrvm:\n- 2.1.10\n- 2.2.5\n- - 2.3.1\n- 2.3.3\n- 2.4.0\n- jruby-9.1.4.0\n@@ -32,7 +31,11 @@ matrix:\nallow_failures:\n- rvm: 2.2.5\ngemfile: gemfiles/rails.gemfile\n- - rvm: 2.3.1\n+ - rvm: 2.3.3\n+ gemfile: gemfiles/rails.gemfile\n+ - rvm: 2.4.0\n+ gemfile: gemfiles/rails.gemfile\n+ - rvm: jruby-9.1.4.0\ngemfile: gemfiles/rails.gemfile\nexclude:\n- rvm: 2.1.10\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Remove extra Ruby 2.3 and allow Rails-head failures. |
287,654 | 16.01.2017 18:50:04 | 28,800 | f370ba9750880c449eaf12f0e7de86bba0ddb15c | Bump Ruby 2.2 version. | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -22,14 +22,14 @@ gemfile:\n- gemfiles/rails5.0.gemfile\nrvm:\n- 2.1.10\n- - 2.2.5\n+ - 2.2.6\n- 2.3.3\n- 2.4.0\n- jruby-9.1.4.0\nmatrix:\nfast_finish: true\nallow_failures:\n- - rvm: 2.2.5\n+ - rvm: 2.2.6\ngemfile: gemfiles/rails.gemfile\n- rvm: 2.3.3\ngemfile: gemfiles/rails.gemfile\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Bump Ruby 2.2 version. |
287,654 | 16.01.2017 18:55:38 | 28,800 | 716c55d0df0919e9c8cded74609fe7bdf4a4a96b | Exclude binding_of_caller tests on JRuby. | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -52,6 +52,8 @@ matrix:\ngemfile: gemfiles/rails4.1.gemfile\n- rvm: 2.4.0\ngemfile: gemfiles/rails4.2.gemfile\n+ - rvm: jruby-9.1.4.0\n+ gemfile: gemfiles/binding_of_caller.gemfile\nenv:\nglobal:\nsecure: DwQI6QHuRRaMoKvE9rnXmw3U1KLKH6Y1ZTXCcDN34Zkq7QG5KPt195zvL6XPbsefvd2fOHq4es5D6jxgLlEdKB7njhWX8XNMgb/eprz6zTxSAS/ep31zYHEJ3krWSPM6a7fXJOjdYIzXhVl7I0NRDZGy/Sf6LgHIBMpaGVKGc34=\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Exclude binding_of_caller tests on JRuby. |
287,654 | 19.01.2017 11:18:09 | 28,800 | 66a3c0130a12beca08d219d8c458daf2c11e450f | Don't require rails in aruba tests.
Blows up JRuby with an encoding error, and I don't think there was a
reason to require it anyway. | [
{
"change_type": "MODIFY",
"old_path": "spec/features/install_spec.rb",
"new_path": "spec/features/install_spec.rb",
"diff": "require 'honeybadger/config'\nrequire 'pathname'\n-begin\n- require 'rails'\n-rescue LoadError\n- nil\n-end\n-\nfeature \"Installing honeybadger via the cli\" do\nshared_examples_for \"cli installer\" do |rails|\nlet(:config) { Honeybadger::Config.new(:api_key => 'asdf', :'config.path' => config_file) }\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Don't require rails in aruba tests.
Blows up JRuby with an encoding error, and I don't think there was a
reason to require it anyway. |
287,654 | 19.01.2017 12:29:35 | 28,800 | ffd6a6095d3f68f554c47ee69599fd0a4999ee10 | Add JRuby 9 to README. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -12,7 +12,7 @@ When an uncaught exception occurs, Honeybadger will POST the relevant data to th\n| Ruby Interpreter | Supported Version |\n| ---- | ---- |\n| MRI | >= 2.1.0 |\n-| Rubinius | >= 2.0 |\n+| JRuby | >= 9.1 |\n## Supported web frameworks\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add JRuby 9 to README. |
287,654 | 23.01.2017 12:38:25 | 28,800 | 85e2513635fa3dcf69f1f1e49b75b3c48cc23db5 | Detect and send git revision with errors. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -28,6 +28,8 @@ adheres to [Semantic Versioning](http://semver.org/).\n- `Honeybadger.notify` now converts arguments which are not `Exception` or\n`Hash` types to strings and assigns them as the error message. Example:\n`Honeybadger.notify(\"Something went wrong\")`.\n+- The currently deployed git revision is now detected automatically and sent\n+ with error reports.\n### Changed\n- `Honeybadger.start` has been deprecated and has no effect.\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/config.rb",
"new_path": "lib/honeybadger/config.rb",
"diff": "@@ -9,6 +9,7 @@ require 'honeybadger/logging'\nrequire 'honeybadger/backend'\nrequire 'honeybadger/config/defaults'\nrequire 'honeybadger/util/http'\n+require 'honeybadger/util/revision'\nrequire 'honeybadger/logging'\nmodule Honeybadger\n@@ -46,6 +47,7 @@ module Honeybadger\nself.framework = opts.freeze\nself.env = Env.new(env).freeze\nload_config_from_disk {|yaml| self.yaml = yaml.freeze }\n+ detect_revision!\ninit_logging!\ninit_backend!\nlogger.info(sprintf('Initializing Honeybadger Error Tracker for Ruby. Ship it! version=%s framework=%s', Honeybadger::VERSION, detected_framework))\n@@ -273,6 +275,11 @@ module Honeybadger\nprivate\n+ def detect_revision!\n+ return if self[:revision]\n+ set(:revision, Util::Revision.detect(self[:root]))\n+ end\n+\n# Internal: Optional path to honeybadger.log log file.\n#\n# Returns the Pathname log path if a log path was specified.\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/config/defaults.rb",
"new_path": "lib/honeybadger/config/defaults.rb",
"diff": "@@ -46,6 +46,11 @@ module Honeybadger\ndefault: Dir.pwd,\ntype: String\n},\n+ revision: {\n+ description: 'The git revision of the project.',\n+ default: nil,\n+ type: String\n+ },\nhostname: {\ndescription: 'The hostname of the current box.',\ndefault: Socket.gethostname,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/notice.rb",
"new_path": "lib/honeybadger/notice.rb",
"diff": "@@ -185,6 +185,7 @@ module Honeybadger\nrequest: @request,\nserver: {\nproject_root: s(config[:root]),\n+ revision: s(config[:revision]),\nenvironment_name: s(config[:env]),\nhostname: s(config[:hostname]),\nstats: stats,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/honeybadger/util/revision.rb",
"diff": "+module Honeybadger\n+ module Util\n+ class Revision\n+ class << self\n+ def detect(root = Dir.pwd)\n+ from_heroku ||\n+ from_capistrano(root) ||\n+ from_git\n+ end\n+\n+ private\n+\n+ # Requires (currently) alpha platform feature\n+ # `heroku labs:enable runtime-dyno-metadata`\n+ #\n+ # See https://devcenter.heroku.com/articles/dyno-metadata\n+ def from_heroku\n+ ENV['HEROKU_SLUG_COMMIT']\n+ end\n+\n+ def from_capistrano(root)\n+ file = File.join(root, 'REVISION')\n+ return nil unless File.file?(file)\n+ File.read(file).strip rescue nil\n+ end\n+\n+ def from_git\n+ return nil unless File.directory?('.git')\n+ `git rev-parse HEAD`.strip rescue nil\n+ end\n+ end\n+ end\n+ end\n+end\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "spec/fixtures/REVISION",
"diff": "+rspec testing\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "spec/unit/honeybadger/util/revision_spec.rb",
"diff": "+require 'honeybadger/util/revision'\n+\n+describe Honeybadger::Util::Revision do\n+ after do\n+ ENV.delete('HEROKU_SLUG_COMMIT')\n+ end\n+\n+ it \"detects capistrano revision\" do\n+ root = FIXTURES_PATH.to_s\n+ expect(Honeybadger::Util::Revision.detect(root)).to eq('rspec testing')\n+ end\n+\n+ it \"detects git revision\" do\n+ expect(Honeybadger::Util::Revision.detect).to eq(`git rev-parse HEAD`.strip)\n+ end\n+\n+ it \"detects heroku revision\" do\n+ ENV['HEROKU_SLUG_COMMIT'] = 'heroku revision'\n+ expect(Honeybadger::Util::Revision.detect).to eq('heroku revision')\n+ end\n+end\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Detect and send git revision with errors. |
287,654 | 24.01.2017 13:51:30 | 28,800 | f232e42620ee62093147ede1794502e9b134fc59 | Delete ping. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/backend/server.rb",
"new_path": "lib/honeybadger/backend/server.rb",
"diff": "@@ -10,7 +10,6 @@ module Honeybadger\nmodule Backend\nclass Server < Base\nENDPOINTS = {\n- ping: '/v1/ping'.freeze,\nnotices: '/v1/notices'.freeze,\ndeploys: '/v1/deploys'.freeze\n}.freeze\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/config.rb",
"new_path": "lib/honeybadger/config.rb",
"diff": "@@ -52,9 +52,6 @@ module Honeybadger\ninit_backend!\nlogger.info(sprintf('Initializing Honeybadger Error Tracker for Ruby. Ship it! version=%s framework=%s', Honeybadger::VERSION, detected_framework))\nlogger.warn('Entering development mode: data will not be reported.') if dev? && backend.kind_of?(Backend::Null)\n- if valid? && !ping\n- logger.warn('Failed to connect to Honeybadger service -- please verify that api.honeybadger.io is reachable (connection will be retried).')\n- end\nself\nend\n@@ -141,10 +138,6 @@ module Honeybadger\n!self[:env] || !dev?\nend\n- def valid?\n- self[:api_key].to_s =~ /\\S/\n- end\n-\ndef debug?\n!!self[:debug]\nend\n@@ -241,14 +234,6 @@ module Honeybadger\n@root_regexp = Regexp.new(\"^#{ Regexp.escape(root) }\")\nend\n- def ping\n- if result = send_ping\n- return true\n- end\n-\n- false\n- end\n-\ndef detected_framework\nif self[:framework] =~ NOT_BLANK\nself[:framework].to_sym\n@@ -376,33 +361,6 @@ module Honeybadger\nobj.map(&:to_sym).include?(value.to_sym)\nend\n- def ping_payload\n- {\n- version: VERSION,\n- framework: framework_name,\n- environment: self[:env],\n- hostname: self[:hostname],\n- config: to_hash\n- }\n- end\n-\n- def send_ping\n- payload = ping_payload\n- debug { sprintf('ping payload=%s', payload.to_json.dump) }\n- response = backend.notify(:ping, payload)\n- if response.success?\n- debug { sprintf('ping response=%s', response.body.dump) }\n- JSON.parse(response.body)\n- else\n- warn do\n- msg = sprintf('ping failure code=%s', response.code)\n- msg << sprintf(' message=%s', response.message.dump) if response.message =~ NOT_BLANK\n- msg\n- end\n- nil\n- end\n- end\n-\ndef locate_absolute_path(path, root)\npath = Pathname.new(path.to_s)\nif path.absolute?\n"
},
{
"change_type": "MODIFY",
"old_path": "spec/unit/honeybadger/config_spec.rb",
"new_path": "spec/unit/honeybadger/config_spec.rb",
"diff": "@@ -3,8 +3,6 @@ require 'honeybadger/backend/base'\nrequire 'net/http'\ndescribe Honeybadger::Config do\n- it { should_not be_valid }\n-\nspecify { expect(subject[:disabled]).to eq false }\nspecify { expect(subject[:env]).to eq nil }\nspecify { expect(subject[:'delayed_job.attempt_threshold']).to eq 0 }\n@@ -14,10 +12,6 @@ describe Honeybadger::Config do\nlet(:env) { {} }\nlet(:config) { Honeybadger::Config.new(logger: NULL_LOGGER) }\n- before do\n- allow(config).to receive(:ping).and_return(true)\n- end\n-\nit \"returns the config object\" do\nexpect(config.init!).to eq(config)\nend\n@@ -153,55 +147,6 @@ describe Honeybadger::Config do\nend\nend\n- describe \"#ping\" do\n- let(:instance) { Honeybadger::Config.new(logger: NULL_LOGGER, disabled: true, debug: true) }\n- let(:logger) { instance.logger }\n- let(:body) { {'top' => 'foo'} }\n-\n- subject { instance.ping }\n-\n- before do\n- allow(logger).to receive(:debug)\n- end\n-\n- it \"calls the backend with object (not JSON)\" do\n- backend = double('Honeybadger::Backend::Server')\n- response = Honeybadger::Backend::Response.new(201, '{}')\n- allow(instance).to receive(:backend).and_return(backend)\n- expect(backend).to receive(:notify).with(:ping, kind_of(Hash)).and_return(response)\n- instance.ping\n- end\n-\n- context \"when connection succeeds\" do\n- before { stub_http(body: body.to_json) }\n-\n- it { should eq true }\n-\n- it \"logs debug action\" do\n- expect(logger).to receive(:debug).with(/ping payload/i)\n- instance.ping\n- end\n-\n- it \"logs debug response\" do\n- expect(logger).to receive(:debug).with(/ping response/i)\n- instance.ping\n- end\n- end\n-\n- context \"when connection fails\" do\n- before do\n- stub_http(response: Net::HTTPServerError.new('1.2', '500', 'Internal Error'), body: nil)\n- end\n-\n- it { should eq false }\n-\n- it \"warns logger\" do\n- expect(logger).to receive(:warn).with(/ping failure code=500 message=\"Internal Error\"/)\n- instance.ping\n- end\n- end\n- end\n-\ndescribe \"#detected_framework\" do\nconstants = [:Rails, :Sinatra, :Rack]\nconstants_backup = {}\n"
},
{
"change_type": "MODIFY",
"old_path": "spec/unit/honeybadger/rack/user_feedback_spec.rb",
"new_path": "spec/unit/honeybadger/rack/user_feedback_spec.rb",
"diff": "@@ -13,12 +13,6 @@ describe Honeybadger::Rack::UserFeedback do\nlet(:informer_app) { Honeybadger::Rack::UserFeedback.new(main_app, agent) }\nlet(:result) { informer_app.call({}) }\n- context \"feedback feature is disabled by ping\" do\n- it \"does not modify the output\" do\n- expect(result[2][0]).to eq '<!-- HONEYBADGER FEEDBACK -->'\n- end\n- end\n-\ncontext \"there is a honeybadger id\" do\nlet(:honeybadger_id) { 1 }\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Delete ping. |
287,654 | 24.01.2017 13:58:05 | 28,800 | 9b764e5129b099bdc25624159add7b626a806b7a | Add comment about Config#init! | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/config.rb",
"new_path": "lib/honeybadger/config.rb",
"diff": "@@ -13,6 +13,7 @@ require 'honeybadger/util/revision'\nrequire 'honeybadger/logging'\nmodule Honeybadger\n+ # Internal\nclass Config\nextend Forwardable\n@@ -43,6 +44,9 @@ module Honeybadger\nattr_accessor :ruby, :env, :yaml, :framework\n+ # Called by framework (see lib/honeybadger/init/) at the point of\n+ # initialization. This is not required for the notifier to work (i.e. with\n+ # `require 'honeybadger/ruby'`).\ndef init!(opts = {}, env = ENV)\nself.framework = opts.freeze\nself.env = Env.new(env).freeze\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add comment about Config#init! |
287,654 | 24.01.2017 14:03:37 | 28,800 | fb54b4eb35507a00b46028e24cfb2f8cc9409669 | Require argument to honeybadger exec. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/cli/main.rb",
"new_path": "lib/honeybadger/cli/main.rb",
"diff": "@@ -109,10 +109,15 @@ WELCOME\nproject_options\noption :quiet, required: false, type: :boolean, aliases: :'-q', default: false, desc: 'Suppress all output unless notification fails.'\ndef exec(*args)\n+ if args.size == 0\n+ say(\"honeybadger: exec needs a command to run\", :red)\n+ exit(1)\n+ end\n+\nconfig = build_config(options)\nif config.get(:api_key).to_s =~ BLANK\n- say(\"No value provided for required options '--api-key'\")\n+ say(\"No value provided for required options '--api-key'\", :red)\nexit(1)\nend\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Require argument to honeybadger exec. |
287,654 | 30.01.2017 17:49:22 | 28,800 | a3a9b2b9b761929d29c4bff33b21c2ad639f3f0c | Add support for reporting Resque::DirtyExit exceptions. | [
{
"change_type": "MODIFY",
"old_path": "Appraisals",
"new_path": "Appraisals",
"diff": "@@ -21,6 +21,11 @@ appraise 'delayed_job' do\ngem 'delayed_job', '< 4.1.2' # See https://github.com/collectiveidea/delayed_job/pull/931\nend\n+appraise 'resque' do\n+ gem 'resque'\n+ gem 'mock_redis'\n+end\n+\nappraise 'rails3.2' do\ngem 'rails', '~> 3.2.12'\ngem 'better_errors', require: false, platforms: [:ruby_20, :ruby_21]\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "gemfiles/resque.gemfile",
"diff": "+# This file was generated by Appraisal\n+\n+source \"https://rubygems.org\"\n+\n+gem \"allocation_stats\", :platforms => :mri, :require => false\n+gem \"appraisal\", \"~> 2.1\"\n+gem \"aruba\", \"~> 0.14\"\n+gem \"guard\"\n+gem \"guard-rspec\"\n+gem \"pry\"\n+gem \"pry-byebug\", :platforms => :mri\n+gem \"rdoc\"\n+gem \"rspec\", \"~> 3.0\"\n+gem \"rspec-its\"\n+gem \"ruby-prof\", :platforms => :mri, :require => false\n+gem \"timecop\"\n+gem \"webmock\"\n+gem \"capistrano\"\n+gem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\n+gem \"resque\"\n+gem \"mock_redis\"\n+\n+gemspec :path => \"../\"\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/plugins/resque.rb",
"new_path": "lib/honeybadger/plugins/resque.rb",
"diff": "@@ -6,26 +6,22 @@ module Honeybadger\nmodule Resque\nmodule Extension\ndef around_perform_with_honeybadger(*args)\n- Honeybadger.flush do\n- begin\n- yield\n- rescue Exception => e\n- Honeybadger.notify(e, parameters: { job_arguments: args }) if send_exception?(e, args)\n- raise e\n- end\n- end\n+ Honeybadger.flush { yield }\nensure\nHoneybadger.context.clear!\nend\n- def send_exception?(e, args)\n+ def on_failure_with_honeybadger(e, *args)\n+ Honeybadger.notify(e, parameters: { job_arguments: args }) if send_exception_to_honeybadger?(e, args)\n+ end\n+\n+ def send_exception_to_honeybadger?(e, args)\nreturn true unless respond_to?(:retry_criteria_valid?)\nreturn true if ::Honeybadger.config[:'resque.resque_retry.send_exceptions_when_retrying']\n!retry_criteria_valid?(e)\nrescue => e\nHoneybadger.notify(e, parameters: { job_arguments: args })\n- raise e\nend\nend\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "spec/integration/resque_spec.rb",
"diff": "+begin\n+ require 'resque'\n+ require 'mock_redis'\n+ RESQUE_PRESENT = true\n+rescue LoadError\n+ RESQUE_PRESENT = false\n+ puts 'Skipping Resque integration specs.'\n+end\n+\n+if RESQUE_PRESENT\n+ require 'honeybadger'\n+\n+ ERROR = StandardError.new('This is a failure inside Honeybadger integration test suite')\n+\n+ class TestWorker\n+ @queue = :test\n+\n+ def self.perform\n+ raise ERROR\n+ end\n+ end\n+\n+ class DirtyWorker\n+ @queue = :test\n+\n+ def self.perform\n+ Resque.shutdown!\n+ end\n+ end\n+\n+ describe 'Resque integration' do\n+ let(:worker) { Resque::Worker.new(:test) }\n+\n+ before(:all) do\n+ Resque.redis = MockRedis.new\n+ end\n+\n+ it \"reports failed jobs to Honeybadger\" do\n+ job = Resque::Job.new(:jobs, {'class' => 'TestWorker', 'args' => nil})\n+\n+ expect(Honeybadger).to receive(:notify).once.with(ERROR, anything)\n+\n+ worker.perform(job)\n+ end\n+\n+ it \"reports DirtyExit to Honeybadger\" do\n+ job = Resque::Job.new(:jobs, {'class' => 'TestWorker', 'args' => nil})\n+\n+ expect(Honeybadger).to receive(:notify).once.with(kind_of(Resque::DirtyExit), anything)\n+\n+ worker.working_on(job)\n+ worker.unregister_worker\n+ end\n+ end\n+end\n"
},
{
"change_type": "MODIFY",
"old_path": "spec/integration/sinatra_spec.rb",
"new_path": "spec/integration/sinatra_spec.rb",
"diff": "begin\nrequire 'sinatra/base'\n+ require 'rack/test'\nSINATRA_PRESENT = true\nrescue LoadError\nSINATRA_PRESENT = false\n@@ -9,7 +10,6 @@ end\nif SINATRA_PRESENT\nrequire FIXTURES_PATH.join('sinatra', 'app.rb')\nrequire 'honeybadger/init/sinatra'\n- require 'rack/test'\ndescribe 'Sinatra integration' do\ninclude Rack::Test::Methods\n"
},
{
"change_type": "MODIFY",
"old_path": "spec/unit/honeybadger/plugins/resque_spec.rb",
"new_path": "spec/unit/honeybadger/plugins/resque_spec.rb",
"diff": "@@ -7,30 +7,19 @@ class TestWorker\nend\ndescribe TestWorker do\n- shared_examples_for \"clears the context\" do\n- it \"\" do\n- expect {\n- described_class.around_perform_with_honeybadger do\n- Honeybadger.context(badgers: true)\n- end\n- }.not_to change { Thread.current[:__honeybadger_context] }.from(nil)\n- end\n- end\n+ describe \"::on_failure_with_honeybadger\" do\n+ let(:error) { RuntimeError.new('Failure in Honeybadger resque_spec') }\nshared_examples_for \"reports exceptions\" do\n- it \"\" do\n- expect(Honeybadger).to receive(:notify).with(kind_of(RuntimeError), hash_including(parameters: {job_arguments: [1, 2, 3]}))\n- expect {\n- described_class.around_perform_with_honeybadger(1, 2, 3) do\n- fail 'foo'\n- end\n- }.to raise_error(RuntimeError)\n+ specify do\n+ expect(Honeybadger).to receive(:notify).with(error, hash_including(parameters: {job_arguments: [1, 2, 3]}))\n+ described_class.on_failure_with_honeybadger(error, 1, 2, 3)\nend\nend\nshared_examples_for \"does not report exceptions\" do\n- it \"\" do\n- expect(Honeybadger).not_to receive(:notify).with(kind_of(RuntimeError), hash_including(parameters: {job_arguments: [1, 2, 3]}))\n+ specify do\n+ expect(Honeybadger).not_to receive(:notify)\nexpect {\ndescribed_class.around_perform_with_honeybadger(1, 2, 3) do\nfail 'foo'\n@@ -39,38 +28,25 @@ describe TestWorker do\nend\nend\n- shared_examples_for \"raises exceptions\" do\n- it \"\" do\n- expect {\n- described_class.around_perform_with_honeybadger do\n- fail 'foo'\n- end\n- }.to raise_error(RuntimeError)\n- end\n- end\n+ it_behaves_like \"reports exceptions\"\n- describe \"::around_perform_with_honeybadger\" do\ndescribe \"with worker not extending Resque::Plugins::Retry\" do\ncontext \"when send exceptions on retry enabled\" do\nbefore { ::Honeybadger.config[:'resque.resque_retry.send_exceptions_when_retrying'] = true }\n- it_behaves_like \"clears the context\"\nit_behaves_like \"reports exceptions\"\n- it_behaves_like \"raises exceptions\"\nend\ncontext \"when send exceptions on retry disabled\" do\nbefore { ::Honeybadger.config[:'resque.resque_retry.send_exceptions_when_retrying'] = false }\n- it_behaves_like \"clears the context\"\nit_behaves_like \"reports exceptions\"\n- it_behaves_like \"raises exceptions\"\nend\nend\ndescribe \"with worker extending Resque::Plugins::Retry\" do\nlet(:retry_criteria_valid) { false }\n+\nbefore do\nclass TestWorker\n- extend Honeybadger::Plugins::Resque::Extension\ndef self.retry_criteria_valid?(e)\nend\nend\n@@ -82,16 +58,12 @@ describe TestWorker do\nbefore { ::Honeybadger.config[:'resque.resque_retry.send_exceptions_when_retrying'] = true }\ncontext \"with retry criteria invalid\" do\n- it_behaves_like \"clears the context\"\nit_behaves_like \"reports exceptions\"\n- it_behaves_like \"raises exceptions\"\nend\ncontext \"with retry criteria valid\" do\nlet(:retry_criteria_valid) { true }\n- it_behaves_like \"clears the context\"\nit_behaves_like \"reports exceptions\"\n- it_behaves_like \"raises exceptions\"\nend\nend\n@@ -99,32 +71,42 @@ describe TestWorker do\nbefore { ::Honeybadger.config[:'resque.resque_retry.send_exceptions_when_retrying'] = false }\ncontext \"with retry criteria invalid\" do\n- it_behaves_like \"clears the context\"\nit_behaves_like \"reports exceptions\"\n- it_behaves_like \"raises exceptions\"\nend\ncontext \"with retry criteria valid\" do\nlet(:retry_criteria_valid) { true }\n- it_behaves_like \"clears the context\"\nit_behaves_like \"does not report exceptions\"\n- it_behaves_like \"raises exceptions\"\nend\ncontext \"and retry_criteria_valid? raises exception\" do\n- before do\n- allow(described_class).to receive(:retry_criteria_valid?).and_raise(StandardError)\n+ it \"should report raised error to honeybadger\" do\n+ other_error = StandardError.new('stubbed Honeybadger error in retry_criteria_valid?')\n+ allow(described_class).to receive(:retry_criteria_valid?).and_raise(other_error)\n+ expect(Honeybadger).to receive(:notify).with(other_error, hash_including(parameters: {job_arguments: [1, 2, 3]}))\n+ described_class.on_failure_with_honeybadger(error, 1, 2, 3)\n+ end\n+ end\n+\n+ end\n+ end\nend\n- it \"should report error to honeybadger\" do\n- expect(Honeybadger).to receive(:notify).with(StandardError, hash_including(parameters: {job_arguments: [1, 2, 3]}))\n+ describe \"::around_perform_with_honeybadger\" do\n+ it \"clears the context\" do\nexpect {\n- described_class.around_perform_with_honeybadger(1, 2, 3)\n- }.to raise_error(StandardError)\n+ described_class.around_perform_with_honeybadger do\n+ Honeybadger.context(badgers: true)\nend\n+ }.not_to change { Thread.current[:__honeybadger_context] }.from(nil)\nend\n+ it \"raises exceptions\" do\n+ expect {\n+ described_class.around_perform_with_honeybadger do\n+ fail 'foo'\nend\n+ }.to raise_error(RuntimeError)\nend\nend\nend\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add support for reporting Resque::DirtyExit exceptions. |
287,654 | 31.01.2017 09:12:17 | 28,800 | 82c207a1d4c4a893a0a51c3b9319bb74e1119fe2 | Bump max string size to 64K. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/util/sanitizer.rb",
"new_path": "lib/honeybadger/util/sanitizer.rb",
"diff": "@@ -16,7 +16,7 @@ module Honeybadger\nIMMUTABLE = [NilClass, FalseClass, TrueClass, Symbol, Numeric, BigDecimal, Method].freeze\n- MAX_STRING_SIZE = 2048\n+ MAX_STRING_SIZE = 65536\nTRUNCATION_REPLACEMENT = '[TRUNCATED]'.freeze\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Bump max string size to 64K. |
287,654 | 31.01.2017 09:44:21 | 28,800 | 46d914ea1e537d066daeed6b1a4fd67ece199d91 | Add Shoryuken to list of supported queues. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -36,6 +36,7 @@ Integrating with other libraries/frameworks is simple! [See the documentation](h\n| Resque | any | yes |\n| Delayed Job | any | yes |\n| Sucker Punch | any | yes |\n+| Shoryuken | any | yes |\nYou can integrate honeybadger into any Ruby script via the `Honeybadger.notify` method.\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add Shoryuken to list of supported queues. |
287,654 | 31.01.2017 10:18:56 | 28,800 | d6b58dbd2777a65f995033af2c638104883ae561 | List other integrations in README. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -30,7 +30,7 @@ Integrating with other libraries/frameworks is simple! [See the documentation](h\n## Supported job queues\n-| Framework | Version | Native? |\n+| Library | Version | Native? |\n| ------------- | ------------- | ------------ |\n| Sidekiq | any | yes |\n| Resque | any | yes |\n@@ -38,6 +38,13 @@ Integrating with other libraries/frameworks is simple! [See the documentation](h\n| Sucker Punch | any | yes |\n| Shoryuken | any | yes |\n+## Other integrations\n+\n+| Library | Version | Native? | Description |\n+| ------------- | ------------- | ------------ | ----------- |\n+| Devise/Warden | any | yes | Exceptions are automatically associated with the current user. |\n+| Thor | any | yes | Exceptions in commands are automatically reported. |\n+\nYou can integrate honeybadger into any Ruby script via the `Honeybadger.notify` method.\n## Getting Started\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | List other integrations in README. |
287,654 | 06.02.2017 06:10:42 | 28,800 | eeef51691001298d3d569165aafe4c484f08314c | Add Resque change to CHANGELOG. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -69,6 +69,7 @@ adheres to [Semantic Versioning](http://semver.org/).\n### Fixed\n- Arrays are no longer compacted during sanitization (`nil` values will be sent\nas they originally appeared).\n+- Resque plugin now reports `Resque::DirtyExit` exceptions.\n## [2.7.2] - 2016-12-12\n### Fixed\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add Resque change to CHANGELOG. |
287,654 | 10.02.2017 11:49:12 | 28,800 | 6286efd29111bfeadf24e541aa90340a108f1946 | Skip non-string keys in Rack env. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -4,6 +4,9 @@ CHANGELOG](http://keepachangelog.com/) for how to update this file. This project\nadheres to [Semantic Versioning](http://semver.org/).\n## [Unreleased]\n+### Fixed\n+- Fixed a bug which caused a NoMethodError (undefined method \\`start_with?') when\n+ Rack env contained non-string keys.\n## [3.0.0] - 2017-02-06\n### Added\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/util/request_hash.rb",
"new_path": "lib/honeybadger/util/request_hash.rb",
"diff": "@@ -62,6 +62,7 @@ module Honeybadger\ndef self.extract_cgi_data(request)\nrequest.env.each_with_object({}) do |(k,v), env|\n+ next unless k.is_a?(String)\nnext unless k.start_with?(HTTP_HEADER_PREFIX) || CGI_WHITELIST.include?(k)\nenv[k] = v\nend\n"
},
{
"change_type": "MODIFY",
"old_path": "spec/unit/honeybadger/util/request_hash_spec.rb",
"new_path": "spec/unit/honeybadger/util/request_hash_spec.rb",
"diff": "@@ -25,5 +25,10 @@ describe Honeybadger::Util::RequestHash, if: defined?(Rack) do\nrack_env['QUERY_STRING'] = 'foo'\nexpect(subject[:cgi_data]).not_to have_key 'QUERY_STRING'\nend\n+\n+ it \"excludes symbols\" do\n+ rack_env[:foo] = 'foo'\n+ expect(subject[:cgi_data]).not_to have_key :foo\n+ end\nend\nend\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Skip non-string keys in Rack env. #215 |
287,654 | 16.02.2017 08:33:57 | 28,800 | b2ba41ad9fe8e10593d996dc53cd4d127b67eccd | Fix semantic_logger bug. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -4,6 +4,8 @@ CHANGELOG](http://keepachangelog.com/) for how to update this file. This project\nadheres to [Semantic Versioning](http://semver.org/).\n## [Unreleased]\n+### Fixed\n+- Fixed a bug caused by an interaction with the semantic\\_logger gem.\n## [3.0.1] - 2017-02-10\n### Fixed\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/logging.rb",
"new_path": "lib/honeybadger/logging.rb",
"diff": "@@ -20,19 +20,19 @@ module Honeybadger\nalias :d :debug\ndef info(msg = nil)\n- return true if Logger::Severity::INFO < logger.level\n+ return true unless logger.info?\nmsg = yield if block_given?\nlogger.info(msg)\nend\ndef warn(msg = nil)\n- return true if Logger::Severity::WARN < logger.level\n+ return true unless logger.warn?\nmsg = yield if block_given?\nlogger.warn(msg)\nend\ndef error(msg = nil)\n- return true if Logger::Severity::ERROR < logger.level\n+ return true unless logger.error?\nmsg = yield if block_given?\nlogger.error(msg)\nend\n"
},
{
"change_type": "MODIFY",
"old_path": "spec/unit/honeybadger/logging_spec.rb",
"new_path": "spec/unit/honeybadger/logging_spec.rb",
"diff": "@@ -28,6 +28,34 @@ describe Honeybadger::Logging::BootLogger.instance do\nend\nend\n+describe Honeybadger::Logging::Helper do\n+ let(:logger) { Logger.new('/dev/null') }\n+ let(:config) { double('Honeybadger::Config', logger: logger) }\n+\n+ class HelperSubject\n+ include Honeybadger::Logging::Helper\n+\n+ def initialize(config)\n+ @config = config\n+ end\n+\n+ def log_debug(msg); debug(msg); end\n+ def log_info(msg); info(msg); end\n+ def log_warn(msg); warn(msg); end\n+ def log_error(msg); error(msg); end\n+ end\n+\n+ subject { HelperSubject.new(config) }\n+\n+ it \"doesn't rely on Integer logger.level\" do\n+ allow(logger).to receive(:level).and_return(:info)\n+ subject.log_debug('debug message')\n+ subject.log_info('info message')\n+ subject.log_warn('warn message')\n+ subject.log_error('error message')\n+ end\n+end\n+\ndescribe Honeybadger::Logging::FormattedLogger do\nlet(:logger) { Logger.new('/dev/null') }\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Fix semantic_logger bug. #218 |
287,654 | 16.02.2017 09:16:34 | 28,800 | 3dc552cc26a135096d4d001a3d416fad71b714a9 | Add logging predicates to base. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/logging.rb",
"new_path": "lib/honeybadger/logging.rb",
"diff": "require 'logger'\nrequire 'singleton'\nrequire 'delegate'\n+require 'forwardable'\nmodule Honeybadger\nmodule Logging\n@@ -47,6 +48,10 @@ module Honeybadger\ndefine_method severity.downcase do |msg|\nadd(Logger::Severity.const_get(severity), msg)\nend\n+\n+ define_method :\"#{severity.downcase}?\" do\n+ true\n+ end\nend\ndef add(severity, msg)\n@@ -78,6 +83,8 @@ module Honeybadger\nend\nclass StandardLogger < Base\n+ extend Forwardable\n+\ndef initialize(logger = Logger.new('/dev/null'))\nraise ArgumentError, 'logger not specified' unless logger\nraise ArgumentError, 'logger must be a logger' unless logger.respond_to?(:add)\n@@ -85,13 +92,7 @@ module Honeybadger\n@logger = logger\nend\n- def add(severity, msg)\n- @logger.add(severity, msg)\n- end\n-\n- def level\n- @logger.level\n- end\n+ def_delegators :@logger, :level, :add, :debug?, :info?, :warn?, :error?\nend\nclass FormattedLogger < StandardLogger\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add logging predicates to base. |
287,654 | 16.02.2017 09:36:53 | 28,800 | de0ddb054f00be567e875f9204778420d1c7b27b | Initialize sinatra config immediately. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/init/sinatra.rb",
"new_path": "lib/honeybadger/init/sinatra.rb",
"diff": "@@ -7,28 +7,23 @@ module Honeybadger\n::Sinatra::Base.class_eval do\nclass << self\ndef build_with_honeybadger(*args, &block)\n+ configure_honeybadger\ninstall_honeybadger\nbuild_without_honeybadger(*args, &block)\nend\nalias :build_without_honeybadger :build\nalias :build :build_with_honeybadger\n- def honeybadger_config(app)\n- {\n- api_key: defined?(honeybadger_api_key) ? honeybadger_api_key : nil,\n- env: ENV['APP_ENV'] || ENV['RACK_ENV'],\n- framework: :sinatra,\n- :'logging.path' => 'STDOUT'\n- }\n+ def configure_honeybadger\n+ return unless defined?(honeybadger_api_key)\n+ Honeybadger.configure do |config|\n+ config.api_key = honeybadger_api_key\n+ end\nend\ndef install_honeybadger\n- Honeybadger.init!(honeybadger_config(self))\n- Honeybadger.load_plugins!\n-\nconfig = Honeybadger.config\nreturn unless config[:'sinatra.enabled']\n-\ninstall_honeybadger_middleware(Honeybadger::Rack::ErrorNotifier) if config[:'exceptions.enabled']\nend\n@@ -41,3 +36,11 @@ module Honeybadger\nend\nend\nend\n+\n+Honeybadger.init!({\n+ env: ENV['APP_ENV'] || ENV['RACK_ENV'],\n+ framework: :sinatra,\n+ :'logging.path' => 'STDOUT'\n+})\n+\n+Honeybadger.load_plugins!\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Initialize sinatra config immediately. |
287,654 | 03.03.2017 00:42:14 | 28,800 | 1f91ab3ac3c904e7a330d5334cd8f6e7bef5390e | Update config options in README. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -228,7 +228,7 @@ You can use any of the options below in your config file, or in the environment.\n| `config_path` | String | The path of the honeybadger config file. Can only be set via the `$HONEYBADGER_CONFIG_PATH` environment variable |\n|`development_environments` | Array | Environments which will not report data by default (use report_data to enable/disable explicitly).<br/>_Default: `[\"development\", \"test\", \"cucumber\"]`_|\n|`plugins` | Array | An optional list of plugins to load. Default is to load all plugins.<br/>_Default: `[]`_|\n-|`plugins.skip` | Array | An optional list of plugins to skip.<br/>_Default: `[]`_|\n+|`skipped_plugins` | Array | An optional list of plugins to skip.<br/>_Default: `[]`_|\n| | ||\n|__LOGGING__ | ||\n|`logging.path` | String | The path (absolute, or relative from config.root) to the log file. Defaults to the rails logger or STDOUT. To log to standard out, use 'STDOUT'.<br/>_Default: `nil`_|\n@@ -271,9 +271,11 @@ You can use any of the options below in your config file, or in the environment.\n| | ||\n|__SIDEKIQ__ | ||\n|`sidekiq.attempt_threshold` | Integer | The number of attempts before notifications will be sent.<br/>_Default: `0`_|\n-|`sidekiq.use_component` | Boolean | Automatically set the component to the class of the job. Helps with grouping.<br/>_Default: `false`_|\n+|`sidekiq.use_component` | Boolean | Automatically set the component to the class of the job. Helps with grouping.<br/>_Default: `true`_|\n|__DELAYED JOB__ | ||\n|`delayed_job.attempt_threshold` | Integer | The number of attempts before notifications will be sent.<br/>_Default: `0`_|\n+|__SHORYUKEN__ | ||\n+|`shoryuken.attempt_threshold` | Integer | The number of attempts before notifications will be sent.<br/>_Default: `0`_|\n|__SINATRA__ | ||\n|`sinatra.enabled` | Boolean | Enable Sinatra auto-initialization.<br/>_Default: `true`_|\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/config/defaults.rb",
"new_path": "lib/honeybadger/config/defaults.rb",
"diff": "@@ -271,6 +271,11 @@ module Honeybadger\ndefault: 0,\ntype: Integer\n},\n+ :'shoryuken.attempt_threshold' => {\n+ description: 'The number of attempts before notifications will be sent.',\n+ default: 0,\n+ type: Integer\n+ },\n:'sidekiq.use_component' => {\ndescription: 'Automatically set the component to the class of the job. Helps with grouping.',\ndefault: true,\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Update config options in README. |
287,654 | 03.03.2017 00:45:54 | 28,800 | e9b8a6be0b5f1d20a74fbf0e8a802f94c38e5311 | Add Honeybadger.configure to readme. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -208,6 +208,17 @@ export HONEYBADGER_LOGGING_PATH=/path/to/honeybadger.log\nENV options override other options read from framework or `honeybadger.yml` sources, so both can be used together.\n+### Configuration via Ruby (programmatic)\n+\n+To configure Honeybadger from Ruby, use `Honeybadger.configure`:\n+\n+```ruby\n+Honeybadger.configure do |config|\n+ config.api_key = 'project api key'\n+ config.exceptions.ignore += [CustomError]\n+end\n+```\n+\n## Configuration Options\nYou can use any of the options below in your config file, or in the environment.\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add Honeybadger.configure to readme. |
287,654 | 03.03.2017 00:59:51 | 28,800 | 1577f821421b97314e69cdf1e3008603f9237073 | Document additional public api methods. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -320,6 +320,9 @@ end\n# Clearing global context:\nHoneybadger.context.clear!\n+\n+# Fetching current context\n+Honeybadger.get_context\n```\n---\n@@ -349,6 +352,26 @@ end\n---\n+### `Honeybadger.configure()`: Configure Honeybadger from Ruby\n+\n+This method allows you to configure Honeybadger at runtime.\n+\n+#### Use this method if:\n+\n+* You want to change Honeybadger's configuration from inside Ruby rather than\n+ (or in addition to) using the honeybadger.yml file or environment variables.\n+\n+#### Examples:\n+\n+```ruby\n+Honeybadger.configure do |config|\n+ config.api_key = 'project api key'\n+ config.exceptions.ignore += [CustomError]\n+end\n+```\n+\n+---\n+\n### `Honeybadger.exception_filter()`: Programmatically ignore exceptions\nThis method lets you add a callback that will be run every time an exception is about to be reported to Honeybadger. If your callback returns a truthy value, the exception won't be reported. [View full method documentation](http://www.rubydoc.info/gems/honeybadger/Honeybadger%3Aexception_filter)\n@@ -378,6 +401,43 @@ end\n```\n__WARNING:__ While it is possible to use this callback to modify the data that is reported to Honeybadger, this is not officially supported and may not be allowed in future versions of the gem.\n+---\n+\n+### `Honeybadger.exception_fingerprint()`: Customize your error grouping.\n+\n+This method lets you add a callback that should return a unique string given a `Honeybadger::Notice` instance. All notices which match the same string will be grouped together in Honeybadger.\n+\n+#### Use this method if:\n+\n+* You currently receive too many error notifications\n+* You want to group some errors together which are currently unique\n+* You *don't* want to group some errors which are currently grouped\n+\n+#### Examples:\n+\n+```ruby\n+Honeybadger.exception_fingerprint do |notice|\n+ [notice[:error_class], notice[:component], notice[:backtrace].to_s].join(':')\n+end\n+```\n+\n+---\n+\n+### `Honeybadger.backtrace_filter()`: Filter your backtrace.\n+\n+This method allows you to add a callback which modifies each line of the backtrace before a notification happens.\n+\n+#### Use this method if:\n+\n+* You want to change or sanitize common data in your exception backtraces\n+\n+#### Examples:\n+\n+```ruby\n+Honeybadger.backtrace_filter do |line|\n+ line.gsub(/^\\/my\\/unknown\\/bundle\\/path/, \"[GEM_ROOT]\")\n+end\n+```\n## Deployment Tracking\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Document additional public api methods. |
287,654 | 03.03.2017 01:06:14 | 28,800 | a6f468fbd076f0b3b76fabb5faaf29c75b925cc5 | Update rubydoc.info link. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -293,7 +293,7 @@ You can use any of the options below in your config file, or in the environment.\n## Public Methods\n-> What follows is a summary of the gem's most commonly-used public methods. For a more authoritative list, read the [full API documentation](http://www.rubydoc.info/gems/honeybadger/Honeybadger).\n+> What follows is a summary of the gem's most commonly-used public methods. For a more authoritative list, read the [full API documentation](http://www.rubydoc.info/gems/honeybadger/Honeybadger/Agent).\n### `Honeybadger.context()`: Set metadata to be sent if an exception occurs\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Update rubydoc.info link. |
287,654 | 03.03.2017 01:15:47 | 28,800 | 6c920397ada6135361f9fe8aa25f34446e3ae676 | Add exec and notify CLI command docs to README. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -499,6 +499,35 @@ bundle exec honeybadger deploy --environment=production\nRun `bundle exec honeybadger help deploy` for all available options.\n+## Cron/command line monitoring\n+\n+`honeybadger exec` can be used from the command line/terminal to monitor failed\n+commands. To use it, prefix any normal command with `honeybadger exec` (much\n+like `bundle exec`):\n+\n+```sh\n+$ honeybadger exec my-command --my-flag\n+```\n+\n+If the command executes successfully, honeybadger exits with code 0. It prints\n+any output from the command by default. To use with cron's automatic email\n+feature, use the `--quiet` flag, which will suppress all standard output from\n+the origin command unless the command fails *and* the Honeybadger notification\n+fails, in which case it will dump the output so that cron can send a backup\n+email notification.\n+\n+For full usage run `honeybadger help exec`.\n+\n+## Notify from the command line\n+\n+To send a Honeybadger notification from the command line/terminal, use\n+`honeybadger notify`:\n+\n+```sh\n+$ honeybadger notify --message \"This is an error from the command line\"\n+```\n+\n+For full usage run `honeybadger help notify`.\n## Custom Error Pages\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add exec and notify CLI command docs to README. |
287,654 | 03.03.2017 01:18:55 | 28,800 | 570fb61665045818702c3f810f38f6f4589ca3fd | Add plain ruby setup section. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -139,6 +139,24 @@ use Honeybadger::Rack::ErrorNotifier\nrun app\n```\n+#### Plain Ruby\n+\n+To use Honeybadger without any of the automatic integrations, `require\n+honeybadger/ruby` instead of `require 'honeybadger'`:\n+\n+```\n+require 'honeybadger/ruby'\n+\n+begin\n+ # Failing code\n+rescue => exception\n+ Honeybadger.notify(exception)\n+end\n+```\n+\n+All of the public API methods are still available, but none of the plugins,\n+framework integrations, or hooks are run. You will need to manually set up your\n+own middleware and hooks for error monitoring in whatever frameworks you use.\n## Advanced Configuration\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add plain ruby setup section. |
287,654 | 03.03.2017 01:22:20 | 28,800 | a2738e0047ca3fa481a338e6e98cdd7dbec00897 | Add Honeybadger::Agent documentation to README. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -547,6 +547,27 @@ $ honeybadger notify --message \"This is an error from the command line\"\nFor full usage run `honeybadger help notify`.\n+## Reporting to multiple Honeybadger projects in the same app\n+\n+To send errors to another Honeybadger project, configure an additional agent:\n+\n+```ruby\n+OtherBadger = Honeybadger::Agent.new\n+\n+OtherBadger.configure do |config|\n+ config.api_key = 'project api key'\n+end\n+\n+begin\n+ # Failing code\n+rescue => exception\n+ OtherBadger.notify(exception)\n+end\n+```\n+\n+Agents do not use the global honeybadger.yml or environment variable\n+configuration and must be configured manually after they are instantiated.\n+\n## Custom Error Pages\nThe Honeybadger gem has a few special tags that it looks for whenever you render an error page. These can be used to display extra information about the error, or to ask the user for information about how they triggered the error.\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add Honeybadger::Agent documentation to README. |
287,654 | 06.03.2017 09:20:12 | 28,800 | eaa8f5f865bc4aeee5b6fc4dfc54e747ddbedaca | Add section on integration testing. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -624,6 +624,81 @@ en:\ncomment: \"Comment (required)\"\n```\n+## Testing Honeybadger in your integration tests\n+\n+It is possible to test Honeybadger's integration with your application using the\n+included test backend.\n+\n+The test backend replaces the default server backend with a stub that records\n+error notices rather than sending them, allowing all but the HTTP notification\n+itself to be verified. Alternatively, you could use something like\n+[WebMock](https://github.com/bblimke/webmock) to perform a similar test using\n+the \"server\" backend.\n+\n+### Configuring the test backend\n+\n+To use the test backend, set the `backend` configuration option to \"test\" in\n+honeybadger.yml for your test environment only:\n+\n+```yaml\n+test:\n+ backend: test\n+```\n+\n+You can also use the *HONEYBADGER_BACKEND* environment variable to configure the\n+test backend.\n+\n+### Writing the integration test\n+\n+The test backend can be used in any testing framework to test any code which\n+reports an error with `Honeybadger.notify`. A common scenario is to test the\n+Rails-integration which reports exceptions in a Rails controller automatically.\n+\n+The following example uses RSpec to test error notification in a Rails\n+controller.\n+\n+First, create the controller:\n+\n+```ruby\n+# app/controllers/honeybadger_test_controller.rb\n+class HoneybadgerTestController < ApplicationController\n+ ERROR = RuntimeError.new(\"testing reporting an error to Honeybadger\")\n+\n+ def index\n+ raise ERROR\n+ end\n+end\n+```\n+\n+Next, create a route. For security, it's a good idea to enable the route only in\n+the test environment:\n+\n+```ruby\n+ # ...\n+ get '/test/honeybadger' => 'honeybadger_test#index' if Rails.env.test?\n+```\n+\n+Finally, create the integration test:\n+\n+```ruby\n+# spec/features/honeybadger_spec.rb\n+require 'rails_helper'\n+\n+describe \"error notification\" do\n+ it \"notifies Honeybadger\" do\n+ expect {\n+ # Code to test goes here:\n+ expect { visit '/test/honeybadger' }.to raise_error(HoneybadgerTestController::ERROR)\n+\n+ # Important: `Honeybadger.flush` ensures that asynchronous notifications\n+ # are delivered before the test's remaining expectations are verified.\n+ Honeybadger.flush\n+ }.to change(Honeybadger::Backend::Test.notifications[:notices], :size).by(1)\n+ expect(Honeybadger::Backend::Test.notifications[:notices].first.error_message).to eq('testing reporting an error to Honeybadger')\n+ end\n+end\n+```\n+\n## Changelog\nSee https://github.com/honeybadger-io/honeybadger-ruby/blob/master/CHANGELOG.md\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add section on integration testing. |
287,654 | 06.03.2017 11:39:48 | 28,800 | f379247e4a6248a12c44b77fff9ca9a2802bcfec | Use config env in deploy cmd. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -4,6 +4,9 @@ CHANGELOG](http://keepachangelog.com/) for how to update this file. This project\nadheres to [Semantic Versioning](http://semver.org/).\n## [Unreleased]\n+### Fixed\n+- `honeybadger deploy` cli command now reads default environment from\n+ honeybadger.yml/environment variable.\n## [3.1.0] - 2017-03-01\n### Changed\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/cli/deploy.rb",
"new_path": "lib/honeybadger/cli/deploy.rb",
"diff": "@@ -18,7 +18,7 @@ module Honeybadger\ndef run\npayload = {\n- environment: options['environment'],\n+ environment: config.get(:env),\nrevision: options['revision'],\nrepository: options['repository'],\nlocal_username: options['user']\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Use config env in deploy cmd. |
287,654 | 06.03.2017 12:08:09 | 28,800 | 48a8bb286927ede90841af19fe3cfd23f91b9066 | Rename configuration heading. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -158,7 +158,7 @@ All of the public API methods are still available, but none of the plugins,\nframework integrations, or hooks are run. You will need to manually set up your\nown middleware and hooks for error monitoring in whatever frameworks you use.\n-## Advanced Configuration\n+## Configuration\nThere are a few ways to configure the Honeybadger gem. You can use a YAML config file. You can use environment variables. You can use Ruby. Or you can use a combination of the three.\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Rename configuration heading. |
287,654 | 06.03.2017 12:22:35 | 28,800 | 347e59b657b6c94615ede22ae643e003e5371976 | Add note about API key in integration test. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -692,12 +692,15 @@ To use the test backend, set the `backend` configuration option to \"test\" in\nhoneybadger.yml for your test environment only:\n```yaml\n+api_key: 'project api key'\ntest:\nbackend: test\n```\nYou can also use the *HONEYBADGER_BACKEND* environment variable to configure the\n-test backend.\n+test backend. Note that you must also configure your API key for the test to\n+succeed.\n+\n### Writing the integration test\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add note about API key in integration test. |
287,654 | 06.03.2017 12:44:34 | 28,800 | 74796556a5dcfe1a0b113ed56eac9e8f9e2eaf2f | Rename headings. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -528,7 +528,7 @@ When using the *honeybadger* gem with Bundler, run `bundle exec honeybadger`.\nTo use outside of bundler, install the Honeybadger gem with `gem install\nhoneybadger` and then run `honeybadger`.\n-### Configuration\n+### CLI Configuration\nThe `honeybadger` command optionally reads configuration from the following\nlocations. Each location in the list takes precedence over the previous\n@@ -546,7 +546,7 @@ The following configuration options are used by the CLI when applicable:\nAll other options must be passed as command-line flags.\n-### Commands\n+### CLI Commands\nThe following commands are available through the `honeybadger` CLI:\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Rename headings. |
287,654 | 20.04.2017 09:42:42 | 25,200 | 721986e09b284e6052d9dc407fbb3b22488ca13a | Notify synchronously in Resque hook
This fixes a bug in the Resque plugin which prevented notifications from
being sent. The issue was that the Resque's callbacks were executed in
an unexpected order which caused the queue to be flushed before error
notification instead of after. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -4,6 +4,11 @@ CHANGELOG](http://keepachangelog.com/) for how to update this file. This project\nadheres to [Semantic Versioning](http://semver.org/).\n## [Unreleased]\n+### Fixed\n+- Fixed a bug in the Resque plugin which prevented error reports from being\n+ sent. The issue was that the Resque's callbacks were executed in an unexpected\n+ order which caused the queue to be flushed before error notification instead\n+ of after.\n## [3.1.1] - 2017-04-13\n### Fixed\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/plugins/resque.rb",
"new_path": "lib/honeybadger/plugins/resque.rb",
"diff": "@@ -5,14 +5,18 @@ module Honeybadger\nmodule Plugins\nmodule Resque\nmodule Extension\n+ # Executed before `on_failure` hook; the flush is necessary so that\n+ # errors reported within jobs get sent before the worker dies.\ndef around_perform_with_honeybadger(*args)\nHoneybadger.flush { yield }\nensure\nHoneybadger.context.clear!\nend\n+ # Error notifications must be synchronous as the `on_failure` hook is\n+ # executed after `around_perform`.\ndef on_failure_with_honeybadger(e, *args)\n- Honeybadger.notify(e, parameters: { job_arguments: args }) if send_exception_to_honeybadger?(e, args)\n+ Honeybadger.notify(e, parameters: { job_arguments: args }, sync: true) if send_exception_to_honeybadger?(e, args)\nend\ndef send_exception_to_honeybadger?(e, args)\n@@ -21,7 +25,7 @@ module Honeybadger\n!retry_criteria_valid?(e)\nrescue => e\n- Honeybadger.notify(e, parameters: { job_arguments: args })\n+ Honeybadger.notify(e, parameters: { job_arguments: args }, sync: true)\nend\nend\n"
},
{
"change_type": "MODIFY",
"old_path": "spec/unit/honeybadger/plugins/resque_spec.rb",
"new_path": "spec/unit/honeybadger/plugins/resque_spec.rb",
"diff": "@@ -12,7 +12,7 @@ describe TestWorker do\nshared_examples_for \"reports exceptions\" do\nspecify do\n- expect(Honeybadger).to receive(:notify).with(error, hash_including(parameters: {job_arguments: [1, 2, 3]}))\n+ expect(Honeybadger).to receive(:notify).with(error, hash_including(parameters: {job_arguments: [1, 2, 3]}, sync: true))\ndescribed_class.on_failure_with_honeybadger(error, 1, 2, 3)\nend\nend\n@@ -83,7 +83,7 @@ describe TestWorker do\nit \"should report raised error to honeybadger\" do\nother_error = StandardError.new('stubbed Honeybadger error in retry_criteria_valid?')\nallow(described_class).to receive(:retry_criteria_valid?).and_raise(other_error)\n- expect(Honeybadger).to receive(:notify).with(other_error, hash_including(parameters: {job_arguments: [1, 2, 3]}))\n+ expect(Honeybadger).to receive(:notify).with(other_error, hash_including(parameters: {job_arguments: [1, 2, 3]}, sync: true))\ndescribed_class.on_failure_with_honeybadger(error, 1, 2, 3)\nend\nend\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Notify synchronously in Resque hook (#224)
This fixes a bug in the Resque plugin which prevented notifications from
being sent. The issue was that the Resque's callbacks were executed in
an unexpected order which caused the queue to be flushed before error
notification instead of after. |
287,654 | 21.04.2017 15:46:05 | 25,200 | e11e1b2578b297a62d0dd8317cd5e444517e984c | Update notify documentation. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/agent.rb",
"new_path": "lib/honeybadger/agent.rb",
"diff": "@@ -70,13 +70,21 @@ module Honeybadger\n# to build the notice. All other types of objects will\n# be converted to a String and used as the `:error_message`.\n# opts - The options Hash when the first argument is an\n- # Exception. (default: {}):\n+ # Exception (default: {}):\n# :error_message - The String error message.\n- # :error_class - The String class name of the error. (optional)\n- # :force - Always report the exception, even when\n- # ignored. (optional)\n- #\n- # Examples:\n+ # :error_class - The String class name of the error (default: \"Notice\").\n+ # :backtrace - The Array backtrace of the error (optional).\n+ # :fingerprint - The String grouping fingerprint of the exception (optional).\n+ # :force - Always report the exception when true, even when ignored (default: false).\n+ # :tags - The String comma-separated list of tags (optional).\n+ # :context - The Hash context to associate with the exception (optional).\n+ # :controller - The String controller name (such as a Rails controller) (optional).\n+ # :action - The String action name (such as a Rails controller action) (optional).\n+ # :parameters - The Hash HTTP request paramaters (optional).\n+ # :session - The Hash HTTP request session (optional).\n+ # :url - The String HTTP request URL (optional).\n+ #\n+ # Examples\n#\n# # With an exception:\n# begin\n@@ -88,9 +96,8 @@ module Honeybadger\n# end\n#\n# # Custom notification:\n- # Honeybadger.notify({\n+ # Honeybadger.notify('Something went wrong.', {\n# error_class: 'MyClass',\n- # error_message: 'Something went wrong.',\n# context: {my_data: 'value'}\n# }) # => '06220c5a-b471-41e5-baeb-de247da45a56'\n#\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Update notify documentation. |
287,654 | 21.04.2017 15:51:04 | 25,200 | 4fd82ce75c26a494db7fb0626d4b882e5c081eaa | Tomdoc tweaks. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/agent.rb",
"new_path": "lib/honeybadger/agent.rb",
"diff": "@@ -19,7 +19,7 @@ module Honeybadger\n# This also includes the Rack environment when using the Honeybadger rack\n# middleware.\n#\n- # Examples:\n+ # Examples\n#\n# # Standard usage:\n# OtherBadger = Honeybadger::Agent.new\n@@ -147,7 +147,7 @@ module Honeybadger\n# hash - A Hash of data which will be sent to Honeybadger when an error\n# occurs. (default: nil)\n#\n- # Examples:\n+ # Examples\n#\n# Honeybadger.context({my_data: 'my value'})\n#\n@@ -173,7 +173,7 @@ module Honeybadger\n# Public: Get global context for the current request.\n#\n#\n- # Examples:\n+ # Examples\n#\n# Honeybadger.context({my_data: 'my value'})\n# Honeybadger.get_context #now returns {my_data: 'my value'}\n@@ -190,7 +190,7 @@ module Honeybadger\n# block - The optional block to execute (exceptions will propagate after data\n# is flushed).\n#\n- # Examples:\n+ # Examples\n#\n# # Without a block:\n# it \"sends a notification to Honeybadger\" do\n@@ -222,7 +222,7 @@ module Honeybadger\n# Public: Stops the Honeybadger service.\n#\n- # Examples:\n+ # Examples\n#\n# Honeybadger.stop # => nil\n#\n@@ -238,7 +238,7 @@ module Honeybadger\n#\n# block - The configuration block.\n#\n- # Examples:\n+ # Examples\n#\n# Honeybadger.configure do |config|\n# config.api_key = 'project api key'\n@@ -256,7 +256,7 @@ module Honeybadger\n# block - A block returning TrueClass true (to ignore) or FalseClass false\n# (to send).\n#\n- # Examples:\n+ # Examples\n#\n# # Ignoring based on error message:\n# Honeybadger.exception_filter do |notice|\n@@ -279,7 +279,7 @@ module Honeybadger\n#\n# block - A block returning any Object responding to #to_s.\n#\n- # Examples:\n+ # Examples\n#\n# Honeybadger.exception_fingerprint do |notice|\n# [notice[:error_class], notice[:component], notice[:backtrace].to_s].join(':')\n@@ -296,7 +296,7 @@ module Honeybadger\n# Honeybadger. The block expects one argument (line) which is the String line\n# from the Backtrace, and must return the String new line.\n#\n- # Examples:\n+ # Examples\n#\n# Honeybadger.backtrace_filter do |line|\n# line.gsub(/^\\/my\\/unknown\\/bundle\\/path/, \"[GEM_ROOT]\")\n@@ -312,7 +312,7 @@ module Honeybadger\n# block - A block to call. Errors reported from within the block will\n# include request data.\n#\n- # Examples:\n+ # Examples\n#\n# Honeybadger.with_rack_env(env) do\n# begin\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/backend/base.rb",
"new_path": "lib/honeybadger/backend/base.rb",
"diff": "@@ -21,7 +21,7 @@ module Honeybadger\n# Public: Initializes the Response instance.\n#\n# response - With 1 argument Net::HTTPResponse, the code, body, and\n- # message will be determined automatically. (optional)\n+ # message will be determined automatically (optional).\n# code - The Integer status code. May also be :error for requests which\n# failed to reach the server.\n# body - The String body of the response.\n@@ -76,10 +76,10 @@ module Honeybadger\n# Internal: Process payload for feature.\n#\n# feature - A Symbol feature name (corresponds to HTTP endpoint). Current\n- # options are: :notices, :deploys, :ping\n- # payload - Any Object responding to #to_json.\n+ # options are: `:notices`, `:deploys`, `:ping`.\n+ # payload - Any Object responding to `#to_json`.\n#\n- # Examples:\n+ # Examples\n#\n# backend.notify(:notices, Notice.new(...))\n#\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/backend/test.rb",
"new_path": "lib/honeybadger/backend/test.rb",
"diff": "@@ -5,7 +5,7 @@ module Honeybadger\nclass Test < Null\n# Public: The notification list.\n#\n- # Examples:\n+ # Examples\n#\n# Test.notifications[:notices] # => [Notice, Notice, ...]\n#\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/notice.rb",
"new_path": "lib/honeybadger/notice.rb",
"diff": "@@ -23,7 +23,7 @@ module Honeybadger\n# Internal: Substitution for project root in backtrace lines.\nPROJECT_ROOT = '[PROJECT_ROOT]'.freeze\n- # Internal: Empty String (used for equality comparisons and assignment)\n+ # Internal: Empty String (used for equality comparisons and assignment).\nSTRING_EMPTY = ''.freeze\n# Internal: A Regexp which matches non-blank characters.\n@@ -59,7 +59,7 @@ module Honeybadger\n# Public: Tags which will be applied to error.\nattr_reader :tags\n- # Public: The name of the class of error. (example: RuntimeError)\n+ # Public: The name of the class of error (example: RuntimeError).\nattr_reader :error_class\n# Public: The message from the exception, or a general description of the error.\n@@ -75,7 +75,7 @@ module Honeybadger\ndef params; @request[:params]; end\nalias_method :parameters, :params\n- # Public: The component (if any) which was used in this request. (usually the controller)\n+ # Public: The component (if any) which was used in this request (usually the controller).\ndef component; @request[:component]; end\nalias_method :controller, :component\n@@ -163,9 +163,9 @@ module Honeybadger\n@fingerprint = construct_fingerprint(opts)\nend\n- # Internal: Template used to create JSON payload\n+ # Internal: Template used to create JSON payload.\n#\n- # Returns Hash JSON representation of notice\n+ # Returns Hash JSON representation of notice.\ndef as_json(*args)\n@request[:context] = s(context)\n@request[:local_variables] = local_variables if local_variables\n@@ -195,22 +195,22 @@ module Honeybadger\n}\nend\n- # Public: Creates JSON\n+ # Public: Creates JSON.\n#\n- # Returns valid JSON representation of Notice\n+ # Returns valid JSON representation of Notice.\ndef to_json(*a)\n::JSON.generate(as_json(*a))\nend\n- # Public: Allows properties to be accessed using a hash-like syntax\n+ # Public: Allows properties to be accessed using a hash-like syntax.\n#\n- # method - The given key for an attribute\n+ # method - The given key for an attribute.\n#\n- # Examples:\n+ # Examples\n#\n# notice[:error_message]\n#\n- # Returns the attribute value, or self if given +:request+\n+ # Returns the attribute value, or self if given `:request`.\ndef [](method)\ncase method\nwhen :request\n@@ -220,7 +220,7 @@ module Honeybadger\nend\nend\n- # Internal: Determines if this notice should be ignored\n+ # Internal: Determines if this notice should be ignored.\ndef ignore?\nignore_by_origin? || ignore_by_class? || ignore_by_callbacks?\nend\n@@ -242,15 +242,15 @@ module Honeybadger\nend\n# Gets a property named \"attribute\" of an exception, either from\n- # the #args hash or actual exception (in order of precidence)\n+ # the #args hash or actual exception (in order of precidence).\n#\n# attribute - A Symbol existing as a key in #args and/or attribute on\n- # Exception\n- # default - Default value if no other value is found. (optional)\n+ # Exception.\n+ # default - Default value if no other value is found (optional).\n# block - An optional block which receives an Exception and returns the\n- # desired value\n+ # desired value.\n#\n- # Returns attribute value from args or exception, otherwise default\n+ # Returns attribute value from args or exception, otherwise default.\ndef exception_attribute(attribute, default = nil, &block)\nopts[attribute] || (exception && from_exception(attribute, &block)) || default\nend\n@@ -273,12 +273,12 @@ module Honeybadger\nend\nend\n- # Internal: Determines if error class should be ignored\n+ # Internal: Determines if error class should be ignored.\n#\n# ignored_class_name - The name of the ignored class. May be a\n- # string or regexp (optional)\n+ # string or regexp (optional).\n#\n- # Returns true or false\n+ # Returns true or false.\ndef ignore_by_class?(ignored_class = nil)\n@ignore_by_class ||= Proc.new do |ignored_class|\ncase error_class\n@@ -362,7 +362,7 @@ module Honeybadger\n#\n# exception - The Exception containing the bindings stack.\n#\n- # Returns a Hash of local variables\n+ # Returns a Hash of local variables.\ndef local_variables_from_exception(exception, config)\nreturn nil unless send_local_variables?(config)\nreturn {} unless Exception === exception\n@@ -394,7 +394,7 @@ module Honeybadger\n# Internal: Should local variables be sent?\n#\n- # Returns true to send local_variables\n+ # Returns true to send local_variables.\ndef send_local_variables?(config)\nconfig[:'exceptions.local_variables']\nend\n@@ -486,7 +486,7 @@ module Honeybadger\n# This method restores the correct #session method on @request and warns\n# the user of the issue.\n#\n- # Returns nothing\n+ # Returns nothing.\ndef monkey_patch_action_dispatch_test_process!\nreturn unless defined?(ActionDispatch::TestProcess) && defined?(self.fixture_file_upload)\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/rack/error_notifier.rb",
"new_path": "lib/honeybadger/rack/error_notifier.rb",
"diff": "@@ -8,7 +8,7 @@ module Honeybadger\n# Public: Middleware for Rack applications. Any errors raised by the upstream\n# application will be delivered to Honeybadger and re-raised.\n#\n- # Examples:\n+ # Examples\n#\n# require 'honeybadger/rack/error_notifier'\n#\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Tomdoc tweaks. |
287,654 | 28.04.2017 08:46:13 | 25,200 | eca2d53b65b7a9973694a158201d5d6c2c8a309c | Add Rails 5.1 to appraisals. | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -19,6 +19,7 @@ gemfile:\n- gemfiles/rails4.2.gemfile\n- gemfiles/rails.gemfile\n- gemfiles/rails5.0.gemfile\n+ - gemfiles/rails5.1.gemfile\nrvm:\n- 2.1.10\n- 2.2.6\n@@ -41,6 +42,8 @@ matrix:\ngemfile: gemfiles/rails.gemfile\n- rvm: 2.1.10\ngemfile: gemfiles/rails5.0.gemfile\n+ - rvm: 2.1.10\n+ gemfile: gemfiles/rails5.1.gemfile\n- rvm: 2.1.10\ngemfile: gemfiles/rack.gemfile\n- rvm: 2.1.10\n"
},
{
"change_type": "MODIFY",
"old_path": "Appraisals",
"new_path": "Appraisals",
"diff": "@@ -57,7 +57,6 @@ appraise 'rails4.2' do\nend\nif Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.2.2')\n- # The latest officially supported Rails/Rack release\nappraise 'rails5.0' do\ngem 'rails', '~> 5.0.0'\ngem 'better_errors', require: false, platforms: [:ruby_20, :ruby_21]\n@@ -65,6 +64,15 @@ if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.2.2')\ngem 'rspec-rails'\nend\n+ # The latest officially supported Rails/Rack release\n+ appraise 'rails5.1' do\n+ gem 'rails', '~> 5.1.0'\n+ gem 'better_errors', require: false, platforms: [:ruby_20, :ruby_21]\n+ gem 'rack-mini-profiler', require: false\n+ gem 'rspec-rails'\n+ end\n+\n+ # Rails edge\nappraise 'rails' do\ngem 'rails', github: 'rails/rails'\ngem 'rack', github: 'rack/rack'\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "gemfiles/rails5.1.gemfile",
"diff": "+# This file was generated by Appraisal\n+\n+source \"https://rubygems.org\"\n+\n+gem \"allocation_stats\", :platforms => :mri, :require => false\n+gem \"appraisal\", \"~> 2.1\"\n+gem \"aruba\", \"~> 0.14\"\n+gem \"guard\"\n+gem \"guard-rspec\"\n+gem \"pry\"\n+gem \"pry-byebug\", :platforms => :mri\n+gem \"rdoc\"\n+gem \"rspec\", \"~> 3.0\"\n+gem \"rspec-its\"\n+gem \"ruby-prof\", :platforms => :mri, :require => false\n+gem \"timecop\"\n+gem \"webmock\"\n+gem \"capistrano\"\n+gem \"rake\"\n+gem \"listen\", \"~> 3.0.8\"\n+gem \"rails\", \"~> 5.1.0\"\n+gem \"better_errors\", :require => false, :platforms => [:ruby_20, :ruby_21]\n+gem \"rack-mini-profiler\", :require => false\n+gem \"rspec-rails\"\n+\n+gemspec :path => \"../\"\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Add Rails 5.1 to appraisals. |
287,654 | 16.08.2017 11:25:57 | 25,200 | 17ab25be86ae49d5cfb27ed722307033a051beae | Remove Logger references to /dev/null | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/cli/test.rb",
"new_path": "lib/honeybadger/cli/test.rb",
"diff": "@@ -94,9 +94,9 @@ module Honeybadger\n# logging the framework trace (moved to ActionDispatch::DebugExceptions),\n# which caused cluttered output while running the test task.\ndefined?(::ActionDispatch::DebugExceptions) and\n- ::ActionDispatch::DebugExceptions.class_eval { def logger(*args) ; @logger ||= Logger.new('/dev/null') ; end }\n+ ::ActionDispatch::DebugExceptions.class_eval { def logger(*args) ; @logger ||= Logger.new(nil) ; end }\ndefined?(::ActionDispatch::ShowExceptions) and\n- ::ActionDispatch::ShowExceptions.class_eval { def logger(*args) ; @logger ||= Logger.new('/dev/null') ; end }\n+ ::ActionDispatch::ShowExceptions.class_eval { def logger(*args) ; @logger ||= Logger.new(nil) ; end }\n# Detect and disable the better_errors gem\nif defined?(::BetterErrors::Middleware)\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/config.rb",
"new_path": "lib/honeybadger/config.rb",
"diff": "@@ -359,7 +359,7 @@ module Honeybadger\nreturn framework[:logger] if framework[:logger]\n- Logger.new('/dev/null')\n+ Logger.new(nil)\nend\ndef init_logging!\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/logging.rb",
"new_path": "lib/honeybadger/logging.rb",
"diff": "@@ -85,7 +85,7 @@ module Honeybadger\nclass StandardLogger < Base\nextend Forwardable\n- def initialize(logger = Logger.new('/dev/null'))\n+ def initialize(logger = Logger.new(nil))\nraise ArgumentError, 'logger not specified' unless logger\nraise ArgumentError, 'logger must be a logger' unless logger.respond_to?(:add)\n@@ -115,7 +115,7 @@ module Honeybadger\nINFO_SUPPLEMENT = ' level=%s pid=%s'.freeze\nDEBUG_SUPPLEMENT = ' at=%s'.freeze\n- def initialize(config, logger = Logger.new('/dev/null'))\n+ def initialize(config, logger = Logger.new(nil))\n@config = config\n@tty = STDOUT.tty?\n@tty_level = @config.log_level(:'logging.tty_level')\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Remove Logger references to /dev/null |
287,654 | 01.09.2017 15:11:01 | 25,200 | 5af6f70f12ed9fff5db71642af865985a1cfd206 | Support adding context to exceptions. Closes | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -8,6 +8,9 @@ adheres to [Semantic Versioning](http://semver.org/).\n- The exception cause may now be set using an optional `:cause` option when\ncalling `Honeybadger.notify`. If not present, the exception's cause will be\nused, or the global `$!` exception if available.\n+- Context can now be added to any exception object by defining the\n+ `#honeybadger_context` method. The method should have no arguments and return\n+ a `Hash` of context data.\n## [3.1.2] - 2017-04-20\n### Fixed\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/notice.rb",
"new_path": "lib/honeybadger/notice.rb",
"diff": "@@ -147,7 +147,7 @@ module Honeybadger\n@request = construct_request_hash(config, opts)\n- @context = construct_context_hash(opts)\n+ @context = construct_context_hash(opts, exception)\n@cause = opts[:cause] || exception_cause(@exception) || $!\n@causes = unwrap_causes(@cause)\n@@ -321,9 +321,15 @@ module Honeybadger\nUtil::RequestPayload.build(request)\nend\n- def construct_context_hash(opts)\n+ def exception_context(exception)\n+ return {}.freeze unless exception && exception.respond_to?(:honeybadger_context)\n+ exception.honeybadger_context\n+ end\n+\n+ def construct_context_hash(opts, exception)\ncontext = {}\ncontext.merge!(opts[:global_context]) if opts[:global_context]\n+ context.merge!(exception_context(exception))\ncontext.merge!(opts[:context]) if opts[:context]\ncontext.empty? ? nil : context\nend\n"
},
{
"change_type": "MODIFY",
"old_path": "spec/unit/honeybadger/notice_spec.rb",
"new_path": "spec/unit/honeybadger/notice_spec.rb",
"diff": "@@ -280,10 +280,49 @@ describe Honeybadger::Notice do\nend\ndescribe \"#context\" do\n- it \"merges context from args with context from Honeybadger#context\" do\n- global_context = {'one' => 'two', 'foo' => 'bar'}\n- notice = build_notice(global_context: global_context, context: {'three' => 'four', 'foo' => 'baz'})\n- expect(notice[:request][:context]).to eq({'one' => 'two', 'three' => 'four', 'foo' => 'baz'})\n+ it \"merges local context\" do\n+ notice = build_notice(context: { local: 'local' })\n+ expect(notice[:request][:context]).to eql({ local: 'local' })\n+ end\n+\n+ it \"merges global context\" do\n+ notice = build_notice(global_context: { global: 'global' })\n+ expect(notice[:request][:context]).to eql({ global: 'global' })\n+ end\n+\n+ it \"merges exception context\" do\n+ exception = Class.new(RuntimeError) do\n+ def honeybadger_context\n+ { exception: 'exception' }\n+ end\n+ end\n+ notice = build_notice(exception: exception.new)\n+\n+ expect(notice[:request][:context]).to eql({ exception: 'exception' })\n+ end\n+\n+ it \"skips exception context when method isn't defined\" do\n+ notice = build_notice(exception: RuntimeError.new)\n+ expect(notice[:request][:context]).to be_nil\n+ end\n+\n+ it \"merges context in order of precedence: local, exception, global\" do\n+ global_context = { global: 'global', local_override: 'global', exception_override: 'global' }\n+ exception = Class.new(RuntimeError) do\n+ def honeybadger_context\n+ { exception: 'exception', local_override: 'exception', exception_override: 'exception' }\n+ end\n+ end\n+ local_context = { local: 'local', local_override: 'local' }\n+ notice = build_notice(exception: exception.new, global_context: global_context, context: local_context)\n+\n+ expect(notice[:request][:context]).to eq({\n+ global: 'global',\n+ exception: 'exception',\n+ local: 'local',\n+ local_override: 'local',\n+ exception_override: 'exception'\n+ })\nend\nit \"doesn't mutate global context\" do\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Support adding context to exceptions. Closes #233 (#236) |
287,654 | 05.09.2017 11:20:52 | 25,200 | 0f3a17d08bb30d036ee1ed2d79a8e92f12b0d13f | Update troubleshooting link. | [
{
"change_type": "MODIFY",
"old_path": "lib/honeybadger/cli/test.rb",
"new_path": "lib/honeybadger/cli/test.rb",
"diff": "@@ -212,7 +212,7 @@ MSG\nnotices.each {|n| say(\"\\n - #{n.error_class}: #{n.error_message}\", :red) }\nend\n- say(\"\\nSee https://git.io/vXCYp for more troubleshooting help.\\n\\n\", :red)\n+ say(\"\\nSee https://docs.honeybadger.io/gem-troubleshooting for more troubleshooting help.\\n\\n\", :red)\nsay(\"!! --- End -------------------------------------------------------------------- !!\", :red)\nexit(1)\n@@ -245,7 +245,7 @@ Optional steps:\nIf you ever need help:\n- - Read the gem troubleshooting guide: https://git.io/vXCYp\n+ - Read the gem troubleshooting guide: https://docs.honeybadger.io/gem-troubleshooting\n- Check out our documentation: http://docs.honeybadger.io/\n- Email the founders: support@honeybadger.io\n"
}
] | Ruby | MIT License | honeybadger-io/honeybadger-ruby | Update troubleshooting link. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.