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_normis a Scalar (Global Clipping): Calculates the global L2 norm of the input PyTree; & if the norm exceedsclip_norm, the entire PyTree is scaled down.If
clip_normis a PyTree (Per-Layer Clipping): Calculates the L2 norm for each individual leaf; & if a leaf’s norm exceeds its corresponding threshold inclip_norm, that specific leaf is scaled down. Theclip_normPyTree structure must be a prefix of the inputpytree. Whereclip_normterminates early, its leaf values automatically broadcast down to match all corresponding sub-leaves ofpytree.
If
rescale_to_unit_normisTrue, the PyTree is additionally scaled by1.0 / clip_norm(resulting in a norm of at most 1.0 no matter whatclip_normis). 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_normifrescale_to_unit_normisFalse, and at most 1.0 if it isTrue. 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) – IfTrue, the output PyTree’s norm is rescaled by1.0 / clip_normafter potential clipping. IfFalse, the output PyTree has norm at mostclip_norm.
- Returns:
A tuple
(clipped_pytree, original_l2_norm), whereclipped_pytreeis the processed PyTree andoriginal_l2_normis the L2 norm of the input PyTree. In case of per-layer clipping,original_l2_normis a PyTree containing L2 norms of each leaf.