jax_privacy.clipping.clipped_grad#
- jax_privacy.clipping.clipped_grad(fun, argnums=0, has_aux=False, *, l2_clip_norm, rescale_to_unit_norm=False, normalize_by=1.0, batch_argnums=1, keep_batch_dim=True, return_values=False, return_grad_norms=False, pre_clipping_transform=<function <lambda>>, microbatch_size=None, nan_safe=True, dtype=None, prng_argnum=None, spmd_axis_name=None, grid_scale=None, slack=None)[source]#
Create a function to compute the sum of clipped gradients of fun.
This function acts as a transformation similar to
jax.grad(), but with added functionality for gradient clipping applied on a per-example (or per-group) basis before summation. It computes the gradient offunwith respect toargnums, calculates the L2 norm of the gradient for each example slice along the first axis of thebatch_argnumsargs, clips each per-example gradient to have a norm of at mostl2_clip_norm, and finally sums these clipped gradients.Non-grad outputs of the returned function (aux, values, grad_norms) may optionally be returned by setting the arguments
has_aux,return_values, and/orreturn_grad_normstoTrue. These outputs are per-example, and hence have a batch axis. It is up to the caller to handle these as necessary. See theDP Sensitivity Guaranteebelow for more details on this design choice.- Example Usage:
>>> import jax.numpy as jnp >>> f = lambda param, data: 0.5 * jnp.mean((data - param)**2) >>> g = clipped_grad(f, l2_clip_norm=jnp.inf) >>> g(3.0, jnp.array([0, 7, -2])) Array(4., dtype=float32)
- Example Usage (with Auxiliary Output):
>>> g = clipped_grad( ... f, l2_clip_norm=jnp.inf, return_values=True, return_grad_norms=True ... ) >>> _, aux = g(3.0, jnp.array([0, 7, -2])) >>> aux.values Array([ 4.5, 8. , 12.5], dtype=float32) >>> aux.grad_norms Array([3., 4., 5.], dtype=float32)
- Example Usage (with Per-User Clipping):
>>> f = lambda param, data: 0.5 * jnp.mean((data - param)**2) >>> g = clipped_grad(f, l2_clip_norm=jnp.inf, keep_batch_dim=False) >>> userA = jnp.array([1, -1]) >>> userB = jnp.array([2, 2]) >>> userC = jnp.array([0, 3]) >>> g(3.0, jnp.array([userA, userB, userC])) Array(5.5, dtype=float32)
- Formal Guarantees:
- For the primary output:
When
slackis set, the primary output contains both the gradient and slack fields ofClippedGradOutput; otherwise it is the gradient PyTree. The L2 sensitivity of the returned callable is a complex function of the input parameters (l2_clip_norm,rescale_to_unit_norm,normalize_by,grid_scale, per-layer clipping settings, etc.) and may change as new features are added. Rather than reasoning about the sensitivity from the parameters, callers should query the returned callable’s.sensitivity()method (or equivalently its.l2_norm_boundattribute for add-or-remove-one DP) directly.- All auxiliary outputs (aux, values, grad_norms) are per-example. This
function guarantees that per-example outputs only depend on the data for the same example. This allows maximum flexibility for the caller to aggregate these as desired (possibly with a DP mean, median, quantile, or histogram mechanism).
- Parameters:
fun (
Callable) – The function to be differentiated, which should return a scalar loss value. Ifhas_auxisTrue, it should return a tuple(value, aux).argnums (
int|Sequence[int]) – Specifies which argument(s) offunto differentiate with respect to. Can be an integer or a sequence of integers. These arguments should not have a batch dimension.has_aux (
bool) – IfTrue,funis expected to return a tuple(value, aux). The auxiliary dataauxwill be returned by the transformed function. Exercise caution when using this as no DP sensitivity guarantees are provided for the auxiliary data.l2_clip_norm (
Union[float,Array,ndarray,bool,number,bool,int,complex,Iterable[optax.ArrayTree],Mapping[Any, optax.ArrayTree]]) – The maximum L2 norm for each per-example gradient. Gradients with a norm larger than this value will be scaled down. Can be a single float or a PyTree. If Scalar: It does global clipping across all gradients. If PyTree: It does per-layer clipping and contains l2 norm associated with each leaf of the PyTree. 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.rescale_to_unit_norm (
bool) – IfTrue, the clipped gradient PyTree’s norm is rescaled by1.0 / l2_clip_normafter potential clipping. IfFalse, each per-example gradient has norm at mostl2_clip_norm. Sensitivity also depends onnormalize_byand per-layer clipping; use.sensitivity()/.l2_norm_boundrather than deriving it from these flags. The motivation for setting this toTrueis to decouple the clipping norm from the learning rate for non-adaptive optimizers, as described in https://arxiv.org/abs/2204.13650normalize_by (
float) – Divide the clipped output by this value before returning.batch_argnums (
int|Sequence[int]) – Specifies which argument(s) offuncontain the batch dimension (usually the data and labels). Can be an integer or a sequence of integers. All arguments specified here must have the same size along their first dimension (the batch dimension). The default value of 1 assumes the signature of fun isfun(params, batch).keep_batch_dim (
bool) – IfTrue, batch inputs will be passed tofunwith a leading batch axis of size 1. IfFalse, this size 1 axis will be dropped (reducing the rank of the batch args by 1 before passing tofun). The default value ofTrueassumes thatfunexpects inputs with a batch axis. Overriding this default can be useful if fun defines the loss function for a single example, or if clipping should be applied at the group or user level (in which case an extra batch axis is added to the inputs).return_values (
bool) – IfTrue, the transformed function will also return the per-example values, before clipping.return_grad_norms (
bool) – IfTrue, the transformed function will also return the per-example gradient norms, before clipping. Ifl2_clip_normis a scalar, it returns a single global norm for the entire gradient PyTree. Ifl2_clip_normis a PyTree, it returns a matching PyTree structure where each leaf contains the L2 norm of the corresponding subtree in the gradient PyTree.pre_clipping_transform (
Callable[[Union[Array,ndarray,bool,number,bool,int,float,complex,Iterable[optax.ArrayTree],Mapping[Any, optax.ArrayTree]]],Union[Array,ndarray,bool,number,bool,int,float,complex,Iterable[optax.ArrayTree],Mapping[Any, optax.ArrayTree]]]) – An optional function to apply to the per-example gradients before clipping. The function should consume the gradient pytree for a single example and return a new pytree (possibly with different structure). Can be used to e.g., scale the leaves of the pytree to accommodate preconditioner clipping. Does not affect the sensitivity guarantee.microbatch_size (
int|None) – If set, input groups are formed into microbatches of this size. These microbatches are then processed sequentially, with operations on the groups within each microbatch being vectorized usingjax.vmap(). This can be used to reduce peak memory usage at the cost of increased sequential computation. Microbatching will be at the level of users/groups. E.g., if there are 500 users, with 7 examples per user, andmicrobatch_size=100, then the input will be broken into 5 microbatches of 100 users, and when processing a microbatch,funwill be invoked 100 times (in parallel with vmap) on groups of 7 examples.nan_safe (
bool) – IfTrue, per-example gradients with non-finite L2 norms (NaN or inf) are zeroed out before aggregation, preserving the formal guarantees.dtype (
Union[str,type[Any],dtype,SupportsDType,None]) – Optional dtype for the returned gradient. IfNone, the dtype will be the same as the dtypes of the gradient function. Can be useful to avoid overflow issues when using low-precision dtypes as the returned function computes a sum over a potentially large batch.prng_argnum (
int|None) – If set, specifies which argument offunis a PRNG key. The PRNG will be split to have a batch dimension and vmapped over.spmd_axis_name (
str|None) – Seejax.vmap(). Only relevant in distributed settings.grid_scale (
int|None) – If set, per-example grads are additionally scaled and rounded to an integer grid after clipping. Specifically, each clipped grad is multiplied bygrid_scale / l2_clip_norm, rounded to the nearest integer, and cast tojnp.int64. The clipping norm is tightened automatically so that the integer L2 norm of each rounded output is at mostgrid_scale. This option is designed for use with the discrete Gaussian mechanism. Incompatible withrescale_to_unit_norm=Trueandnormalize_by != 1.0. When set,dtypeis ignored (output is alwaysjnp.int64).slack (
int|None) – Optional number of SlaClip slack coordinates. Must be a positive Python integer. When set, the sensitivity-bounded primary output is aClippedGradOutput. Its gradient and slack fields must be privatized together. The float32 slack is built from the same norm used for clipping afterpre_clipping_transform. Only scalar global clipping is currently supported.
- Return type:
- Returns:
A
BoundedSensitivityCallablewrapping a new functionvalues_and_clipped_grad_fnthat computes the sum of clipped per-group gradients offun. The returned callable accepts the same positional arguments asfun, plus an optionalis_padding_examplekeyword argument (see__call__()for details).The returned function returns
gradifreturn_values,return_grad_norms, andhas_auxare allFalse. Otherwise, it returns a tuple(grad, AuxiliaryOutput), whereAuxiliaryOutputis a namedtuple with fields(values, grad_norms, aux). Each field is set toNonewhen its corresponding flag isFalse:valuesisNoneunlessreturn_values=True,grad_normsisNoneunlessreturn_grad_norms=True, andauxisNoneunlesshas_aux=True. When present, these outputs are per-example (i.e., they retain a batch axis).When
slackis set, grad is aClippedGradOutput; otherwise it retains the original gradient structure.