Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions opacus/grad_sample/embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ def compute_embedding_grad_sample(
layer: Layer
activations: Activations
backprops: Backpropagations

Note:
The input activations are expected to carry the batch dimension as the first dimension.
When fine-tuning transformer models (such as GPT-2 or BERT) where position IDs might be
unexpanded or broadcasted (e.g. shape ``[1, seq_len]``), inputs must be explicitly expanded
to match the batch size (e.g., ``position_ids.expand(batch_size, -1)``) or frozen with
``requires_grad=False`` to ensure valid per-sample gradients can be computed.
"""
activations = activations[0]
ret = {}
Expand Down
5 changes: 4 additions & 1 deletion opacus/grad_sample/grad_sample_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
trainable_parameters,
)


logger = logging.getLogger(__name__)
logger.disabled = True

Expand Down Expand Up @@ -138,6 +137,10 @@ def __init__(
"Using non-strict mode, continuing"
)

for p_name, p in trainable_parameters(self._module):
if not hasattr(p, "_param_name"):
p._param_name = p_name

self.hooks_enabled = False
self.grad_accumulation_allowed = True
self.batch_first = batch_first
Expand Down
3 changes: 2 additions & 1 deletion opacus/optimizers/adaclipoptimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
_generate_noise,
_mark_as_processed,
)

from .utils import check_grad_sample_batch_size_consistency

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -89,6 +89,7 @@ def zero_grad(self, set_to_none: bool = False):
self.unclipped_num = 0

def clip_and_accumulate(self):
check_grad_sample_batch_size_consistency(self.params, self.grad_samples)
per_param_norms = [
g.view(len(g), -1).norm(2, dim=-1) for g in self.grad_samples
]
Expand Down
7 changes: 5 additions & 2 deletions opacus/optimizers/optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@
from typing import Callable, List, Optional, Union

import torch
from opacus.optimizers.utils import params
from opacus.optimizers.utils import (
check_grad_sample_batch_size_consistency,
params,
)
from torch import nn
from torch.distributed.tensor import DTensor
from torch.optim import Optimizer


logger = logging.getLogger(__name__)
logger.disabled = True

Expand Down Expand Up @@ -441,6 +443,7 @@ def clip_and_accumulate(self):
(0,), device=self.grad_samples[0].device
)
else:
check_grad_sample_batch_size_consistency(self.params, self.grad_samples)
per_param_norms = [
g.reshape(len(g), -1).norm(2, dim=-1) for g in self.grad_samples
]
Expand Down
6 changes: 5 additions & 1 deletion opacus/optimizers/perlayeroptimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
from typing import List, Optional

import torch
from opacus.optimizers.utils import params
from opacus.optimizers.utils import (
check_grad_sample_batch_size_consistency,
params,
)
from torch.optim import Optimizer

from .optimizer import DPOptimizer, _check_processed_flag, _mark_as_processed
Expand Down Expand Up @@ -56,6 +59,7 @@ def __init__(
)

def clip_and_accumulate(self):
check_grad_sample_batch_size_consistency(self.params, self.grad_samples)
for p, max_grad_norm in zip(self.params, self.max_grad_norms):
_check_processed_flag(p.grad_sample)

Expand Down
47 changes: 47 additions & 0 deletions opacus/optimizers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from collections import Counter
from typing import List

import torch
import torch.nn as nn
from torch.optim import Optimizer

Expand All @@ -31,3 +33,48 @@ def params(optimizer: Optimizer) -> List[nn.Parameter]:
for param_group in optimizer.param_groups:
ret += [p for p in param_group["params"] if p.requires_grad]
return ret


def check_grad_sample_batch_size_consistency(
params: List[torch.Tensor], grad_samples: List[torch.Tensor]
) -> None:
"""
Validates that all per-sample gradient tensors have a consistent batch size (first dimension).

Args:
params: List of parameters
grad_samples: List of per-sample gradient tensors corresponding to params

Raises:
ValueError: If different parameters have different batch sizes (e.g. due to batch-broadcasted
or unexpanded inputs in embedding layers).
"""
if not grad_samples:
return

batch_sizes = [len(g) for g in grad_samples]
if len(set(batch_sizes)) <= 1:
return

counts = Counter(batch_sizes)
expected_batch_size = counts.most_common(1)[0][0]
mismatches = []
for p, g in zip(params, grad_samples):
if len(g) != expected_batch_size:
param_name = (
getattr(p, "_param_name", None)
or getattr(p, "name", None)
or f"tensor with shape {tuple(p.shape)}"
)
mismatches.append(
f"Parameter ({param_name}) has batch dimension {len(g)}, expected {expected_batch_size}"
)

mismatch_str = "; ".join(mismatches)
raise ValueError(
f"Inconsistent per-sample gradient batch dimensions across parameters: {mismatch_str}. "
"This often occurs when a layer receives batch-broadcasted or unexpanded inputs (e.g., position "
"embeddings with batch size 1 in models like GPT-2). For differential privacy, each trainable "
"parameter must receive inputs expanded along the batch dimension (e.g., position_ids.expand(batch_size, -1)), "
"or be frozen with requires_grad=False if it should not be trained privately."
)
242 changes: 242 additions & 0 deletions opacus/tests/batch_broadcast_embedding_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

import torch
import torch.nn as nn
from opacus import PrivacyEngine
from opacus.optimizers.adaclipoptimizer import AdaClipDPOptimizer
from opacus.optimizers.perlayeroptimizer import DPPerLayerOptimizer
from opacus.optimizers.utils import check_grad_sample_batch_size_consistency


class BroadcastEmbeddingModel(nn.Module):
def __init__(self, vocab_size=50, max_positions=32, embedding_dim=16):
super().__init__()
self.wte = nn.Embedding(vocab_size, embedding_dim)
self.wpe = nn.Embedding(max_positions, embedding_dim)

def forward(self, input_ids, position_ids=None):
B, T = input_ids.shape
if position_ids is None:
# Broadcasted position embeddings with batch size 1 (like HuggingFace GPT-2)
position_ids = torch.arange(T, device=input_ids.device).unsqueeze(0)
return self.wte(input_ids) + self.wpe(position_ids)


class BatchBroadcastEmbeddingTest(unittest.TestCase):
def test_check_grad_sample_batch_size_consistency_unit(self):
p1 = nn.Parameter(torch.zeros(10, 16))
p1._param_name = "wte.weight"
p2 = nn.Parameter(torch.zeros(10, 16))
p2._param_name = "wpe.weight"

# Matching batch sizes (batch_size=4)
g1 = torch.zeros(4, 10, 16)
g2 = torch.zeros(4, 10, 16)
check_grad_sample_batch_size_consistency([p1, p2], [g1, g2])

# Mismatched batch sizes (4 vs 1)
g2_mismatch = torch.zeros(1, 10, 16)
with self.assertRaises(ValueError) as ctx:
check_grad_sample_batch_size_consistency([p1, p2], [g1, g2_mismatch])

err_msg = str(ctx.exception)
self.assertIn("Inconsistent per-sample gradient batch dimensions", err_msg)
self.assertIn("wpe.weight", err_msg)
self.assertIn("batch dimension 1, expected 4", err_msg)
self.assertIn("position_ids.expand", err_msg)

def test_unexpanded_position_ids_raises_informative_error(self):
model = BroadcastEmbeddingModel()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
privacy_engine = PrivacyEngine()
model, optimizer, _ = privacy_engine.make_private(
module=model,
optimizer=optimizer,
data_loader=torch.utils.data.DataLoader(
torch.randint(0, 50, (8, 10)), batch_size=4
),
noise_multiplier=1.0,
max_grad_norm=1.0,
)

input_ids = torch.randint(0, 50, (4, 10))
# Forward with unexpanded position IDs (broadcasted internally)
out = model(input_ids)
loss = out.sum()
loss.backward()

with self.assertRaises(ValueError) as ctx:
optimizer.step()

err_msg = str(ctx.exception)
self.assertIn("Inconsistent per-sample gradient batch dimensions", err_msg)
self.assertIn("wpe.weight", err_msg)
self.assertIn("batch dimension 1, expected 4", err_msg)

def test_expanded_position_ids_succeeds(self):
model = BroadcastEmbeddingModel()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
privacy_engine = PrivacyEngine()
model, optimizer, _ = privacy_engine.make_private(
module=model,
optimizer=optimizer,
data_loader=torch.utils.data.DataLoader(
torch.randint(0, 50, (8, 10)), batch_size=4
),
noise_multiplier=1.0,
max_grad_norm=1.0,
)

B, T = 4, 10
input_ids = torch.randint(0, 50, (B, T))
position_ids = torch.arange(T).unsqueeze(0).expand(B, T)
out = model(input_ids, position_ids=position_ids)
loss = out.sum()
loss.backward()

# Should step without errors
optimizer.step()
self.assertEqual(model._module.wte.weight.grad_sample.shape[0], B)
self.assertEqual(model._module.wpe.weight.grad_sample.shape[0], B)

def test_frozen_position_embedding_succeeds(self):
model = BroadcastEmbeddingModel()
model.wpe.weight.requires_grad = False
trainable_params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(trainable_params, lr=0.1)
privacy_engine = PrivacyEngine()
model, optimizer, _ = privacy_engine.make_private(
module=model,
optimizer=optimizer,
data_loader=torch.utils.data.DataLoader(
torch.randint(0, 50, (8, 10)), batch_size=4
),
noise_multiplier=1.0,
max_grad_norm=1.0,
)

input_ids = torch.randint(0, 50, (4, 10))
out = model(input_ids) # uses unexpanded position IDs, but wpe is frozen
loss = out.sum()
loss.backward()

optimizer.step()
self.assertEqual(model._module.wte.weight.grad_sample.shape[0], 4)
self.assertFalse(hasattr(model._module.wpe.weight, "grad_sample"))

def test_adaclip_mismatch_raises_informative_error(self):
model = BroadcastEmbeddingModel()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
dp_opt = AdaClipDPOptimizer(
optimizer=optimizer,
noise_multiplier=1.0,
max_grad_norm=1.0,
expected_batch_size=4,
target_unclipped_quantile=0.8,
clipbound_learning_rate=0.1,
max_clipbound=10.0,
min_clipbound=0.1,
unclipped_num_std=1.0,
)
p1, p2 = model.wte.weight, model.wpe.weight
p1._param_name = "wte.weight"
p2._param_name = "wpe.weight"
p1.grad_sample = torch.zeros(4, 50, 16)
p2.grad_sample = torch.zeros(1, 32, 16)

with self.assertRaises(ValueError) as ctx:
dp_opt.clip_and_accumulate()

self.assertIn(
"Inconsistent per-sample gradient batch dimensions", str(ctx.exception)
)

def test_perlayer_mismatch_raises_informative_error(self):
model = BroadcastEmbeddingModel()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
dp_opt = DPPerLayerOptimizer(
optimizer=optimizer,
noise_multiplier=1.0,
max_grad_norm=[1.0, 1.0],
expected_batch_size=4,
)
p1, p2 = model.wte.weight, model.wpe.weight
p1._param_name = "wte.weight"
p2._param_name = "wpe.weight"
p1.grad_sample = torch.zeros(4, 50, 16)
p2.grad_sample = torch.zeros(1, 32, 16)

with self.assertRaises(ValueError) as ctx:
dp_opt.clip_and_accumulate()

self.assertIn(
"Inconsistent per-sample gradient batch dimensions", str(ctx.exception)
)

def test_gpt2_full_finetuning_informative_error_and_resolution(self):
try:
from transformers import GPT2Config, GPT2LMHeadModel
except ImportError:
self.skipTest("transformers not installed")

config = GPT2Config(
vocab_size=100, n_positions=64, n_embd=32, n_layer=2, n_head=2
)
model = GPT2LMHeadModel(config)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
privacy_engine = PrivacyEngine()
model, optimizer, _ = privacy_engine.make_private(
module=model,
optimizer=optimizer,
data_loader=torch.utils.data.DataLoader(
torch.randint(0, 100, (8, 16)), batch_size=4
),
noise_multiplier=1.0,
max_grad_norm=1.0,
)

B, T = 4, 16
input_ids = torch.randint(0, 100, (B, T))

# 1. Without explicit position_ids (GPT-2 broadcasts [1, T] position embeddings):
# Must raise informative ValueError mentioning transformer.wpe.weight
outputs = model(input_ids=input_ids, labels=input_ids)
outputs.loss.backward()
with self.assertRaises(ValueError) as ctx:
optimizer.step()

err_msg = str(ctx.exception)
self.assertIn("Inconsistent per-sample gradient batch dimensions", err_msg)
self.assertIn("transformer.wpe.weight", err_msg)
self.assertIn("batch dimension 1, expected 4", err_msg)

# Clear grads for second test
optimizer.zero_grad()

# 2. With expanded position_ids: Must succeed!
position_ids = torch.arange(T).unsqueeze(0).expand(B, T)
outputs = model(
input_ids=input_ids, position_ids=position_ids, labels=input_ids
)
outputs.loss.backward()
optimizer.step()
self.assertEqual(model._module.transformer.wpe.weight.grad_sample.shape[0], B)


if __name__ == "__main__":
unittest.main()