privacyarena-mia-data / code /mia /membership.py
dwahdany's picture
Upload folder using huggingface_hub
90566fd
"""Membership matrix generation and management for LiRA-style MIA experiments."""
import numpy as np
from pathlib import Path
from typing import Optional
def create_membership_matrix(
num_samples: int,
num_models: int,
seed: int = 0,
) -> np.ndarray:
"""
Create a membership matrix where each sample appears in exactly 50% of models.
Args:
num_samples: Total number of samples in the dataset
num_models: Number of models to create membership for
seed: Random seed for reproducibility
Returns:
Boolean matrix of shape (num_samples, num_models) where
matrix[i, j] = True means sample i is IN model j's training set
"""
rng = np.random.RandomState(seed)
matrix = np.zeros((num_samples, num_models), dtype=bool)
models_per_sample = num_models // 2
for sample_idx in range(num_samples):
# Each sample appears in exactly half the models
selected_models = rng.choice(num_models, size=models_per_sample, replace=False)
matrix[sample_idx, selected_models] = True
return matrix
class MembershipMatrix:
"""Manages membership matrices for MIA experiments."""
def __init__(
self,
matrix: np.ndarray,
seed: int,
name: str = "membership",
):
"""
Initialize membership matrix.
Args:
matrix: Boolean array of shape (num_samples, num_models)
seed: Random seed used to generate the matrix
name: Name identifier for this matrix (e.g., 'shadow', 'target_train')
"""
self.matrix = matrix
self.seed = seed
self.name = name
@property
def num_samples(self) -> int:
return self.matrix.shape[0]
@property
def num_models(self) -> int:
return self.matrix.shape[1]
@classmethod
def create(
cls,
num_samples: int,
num_models: int,
seed: int = 0,
name: str = "membership",
) -> "MembershipMatrix":
"""Create a new membership matrix."""
matrix = create_membership_matrix(num_samples, num_models, seed)
return cls(matrix, seed, name)
def get_in_indices(self, model_id: int) -> np.ndarray:
"""Get indices of samples that are IN the training set for model_id."""
return np.where(self.matrix[:, model_id])[0]
def get_out_indices(self, model_id: int) -> np.ndarray:
"""Get indices of samples that are OUT of the training set for model_id."""
return np.where(~self.matrix[:, model_id])[0]
def is_member(self, sample_idx: int, model_id: int) -> bool:
"""Check if sample is a member of model's training set."""
return self.matrix[sample_idx, model_id]
def get_membership_labels(self, model_id: int) -> np.ndarray:
"""Get membership labels (1=IN, 0=OUT) for all samples for a given model."""
return self.matrix[:, model_id].astype(int)
def get_sample_membership_count(self, sample_idx: int) -> int:
"""Get number of models that include this sample."""
return self.matrix[sample_idx].sum()
def get_model_sample_count(self, model_id: int) -> int:
"""Get number of samples in this model's training set."""
return self.matrix[:, model_id].sum()
def save(self, path: Path) -> None:
"""Save membership matrix to disk."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
np.savez(
path,
matrix=self.matrix,
seed=self.seed,
name=self.name,
)
@classmethod
def load(cls, path: Path) -> "MembershipMatrix":
"""Load membership matrix from disk."""
data = np.load(path)
return cls(
matrix=data["matrix"],
seed=int(data["seed"]),
name=str(data["name"]),
)
def __repr__(self) -> str:
return (
f"MembershipMatrix(name='{self.name}', "
f"samples={self.num_samples}, models={self.num_models}, seed={self.seed})"
)
def stats(self) -> dict:
"""Get statistics about the membership matrix."""
samples_per_model = self.matrix.sum(axis=0)
models_per_sample = self.matrix.sum(axis=1)
return {
"num_samples": self.num_samples,
"num_models": self.num_models,
"samples_per_model_mean": samples_per_model.mean(),
"samples_per_model_std": samples_per_model.std(),
"models_per_sample_mean": models_per_sample.mean(),
"models_per_sample_std": models_per_sample.std(),
"expected_models_per_sample": self.num_models // 2,
}