i am sending batch return advaersraical batch with using information (i e same dime )…
- User
i am sending batch return advaersraical batch with using information (i e same dime ) NOTE: we have change every thing in api it self (rlpe) (base) hemanth@aics:/scratch/hemanth /scratch/hemanth/anaconda/envs/rlpe/bin/python /scratch/hemanth/Hemanth/RLPE/rlpe.py INFO:rldata.rlpedata:Loading dataset from zh-plus/tiny-imagenet Fast image processor class <class 'transformers.models.vit.image_processing_vit_fast.ViTImageProcessorFast'> is available for this model. Using slow image processor class. To use the fast image processor class set `use_fast=True`. Some weights of ViTForImageClassification were not initialized from the model checkpoint at google/vit-base-patch16-224-in21k and are newly initialized: ['classifier.bias', 'classifier.weight'] You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference. INFO:model.modelloader:Successfully initialized transformers model: google/vit-base-patch16-224-in21k INFO:art.estimators.classification.pytorch:Inferred 1 hidden layers on PyTorch classifier. Original images shape: torch.Size([32, 3, 224, 224]) INFO:defences.defencerlpe:DefenseManager initialized with available defenses. INFO:attacks.attackrlpe:Initializing attack: AdversarialPatch INFO:art.attacks.evasion.adversarial_patch.adversarial_patch:Creating adversarial patch. Adversarial Patch PyTorch: 100%|███████████████████████████████████| 10/10 [00:08<00:00, 1.12it/s] WARNING:attacks.attackrlpe:attack.generate returned a tuple. Logging contents to understand structure. INFO:attacks.attackrlpe:Extracted adversarial_examples from the tuple. ERROR:attacks.attackrlpe:attack.generate returned type <class 'torch.Tensor'>, expected np.ndarray. ERROR:attacks.attackrlpe:Unexpected error during 'AdversarialPatch': attack.generate returned a non-ndarray type. Traceback (most recent call last): File "/scratch/hemanth/Hemanth/RLPE/rlpe.py", line 111, in <module> adversarial_images = apply_attack( ^^^^^^^^^^^^^ File "/scratch/hemanth/Hemanth/RLPE/attacks/attackrlpe.py", line 990, in apply_attack raise TypeError("attack.generate returned a non-ndarray type.") TypeError: attack.generate returned a non-ndarray type. (rlpe) (base) hemanth@aics:/scratch/hemanth def apply_attack( attack_name: str, classifier: Any, x: Union[np.ndarray, torch.Tensor], y: Optional[Union[np.ndarray, torch.Tensor]] = None, new_params: Optional[Dict[str, Any]] = None, ) -> Union[np.ndarray, torch.Tensor]: """ Apply a single adversarial attack with the ability to update attack parameters.
Args: attack_name (str): The name of the attack to apply. classifier (Any): The trained classifier or estimator. x (np.ndarray or torch.Tensor): Input data. y (Optional[np.ndarray or torch.Tensor]): True labels. Required for some attacks. new_params (Optional[Dict[str, Any]]): New parameters to update the attack. Returns: np.ndarray or torch.Tensor: Adversarial examples, same type as input `x`. """ logger.info(f"Initializing attack: {attack_name}") try: attack_class = get_attack_class(attack_name) if not attack_class: raise NotImplementedError(f"The attack '{attack_name}' is not supported.") params = get_attack_parameters(attack_name) if new_params: params = update_attack_parameters(params, new_params) # Assign the classifier or estimator correctly if "estimator" in params: params["estimator"] = classifier if "classifier" in params: params["classifier"] = classifier # Handle special parameters if necessary if attack_name == "AutoAttack": params["estimator_orig"] = classifier elif attack_name == "AdversarialPatchPyTorch": params["estimator"] = classifier # Initialize the attack with the classifier and parameters attack = attack_class(**params) # If input is a tensor, move it to CPU and convert to NumPy if isinstance(x, torch.Tensor): original_device = x.device x_numpy = x.detach().cpu().numpy() logger.debug(f"Converted input tensor to NumPy array on CPU with shape {x_numpy.shape}") if y is not None: if isinstance(y, torch.Tensor): y_numpy = y.detach().cpu().numpy() logger.debug(f"Converted label tensor to NumPy array on CPU with shape {y_numpy.shape}") else: y_numpy = y logger.debug(f"Label is already a NumPy array with shape {y_numpy.shape}") else: x_numpy = x y_numpy = y logger.debug(f"Input is a NumPy array with shape {x_numpy.shape}") if y_numpy is not None: logger.debug(f"Label is a NumPy array with shape {y_numpy.shape}") # Validate that inputs are NumPy arrays if not isinstance(x_numpy, np.ndarray): raise TypeError(f"Expected x to be a NumPy array after conversion, got {type(x_numpy)}") if y_numpy is not None and not isinstance(y_numpy, np.ndarray): raise TypeError(f"Expected y to be a NumPy array after conversion, got {type(y_numpy)}") # Generate adversarial examples adversarial_output = attack.generate(x=x_numpy, y=y_numpy) logger.debug(f"Generated adversarial_output of type {type(adversarial_output)}") logger.debug(f"adversarial_output length: {len(adversarial_output) if isinstance(adversarial_output, tuple) else 'N/A'}") # Handle tuple output if isinstance(adversarial_output, tuple): logger.warning( "attack.generate returned a tuple. Logging contents to understand structure." ) for idx, elem in enumerate(adversarial_output): logger.debug(f"Tuple element {idx}: Type={type(elem)}, Shape={elem.shape if isinstance(elem, np.ndarray) else 'N/A'}") # Decide how to handle the tuple based on its contents # For example, if adversarial_examples are the first element: tensor_list = [torch.tensor(arr) for arr in adversarial_output] my_tensor = torch.stack(tensor_list) adversarial_examples =my_tensor logger.info("Extracted adversarial_examples from the tuple.") else: adversarial_examples = adversarial_output logger.info("attack.generate returned adversarial_examples as a NumPy array.") # Ensure adversarial_examples is a NumPy array if not isinstance(adversarial_examples, np.ndarray): logger.error( f"attack.generate returned type {type(adversarial_examples)}, expected np.ndarray." ) raise TypeError("attack.generate returned a non-ndarray type.") logger.debug(f"Adversarial examples shape: {adversarial_examples.shape}") # If original input was a tensor, convert adversarial_examples back to tensor if isinstance(x, torch.Tensor): adversarial_tensor = torch.from_numpy(adversarial_examples).to(original_device) adversarial_tensor = adversarial_tensor.type_as(x) logger.debug(f"Converted adversarial_examples back to tensor with shape {adversarial_tensor.shape} and dtype {adversarial_tensor.dtype}") adversarial_examples = adversarial_tensor logger.info(f"Attack '{attack_name}' performed successfully.") return adversarial_examples except Exception as e: logger.error(f"Unexpected error during '{attack_name}': {e}") raise - Assistant