Skip to content

Commit

Permalink
Update doc (#177)
Browse files Browse the repository at this point in the history
* add the contribution guide

* fix typos

* update

* solve callble issues

* update docstrings
  • Loading branch information
Koukyosyumei authored Apr 7, 2024
1 parent 22d3fcc commit f65f82b
Show file tree
Hide file tree
Showing 20 changed files with 627 additions and 19 deletions.
21 changes: 21 additions & 0 deletions docs/source/aijack.collaborative.fedexp.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
aijack.collaborative.fedexp package
===================================

Submodules
----------

aijack.collaborative.fedexp.server module
-----------------------------------------

.. automodule:: aijack.collaborative.fedexp.server
:members:
:undoc-members:
:show-inheritance:

Module contents
---------------

.. automodule:: aijack.collaborative.fedexp
:members:
:undoc-members:
:show-inheritance:
21 changes: 21 additions & 0 deletions docs/source/aijack.collaborative.moon.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
aijack.collaborative.moon package
=================================

Submodules
----------

aijack.collaborative.moon.client module
---------------------------------------

.. automodule:: aijack.collaborative.moon.client
:members:
:undoc-members:
:show-inheritance:

Module contents
---------------

.. automodule:: aijack.collaborative.moon
:members:
:undoc-members:
:show-inheritance:
2 changes: 2 additions & 0 deletions docs/source/aijack.collaborative.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ Subpackages
aijack.collaborative.core
aijack.collaborative.dsfl
aijack.collaborative.fedavg
aijack.collaborative.fedexp
aijack.collaborative.fedgems
aijack.collaborative.fedkd
aijack.collaborative.fedmd
aijack.collaborative.fedprox
aijack.collaborative.moon
aijack.collaborative.optimizer
aijack.collaborative.splitnn
aijack.collaborative.tree
Expand Down
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,4 @@
"style.css",
]

jupyter_execute_notebooks = "off"
nb_execution_mode = "off"
34 changes: 34 additions & 0 deletions src/aijack/attack/evasion/diva.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,30 @@


class DIVAWhiteBoxAttacker(BaseAttacker):
"""Class implementing the DIVA white-box attack.
This class provides functionality to perform the DIVA white-box attack on a target model.
Args:
target_model (torch.nn.Module): The target model to be attacked.
target_model_on_edge (torch.nn.Module): The target model deployed on the edge.
c (float, optional): The trade-off parameter between origin and edge predictions. Defaults to 1.0.
num_itr (int, optional): The number of iterations for the attack. Defaults to 1000.
eps (float, optional): The maximum perturbation allowed. Defaults to 0.1.
lam (float, optional): The step size for gradient updates. Defaults to 0.01.
device (str, optional): The device to perform computation on. Defaults to "cpu".
Attributes:
target_model (torch.nn.Module): The target model to be attacked.
target_model_on_edge (torch.nn.Module): The target model deployed on the edge.
c (float): The trade-off parameter between origin and edge predictions.
num_itr (int): The number of iterations for the attack.
eps (float): The maximum perturbation allowed.
lam (float): The step size for gradient updates.
device (str): The device to perform computation on.
"""

def __init__(
self,
target_model,
Expand All @@ -23,6 +47,16 @@ def __init__(
self.device = device

def attack(self, data):
"""Performs the DIVA white-box attack on input data.
Args:
data (tuple): A tuple containing input data and corresponding labels.
Returns:
tuple: A tuple containing the adversarial examples and attack logs.
"""

x, y = data
x = x.to(self.device)
y = y.to(self.device)
Expand Down
22 changes: 4 additions & 18 deletions src/aijack/attack/evasion/evasion_attack.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@


class Evasion_attack_sklearn(BaseAttacker):
"""Creates an adversarial example against sklearn objects
reference https://arxiv.org/abs/1708.06131
"""Creates an adversarial example against sklearn objects based on https://arxiv.org/abs/1708.06131
Args:
target_model (sklearn): sklearn classifier
Expand All @@ -26,10 +25,8 @@ class Evasion_attack_sklearn(BaseAttacker):
Attributes:
target_model (sklearn): sklearn classifier
X_minus_1 (numpy.array): datasets that contains
only the class you want to misclasssify
dmax (float): max distance between the adversarial example
and initial one
X_minus_1 (numpy.array): datasets that contains only the class you want to misclasssify
dmax (float): max distance between the adversarial example and initial one
max_iter (int): maxium number of iterations
gamma (float): parameter gamma of svm (used for only svm)
lam (float): trade - off parameter
Expand All @@ -38,22 +35,11 @@ class Evasion_attack_sklearn(BaseAttacker):
distance (str): type of distance such as L2 or L1
kde_type (str): type of kernel density estimator
n_minus_1 (int): number of rows of X_minus_1
delta_g (func): deviation of he discriminant function of a
surrogate classifier f learnt on D
delta_g (func): deviation of he discriminant function of a surrogate classifier f learnt on D
Raises:
ValueError: if given distance is not supported.
Examples:
>>>X_minus_1 = X_train[np.where(y_train == "3")]
>>>attacker = Attack_sklearn(target_model = target_model,
X_minus_1 = X_minus_1,
dmax = (5000 / 255) * 2.5,
max_iter = 300,
gamma = 1 / (X_train.shape[1] *
np.var(X_train)),
lam = 10, t = 0.5, h = 10)
>>>xm, log = attacker.attack(x0)
"""

def __init__(
Expand Down
31 changes: 31 additions & 0 deletions src/aijack/attack/evasion/fgsm.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,29 @@


class FGSMAttacker(BaseAttacker):
"""Class implementing the Fast Gradient Sign Method (FGSM) attack.
This class provides functionality to perform the FGSM attack on a target model.
Args:
target_model (torch.nn.Module): The target model to be attacked.
criterion: The criterion to compute the loss.
eps (float, optional): The epsilon value for the FGSM attack. Defaults to 0.3.
grad_lower_bound (float, optional): The lower bound for the gradient. Defaults to -0.1.
grad_upper_bound (float, optional): The upper bound for the gradient. Defaults to 0.1.
output_lower_bound (float, optional): The lower bound for the output values. Defaults to -1.0.
output_upper_bound (float, optional): The upper bound for the output values. Defaults to 1.0.
Attributes:
target_model (torch.nn.Module): The target model to be attacked.
criterion: The criterion to compute the loss.
eps (float): The epsilon value for the FGSM attack.
grad_lower_bound (float): The lower bound for the gradient.
grad_upper_bound (float): The upper bound for the gradient.
output_lower_bound (float): The lower bound for the output values.
output_upper_bound (float): The upper bound for the output values.
"""

def __init__(
self,
target_model,
Expand All @@ -24,6 +47,14 @@ def __init__(
self.output_upper_bound = output_upper_bound

def attack(self, data):
"""Performs the FGSM attack on input seed data.
Args:
data (tuple): A tuple containing input seed data and corresponding labels.
Returns:
torch.Tensor: The perturbed input data.
"""
x, y = data
x.requires_grad = True

Expand Down
20 changes: 20 additions & 0 deletions src/aijack/attack/inversion/utils/distance.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
def l2(fake_gradients, received_gradients, gradient_ignore_pos):
"""Computes the L2 distance between fake and received gradients.
Args:
fake_gradients (list of torch.Tensor): List of fake gradients.
received_gradients (list of torch.Tensor): List of received gradients.
gradient_ignore_pos (list of int): Positions to ignore while computing distance.
Returns:
float: The L2 distance.
"""
distance = 0
for i, (f_g, c_g) in enumerate(zip(fake_gradients, received_gradients)):
if i not in gradient_ignore_pos:
Expand All @@ -7,6 +17,16 @@ def l2(fake_gradients, received_gradients, gradient_ignore_pos):


def cossim(fake_gradients, received_gradients, gradient_ignore_pos):
"""Computes the cosine similarity distance between fake and received gradients.
Args:
fake_gradients (list of torch.Tensor): List of fake gradients.
received_gradients (list of torch.Tensor): List of received gradients.
gradient_ignore_pos (list of int): Positions to ignore while computing distance.
Returns:
float: The cosine similarity distance.
"""
distance = 0
pnorm_0 = 0
pnorm_1 = 0
Expand Down
35 changes: 35 additions & 0 deletions src/aijack/attack/inversion/utils/regularization.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,58 @@


def total_variance(x):
"""Computes the total variance of an input tensor.
Args:
x (torch.Tensor): The input tensor.
Returns:
torch.Tensor: The total variance.
"""
dx = torch.mean(torch.abs(x[:, :, :, :-1] - x[:, :, :, 1:]))
dy = torch.mean(torch.abs(x[:, :, :-1, :] - x[:, :, 1:, :]))
return dx + dy


def label_matching(pred, label):
"""Computes the label matching loss between predicted and target labels.
Args:
pred (torch.Tensor): Predicted labels.
label (torch.Tensor): Target labels.
Returns:
torch.Tensor: The label matching loss.
"""
onehot_label = torch.eye(pred.shape[-1])[label]
onehot_label = onehot_label.to(pred.device)
return torch.sqrt(torch.sum((pred - onehot_label) ** 2))


def group_consistency(x, group_x):
"""Computes the group consistency loss between an input and a group of inputs.
Args:
x (torch.Tensor): The input tensor.
group_x (list): List of tensors representing the group.
Returns:
torch.Tensor: The group consistency loss.
"""
mean_group_x = sum(group_x) / len(group_x)
return torch.norm(x - mean_group_x, p=2)


def bn_regularizer(feature_maps, bn_layers):
"""Computes the batch normalization regularizer loss.
Args:
feature_maps (list): List of feature maps.
bn_layers (list): List of batch normalization layers.
Returns:
torch.Tensor: The batch normalization regularizer loss.
"""
bn_reg = 0
for i, layer in enumerate(bn_layers):
fm = feature_maps[i]
Expand Down
12 changes: 12 additions & 0 deletions src/aijack/attack/labelleakage/normattack.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@
def attach_normattack_to_splitnn(
cls, attack_criterion, target_client_index=0, device="cpu"
):
"""Attaches a normalization attack to a SplitNN model.
Args:
cls: The SplitNN model class.
attack_criterion: The criterion for the attack.
target_client_index (int, optional): Index of the target client. Defaults to 0.
device (str, optional): Device for computation. Defaults to "cpu".
Returns:
class: A wrapper class with attached normalization attack.
"""

class NormAttackSplitNNWrapper(cls):
def __init__(self, *args, **kwargs):
super(NormAttackSplitNNWrapper, self).__init__(*args, **kwargs)
Expand Down
10 changes: 10 additions & 0 deletions src/aijack/attack/poison/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@


def attach_history_attack_to_client(cls, lam):
"""Attaches a history attack to a client.
Args:
cls: The client class.
lam (float): The lambda parameter for the attack.
Returns:
class: A wrapper class with attached history attack.
"""

class HistoryAttackClientWrapper(cls):
"""Implementation of history attack proposed in https://arxiv.org/pdf/2203.08669.pdf"""

Expand Down
12 changes: 12 additions & 0 deletions src/aijack/attack/poison/label_flip.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@
def attach_label_flip_attack_to_client(
cls, victim_label, target_label=None, class_num=None
):
"""Attaches a label flip attack to a client.
Args:
cls: The client class.
victim_label: The label to be replaced.
target_label: The label to replace the victim label with. If None, a random label will be chosen.
class_num: The number of classes.
Returns:
class: A wrapper class with attached label flip attack.
"""

class LabelFlipAttackClientWrapper(cls):
def __init__(self, *args, **kwargs):
super(LabelFlipAttackClientWrapper, self).__init__(*args, **kwargs)
Expand Down
12 changes: 12 additions & 0 deletions src/aijack/attack/poison/mapf.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@


def attach_mapf_to_client(cls, lam, base_model_parameters=None):
"""Attaches a MAPF attack to a client.
Args:
cls: The client class.
lam (float): The lambda parameter for the attack.
base_model_parameters (list, optional): Base model parameters for parameter flipping.
If None, random parameters will be generated. Defaults to None.
Returns:
class: A wrapper class with attached MAPF attack.
"""

class MAPFClientWrapper(cls):
"""Implementation of MAPF proposed in https://arxiv.org/pdf/2203.08669.pdf"""

Expand Down
Loading

0 comments on commit f65f82b

Please sign in to comment.