jax_privacy.clipping.clip_pytree

Contents

jax_privacy.clipping.clip_pytree#

jax_privacy.clipping.clip_pytree(pytree, clip_norm, rescale_to_unit_norm=False)[source]#

Clips a PyTree of jax arrays.

The clipping behavior is determined by the type of clip_norm, like so:

  • If clip_norm is a Scalar (Global Clipping): Calculates the global L2 norm of the input PyTree; & if the norm exceeds clip_norm, the entire PyTree is scaled down.

  • If clip_norm is a PyTree (Per-Layer Clipping): Calculates the L2 norm for each individual leaf; & if a leaf’s norm exceeds its corresponding threshold in clip_norm, that specific leaf is scaled down. The clip_norm PyTree structure must be a prefix of the input pytree. Where clip_norm terminates early, its leaf values automatically broadcast down to match all corresponding sub-leaves of pytree.

If rescale_to_unit_norm is True, the PyTree is additionally scaled by 1.0 / clip_norm (resulting in a norm of at most 1.0 no matter what clip_norm is). Handles cases where the original norm is zero, or the clip norm is 0 or infinity.

Formal Guarantees:

  • When the input PyTree is all-finite, the output PyTree will have norm at most clip_norm if rescale_to_unit_norm is False, and at most 1.0 if it is True. For low-precision leaves (e.g., float16), the norm bound may be exceeded by up to the leaf dtype’s machine epsilon due to rounding.

  • The output PyTree will have the same structure+dtypes as the input PyTree.

  • The output PyTree may contain NaN or inf values, but only when the returned L2 norm is non-finite (i.e., NaN or inf). If the returned L2 norm is finite, the output is guaranteed to be all-finite.

Edge Case Handling:

Case

rescale_to_unit_norm

Output

clip_norm = 0

False

Zero

clip_norm = 0

True

Input / norm, as clip_norm -> 0

clip_norm = inf

False

Unchanged

clip_norm = inf

True

Zero

clip_norm < 0 (static)

Raises ValueError

clip_norm < 0 (dynamic)

Zero

pytree_norm = 0

Unchanged

Parameters:
  • pytree (Union[Array, ndarray, bool, number, bool, int, float, complex, Iterable[optax.ArrayTree], Mapping[Any, optax.ArrayTree]]) – The PyTree of arrays to clip.

  • clip_norm (Union[float, Array, ndarray, bool, number, bool, int, complex, Iterable[optax.ArrayTree], Mapping[Any, optax.ArrayTree]]) – The maximum L2 norm allowed. Can be a single float or a PyTree; depending on whether Global / “Per-Layer” clipping is to be done (see details above).

  • rescale_to_unit_norm (bool) – If True, the output PyTree’s norm is rescaled by 1.0 / clip_norm after potential clipping. If False, the output PyTree has norm at most clip_norm.

Returns:

A tuple (clipped_pytree, original_l2_norm), where clipped_pytree is the processed PyTree and original_l2_norm is the L2 norm of the input PyTree. In case of per-layer clipping, original_l2_norm is a PyTree containing L2 norms of each leaf.