1616
1717from typing import Any , NamedTuple , Optional
1818
19+ import chex
1920import jax
2021from optax ._src import base
2122from optax ._src import clipping
2223from optax ._src import combine
2324from optax ._src import transform
25+ from optax ._src import utils
2426
2527
2628class DifferentiallyPrivateAggregateState (NamedTuple ):
@@ -33,14 +35,16 @@ class DifferentiallyPrivateAggregateState(NamedTuple):
3335
3436
3537def differentially_private_aggregate (
36- l2_norm_clip : float , noise_multiplier : float , seed : int
38+ l2_norm_clip : float ,
39+ noise_multiplier : float ,
40+ key : chex .PRNGKey | int
3741) -> base .GradientTransformation :
3842 """Aggregates gradients based on the DPSGD algorithm.
3943
4044 Args:
4145 l2_norm_clip: maximum L2 norm of the per-example gradients.
4246 noise_multiplier: ratio of standard deviation to the clipping norm.
43- seed: initial seed used for the jax. random.PRNGKey
47+ key: a PRNG key used as the random key.
4448
4549 Returns:
4650 A :class:`optax.GradientTransformation`.
@@ -63,10 +67,11 @@ def differentially_private_aggregate(
6367 specific way.
6468 """
6569 noise_std = l2_norm_clip * noise_multiplier
70+ key = utils .to_random_key (key )
6671
6772 def init_fn (params ):
6873 del params
69- return DifferentiallyPrivateAggregateState (rng_key = jax . random . PRNGKey ( seed ))
74+ return DifferentiallyPrivateAggregateState (rng_key = utils . to_random_key ( key ))
7075
7176 def update_fn (updates , state , params = None ):
7277 del params
@@ -91,7 +96,7 @@ def dpsgd(
9196 learning_rate : base .ScalarOrSchedule ,
9297 l2_norm_clip : float ,
9398 noise_multiplier : float ,
94- seed : int ,
99+ key : chex . PRNGKey | int ,
95100 momentum : Optional [float ] = None ,
96101 nesterov : bool = False ,
97102) -> base .GradientTransformation :
@@ -106,7 +111,7 @@ def dpsgd(
106111 learning_rate: A fixed global scaling factor.
107112 l2_norm_clip: Maximum L2 norm of the per-example gradients.
108113 noise_multiplier: Ratio of standard deviation to the clipping norm.
109- seed: Initial seed used for the jax. random.PRNGKey
114+ key: a PRNG key used as the random key.
110115 momentum: Decay rate used by the momentum term, when it is set to `None`,
111116 then momentum is not used at all.
112117 nesterov: Whether Nesterov momentum is used.
@@ -133,7 +138,7 @@ def dpsgd(
133138 differentially_private_aggregate (
134139 l2_norm_clip = l2_norm_clip ,
135140 noise_multiplier = noise_multiplier ,
136- seed = seed ,
141+ key = utils . to_random_key ( key ) ,
137142 ),
138143 (
139144 transform .trace (decay = momentum , nesterov = nesterov )
0 commit comments