Attacks

How to implement a new attack

To add a new attack you need to inherit BaseAttack class and implement __call__ method. For more examples, refer to the wibench.attacks module.

Create your_attack.py file in user_plugins directory.

Custom attack

Attack class should inherit BaseAttack class and implement __call__ method.

from wibench.attacks import BaseAttack

class MyAttack(BaseAttack):
    def __init__(self, any_parameters_of_atack):
        ...

    def __call__(self, object_to_attack):
        # Attack input object here
        ...
        return attacked_object

Implemented attacks

Common

class wibench.attacks.common.Identity[source]

Implementation of “no attack” case

__call__(watermark_object: TorchImg) TorchImg[source]

Copy of input image.

Parameters

imageTorchImg

Input image tensor

Returns

TorchImg

Copy of image tensor

class wibench.attacks.common.Combination(attacks: List[Dict[str, Any]])[source]

Combination of attacks. Any combination of registered attack is supported. For example, you may use combination of rotation and center crop as:

- combination:
    report_name: rotate_crop
    attacks:
    - rotate:
        angle: 30
    - centercrop:
        ratio: 0.5

Parameters

attacks: list[dict[str, Any]]

List of attacks with their parameters to apply one-by-one.

__call__(watermark_object: TorchImg) TorchImg[source]

Apply attack to an object.

class wibench.attacks.common.ImageWatermark(algorithm: str = 'dct_marker', config: Optional[Dict[str, Any]] = None)[source]

Applies watermark as attack on another watermark. Watermark data (e.g. bit message) is chosen randomly. Example of configuration (default algorithm parameters):

- ImageWatermark:
    report_name: trustmark_attack
    algorithm: trustmark 

Or you may pass specified algorithm parameters via config field:

- ImageWatermark:
    report_name: trustmark_attack
    algorithm: trustmark 
    config:
      params:
      wm_length: 100
      model_type: Q
      wm_strength: 0.75
      device: cpu

Parameters

algorithm: str

Watermarking algorithm to apply. Any post-hoc algorithm available

config: Optional[Dict[str, Any]]

Configuration for AlgorithmWrapper

__call__(watermark_object: TorchImg) TorchImg[source]

Apply attack to an object.

Distortions

This block contains basic distortion attacks.

class wibench.attacks.distortions.JPEGCompression(quality: int = 50)[source]

JPEG compression attack.

Parameters

qualityint

JPEG quality factor (1-100)

class wibench.attacks.distortions.Rotate90(direction: Literal['clock', 'counter'] = 'clock')[source]

Rotates image by 90 degrees clockwise or counter-clockwise.

Parameters

directionLiteral[“clock”, “counter”], optional

Rotation direction, either “clock” for clockwise or “counter” for counter-clockwise. Default is “clock”.

class wibench.attacks.distortions.Rotate(angle: float = 30, interpolation: str = 'bilinear', expand=False)[source]

Rotates image by arbitrary angle counter-clockwise.

Parameters

anglefloat

Rotation angle in degrees counter-clockwise. For clockwise rotation use negative numbers

interpolationstr, optional

Interpolation mode (‘nearest’, ‘bilinear’, ‘bicubic’). Default is ‘bilinear’.

expandbool, optional

Whether to expand output image size to fit rotated image. Default is False.

class wibench.attacks.distortions.GaussianBlur(kernel_size: int = 3)[source]

Applies Gaussian blur to image.

Parameters

kernel_sizeint

Size of Gaussian kernel (must be odd and positive)

class wibench.attacks.distortions.GaussianNoise(sigma: float = 0.03)[source]

Adds Gaussian noise to image.

Parameters

sigmafloat

Standard deviation of Gaussian noise distribution

class wibench.attacks.distortions.CenterCrop(ratio: float = 0.8)[source]

Center crops image by specified area ratio.

Parameters

ratiofloat

Ratio of area to keep (0-1). For example, 0.5 keeps 50% of image area.

class wibench.attacks.distortions.Resize(x_ratio: float = 0.5, y_ratio: float = 0.5, interpolation: str = 'bilinear')[source]

Resizes image by specified width and height ratios.

Parameters

x_ratiofloat, optional

Width scaling factor. Default is 1 (no change).

y_ratiofloat, optional

Height scaling factor. Default is 1 (no change).

interpolationstr, optional

Interpolation mode (‘nearest’, ‘bilinear’, ‘bicubic’). Default is ‘bilinear’.

class wibench.attacks.distortions.RandomCrop(ratio: float = 0.8)[source]

Randomly crops a rectangular region of specified area ratio. Removes the remaining area.

Parameters

ratiofloat

Ratio of area to keep (0-1). For example, 0.8 keeps 80% of image area.

class wibench.attacks.distortions.RandomCropout(ratio: float = 0.8)[source]

Randomly crops out a rectangular region of specified area ratio. Fills the remaining area with black color.

Parameters

ratiofloat

Ratio of area to keep (0-1). For example, 0.8 keeps 80% of image area.

class wibench.attacks.distortions.Brightness(factor: float = 1.2)[source]

Adjusts image brightness.

Parameters

factorfloat

Brightness adjustment factor:

  • 1.0 returns original image,

  • <1.0 darkens image,

  • >1.0 brightens image

class wibench.attacks.distortions.Contrast(factor: float = 1.2)[source]

Adjusts image contrast.

Parameters

factorfloat

Contrast adjustment factor:

  • 1.0 returns original image,

  • <1.0 reduces contrast,

  • >1.0 increases contrast

class wibench.attacks.distortions.PixelShift(delta: int = 7)[source]

Shifts image pixels horizontally with edge wrapping.

Parameters

deltaint, optional

Number of pixels to shift right. Leftmost pixels wrap around to right. Default is 7.

class wibench.attacks.distortions.ColorInversion[source]

Inverts colors in image.

SADRE

class wibench.attacks.SADRE.sadre.WPWMAttacker(pipe=None, noise_step=60, saliency_mask=None, device='cpu')[source]

Saliency-Aware Diffusion Reconstruction for Effective Invisible Watermark Removal. For more information visit the following page.

estimate_watermark_strength(x_w)[source]

Estimate watermark strength using entropy of the normalized image.

Args:

x_w (torch.Tensor): Input watermarked image (C, H, W).

Returns:

float: Entropy as a measure of watermark strength.

compute_latent_saliency_mask(latents)[source]

Compute a saliency mask using features from a pre-trained VGG network.

Args:

img (torch.Tensor): Input image tensor (C, H, W).

Returns:

torch.Tensor: Saliency mask of shape (1, 1, H, W).

__call__(img: TorchImg, prompts=None) TorchImg[source]

Apply attack to an object.

DIP

class wibench.attacks.dip_attack.dip_attack.DIPAttack(device: str = 'cpu', dtype: str = 'float32', total_iters: int = 150, lr: float = 0.01, arch: str = 'vanila')[source]

DIP-based watermark evasion attack adopted from the github repository.

NOTE: It uses slightly incorrect (non-randomized) input during DIP training. More correct version is available below.

__call__(img: TorchImg) TorchImg[source]

Apply attack to an object.

class wibench.attacks.dip_attack.dip_attack.DIPAttackNoise(device: str = 'cpu', dtype: str = 'float32', total_iters: int = 500, lr: float = 0.001, arch: str = 'vanila', input_noise_method: str = 'n', input_noise_var: float = 0.1)[source]

DIP-based watermark evasion attack with correct noise input. It follows original DIP model input initialization from the github repository.

__call__(img: TorchImg) TorchImg[source]

Apply attack to an object.

Adversarial

class wibench.attacks.adversarial.adversarial.AdversarialEmbedding(encoder: str = 'resnet18', device: torch.device | str = 'cpu', loss_type: str = 'l2', strength: int = 2, eps_factor: float = 0.00392156862745098, alpha_factor: float = 0.05, n_steps: int = 200, random_start: bool = True)[source]

Adversarial embedding attack from WAVES benchmark.

__call__(img: Tensor) Tensor[source]

Apply attack to an object.

class wibench.attacks.adversarial.adversarial.AdversarialEmbeddingPSNR(encoder: str = 'resnet18', device: torch.device | str = 'cpu', psnr: float = 40, loss_type: str = 'l2', alpha: float = 10.0, n_steps: int = 100)[source]

Modification of adversarial embedding attack that uses PSNR instead of \(\ell_\infty\) norm to measure closeness between images.

__call__(img: Tensor) Tensor[source]

Apply attack to an object.

Averaging

class wibench.attacks.averaging.averaging.Averaging(pattern_load_path: str | None = './resources/averaging/pattern_stegastamp.pth', num_images: Optional[int] = None, device: torch.device | str = 'cpu')[source]

Attack based on simple averaging from https://arxiv.org/abs/2406.09026.

Args:

pattern_load_path: the precomputed pattern needed for the attack num_images: if None use all images in the directories to compute the pattern, if =n use first n images. Defaults to None. device: device to compute on. Defaults to “cuda”.

__call__(img: TorchImg) TorchImg[source]

Apply attack to an object.

compute_pattern(dir_watermarked: str, dir_clean: str, batch_size: int = 1) Tensor[source]

Compute the pattern needed for the attack by subtracting averaged watermarked images and clean images.

The pattern is saved as a class attribute.

Args:

dir_watermarked: directory with watermarked images dir_clean: directory with clean non-watermarked images batch_size: batch size to use when computing average

Returns:

computed pattern, (1,c,h,w) tensor

Blur Deblur

class wibench.attacks.blur_deblur.blur_deblur.DoGBlur(alpha: float = 1.0, sigma_1: float = 1.0, sigma_2: float = 16.0, kernel_size: Optional[int] = None, num_channels: int = 3, device: str = 'cuda:0')[source]

Blur that processes only middle frequencies based on Difference of Gaussians.

__call__(image: Tensor) Tensor[source]

Apply attack to an object.

class wibench.attacks.blur_deblur.blur_deblur.BlurDeblurFPNInception(sigma: float = 3.0, weights_path: str = './model_files/blur_deblur/fpn_inception.h5', device: str = 'cpu')[source]

Attack that blurs the image and then restores it using deblurring architecture from DeblurGAN-v2 paper.

load_deblur_weights(weights_path: str) None[source]

Load weights for the deblur model from the original repo.

__call__(image: Tensor) Tensor[source]

Apply attack to an object.

class wibench.attacks.blur_deblur.blur_deblur.DoGBlurDeblurFPNInception(alpha: float = 0.5, sigma_1: float = 1.0, sigma_2: float = 1.6, weights_path: str = './model_files/blur_deblur/fpn_inception.h5', device: str = 'cpu')[source]

Attack that blurs the image with DoG blur and then restores it using deblurring architecture from DeblurGAN-v2 paper.

load_deblur_weights(weights_path: str) None[source]

Load weights for the deblur model from the original repo.

__call__(image: Tensor) Tensor[source]

Apply attack to an object.

BM3D

class wibench.attacks.bm3d.bm3d.BM3DDenoising[source]

For more information, please refer to the following page.

__call__(img: TorchImg) TorchImg[source]

Apply attack to an object.

VAE

class wibench.attacks.vae.vae.VAEAttack(n_avg_imgs: int = 100, noise_level: float = 0.5, device: str = 'cpu', cache_dir: Optional[str] = None)[source]

Adversarial attack using a VAE to generate noisy image reconstructions.

Encodes an image into latent space, adds Gaussian noise to the latents, then decodes multiple noisy versions. Returns the average of these reconstructions as an attacked image. Uses the FLUX.1-schnell VAE.

Parameters

n_avg_imgs: int

Number of noisy reconstructions to average.

noise_level: float

Standard deviation of Gaussian noise added to latents.

device: str

Device to run the VAE on.

cache_dir: str

Directory for caching the VAE model.

__call__(img: Tensor) Tensor[source]

Apply attack to an object.

StegastampInversion

class wibench.attacks.stegastamp_inversion.stegastamp_inversion.StegastampInversion(stegastamp_model_path: str = './model_files/stega_stamp/stega_stamp.onnx', device_id: int = 0)[source]

Adversarial attack that inverts watermarks encoded by Stegastamp from here. This attack decodes the hidden watermark from a watermarked image, inverts it (1 - watermark), and re-encodes the inverted watermark back into the image. The process is designed to disrupt Stegastamp’s watermark decoding while maintaining visual similarity to the original.

Parameters

stegastamp_model_path: str

path to StegaStamp onnx model

device_id: int

ID of cuda device to run Stegastamp on

TODO:
  • run with GPU tensors, see the following link

  • convert from onnx to pytorch?

__call__(img: TorchImg) TorchImg[source]

Apply attack to an object.

Regeneration

This block contains regeneration attacks.

class wibench.attacks.diffusion_regeneration.regeneration.DiffusionRegeneration(pipe=None, device='cpu', noise_step=60)[source]

Based on the code from here.

__call__(img: TorchImg, prompts: list[str] | None = None, return_latents: bool = False, return_dist: bool = False) Tensor[source]

Apply attack to an object.

class wibench.attacks.flux_regeneration.regeneration.FluxRegeneration(device: torch.device | str = 'cpu', dtype: str = 'bfloat16', cpu_offload: bool = True, sequential_cpu_offload: bool = False, cache_dir: Optional[str] = None, prompt: str = 'original image', strength: float = 0.3, guidance_scale: float = 8.5, num_inference_steps: int = 12, max_sequence_length: int = 512)[source]

Attack regeneration from here. Image regeneration attack using FLUX image-to-image diffusion model. Applies a single-step FLUX diffusion transformation to subtly alter an input image while maintaining its overall structure.

TODO: check if this works with batches.

__call__(img: Tensor) Tensor[source]

Apply attack to an object.

class wibench.attacks.flux_regeneration.regeneration.FluxRinsing(rinsing_times: int = 2, device: torch.device | str = 'cuda:0', dtype: str = 'bfloat16', cpu_offload: bool = True, sequential_cpu_offload: bool = False, cache_dir: Optional[str] = None, prompt: str = 'original image', strength: float = 0.3, guidance_scale: float = 8.5, num_inference_steps: int = 12, max_sequence_length: int = 512)[source]

Attack rinse2x from here. Multi-step image purification using repeated FLUX regeneration.

__call__(img: Tensor) Tensor[source]

Apply attack to an object.

class wibench.attacks.VAERegeneration.regeneration.VAERegeneration(model_name='bmshj2018-factorized', quality=1, device='cpu')[source]

Based on the code from here.

__call__(img: Tensor) Tensor[source]

Apply attack to an object.

Frequency Masking

class wibench.attacks.frequency_masking.frequency_masking.FrequencyMasking(normalize=True)[source]

Image-domain frequency masking attack that suppresses low-frequency components. Applies a circular mask to the Fourier spectrum of an image to remove central low-frequency information.

__call__(image: TorchImg) TorchImg[source]

Apply attack to an object.

class wibench.attacks.frequency_masking.frequency_masking.LatentFrequencyMasking(beta: float = 0.0, mask_mode: str = 'zero', model: str = 'WIBE-HuggingFace/stable-diffusion-2-1-base', mask_radius: int = 10, mask_channel: int = 0, cache_dir: Optional[str] = None, device: str = 'cpu')[source]

Latent-space frequency masking attack for diffusion model representations. Projects images into a VAE’s latent space, applies frequency masking in the Fourier domain, and reconstructs modified images. Supports various masking modes (zero, random, mean) for controlled perturbations.

__call__(image: TorchImg)[source]

Apply attack to an object.

Image Editing

class wibench.attacks.image_editing.ImageEditingFluxContext.ImageEditingFLuxContext(device_vl: str = 'cpu', device_flux: str = 'cpu', internvl_path: str = 'OpenGVLab/InternVL2_5-8B', fluxcontext_path: str = 'black-forest-labs/FLUX.1-Kontext-dev', prompts_path: str = './resources/flux_prompts.json', guidance_scale: float = 7.5, num_inference_steps: int = 28, is_prompts: bool = True, mode: str = 'base', custom_prompt: Optional[str] = None)[source]

Adversarial attack that edits images using instruction-guided generation.

Combines InternVL2 for natural language understanding and FLUX.1-Kontext for instruction-guided image editing. Generates textual instructions describing the input image, then uses them to guide image-to-image transformations that create adversarial outputs.

__call__(image: TorchImg) TorchImg[source]

If you want to use one prompt for isntruction using set of prompts, use is_prompts=True.

class wibench.attacks.image_editing.InstructPix2Pix.ImageEditingInstructPix2Pix(device: str = 'cpu', internvl_path: str = 'OpenGVLab/InternVL2_5-8B', instructpix2pix_path: str = 'timbrooks/instruct-pix2pix', prompts_path: str = './resources/prompts_internvl.json', guidance_scale: float = 2.0, is_prompts: bool = True, mode: str = 'base', custom_prompt: Optional[str] = None)[source]

Adversarial attack using instruction-guided image-to-image editing.

Combines InternVL2 for instruction generation with InstructPix2Pix for semantic image editing. Generates text instructions describing desired modifications, then applies them via diffusion-based editing.

__call__(image: TorchImg) TorchImg[source]

If you want to use one prompt for isntruction using set of prompts, use is_prompts=True. The mode variable is responsible for the type of prompt for generating instructions:

base - focuses on keeping the overall scene recognizable, and changing some texture or style. details - focuses on high-frequency details and textures where watermarks typically reside. content_preserving - use blurring, noise injection, or micro-texture replacement. local_changes - focuses on changing local details on image (for example, change eyes color).

LIIF

class wibench.attacks.liif.liif_attack.LIIFAttack(device: str = 'cpu', model_path: str = './model_files/liif/rdn-liif.pth')[source]

Attack using Local Implicit Image Function (LIIF) for image super-resolution.

Reconstructs images through an implicit neural representation that learns continuous image functions. The attack queries the LIIF model at specific coordinates to generate a modified version of the input image, effectively applying learned upsampling/denoising.

__call__(img: TorchImg) TorchImg[source]

Apply attack to an object.

SEMAttack

class wibench.attacks.SemanticImprintRemoval.semantic_attack.SEMAttack(modelid_attacker: str = 'WIBE-HuggingFace/stable-diffusion-2-1-base', scheduler_attacker: str = 'DDIM', num_inference_steps_attacker: int = 50, lr: float = 0.01, steps: int = 151, seed: Optional[int] = None, device: str = 'cpu', cache_dir=None)[source]

Attack from “Black-Box Forgery Attacks on Semantic Watermarks for Diffusion Models”

code is based on https://github.com/and-mill/semantic-forgery

__call__(image: Tensor) Tensor[source]

Apply attack to an object.

WMForger

class wibench.attacks.wmforger.wmforger.WMForger(weights_path: str = './model_files/wmforger/convnext_pref_model.pth', num_steps: int = 50, lr: float = 0.05, device: str = 'cpu')[source]

Attack from Transferable Black-Box One-Shot Forging of Watermarks via Image Preference Models.

code is based on https://github.com/facebookresearch/videoseal/blob/main/wmforger

__call__(image: Tensor) Tensor[source]

Apply attack to an object.

TrustMarkRM

class wibench.attacks.trustmark_rm.trustmark_rm.TrustMarkRM(model_type: str = 'Q', device: str = 'cpu')[source]

TrustMark: Universal Watermarking for Arbitrary Resolution Images - Image Watermarking Algorithm.

Using TrustmarkRM model as an attack on watermarks. Based on the code from here.

__call__(image: TorchImg) TorchImg[source]

Apply attack to an object.

NRP

class wibench.attacks.nrp.nrp.NRPSmall(defence_type: str = 'nonadaptive', eps: float = 0.06274509803921569, weights_path: str = './model_files/nrp/NRP_resG.pth', device: str = 'cpu')[source]

Adversarial defense method NRP from the paper ‘A Self-supervised Approach for Adversarial Robustness’. Smaller backbone variant. https://openaccess.thecvf.com/content_CVPR_2020/papers/Naseer_A_Self-supervised_Approach_for_Adversarial_Robustness_CVPR_2020_paper.pdf

__call__(image)[source]

Apply attack to an object.

class wibench.attacks.nrp.nrp.NRPLarge(defence_type: str = 'nonadaptive', eps: float = 0.06274509803921569, weights_path: str = './model_files/nrp/NRP.pth', device: str = 'cpu')[source]

Adversarial defense method NRP from the paper ‘A Self-supervised Approach for Adversarial Robustness’. Larger backbone variant. https://openaccess.thecvf.com/content_CVPR_2020/papers/Naseer_A_Self-supervised_Approach_for_Adversarial_Robustness_CVPR_2020_paper.pdf

__call__(image)[source]

Apply attack to an object.

MPRNet

class wibench.attacks.mprnet.MPRNetAttack(weights_path: str = './model_files/mprnet/mprnet_denoise.pth', device: str = 'cpu')[source]

Adversarial defense based on image restoration model MPRNet from ‘ Multi-stage progressive image restoration.’ https://arxiv.org/abs/2102.02808

__call__(image)[source]

Apply attack to an object.

Flux Attacks

class wibench.attacks.UniEdit_FLUX.image_editing.UniEditAttackFlux(model_name: str = 'flux-dev', module_path: str = './src/wibench/attacks/UniEdit_FLUX/UniEdit-Flow_FLUX/src', device: str = 'cpu', num_steps: int = 30, source_prompt: str = 'photorealistic image', target_prompt: str = '4k, highly detailed photorealistic image, no artifacts', alpha: float = 0.6, omega: float = 5.0, guidance: float = 1.0, offload: bool = False, zero_init: bool = False)[source]

Image Editing using Flux model.

__call__(image: Tensor) Tensor[source]

Perform image editing attack.

Args:

img: input image, (b,c,h,w) tensor, RGB channels in range [0,1]

Returns:

edited_img, (b,c,h,w) tensor, RGB channels in range [0,1]

class wibench.attacks.UniEdit_FLUX.image_editing.UniInvAttackFlux(model_name: str = 'flux-dev', module_path: str = './src/wibench/attacks/UniEdit_FLUX/UniEdit-Flow_FLUX/src', device: str = 'cpu', num_steps: int = 30, prompt: str = 'photorealistic image', offload: bool = False, zero_init: bool = False)[source]

Image Inversion and Reconstruction using Flux model.

__call__(image: Tensor) Tensor[source]

Perform inversion and reconstruction attack.

Args:

img: input image, (b,c,h,w) tensor, RGB channels in range [0,1]

Returns:

reconstructed_img, (b,c,h,w) tensor, RGB channels in range [0,1]

DISCO

class wibench.attacks.disco.defence.DISCOAttack(weights_path: str = './model_files/disco/disco_pgd.pth', module_path: str = './src/wibench/attacks/disco/dfsrc_disco', device: str = 'cpu')[source]

Based on adversarial defense from ‘DISCO: Adversarial Defense with Local Implicit Functions’ https://arxiv.org/abs/2212.05630

__call__(image: Tensor) Tensor[source]

Apply attack to an object.

Instagram/CSS filters

class wibench.attacks.instagramcss_filters.instagramcss_filters.InstagramCSSFilters(attack: str, module: Optional[str] = None)[source]

Attack Instagram/CSS filters from here.

Image postprocessing attack using Instagram-style and CSS-like filters from the pilgram package. Applies predefined color and tone transformations to an input image, including CSS filters such as contrast, grayscale, hue rotation, saturation, and sepia. Instagram-style presets are provided by pilgram; see the original repository for the full list of available filters.

__call__(image: TorchImg) TorchImg[source]

Apply attack to an object.

DiffPure

class wibench.attacks.diffpure.defence.DiffPureAttack(weights_path: str = './model_files/diffpure/256x256_diffusion_uncond.pt', device: str = 'cpu', factor: float = 1.0)[source]

ToDo

__call__(image)[source]

Apply attack to an object.

RealESRGAN

class wibench.attacks.realesrgan.realesrgan_attack.RealESRGANAttack(model_name='realesr-general-x4v3', model_path='./model_files/realesrgan/realesr-general-x4v3.pth', denoise_strength=0.2, outscale=1, tile=0, tile_pad=10, pre_pad=0, device: str = 'cpu', fp32=True)[source]

ToDo

__call__(image)[source]

Apply attack to an object.

UnMarkerAttack

class wibench.attacks.UnMarker.unmark.UnMarkerAttack(models_path: str = './model_files/unmarker/', config_path: str = './src/wibench/attacks/UnMarker/attack_configs/Yu2.yaml', image_size=512, device='cuda')[source]
__call__(image: Tensor)[source]

Apply attack to an object.